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:
SYNC REQUESTon the device gives the request (§M16.7 Y4).- The driver runs
SYNC $1on the server with that request. SYNC APPLY $1on 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 noDISTINCT, grouping, windows, ordering, limit orWITH, and calls no function whose answer changes without a commit. Anything else is0A000. TheWHEREmay 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 againAS OF COMMITthat 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
WHEREreads.
- A row gone, or one the device must no longer hold, is
- The changes come gone first, then come, each in key order. Rows
are
jsonobjects 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:resetis true and every row is[1, row]. columnsgives each column’s type as the catalog writes it, and whether it isNOT NULL.keygives the primary key’s columns.- A position past the server’s newest commit is
22023.
- With a shape’s
- Waiting. With
wait(ms, at most an hour) and nothing to send, the server waits for a commit that writes a shape’s table, asCHANGES … WAITdoes (§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
clockseen. 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) carrieswritesin the order of theirseq. Each write is{"seq", "table", "op", "key", "after", "before", "clock"}: an insert hasafter, an update both, a deletebefore, and the key is an object of the primary key’s columns. Values are read by the column’s type, asCASTreads their text. A write to a table that no shape of the request reads, writes out of order, or writes without a device are22023, 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 ofbeforeequal (IS NOT DISTINCT FROM). Otherwise it is refused with23N01. A delete of a row already gone is applied. - Exactly once. The server keeps, per user and device, the last
seqapplied and the refusals since the device’sacked, written in the writes’ own transaction (keys00 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, orrefusedwithcodeandmessage), androw.rowis the row as the write’s shape reads it now, ornullwhen 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 --schemawrites it back.server_winsis the default, as above.last_writer_winsdecides 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 indexu32::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 ofafter, a delete as a delete. Otherwise it is refused with23N01. - 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.
- Each row keeps the clock of its last write, and the device that
made it (
merge:fcalls a function on a conflict. A write whose row is not asbeforeholds it is a conflict, and the functionf(before, server, device)decides.fis a module’s function (§8.12), taking threejsonvalues and answeringjson. An absent row is json’snull, not SQL’sNULL, so a strict function is still called.- An object is the row to write (an upsert),
nulldeletes 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:
22023for another word, and42883for 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 querykeeps a shape (keys00 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.
- It marks the table of the same name, if it is here, as a shape’s
(
-
SYNC DROP SHAPE nameforgets 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,afterandbeforeasjson; - 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, head00 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_outboxshows it:seq,table_name,op,key,after,before,clock. - the table,
-
SYNC REQUEST [WAIT ms]answers one row with onejsonvalue: the device’s id, its last acknowledgedseq, its clock, its shapes with their positions, and the outbox’s first 1,000 writes.waitgoes only when there are none. Before anySYNC SHAPEit is55000. -
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.- 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. - 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). - Each answered write’s row is set to the server’s (
null: deleted). - 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).
- Each answered write leaves the outbox. A refused one goes into
-
nc_catalog.sync_shapesshows 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.