Referencia · §8.48

Sync between devices and a server

sync, §M16.7

Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.

A device’s database (§11, In the process) keeps a server’s rows and writes them offline. Changes flow both ways when a connection exists (D24). The device holds shapes. A shape is the rows one query selects from one of the server’s tables, read as the device’s user, so the user’s privileges and row-level security decide what the device holds.

Sync is three statements, so every driver and transport carries it as it is:

  1. SYNC REQUEST on the device gives the request (§M16.7 Y4).
  2. The driver runs SYNC $1 on the server with that request.
  3. SYNC APPLY $1 on the device takes the answer.

On the server (§M16.7 Y1): SYNC <request> takes a json request as a string or a parameter, and answers one row with one json value. It runs as a statement of its own, outside a transaction block (25001 inside one).

SYNC '{"shapes": [{"name": "mine", "query": "SELECT id, title, done FROM todos WHERE list = 1",
                   "position": 1042}], "wait": 30000}';
-- {"position": 1077, "clock": 1764672000123456,
--  "shapes": [{"name": "mine", "table": "todos", "reset": false, "key": ["id"],
--              "columns": [{"name": "id", "type": "integer", "not_null": true}, …],
--              "changes": [[-1, {"id": 2, …}], [1, {"id": 1, "done": true, …}]]}]}
  • A shape is SELECT columns FROM t [WHERE …]. It reads one table that has a primary key, and selects its columns unrenamed (or *), the key’s among them. It has no DISTINCT, grouping, windows, ordering, limit or WITH, and calls no function whose answer changes without a commit. Anything else is 0A000. The WHERE may hold any condition, subqueries included.
    • A request names each table in one shape at most.
    • It is not a stream, and has no subject columns: copies on devices would outlive FORGET SUBJECT.
    • Privileges are checked as a query’s (42501).
  • Its changes. All the request’s shapes are read at one snapshot, the answer’s position (a commit).
    • With a shape’s position (the one the device holds), the shape is read again AS OF COMMIT that position (§M14.14) and the two are compared by primary key.
      • A row gone, or one the device must no longer hold, is [-1, row].
      • A row there now that differs, or is new, is [1, row].
      • So a row that leaves the shape by any cause leaves the device: a policy, a grant, the row’s own write, or another table’s that the WHERE reads.
    • The changes come gone first, then come, each in key order. Rows are json objects of the columns (to_json’s forms).
    • Without a position, or where the history no longer reaches it (§5.2: the server’s --history), or where the table was made again or altered since, the shape comes whole: reset is true and every row is [1, row].
    • columns gives each column’s type as the catalog writes it, and whether it is NOT NULL. key gives the primary key’s columns.
    • A position past the server’s newest commit is 22023.
  • Waiting. With wait (ms, at most an hour) and nothing to send, the server waits for a commit that writes a shape’s table, as CHANGES … WAIT does (§8.47), and answers once a shape changed or the time is up. No transaction is held while it waits.
  • The clock is the server’s hybrid logical clock, in microseconds since 1970 (Kulkarni et al.). It is never below the last given or a device’s clock seen. Devices order their writes by it (§M16.7 Y3). A clock seen counts only up to 5 minutes past the server’s wall clock (the skew Kerberos allows; Kulkarni et al.’s bound ε, CockroachDB’s maximum offset), so one device’s wrong clock cannot carry every later clock with it.
  • The server keeps nothing per shape. Each request carries its positions, so the cost of a request is that of reading its shapes twice.
  • A device’s writes (§M16.7 Y2). A request with device (its id, 1 to 200 bytes) carries writes in the order of their seq. Each write is {"seq", "table", "op", "key", "after", "before", "clock"}: an insert has after, an update both, a delete before, and the key is an object of the primary key’s columns. Values are read by the column’s type, as CAST reads their text. A write to a table that no shape of the request reads, writes out of order, or writes without a device are 22023, and the whole request is refused.
    • The writes are applied as the session’s user, in one transaction, each under a savepoint, with the table’s constraints, privileges and policies. A refused write is taken back and the next goes on.
    • The rule for now is that the server wins. An insert goes in as it is, so an existing row refuses it (23505). An update or a delete applies only to the row as the device saw it: its key and every column of before equal (IS NOT DISTINCT FROM). Otherwise it is refused with 23N01. A delete of a row already gone is applied.
    • Exactly once. The server keeps, per user and device, the last seq applied and the refusals since the device’s acked, written in the writes’ own transaction (keys 00 20). A write sent again is not applied again, and its answer is the same. A serialization failure runs the request’s writes again, up to 20 times.
    • The answer’s results, one per write, in the same snapshot as the shapes’ changes: seq, table, key, outcome (applied, or refused with code and message), and row. row is the row as the write’s shape reads it now, or null when the device no longer holds it. With it the device sets the row to the server’s, whatever came of its write, as Realm’s compensating writes do.
    • With writes, the server does not wait.
  • The rules (§M16.7 Y3): ALTER TABLE t SET (sync_conflict = …) chooses how a device’s write that conflicts is resolved. nucleus dump --schema writes it back.
    • server_wins is the default, as above.
    • last_writer_wins decides by clock.
      • Each row keeps the clock of its last write, and the device that made it ("" for the server), under the table’s reserved index u32::MAX − 8, by the row’s key.
      • Every write of the table sets it. A device’s write sets its own clock. Any other write, a statement on the server, sets the server’s clock, so a statement is later than whatever a device wrote before it reached the server.
      • A delete keeps its clock as a tombstone, so an older write does not bring the row back.
      • A device’s write is applied when its (clock, device) is past the row’s, in that order. A write whose clock is more than 5 minutes past the server’s wall clock is refused (22023): it would win the row for as long. An insert or an update is applied as an upsert of after, a delete as a delete. Otherwise it is refused with 23N01.
      • So the same writes reach the same row whatever order the devices reconnect in. A row written before the rule was set has no clock, and any device’s write is later.
    • merge:f calls a function on a conflict. A write whose row is not as before holds it is a conflict, and the function f(before, server, device) decides.
      • f is a module’s function (§8.12), taking three json values and answering json. An absent row is json’s null, not SQL’s NULL, so a strict function is still called.
      • An object is the row to write (an upsert), null deletes the row, and an error refuses the write with its SQLSTATE.
      • A write that does not conflict is applied as under server_wins.
    • The rule is checked when it is set: 22023 for another word, and 42883 for a function that is not there.

