The same identity was hex TEXT in most tables (NodePubkey's ToSql, or hex::encode by hand) and a BLOB in peer_nodes, peer_health and revoked_certs, so the two could not be joined. NodePubkey's ToSql/FromSql now own one encoding, the raw bytes; every node-key column is BLOB; and the stores bind through NodePubkey instead of as_bytes() or hex::encode. PeerNode and RevokedNode keep their [u8; 32] fields and wrap at the bind. Also brings document-sync.md's sync_sessions excerpt and lifecycle up to date with the previous sync_staging commit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
29 KiB
Document Sync Protocol
Bidirectional, chunked protocol over iroh for nodes to exchange document state. Each sync session is initiated by one node (the requester) but flows in both directions: the requester first pulls from the responder, then the responder pulls back from the requester on the same QUIC connection. Designed for incremental sync over arbitrarily large document sets, with early progress estimates and resumability after connection failure.
Serialization format
Choice: MessagePack via rmp-serde
MessagePack is a compact binary format with a well-maintained Rust crate
(rmp-serde) that acts as a drop-in serde backend — no schema files, no code
generation. Every document struct already derives serde::{Serialize, Deserialize}, so the implementation cost is almost zero.
Forward compatibility works through standard serde mechanisms: add
#[serde(default)] to new fields and they deserialize cleanly from older
messages. Unknown fields are ignored by default.
Why not Cap'n Proto: Schema files + code generation add friction and a build step. The zero-copy deserialization advantage is irrelevant when messages are small (document metadata, not blob payloads). Cap'n Proto would be the right call if we needed to inspect fields in large binary blobs without deserializing them fully.
Why not Protobuf: User preference; also Protobuf's map/oneof/any types are clunky for Rust sum types.
Transport
Uses iroh's existing Endpoint — already set up with the N0 preset, NAT
traversal, and pkarr-based peer discovery. Nodes find each other via the gossip
ensemble discovery that is already implemented.
ALPN: /syn/doc-sync/…, the live value being p2p::doc_sync::DOC_SYNC_ALPN.
The version suffix in the ALPN string provides protocol-level version negotiation for the message shape — a mismatch here means the two peers can't speak to each other at all, so every node has to be on the same number. Which is why no document names that number, here or anywhere else: it moves whenever the shape does, and prose that pins it is wrong from the next bump onward. Read it off the constant.
Successive bumps have added the reverse-pull phase (see Session flow),
document-tombstone propagation (see "Document tombstones (Purge)" below), the
sync_protocol_version field on SyncHeader (see below), and a
DocumentChunk.documents carrying independently-encoded per-record blobs in
place of one array (see below and
docs/adr/0020-sync-protocol-schema-version.md).
Enum variants (DocumentType, PropertyKind, ArtifactKind, EdgeKind) are
versioned separately, via SYNC_PROTOCOL_VERSION — see
docs/adr/0020-sync-protocol-schema-version.md. Peers don't need to match on
this number to sync: SyncHeader.sync_protocol_version is logged when it
differs but never blocks anything. What actually protects a peer is that each
document in a DocumentChunk decodes independently — one record carrying a
variant the receiver doesn't know is dropped and reported, not treated as a
reason to fail the whole chunk (or refuse the sync outright).
Stream model: Each sync session uses two bidirectional QUIC streams on
the same connection. Stream 0 is opened by the requester for the pull phase;
stream 1 is opened by the responder for the reverse-pull phase. Messages on
each stream are length-prefixed (4-byte big-endian u32 giving the byte
length of the MessagePack payload).
Sync model
A sync session is initiated by one node (the requester) and is always bidirectional: both nodes end up with each other's documents. The session uses a single QUIC connection with two streams so both directions share the same NAT hole.
Typical initiators:
- The node the user is currently using (user clicks "sync")
- An always-on cloud node running a recurring background job
Neither node pushes updates spontaneously. Gossip handles liveness detection; this protocol handles data transfer.
Incremental sync and resumability
A sync of "everything since 3 months ago" may involve thousands of documents and take minutes. The protocol is designed to handle this gracefully:
-
Early estimate. The responder sends a
SyncHeaderbefore streaming any documents. The header contains the total matching document count and estimated content sizes in bytes. The requester can display a progress bar and ETA to the user immediately, before a single document has been received. -
Chunked streaming. Documents are sent in batches (
DocumentChunkmessages). Each chunk includes an opaquecursorthat marks the responder's position in the result set. -
Resumable via cursor. If the connection drops mid-sync, the requester can reconnect to the same peer (or any peer in the ensemble) and send a new
SyncRequestwithresume_cursorset to the last cursor it successfully processed. The responder picks up from that point, re-running the query from the cursor position. -
Cursor stability. The cursor encodes
(modified_at_secs: i64, doc_id: [u8; 16]). Results are ordered by(modified_at ASC, id ASC). The two-field key ensures stable pagination even when multiple documents share the samemodified_attimestamp. Documents added to the responder mid-sync (modified_at after the request'ssince) are excluded from the in-progress sync; they'll appear in the next sync. -
Configurable chunk size. The requester specifies
max_chunk_docsin theSyncRequest. A reasonable default is 100 documents per chunk.
Content size tracking
To give accurate transfer estimates, each DocumentRecord in the response
includes two size fields, kept separate because blobs and artifacts will be
fetched via distinct future protocols:
total_blob_bytes: u64— sum ofsize_bytesacross all of the document'sBlobRefs. These are the large immutable files (PDFs, audio, images).total_artifact_bytes: u64— sum ofsize_bytesacross all of the document'sArtifactRefs. These are the SQLite-stored engagement/content values (note bodies, listen progress, reading state).
The SyncHeader carries the sum of each across all matching documents, giving
the requester an ETA estimate for the full data transfer that would follow if
the user requested it.
BlobRef change needed: Add size_bytes: u64. The importer always knows
the file size at import time; synced blob refs carry the size reported by the
originating node. This avoids having to open the blob store to compute estimates
during sync.
ArtifactRef (new type): See ArtifactRefRecord in Messages below. Size
for artifacts is the byte length of the serialized ArtifactValue as stored in
SQLite.
Vault identity
Every document, property, artifact, and blob reference carries a vault_id.
The default vault's id is a constant — the nil UUID (vault::DEFAULT_VAULT_ID)
— so every node agrees on it without coordinating. Its key is what is derived,
by HKDF from the ensemble secret (vault::derive_ensemble_vault_key, and
docs/data-model.md), which is why every member arrives at the same key without
it ever being transported.
Vaults other than the default (e.g. passphrase-protected vaults) are exchanged between nodes via a separate vault-syncing protocol that is future work. For documents in non-default vaults, this protocol still syncs the structural metadata (document rows, property records, blob/artifact refs).
What a receiver without the vault key can and cannot read, today: it cannot
open blob bytes, which are sealed under a key derived from the vault key
(ADR 0028). It can read everything else — PropertyRecord.value is
MessagePack plaintext on the wire and plaintext in SQLite at both ends, and
artifact values are the same. At-rest encryption of those columns is designed
and unbuilt (docs/data-model.md §Security / Vault Model), so until it lands
the vault boundary holds for blob content and nothing else. See
docs/vault-pddb-research.md §2 for the rest of the gap.
What gets synced
In scope:
Documentheader rows (id, type, parent_id, vault_id, created_at, modified_at, origin_node)Propertyrecords (kind, value, modified_at, origin_node) — included inline in eachDocumentRecord; synced eagerly alongside documentsArtifactRefrecords (role, size, modified_at, origin_node — not the artifact value itself)BlobRefrecords (hash references, role, size — not the blob bytes)
Explicitly out of scope:
- Artifact values — fetching the actual SQLite-stored content is a future protocol
- Blob payloads — blob byte transfer is a separate future protocol
- Vault key exchange — vaults other than the default require a future vault-sync protocol
- Clock skew detection — noted as a future TODO; for now we assume nodes have NTP and clocks are within a second or two of each other
Conflict resolution
Properties are last-writer-wins per (document_id, kind) — the row with
the later modified_at wins. The two property write paths are:
DocumentStore::write_property— for local writes (user action, import, agent update). Atomically upserts the property and bumpsdocuments.modified_attoUtc::now()in a single transaction. This is the invariant that drives correct incremental sync: thesincecursor is keyed ondocuments.modified_at, so a property change that doesn't bump it would be invisible to peers on their next incremental sync.DocumentStore::sync_receive_property— for sync receives only. Same merge logic, but does NOT touchdocuments.modified_at. The document's timestamp is managed by the staging promotion step, which sets it from the sender'sDocumentRecord.modified_at.DocumentStore::sync_receive_set_elements— the receive path forSetUnionproperties, which do not arrive as values at all. Merges each element's add and removal independently, keeping the newer stamp on each side, then rebuilds the property row from the result (ADR 0043).DocumentStore::apply_property_tombstone— the receive path for a property removed outright. Recorded even for a property this node never had: a peer's removal that isn't remembered is one the next sync undoes.
Artifacts use the merge strategy declared for the artifact's Role
(LastWriteWins, SetUnion, or eventually Crdt). For this sync protocol, artifact
value transfer is future work, so no merge decisions are made here — the
ArtifactRef is recorded for later fetching.
Receive-side staging
Received documents are buffered in a staging area before being promoted into the live tables. This two-phase approach solves three problems with direct writes:
-
FK violations — a child document can arrive before its parent (because the sender orders chunks by
modified_at, not by tree depth). Staging lets the receiver collect the entire batch and topologically sort it before writing anything, so parents always precede children. -
Partial-apply on interrupt — a dropped connection no longer leaves the live store in a half-applied state. The staging rows remain intact; on reconnect the receiver can resume into the same session without re-staging documents it already received.
-
Concurrent session isolation — multiple inbound syncs (from different peers simultaneously) each get their own UUID session and don't interfere with each other or with the live tables.
Session tables
Two SQLite tables live in the same database file as the document store:
sync_sessions {
session_id TEXT PRIMARY KEY, -- UUID, assigned by the receiver
peer_node BLOB NOT NULL, -- sender NodePubkey, 32 bytes
started_at INTEGER NOT NULL, -- microseconds; read by the abandoned-session prune
last_cursor BLOB -- last committed chunk cursor (for resumption)
}
sync_staging {
session_id TEXT NOT NULL REFERENCES sync_sessions(session_id) ON DELETE CASCADE,
doc_id TEXT NOT NULL, -- UUID string
record_blob BLOB NOT NULL, -- rmp_serde-encoded DocumentRecord
PRIMARY KEY (session_id, doc_id)
}
DocumentRecord already embeds Vec<PropertyRecord> inline, so staging a
document record stages its properties with it at no extra cost.
Session lifecycle
-
Connection open — receiver creates a
sync_sessionrow, first pruning any session started more than a day ago (an abandoned one). If theSyncRequestincludes aresume_cursormatching an existing session for the same peer, that session is reused instead of creating a new one. A row exists only while its pull is open. -
Each chunk received (
stage_chunk) — for eachDocumentRecordin the chunk, serialize it as MessagePack andINSERT OR REPLACEintosync_staging. Then updatesync_sessions.last_cursorto the chunk's cursor. Both writes happen in the same connection; if the process crashes here, the staging rows and cursor are intact. -
is_final=true— trigger promotion (promote_session): a. Load all stagedDocumentRecordblobs for this session. b. Deserialize and topologically sort them (parents before children). c. For each record:add_document(INSERT OR IGNORE), thensync_receive_propertyfor each property, thenadd_blob_reffor each blob ref, thenrecord_artifact_stubfor each artifact ref, thenmark_presentfor the sender and local node. d. Delete the session row, and with it (by cascade) its staging rows. -
Connection drop before
is_final— the session row stays. On reconnect, the requester sendsresume_cursor = last_cursor, the receiver finds the matching session, and new chunks are staged into it.
Resumption across peers
The resume_cursor identifies a position in the sender's dataset, not a
session on the receiver. If the original peer is unavailable, the requester can
send the same resume_cursor to any other ensemble peer that has the same data.
The receiver will create a new session (no matching last_cursor on file) and
stage from that cursor position onward.
Messages
All types use serde with MessagePack encoding, str-keyed maps (field names included). Str-keyed encoding is slightly larger than positional but easier to debug and forward-compatible.
/// Sent by the requester to start (or resume) a sync session.
SyncRequest {
/// If non-empty, only return documents of these types.
doc_types: Vec<DocumentType>,
/// If Some, only return documents whose `modified_at` >= this (unix epoch microseconds, UTC).
since: Option<i64>,
/// If Some, resume from this cursor (returned by a previous SyncHeader or DocumentChunk).
resume_cursor: Option<Vec<u8>>,
/// Maximum number of documents per DocumentChunk. Default: 100.
max_chunk_docs: u32,
}
/// First message sent by the responder. Arrives before any DocumentChunk.
SyncHeader {
/// Estimated total number of documents matching the filter (from a COUNT query).
/// This is an estimate; the actual count may differ if documents are added or
/// removed during the sync.
total_documents: u32,
/// Sum of BlobRef.size_bytes for all matching documents.
total_blob_bytes: u64,
/// Sum of ArtifactRef.size_bytes for all matching documents.
total_artifact_bytes: u64,
/// The sender's SYNC_PROTOCOL_VERSION — logged by the receiver when it
/// differs, purely diagnostic. See docs/adr/0020-sync-protocol-schema-version.md.
sync_protocol_version: u32,
}
/// One batch of documents. The responder sends these sequentially after SyncHeader.
/// On the wire, `documents` is actually a list of independently-encoded
/// per-record MessagePack blobs (see the ADR) so a record the receiver can't
/// decode is dropped on its own, not lost along with the rest of the chunk —
/// this logical shape is what every caller in doc_sync.rs actually works with.
DocumentChunk {
documents: Vec<DocumentRecord>,
/// The cursor representing the position after the last document in this chunk.
/// Clients should persist this after processing each chunk for resumability.
cursor: Vec<u8>,
/// True on the final chunk.
is_final: bool,
}
DocumentRecord {
id: [u8; 16], // UUID bytes
doc_type: DocumentType,
parent_id: Option<[u8; 16]>,
vault_id: [u8; 16], // UUID bytes; identical on all nodes for default vault
created_at: i64, // unix epoch microseconds, UTC — every stamp on the
modified_at: i64, // wire is, the same number the sender stores
origin_node: [u8; 32], // Ed25519 public key bytes
/// Sum of BlobRef.size_bytes for this document. 0 if no blobs.
total_blob_bytes: u64,
/// Sum of ArtifactRef.size_bytes for this document. 0 if no artifacts.
total_artifact_bytes: u64,
properties: Vec<PropertyRecord>,
artifact_refs: Vec<ArtifactRefRecord>,
blob_refs: Vec<BlobRefRecord>,
/// Properties removed outright, and the per-element state of this
/// document's SetUnion properties. Both hang off the document rather than
/// off a PropertyRecord, for the same reason edge tombstones do: the row
/// they refer to may be gone. See ADR 0043.
property_tombstones: Vec<PropertyTombstoneRecord>,
property_set_elements: Vec<SetElementRecord>,
}
/// Carries every property EXCEPT the SetUnion ones, which travel as
/// SetElementRecords instead (ADR 0043). Sending a SetUnion row as a value too
/// would have the receiver read every element as added at the row's
/// modified_at, and a removal arriving alongside it would lose.
PropertyRecord {
kind: PropertyKind,
/// MessagePack-encoded PropertyValue.
value: Vec<u8>,
modified_at: i64,
origin_node: [u8; 32],
}
/// Announces that a whole property row — one (document_id, kind) pair — was
/// removed, so the removal propagates and an equal-or-older copy does not
/// resurrect from this node.
PropertyTombstoneRecord {
kind: PropertyKind,
deleted_at: i64,
origin_node: [u8; 32],
}
/// One element of a SetUnion property. Removed elements are included — a
/// removed element *is* the removal evidence, and omitting it is what let a
/// deleted tag come back. `removed_at`/`removed_by` are absent while the
/// element has never been removed on any node.
SetElementRecord {
kind: PropertyKind,
element: String,
added_at: i64,
added_by: [u8; 32],
removed_at: Option<i64>,
removed_by: Option<[u8; 32]>,
}
/// Declares that an Artifact with this role exists on the sender, without
/// transferring its value. The receiver records this ref for later fetching.
ArtifactRefRecord {
id: [u8; 16], // UUID — stable identity across syncs
role: Role, // determines merge strategy and value type
/// Byte length of the serialized ArtifactValue as stored in SQLite.
/// Used for transfer size estimation; 0 if unknown.
size_bytes: u64,
modified_at: i64,
origin_node: [u8; 32],
}
BlobRefRecord {
stored_hash: [u8; 32], // BLAKE3 of stored (possibly encrypted) content
plaintext_hash: [u8; 32], // BLAKE3 of plaintext content
role: Role,
vault_id: [u8; 16],
size_bytes: u64,
}
/// Announces that a document was purged, so the deletion propagates and a
/// stale copy of it does not resurrect from this node. See "Document
/// tombstones (Purge)" below.
DocumentTombstoneRecord {
id: [u8; 16],
deleted_at: i64,
origin_node: [u8; 32],
}
/// All of the sender's document tombstones matching the request's `since`
/// filter, sent in one shot right after SyncHeader — unpaginated, since
/// tombstone volume is expected to be small for a personal-scale store.
DocumentTombstoneBatch {
tombstones: Vec<DocumentTombstoneRecord>,
}
Session flow
Requester (A) Responder (B)
| |
| ── stream 0: A pulls from B ───────── |
|-- SyncRequest ──────────────────────> | (filter + optional resume cursor)
| | [COUNT query, build estimates]
| <────────────────────── SyncHeader ---| (total count + blob/artifact bytes)
| <──────────── DocumentTombstoneBatch --| (all purged ids since `since`) → A applies them
| | [page 1 query]
| <──────────────── DocumentChunk(1) ---| (documents + cursor, is_final=false)
| <──────────────── DocumentChunk(2) ---|
| ... |
| <──────────────── DocumentChunk(N) ---| (is_final=true) → A promotes session
| |
| ── stream 1: B pulls from A ───────── |
| <────────────────── SyncRequest ---- | (B opens stream 1, requests A's docs)
|-- SyncHeader ───────────────────────> |
|-- DocumentTombstoneBatch ───────────> | (B applies them)
|-- DocumentChunk(1) ─────────────────> |
| ... |
|-- DocumentChunk(M) ─────────────────> | (is_final=true) → B promotes session
| |
[A drops connection]
Each side streams chunks without waiting for explicit acks from the other. QUIC flow control prevents either node from overrunning the other's receive buffer.
Resumption: If the connection drops mid-sync, the receiver's staging session
remains with its last_cursor intact. On reconnect, the requester sends a new
SyncRequest with resume_cursor set to the last cursor it successfully
processed. If the receiver finds a matching session for that peer and cursor,
it resumes staging into it.
The reverse-pull phase (stream 1) always starts from the beginning on reconnect.
Receiver-side behavior
When a DocumentChunk arrives, the receiver calls stage_chunk:
- Serialize each
DocumentRecordas MessagePack and write tosync_staging. - Update
sync_sessions.last_cursorto the chunk cursor.
When the chunk with is_final=true arrives, the receiver calls
promote_session:
- Load all staged
DocumentRecordblobs for this session. - Topological sort — order records so every document appears after its parent within the batch. Records whose parent is not in the batch (already in the live DB, or a root document) are treated as roots and emitted first.
- Apply each record in sorted order:
- Resurrection guard: skip the record entirely if its id (or its
parent_id) has adocument_tombstonesrow — see "Document tombstones (Purge)" below. add_document(INSERT OR IGNORE). Parents are guaranteed to exist before children, so no FK violation can occur.sync_receive_propertyfor eachPropertyRecord. Keeps whichever row has the latermodified_at; does not touchdocuments.modified_at.add_blob_reffor eachBlobRefRecord(if the role isn't already present).record_artifact_stubfor eachArtifactRefRecord.mark_present(doc_id, sender_pubkey)andmark_present(doc_id, local_node).
- Resurrection guard: skip the record entirely if its id (or its
- Mark session complete and delete the staging rows.
Document tombstones (Purge)
Purging a document (see "Removing a Document vs. Purging" in
docs/data-model.md) deletes its row locally and records a
document_tombstones row (id, deleted_at, origin_node) so the deletion
sticks — this protocol is the durable propagation path for peers who were
offline when the purge's gossip broadcast (p2p::gossip::PurgeIntent)
happened, or missed it entirely. Whichever path arrives first wins; the other
is a no-op.
Unlike artifact tombstones, which ride along inside the owning
DocumentRecord (see TombstoneRecord), a document tombstone has no living
document to be a member of, so it can't be embedded that way. Instead
build_document_tombstone_batch sends every local tombstone matching the
request's since filter as one DocumentTombstoneBatch, immediately after
SyncHeader and before any DocumentChunk — in both pull directions, since
both sides call the same serve_pull_response.
The receiver applies the batch (apply_document_tombstone_batch) before
processing chunks, via DocumentStore::apply_tombstone, which:
- Recursively purges any locally known children of the tombstoned id, not just the ids the sender happened to list. This self-heals a divergent tree view — a receiver with children the sender never learned about still ends up with them purged too.
- Is idempotent: re-applying a tombstone for an already-purged id just keeps
the newest
deleted_at.
Applying tombstones before chunks matters: the resurrection guard in
apply_records (step 3 above) checks document_tombstones before inserting,
so a same-session DocumentChunk that (from a stale sender's point of view)
still contains the purged document is correctly dropped instead of
resurrecting it.
Sender authentication
The sender's NodePubkey is known from Connection::remote_id(), mapped
through the ensemble peer map to a NodePubkey. iroh authenticates the
connection using the node's Ed25519 keypair; no additional signature verification
is needed at the protocol layer.
Filtering
Filters are ANDed together:
doc_types: skip documents whosedoc_typeis not in the list (empty = no filter)since: skip documents whosemodified_at < since(None = no filter)resume_cursor: skip documents at or before the cursor position
The since filter uses modified_at (not created_at) so that property updates
to old documents are visible to an incremental sync. A node syncing "last hour"
should see property updates written in the last hour even if the document was
created months ago.
This relies on the invariant that documents.modified_at is always bumped
whenever a property is locally written (enforced by write_property). A
document whose property was updated but whose modified_at was not bumped would
be invisible to peers on their next incremental sync.
Integration with existing code
Implemented in lib/src/p2p/doc_sync.rs:
DocSyncHandler— server-side protocol handler, registered with the irohRouteralongsidePingHandlersync_from_peer(endpoint, peer, request, store, local_node, progress)— client-side entry point, a plain future that reportsSyncProgressthrough theprogresscallback (which can also cancel) and returns aSyncOutcomeSyncStagingStore— staging table management (lib/src/stores/sync_staging.rs)
The existing DocumentStore, NodeDocumentStore, ArtifactStore, and
BlobStore are all thread-safe and called from the async handler context.
Future work
- Artifact value transfer — a protocol for fetching the SQLite-stored
ArtifactValuefor a known artifact ref, with merge strategy applied on receipt - Blob transfer protocol — a separate ALPN for fetching blob payloads by hash
- UI for background sync jobs — progress bar + ETA display, cancel/retry controls
- Background auto-sync — gossip-triggered sync so nodes don't have to wait for a manual button press
- Redundant-send elimination — Phase 2 currently sends all of A's documents
to B, including any that B already sent to A in Phase 1.
apply_recordsskips them correctly at promotion time, but they waste bandwidth. TheNodeDocumentStorealready records which node has which documents (populated during Phase 1), soserve_pull_responsecould filter its output to exclude documents already marked present on the peer before starting Phase 2. - Clock skew detection — detect if remote
modified_attimestamps are implausibly far in the future - Non-default vault key exchange — vault-syncing protocol to distribute keys for passphrase or shared-key vaults so that encrypted content can be decrypted on all member nodes
- Staging table promotion as a single transaction — currently each document
in a promotion batch is applied via individual connection-per-call store methods.
Wrapping the entire promotion in one SQLite transaction would make it atomic and
faster; this requires threading a
Transactionthrough the store layer. - sync_receive_property and document.modified_at — if a peer sends a property
with
modified_atnewer than the document's currentmodified_at(because the property was updated after the document was last touched), the localdocuments.modified_atwill not reflect that property. A future improvement is to setdocuments.modified_at = max(existing, max_property_modified_at)at promotion time.