0019. Sync v2: authoritative sequencer with a compact structural index
Status: Accepted (2026-11-27). Supersedes 0005.
Context
0005 had the server hold every open page document in memory to validate ops. Rejected: server memory would grow with document size (a 682K-node page is ~80 MB as a full doc) and the server would fall over with many users. New requirements:
- 100k+ concurrent connections per instance on modest hardware (ADR 0020).
- Server memory grows with connections plus a small amount per active room, not with document properties.
- The server is the authority: it validates every op itself, and rejected ops get an explicit error so the sender rolls back. Invalid ops never reach the journal or other clients.
- One op pipeline for WebSocket and HTTP (ADR 0022).
Decision
Pipeline (same for WS and HTTP batches): authenticate (signed token) -> authorize (role/scope from token) -> zero-copy decode + stateless validation (gateway) -> structural validation, sequencing, journal group commit (room owner) -> ACK with per-op verdicts to the author -> BROADCAST of accepted ops, encoded once, to everyone else. Broadcast and ACK both happen after the journal commit, so no client ever sees an op the server could lose.
Stateless checks (gateway, every op, ScanBatch in shared/doc-api.ts): framing, op kind, varint bounds, prop id range, value type vs PROP_INFO, finite numbers and min/max, enum ranges, string/blob/key byte sizes, UTF-8, key syntax, ops per batch, CREATE id ownership (clientOf(id) === connection clientId), no writes to ROOT, rate limits, role/scope. Zero-copy over the received bytes with preallocated typed-array scratch; target < 300 ns per simple op.
Structural checks (room owner, StructIndex): node exists, id unique, parent exists and is a container, no reparent cycle, prop applicable to the node’s kind, no edits to deleted nodes, nodes-per-page limit. Uses a per-room structural index, no properties:
| Column |
Type |
Bytes/node |
| id (sorted base array; position = slot) |
Float64 |
8 |
| parent slot |
Int32 |
4 |
| kind |
Uint8 |
1 |
| flags (deleted, …) |
Uint8 |
1 |
| total |
|
14 |
- Lookup: binary search on the sorted ids (~20 steps for 1M nodes) + a small delta hash for nodes created since load (~30 B each until the next merge, merged into the base when it exceeds max(64K, 10%) entries, O(n) off the critical path).
- Delete marks only the deleted root; “exists” walks ancestors (O(depth)), so deletes are O(1) and need no child lists. Re-creating a deleted id (undo) allocates a fresh slot, so stale descendants stay dead.
- Loaded lazily on the first op batch (viewer-only rooms never load it) from the snapshot’s dedicated structure section (ids already sorted, parents as slots; a memcpy, never rebuilt from properties) plus a structural replay of the journal tail. Dropped when the room has had no ops for 10 minutes or no subscribers; per-room cap 128 MiB (above
MAX_NODES_PER_PAGE); process budget 4 GiB with LRU by last op. When the budget is full of active rooms, new loads answer busy (clients keep their ops pending and retry).
- Cost: a typical page (8K nodes) is 112 KB; the 682K-node website page is 9.5 MB; the 8M-node maximum is 112 MB. A full doc (~110 B/node including strings) would be ~8x larger.
Clients (local = canonical + pending):
- Property writes: pending keys + shadow values (as in 0005). Remote writes to a pending key update only the shadow; on ACK the key clears; a rejected write restores the shadow.
- Structural pending ops (DELETE, PARENT_INDEX): when a remote batch containing structural ops arrives while some are pending, the client reverts its pending structural ops (applying their inverses), applies the remote batch, then re-applies them with the same validation rules the server uses. An op that now fails is one the server will reject; it is dropped at once and the ACK confirms it. Pending CREATEs need no rebase (shown in sync.md).
- The client compares the ACK’s verdicts with its own; any mismatch (a bug) triggers a page resync from the snapshot. The server is the authority.
Defence in depth: replicas apply sequenced batches with origin: 'sequenced', where any still-invalid op is a deterministic no-op. Canonical snapshots (pre-order, props sorted) make replicas byte-comparable in tests.
Dedupe and ids: batches carry clientSeq; the owner keeps the last committed clientSeq per connected client and, on resume, reads max(client_seq) for that client from the journal (one indexed query, only for clients that report pending batches). clientIds are allocated in blocks of 1,024 per file (one DB write per block) and bound to the user by a signed clientId grant (24 h), so a reconnecting client keeps its id space without server memory or a DB read.
Rules versioning: DOC_RULES_VERSION is sent in hello and stored per journal row. Any change that could make two builds disagree on validity bumps it. Mismatched clients reload. Deploys that bump it compact every page with a non-empty tail before switching.
Why a malicious or buggy client cannot break convergence or corrupt state
- It cannot create ids in someone else’s space (ownership check), so it cannot pre-empt another client’s creates.
- Everything it sends is validated statelessly and structurally before sequencing; rejected ops are never journaled or broadcast.
- Replicas apply only server-accepted batches, in server order, with deterministic total functions (no exceptions, no clocks, no randomness, f32 values stored bit-exact).
- It can only damage documents it has editor rights on (authorization), bounded by rate and size limits; snapshots keep version history for recovery.
- It cannot rewrite history: seq is server-assigned, journal rows are immutable, resends dedupe by (clientId, clientSeq).
Alternatives
- Full doc in the server (0005): ~110 B/node and property churn on every op. Rejected by the user.
- Relay only, with deterministic apply rules on clients: O(1) per-room state and convergent, but the server cannot tell a sender its op was rejected, and invalid ops would sit in the journal forever. Rejected because the server must be the authority.
- Structural index with child lists (22 B/node): O(subtree) deletes for no validation benefit.
- Hash map id -> slot (~24 B/node): simpler but 70% bigger than sorted base + delta.
- Yjs/Automerge on the server: far heavier (ADR 0003).
Consequences
- Room owners need the structure section next to each snapshot (compactor writes both).
- The realtime tier depends on packages/doc only for
ScanBatch and StructIndex, which share their rule tables with DocCore local validation, so client and server rules come from one source.
- Capacity numbers: ADR 0020.