Sync / foldkit-sync

When things go wrong

Each case is designed, not incidental. The ones that change how you build the application come first.

  • The network is gone. Edits keep applying and keep being saved. pending grows; the loop retries. Nothing to handle.
  • The server rejects an edit. Dropped from pending, the rest replayed, the Model re-installed. Explain it from status.rejected.
  • The page unloads before the persist finishes. The browser asks first; leaving anyway loses the edits not yet stored.
  • The persist fails. The edit is reverted and onPersistenceFailure runs. The user has to redo it.
  • Local storage was evicted. The replica starts at cursor 0 and catches up from the server, but edits that lived only in the outbox are gone. The outbox is user data, not a cache.
  • Two tabs share one store. Compare-and-swap fails the stale writer with StorageError. Sync.tabStorage gives each tab its own; a store named by hand with Sync.indexedDb(name) must be one tab's.
  • The replica is far behind. The server may answer in pages (more), and synchronize asks again at once until caught up. If the server compacted the history it needs, it sends a checkpoint instead: a snapshot and cursor the replica adopts as its base before replaying its pending edits. A checkpoint behind the replica's cursor is refused (CheckpointRegressionError), never applied backwards.
  • The server lost its history. A server names its history with an epoch; a replica that hears a new one rebuilds its committed state from that answer and resends its outbox. Everything the old server committed is gone on every replica. A replica that never heard an epoch cannot tell, and fails every exchange until its storage is cleared.
  • Stored state is from another version. Opening fails with UnsupportedReplicaVersionError naming both versions; the bytes are left for a deliberate migration or reset. That versions Sync's own envelope; a durable Message's versions are the document's history (change a durable Message), and snapshot migrations stay yours.
  • An operation from another build of the application. An older version no step reads lands in status.refused, kept until dismissed; a newer one refuses to open the replica, or fails the exchange, with UnsupportedMessageVersionError, and nothing is removed. Moving an operation to refused is the one write an open makes, under the revision it read: if another tab wrote the store meanwhile, the open fails with StorageError, and opening again reads both.
  • The server answers nonsense. Malformed exchanges, gaps in the committed order, acknowledgements or rejections for operations the replica never sent: each fails the exchange rather than touch local work.

Diagnostics

What Sync keeps going past it reports as a typed diagnostic through Diagnostics.Reporter (foldkit-surface's channel), which by default is Effect's log: the console in a browser, wrangler tail on a Worker.

_taglevelWhen
ExchangeFailedwarningAn exchange failed; recorded in status.lastError and retried on backoff.
ExchangeDefecterrorSync.transport.serve threw an unexpected error; client receives an incident id.
HistoryRebuiltwarningServer returned a new epoch, rebuilding committed state while keeping the outbox.
HostDefecterrorA document host failed at a stage (cause stays server-side; client sees incident).
ListenerFailederrorA user callback threw (presence subscriber, socket listener, or journalChanges).

HostDefect reports the failing stage: Upgrade, Resolve, Journal, and Exchange return HTTP 500 with the incident id; Revalidate closes the socket with 1011; Notice skips sending a commit notice; and Changes stops the commit stream. For ListenerFailed, remaining listeners continue running.

A replica reports to the reporter in the Effect context it runs in: Layer.succeed(Diagnostics.Reporter, report) in the runtime's resources. A host takes one with the upgrade request beside it, used for everything that upgrade runs:

ts
export class SyncHost extends defineDocumentHost(DurableObject, {
  sync: TodoSync,
  openJournal: (_ctx, env) => openTodosJournal(env.DB),
  resolvePrincipal: request => Effect.succeed(request.headers.get('x-actor') ?? 'anon'),
  diagnostics: (diagnostic, request) =>
    Effect.logError(`${request.url}: ${diagnostic.message}`),
}) {}

documentHost takes the same diagnostics, and serveJournal a diagnostics reporter of its own. In a test, Diagnostics.collect() gives a reporter and the array it fills.