Sync / foldkit-durable

What append guarantees

For each new operation, append executes these steps inside one SQLite transaction:

  1. Decode the operation against the Operation codec.
  2. Run validate and authorize against the current snapshot.
  3. Assign the next gap-free Sequence.
  4. Run stamp (if configured), reduce, and judge.
  5. Persist the operation, snapshot, and updated cursor, returning Committed.

For a retransmitted operation, opId controls the outcome:

  • Same opId, same payload and actor: answered from history without applying reduce again.
  • Same opId, different payload or actor: rejected with IdentityConflictError.

Payloads are canonicalized before hashing so reordered JSON keys match. This guarantee holds for as long as the identity row exists; see Retention.

When using a function-pair codec, you can provide compared(input) to normalize older payload versions into the form they were originally written in, ensuring retries across schema upgrades remain recognized while storing the upgraded payload (Sync's journalContract() supplies this automatically).

A commit stamp writes commit-time facts such as the assigned sequence into the operation after validate and authorize but before reduce:

ts
import { type JournalOptions } from 'foldkit-durable'

type Edit = Operation & { readonly at?: number }
const stamping: Pick<JournalOptions<Edit, Snapshot, Principal>, 'stamp'> = {
  stamp: (operation, { sequence }) => ({ ...operation, at: sequence }),
}

Every reader (reduce, read, load, and recover) sees the stamped operation, while retry hashing uses the pre-stamp operation as sent (resending the stamped form under the same opId fails with IdentityConflictError, and changing opId inside stamp fails with InvalidOperationError). See Editing server data through a journal for using commit sequences to reconcile read models.

Interpret each journal result carefully:

You observeIt provesWhat remains external
append returned CommittedThe journal accepted and persisted itClients may not have synced it yet
load returned a snapshot and cursorThe snapshot reflects that committed prefixUncommitted client edits live in outboxes
An effect result is recordedThe journal can reuse that outcomeA crash before recording leaves it uncertain

append returns AlreadyCommitted instead of Committed when the operation was committed earlier and compaction has already dropped its payload. appendAll commits a batch atomically in one SQLite transaction.

On large documents, writing a snapshot on every commit can be costly; pass snapshotEvery: n to write snapshots every n commits and replay the short tail on load. The journal caches the most recent 256 document states in memory (validated against the stored cursor so external writes are noticed); treat values returned by load and passed to reduce as read-only.