Artifact 5fd16625269b53ed7a96cb8653346c7c795c0ebb0354d078d773eaf00c2ef553:
- File docs/archive/2026-11-s0/durability-contracts.md — part of check-in [d66dc3f8af] at 2026-11-21 11:05:58 on branch docs-reorg — docs: short README; manual, reference, dev, design and archive under docs/; AGENTS.md; docs.sh checks docs against code; changelog.inc built at build time (user: dmestas, size: 20803) [annotate] [blame] [check-ins using] [more...]
Durability contracts: pi-durable and chord SQLite
Pinned reference reference/pi @ cead615b48b80d1c61eecab2f0b576d16eeaf4c5. Scope:
packages/durable + packages/chord SQLite/store. First-pass contract map for a future
native C harness, not a port plan. Tests were read, never executed; evidence is marked
doc / impl / test-read per contract.
Core rule (quoted): "A Session atomically commits immutable entries, full task records, and Chord-tracked documents. Only committed state is observable. A commit marked deferred may be observed before it is stored." spec
D01 — Admission is a commit, not a queue insert
Contract: input/write/continue admits inside one atomic commit with the host's writes; busy/idle reads committed pi.live, a rejection throws before any write, submit(tx, draft) must precede the first table write (else ReadAfterWrite), and the admission is provisional until stored.
Evidence: doc+impl+test-read.
Citations: spec §6, submit, guard, test.
C: one transaction; enforce write order with a "tables written" flag; reject pre-write.
D02 — Restart dedup by request ID
Contract: a submission with requestId returns the existing submission (same id) and writes nothing; a reused ID with a different type errors; dedup is keyed per (conversation, requestId) and persisted. Internally, admission projects an existing unanswered record to admission status done; this does not change its stored settlement into an answered result. The dedup branch checks type, not full payload equality.
Evidence: doc+impl+test-read.
Citations: README, dedup, index, test.
C: indexed (conversation_id, request_id) lookup with projected status, no re-admission.
D03 — Commit before visibility
Contract: ordinary commits publish after the storage call settles and their durability receipt is known, in line order, also when that call rejects after recording a receipt. A commit failing before durability publishes nothing. Once the Session has otherwise failed, later durable commits may remain unpublished and are recovered on reopen. Deferred documents are the explicit visibility exception (D21); publication/adoption failure can fail the Session without undoing stored data.
Evidence: doc+impl.
Citations: invariants 1–3,7, order, README, writer.
C: two-phase store-then-publish keyed by seq; publish even on post-commit rejection.
D04 — Batch atomicity, refusal, unknown outcomes
Contract: commit(batches, receive, ctx) stores batches in order, each atomic with its own seq, checked against prior batches; it stops at the first refused batch (earlier stay, that and later do not); receive is a synchronous non-throwing durability receipt; a lost connection or failed statement/COMMIT rejects as an unknown outcome that may have committed.
Evidence: doc+impl+test-read.
Citations: README, types, loop, checks, test.
C: three outcomes (stored / refused / unknown); recover unknown via reopen + requestId.
D05 — Generation retries with a durable backoff
Contract: a model request the host died during is a failed attempt — partial kept as an aborted entry, next attempt waits for settings.retry backoff, no retry left ends the run interrupted; a deferred response being fetched is polled again, not re-requested; a clean close is not a crash.
Evidence: doc+impl+test-read.
Citations: README, retry, interrupted, test.
C: attempt counter and backoff live in the checkpoint; distinguish crash from close.
D06 — Replay safety is per tool call, default unsafe
Contract: each tool call is a durable task whose intent commits before execute(); on crash it reruns only with replay: "safe", otherwise the model gets an interrupted error result with committed output; replay-safe calls cut off restartLimit times end with a restart_limit error result; omitted replay is unsafe.
Evidence: doc+impl+test-read.
Citations: README, spec §7.3, branch, test.
C: default "do not re-execute"; record the opt-in in the committed intent.
D07 — Task checkpoints: a phase reruns from its top
Contract: a task commits a checkpoint each step; there is no mid-phase sleep, so after restart a phase reruns from its start and anything needed later must be in the checkpoint; states are pending, running, waiting, sleeping, completing, terminal.
Evidence: doc+impl+test-read.
Citations: README, statuses, CHECK, test.
C: loop = reserve → run phase → commit state; phases must be re-entrant from the top.
D08 — Ownership tree and structured concurrency
Contract: every task has an immutable owner (conversation or task); abort flows down; owned work does not outlive its owner's finish — a finishing commit with live ordinary owned work stores completing, and terminal is written only after that work drains; background tasks are traversal boundaries.
Evidence: doc+impl.
Citations: spec §5.5, completing, README, terminate.
C: store an owner edge per task; recompute completing at open; terminal writes are conditional.
D09 — Cancel is a committed mark plus an abort protocol
Contract: abort commits an abortRequested mark → signals/joins the active run invocation → waits for ordinary owned work → starts a fresh abort invocation; a run invocation may not commit after its durable mark appears; the cascade is idempotent and marks are re-derived in a reconcile commit and at open.
Evidence: doc+impl+test-read.
Citations: spec §5.4, order, README, test.
C: durable mark first, signal second; refuse every post-mark runtime write.
D10 — Nested calls: keyed, journaled, abandoned safely
Contract: executeTool() runs a nested tool task owned by the caller, keyed by position or { key }, results returning to the caller not the transcript; a replay-safe caller rerunning in the same order gets prior nested calls back; a replay-unsafe caller never reruns and its unfinished nested calls plus everything they own are abandoned; depth is unbounded.
Evidence: doc+impl+test-read.
Citations: README, spec §7.3, abandon, test.
C: per-caller keyed call/result journal plus ownership traversal at open; use iterative traversal and explicit resource limits rather than unbounded C-stack recursion.
D11 — Signals: five delivery results, one wait per key
Contract: signal() returns delivered, duplicate, invalid, closed, or not_found; values live in the task record; a value arriving before the sleep is kept and wakes it at once; the wake consumes the key and a second sleep on it is rejected; nothing authenticates the sender.
Evidence: doc+impl+test-read.
Citations: results, delivery, README, test.
C: memo map on the task record; the five results are a stable wire surface.
D12 — Sleeps, clock, and host-driven wakeups
Contract: a task sleeps by ending its phase; the stored sleep (until and/or keys) holds no process and resumes at its checkpoint when the clock reaches until; a commit returning {status:"sleeping", until, checkpoint} is the same sleep; deadlines use now, so all openers of one storage share a clock; with onWake no timer is armed and {active, at} is reported.
Evidence: doc+impl+test-read.
Citations: README, wake, test.
C: injectable shared clock; sleep deadlines are absolute values.
D13 — Park: a tool may suspend and return later
Contract: a tool returns { sleep: {...} } or { wait: { on, policy, checkpoint? } } instead of a result; on wake execute() reruns with the same arguments, api.wake says why, api.checkpoint holds park state; cancel runs on abort of a parked call and may run more than once; an invalid park ends the call with invalid_park; wrappers never park.
Evidence: doc+impl+test-read.
Citations: README, shape, test.
C: parks are durable task state, not blocked threads; cancel must be idempotent.
D14 — Forks copy stored values, not tracker caches
Contract: a fork points at visible entry E; the child sees entries through E and document state as of E's commit; per document asOf copies at E, current copies the committed parent value at fork time, initial copies nothing; copies read committed stored values, so a fork may not also write a parent current document; tasks and task documents are never copied.
Evidence: doc+impl+test-read.
Citations: spec §3.7, forks.ts, test.
C: server-side document.copy with explicit source incarnation; order-free resolution.
D15 — Compaction is an append, never a rewrite
Contract: compaction summarizes older entries and appends a pi.compaction entry carrying a head marker, raw history stays; it is placed at once when idle, else at the next boundary, or settles stale with a later cut winning; generation compacts and retries once on a context-length error, and a blocking compaction failure fails the generation.
Evidence: doc+impl+test-read.
Citations: README, placement, test.
C: the head marker is an entry property; never delete old entries.
D16 — Read-only: no recovery, no writes, usable reads
Contract: open(storage, { readOnly: true }) recovers nothing (a running task stays as committed); writes, resume(), and task-running calls reject with ReadOnlySession, while reads work; JSONL must also open { readOnly: true }; SQLite opens normally because file locks protect it.
Evidence: doc+impl+test-read.
Citations: README, open, refusal, test.
C: enforce read-only at both the commit and scheduler boundaries; open must not mutate.
D17 — Versions and migrations, at three layers
Contract: documents use stored == token → value, < → migrate(), > → reject, with access-driven pure migration and a required current base on the first successful tx.doc() after a stored-version migration; tasks carry a version with blocked reasons missing_task, task_too_old, migration_failed; SQLite migrations apply atomically at open and a newer database is refused, and changing the table prefix does not migrate data.
Evidence: doc+impl+test-read.
Citations: spec §3.6, migrations, reasons, test.
C: three independent version axes; keep the stored marker until a base write.
D18 — One writer process per storage
Contract: "One process writes a storage at a time; there is no cross-process locking"; SQLite is safe beside a read-only viewer only via its file locks, JSONL needs an explicit readOnly open because a writable open repairs files; Chord's store claims tables and document namespaces in memory and refuses a second StoreStorage on one owner.
Evidence: doc+impl+test-read.
Citations: README, chord claims, node modes, test.
C: take an explicit owner lock; expose read-only as a separate open mode.
D19 — Monitoring is derived committed state
Contract: watches/observers advance on publication (including deferred progress before storage, D21). A Durable watch terminates on failure instead of sending a recoverable {kind:"failed"} value callback; its end reasons are stopped, aborted, ended, listener_error, or failed. Reports enumerate storage/task/extension/host/listener failures. The task graph reflects runtime statuses and registry changes (including blocked reasons without a commit); recovered running work can become pending. Telemetry primarily uses IDs/control metadata; documented diagnostic messages may contain caller content.
Evidence: doc+impl+test-read.
Citations: README, reports, graph, test.
C: observers are post-publish hooks; report kinds are an enumerated stable surface.
D20 — Crash loops end at restartLimit
Contract: open counts each task a crash, eviction, or reset cut off; a new committed state resets the count; at settings.restartLimit (default 5, Infinity disables) the task ends instead of rerunning — tool error restart_limit, compaction into compactionFailure, run runFailure restart_limit, or a custom task faulted; every task running at death is counted; a close is not a crash.
Evidence: doc+impl+test-read.
Citations: README, counting, enforcement, test.
C: persist a restarts counter per live task and reset it on every committed advance.
D21 — Deferred commits are the documented durability exception
Contract: only commits writing exclusively existing conversation documents with history: "latest" and fork: "initial" may be deferred — visible at once, stored later (next touching commit, close, or withinMs), with a crash losing that window; entries, new documents, and task state store at once.
Evidence: doc+impl+test-read.
Citations: invariant 3, §4.1, README, test.
C: require both an explicit deferral request and a structurally eligible write set. Default streamed progress uses this path: UI intervals are 100 ms and persistence window 1000 ms; a crash can lose that progress and an interrupted attempt's usage (progress contract).
D22 — Side effects are not exactly once
Contract: replay-safe tools with external effects still need their own idempotency (memoize the key before the call); a nested call interrupted before its result commit follows its own replay policy; a cancel handler may run more than once; external effects never run inside the Session mutation transaction.
Evidence: doc+impl+test-read.
Citations: README, invariant 4, test.
C: promise atomic record transitions and explicitly scoped deduplication, not universal exactly-once delivery or effects; expose durable idempotency references to tool code.
Caveats
- NORMAL vs FULL. Node SQLite uses WAL +
PRAGMA synchronous = NORMAL: commits survive process crashes, but the newest may be lost on power/host failure (README, adapter). JSONL defaults tofsync: false(process-crash consistency only);{ fsync: true }flushes before each commit marker (spec §11.3). Inference: the real promise is process-crash durability, not power-loss; a C harness must state which failures it covers and verify its selected policy; configurability is a separate design choice. - Deferred exception. D03 is deliberately weakened by D21; the C implementation must make that exception explicit in its types, not implicit.
- API is experimental. "The API changes without notice between releases." (README); treat every signature here as unstable.
- Unverified. Chord store internals beyond claims/open modes, workerd/Durable Object SQLite behavior, JSONL reclaim sidecars, and benchmark figures.