Skip to content
pi-c Artifact [888dcb98d0]
Login

Artifact [888dcb98d0]

Artifact 888dcb98d0f62052960108f70592a8046ef2fad532074f4a6f1a7169c078614d:


# 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](../reference/pi/packages/durable/docs/spec.md#L38-L40)

## 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](../reference/pi/packages/durable/docs/spec.md#L3092), [submit](../reference/pi/packages/durable/src/harness/submissions.ts#L220-L318), [guard](../reference/pi/packages/durable/src/harness/submissions.ts#L80-L85), [test](../reference/pi/packages/durable/test/harness-submit-in-commit.test.ts#L108-L120).
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](../reference/pi/packages/durable/README.md#L129-L138), [dedup](../reference/pi/packages/durable/src/harness/submissions.ts#L229-L237), [index](../reference/pi/packages/durable/src/storage/sqlite/migrations.ts#L56-L63), [test](../reference/pi/packages/durable/test/harness-continue.test.ts#L172-L185).
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](../reference/pi/packages/durable/docs/spec.md#L61-L78), [order](../reference/pi/packages/durable/docs/spec.md#L1904-L1940), [README](../reference/pi/packages/durable/README.md#L94), [writer](../reference/pi/packages/durable/src/session/writer.ts#L255-L280).
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](../reference/pi/packages/durable/README.md#L1062), [types](../reference/pi/packages/durable/docs/spec.md#L6705-L6713), [loop](../reference/pi/packages/durable/src/storage/sqlite/storage.ts#L161-L197), [checks](../reference/pi/packages/durable/src/storage/sqlite/commit.ts#L209-L294), [test](../reference/pi/packages/durable/test/sqlite-commit.test.ts#L368-L380).
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](../reference/pi/packages/durable/README.md#L265), [retry](../reference/pi/packages/durable/src/harness/generation.ts#L329-L346), [interrupted](../reference/pi/packages/durable/src/harness/generation.ts#L568-L585), [test](../reference/pi/packages/durable/test/harness-restart-failure.test.ts#L141-L180).
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](../reference/pi/packages/durable/README.md#L336), [spec §7.3](../reference/pi/packages/durable/docs/spec.md#L4030-L4064), [branch](../reference/pi/packages/durable/src/harness/tool.ts#L236-L246), [test](../reference/pi/packages/durable/test/harness-restart-failure.test.ts#L367-L400).
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](../reference/pi/packages/durable/README.md#L142-L162), [statuses](../reference/pi/packages/durable/src/harness/scheduler.ts#L69-L81), [CHECK](../reference/pi/packages/durable/src/storage/sqlite/migrations.ts#L91-L112), [test](../reference/pi/packages/durable/test/harness-tasks-recovery.test.ts#L114-L150).
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](../reference/pi/packages/durable/docs/spec.md#L2733-L2760), [completing](../reference/pi/packages/durable/docs/spec.md#L2758-L2790), [README](../reference/pi/packages/durable/README.md#L929-L952), [terminate](../reference/pi/packages/durable/src/harness/scheduler.ts#L2002-L2020).
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](../reference/pi/packages/durable/docs/spec.md#L2484-L2540), [order](../reference/pi/packages/durable/docs/spec.md#L2818), [README](../reference/pi/packages/durable/README.md#L882-L884), [test](../reference/pi/packages/durable/test/harness-tasks-recovery.test.ts#L293-L390).
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](../reference/pi/packages/durable/README.md#L366-L390), [spec §7.3](../reference/pi/packages/durable/docs/spec.md#L4090-L4124), [abandon](../reference/pi/packages/durable/src/harness/scheduler.ts#L476-L509), [test](../reference/pi/packages/durable/test/harness-nested-tools-restart.test.ts#L82-L160).
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](../reference/pi/packages/durable/src/signals.ts#L46-L50), [delivery](../reference/pi/packages/durable/src/signals.ts#L200-L220), [README](../reference/pi/packages/durable/README.md#L256-L261), [test](../reference/pi/packages/durable/test/harness-signals.test.ts#L102-L128).
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](../reference/pi/packages/durable/README.md#L140-L166), [wake](../reference/pi/packages/durable/src/harness/scheduler.ts#L570-L590), [test](../reference/pi/packages/durable/test/harness-sleep.test.ts#L88-L168).
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](../reference/pi/packages/durable/README.md#L394-L430), [shape](../reference/pi/packages/durable/src/harness/parks.ts#L26-L38), [test](../reference/pi/packages/durable/test/harness-park-children.test.ts#L107-L160).
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](../reference/pi/packages/durable/docs/spec.md#L1802-L1835), [forks.ts](../reference/pi/packages/durable/src/session/forks.ts#L26-L59), [test](../reference/pi/packages/durable/test/session-forks.test.ts#L29-L80).
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](../reference/pi/packages/durable/README.md#L707-L758), [placement](../reference/pi/packages/durable/src/harness/compaction.ts#L444-L500), [test](../reference/pi/packages/durable/test/harness-compaction.test.ts#L378-L400).
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](../reference/pi/packages/durable/README.md#L127), [open](../reference/pi/packages/durable/src/harness/scheduler.ts#L476-L521), [refusal](../reference/pi/packages/durable/src/session/session.ts#L1112-L1116), [test](../reference/pi/packages/durable/test/harness-read-only.test.ts#L73-L130).
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](../reference/pi/packages/durable/docs/spec.md#L1767-L1800), [migrations](../reference/pi/packages/durable/src/storage/sqlite/migrations.ts#L113-L138), [reasons](../reference/pi/packages/durable/src/harness/types.ts#L877-L892), [test](../reference/pi/packages/durable/test/sqlite-migrations.test.ts#L48-L120).
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](../reference/pi/packages/durable/README.md#L1051-L1053), [chord claims](../reference/pi/packages/chord/src/store/claims.ts#L1-L8), [node modes](../reference/pi/packages/chord/src/sqlite/node.ts#L8-L18), [test](../reference/pi/packages/durable/test/store-storage.test.ts#L136-L152).
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](../reference/pi/packages/durable/README.md#L578-L626), [reports](../reference/pi/packages/durable/README.md#L267), [graph](../reference/pi/packages/durable/README.md#L956-L971), [test](../reference/pi/packages/durable/test/harness-reports.test.ts#L48-L78).
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](../reference/pi/packages/durable/README.md#L265), [counting](../reference/pi/packages/durable/src/harness/scheduler.ts#L500-L512), [enforcement](../reference/pi/packages/durable/src/harness/scheduler.ts#L2005-L2020), [test](../reference/pi/packages/durable/test/harness-restart-failure.test.ts#L330-L366).
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](../reference/pi/packages/durable/docs/spec.md#L71-L78), [§4.1](../reference/pi/packages/durable/docs/spec.md#L2013), [README](../reference/pi/packages/durable/README.md#L996-L1008), [test](../reference/pi/packages/durable/test/session-deferred-commits.test.ts#L189-L268).
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](../reference/pi/packages/durable/README.md#L628)).

## 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](../reference/pi/packages/durable/README.md#L387-L428), [invariant 4](../reference/pi/packages/durable/docs/spec.md#L77), [test](../reference/pi/packages/durable/test/harness-nested-tools-restart.test.ts#L390-L440).
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](../reference/pi/packages/durable/README.md#L1026), [adapter](../reference/pi/packages/chord/src/sqlite/node.ts#L212-L221)). JSONL defaults to `fsync: false` (process-crash consistency only); `{ fsync: true }` flushes before each commit marker ([spec §11.3](../reference/pi/packages/durable/docs/spec.md#L7039-L7046)). 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](../reference/pi/packages/durable/README.md#L3)); 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.