On the device (§M16.7 Y4). The device’s statements, each run as a statement of its own, outside a transaction block:

SYNC SHAPE mine AS SELECT id, title, done FROM todos WHERE list = 1;
SYNC REQUEST WAIT 30000;     -- one json value: the request for the server
SYNC APPLY $1;               -- the server's answer
SELECT * FROM todos;          -- local reads and writes, offline or not
SELECT * FROM nc_sync_refused; -- the writes the server refused
  • SYNC SHAPE name AS query keeps a shape (keys 00 21). Its form is checked as on the server, and each table is one shape’s.

    • It marks the table of the same name, if it is here, as a shape’s (Table::synced, record version 34). The first answer makes the table otherwise, from the server’s columns, types and key.
    • Its first use gives the device an id: 16 random bytes, in hex.
    • It makes nc_sync_refused.
    • The same name with another query starts the shape again: it is sent whole and the rows it no longer selects leave.
  • SYNC DROP SHAPE name forgets the shape and the writes of its table not yet sent. The table stays, and its writes are no longer captured.

  • The outbox. Every write of a shape’s table, by any statement, is captured in its own transaction through the changefeed’s wrap (§8.44):

    • the table, op, key, after and before as json;
    • the device’s clock: its wall clock, never below the last given or the server’s last seen, plus one;
    • a number the commit gives (a stream’s append, §8.43, under keys 00 23, head 00 24), so the writes go in commit order, with no gap and no conflict between writers.

    A rolled-back write is not there. nc_catalog.sync_outbox shows it: seq, table_name, op, key, after, before, clock.

  • SYNC REQUEST [WAIT ms] answers one row with one json value: the device’s id, its last acknowledged seq, its clock, its shapes with their positions, and the outbox’s first 1,000 writes. wait goes only when there are none. Before any SYNC SHAPE it is 55000.

  • SYNC APPLY <answer> applies the server’s answer in one serializable transaction, run again on a serialization failure. The answer’s own writes are not captured.

    1. Each answered write leaves the outbox. A refused one goes into nc_sync_refused (seq, table_name, op, key, after, code, message), and the application reads and deletes it there.
    2. Each shape’s changes are applied by key. A reset first deletes the rows the answer does not hold. A table whose columns changed on the server is made again, unless writes to it wait to be sent (55000).
    3. Each answered write’s row is set to the server’s (null: deleted).
    4. The shapes’ positions and the device’s state are stored.

    A row that a write still in the outbox changed is left as the device wrote it, both by the shapes’ changes and by the rows. Its own answer brings the server’s row later. So the application always reads its own writes, and every row ends as the server’s (Firestore’s latency compensation, Replicache’s rebase of pending writes).

  • nc_catalog.sync_shapes shows the shapes (name, query, table_name, position).

  • A device may also be a server’s table: these are statements of any database. They are not limited to the embedded editions.

The server’s history decides how long a device may be away and still get only the changes. A shape is compared with itself AS OF the device’s position, which the server keeps only as far as its --history reaches (history= for a database in the process, §11). Past it, or with none (the default), every round sends the shapes whole, and a round with nothing to send cannot wait, since a whole shape is never quiet. A server that devices sync with runs with a history that covers how long they are usually offline, as a Postgres replication slot needs its WAL kept. A device away for longer gets its shapes whole, and loses nothing.

The drivers carry a round as the three statements. The device is a connection like any other, usually to a database in the application’s process:

device = nucleus.connect("file:app.db")               # a database in the process
server = nucleus.connect("nucleus://user:pw@host/db")
device.execute("SYNC SHAPE mine AS SELECT * FROM todos WHERE list = 1")
device.sync(server)                 # one round; device.sync(server, wait_ms=30000)
device.sync_settle(server)          # rounds until nothing is left to send
device.sync_pending()               # writes not yet answered
Driver One round Until settled Writes waiting
Rust (nucleus_client::sync) round(&mut device, &mut server, wait) settle(…, rounds) pending(&mut device)
Python device.sync(server, wait_ms=None) device.sync_settle(server) device.sync_pending()
JavaScript (Node, the browser) await device.sync(server, waitMs?) device.syncSettle(server) device.syncPending()
Swift try device.sync(with: server, waitMs:) device.syncSettle(with:) device.syncPending()
Java, Kotlin (Android) device.sync(server[, waitMs]) device.syncSettle(server, rounds) device.syncPending()

The request and the answer pass between the connections as text, so no value goes through a JavaScript number. A round that fails on the way loses nothing: the device keeps its writes until an answer it applied says what became of them, and the server applies a write sent twice only once. So an application simply runs the round again: on a timer, when the network comes back, or in a loop with wait.

Tests: crates/sql/tests/sync.rs:

  • a shape sent whole, then its changes: rows changed, moved out and in, deleted, inserted;
  • a position the history lost, a table altered, and a position from the future;
  • the forms refused;
  • a wait woken by a commit to its table and not by others;
  • row-level security: rows given away and a policy changed.
  • a device’s writes: applied, refused by the rule, by a constraint and by a key, and the answers’ rows; sent again with nothing applied twice; acknowledged; a second device of the same user;
  • writes under privileges and a policy’s WITH CHECK;
  • four devices writing at once, each request sent twice: every insert applied once, and the shared row’s value the number of its updates applied.
  • the last writer by clock, arriving in either order: tombstones, a row never there, equal clocks, the server’s own write, and the rule set back;
  • a merge function (a test module adding to a counter): no conflict, a conflict merged, a delete that loses, and the function’s refusal.

crates/sql/tests/sync_device.rs, the device against a server:

  • a table made from the shape’s columns, writes both ways, a row moved out on the server;
  • a refused write undone and kept in nc_sync_refused;
  • a lost answer asked again and a doubled answer, with nothing applied twice;
  • a write made while an exchange is on its way, kept until its answer;
  • a table the server altered, made again;
  • shapes kept, started again, dropped and refused.

crates/sql/tests/sync_converge.rs, a model test on the simulation (§M16.7 Y5): three devices write offline and exchange in any order, as requests and answers are lost or doubled and the devices and the server crash (now, or within their next operations). Each write also logs a row of its device. When the network heals, every device holds its shapes of the server’s state, and the server holds every committed write once: none lost, none made up, none applied twice. It runs under server_wins and last_writer_wins, and with a history of three commits, so that most rounds send their shapes whole. A device behind the history gets its shape whole, keeping its own write. A device of a user under row-level security holds only that user’s rows. With NUCLEUS_SIM_CASES=500, 1,500 runs pass.

The drivers’ tests run a device in the process against a server: editions/embedded/tests/sync.rs (Rust, a directory closed and opened again with writes waiting, and a round that waits), and the Python, JavaScript (Node and WebAssembly), Swift and Android suites.