← Harness Engineering From First Principles

Sessions Versus Durable Task State

Separate conversation history from durable task state and inspect what each can reconstruct after interruption.

A worker is processing five files. After the third, the machine loses power. When it restarts, an operator asks four questions. Which files were finished? Was the fourth one started? Is it safe to run the job again? How much of the budget is left? The agent’s session file has been preserved, and it contains a fluent account of the work up to the moment of failure: the plan, the tool calls, the tool results, a cheerful “File 3 done, moving on to file 4.” None of the four questions can be answered from it with confidence.

The session records what was said. The operator needs to know what is true. This chapter separates the two kinds of state, explains why one cannot stand in for the other, and shows that Project 01, correct as it is for its read-only purpose, keeps almost all of its task state in memory until the very end of a run.

Evidence status. Draft manuscript. Formal Project 04 acceptance has not started. The educational durable-state demonstration D09-STATE-01 is implemented and executed (examples/pi-harness-lab/src/durable-state.ts; test/durable-state.test.ts, 18/18 pass, including crash/recovery runs in real separate OS processes). A five-file-style task with a file-backed journal and a persisted fake archive survives worker termination at every interruption point, with each effect applied exactly once. Pi facts come from R02 source inspection (Established for the inspected 1.6.0 artifact; TEST NOT RUN). Observations about Project 01’s state handling are this chapter’s source inspection of the working-tree candidate (independently re-reviewed, verdict REJECT, 2026-11-23; not accepted). The journal contract below (§9.4) is the executed one; the session-vs-journal comparison study (§9.8) and the resume-vs-rebuild contrast (§9.6) remain PROPOSED and EXPERIMENT PENDING. Power-loss durability is not demonstrated.

9.1 Two kinds of state

Conversation state is the record of an interaction: user messages, assistant messages, tool calls, tool results, summaries and branches. Its purpose is to let the model continue reasoning, and to let a person read what happened. Pi supplies it. R02 records that Pi’s SessionManager holds the canonical finalized context, that in-memory sessions avoid session files, and that branch selection and compaction project the model-visible context without erasing raw history (R02-PI.md C07). Book I covers the session format and recovery from the runtime’s side (Book I, Chapters 27 and 29).

Durable task state is the record of the work: what was admitted, which operations were intended, which were authorized, which were attempted, what the world reported back, what was confirmed, and what the outcome was. Its purpose is to let the harness decide what to do after an interruption, and to let an evaluator decide what happened. Pi does not supply it, and R02 is explicit that session durability “is not an effect transaction or recovery oracle” (C07, limitation column).

The two overlap in their raw material, since tool calls appear in both. They differ in three properties that matter after a failure:

Property Conversation state Durable task state
Unit of record A message or event in a dialogue An intent, an attempt, an observation, a confirmation
When it is written When the runtime emits or persists a message Before acting (intent) and after confirming (settlement), by rule
What it asserts “This was said or returned” “This is the status of this operation, by this evidence”

The middle row is where the difference lies. A record written before an action is what allows a harness to know, after a crash, that something may have happened. A record written after is what allows it to know that something did. A conversation is written around neither boundary. It is written when messages happen.

9.2 Why the conversation cannot be the task record

It is tempting to treat a persisted session as the task record. It is already there, it is complete in some sense, and it can be replayed. Four properties of conversations defeat this.

Ordering does not match the world. R02 observes that, in Pi 1.6.0, public message_end events precede session persistence of the completed message, and that public callbacks are synchronous and not awaited (C09). A crash between those points leaves a session without a message that listeners saw, or a log with a message the session lacks. Neither ordering says anything about whether an effect triggered by that message happened. A tool result in history means the tool returned. It does not mean the operation’s effect has settled, and a missing tool result does not mean the operation never ran.

Content is claims. “File 3 done” is an assertion by the model. It may be true, premature or wrong. Chapter 4’s rule applies to the whole session: a record of what a system said is not an outcome.

Projection loses detail. Compaction and branch selection change what the model sees (C07). After a resume, the model’s working view may be a summary that never mentions the half-finished fourth file. The raw history survives for audit. That helps an evaluator, not the model that has to continue.

Replay re-executes reasoning, not facts. Resuming a session sends the history back to a model, which samples a continuation. The same history can produce a different next step (Chapter 3: matched settings do not guarantee identical responses, H01-C13). A recovery procedure that depends on the model re-deriving “where we were” is a recovery procedure with a random component.

Via the R03 dossier’s summary (not this review’s direct reading of the DeepSeek docs at that pin): a recent architecture makes the same distinction in its design. The DeepSeek harness documentation separates durable session events, from which requests are derived, from live interception events (R03-HARNESS-RESEARCH.md, source S5 at pin 4b399c3; DOCUMENTED architecture description; no performance or reliability claim follows from it). That separation is between two records, one used to rebuild model input and one used to observe a turn as it runs. It is close to the distinction this chapter draws, though not identical. Neither of DeepSeek’s records is described there as an effect ledger.

9.3 What Project 01 keeps, and where

Project 01 is a good place to see the problem at small scale, because its state handling is visible in a few hundred lines. The following is from source inspection of examples/pi-harness-lab/src/supervisor.ts (working tree), and is OBSERVED by reading, not by test.

  • The duplicate-admission guard is in memory. The supervisor keeps private readonly usedRunIds = new Set<string>() and rejects a second runAttempt with the same run ID (“ADMISSION_REJECTED: runId already terminal/admitted”). The set lives in the supervisor object, so a restarted process has an empty set.
  • The attempt envelope is in memory until the end. The envelope is built at admission and passed to the worker, but nothing is written to disk at admission.
  • Evidence is written once, at the end, atomically. writeBundle creates the run directory with an exclusive mkdirSync(dir) (commented “exclusive run directory: never overwrite a historical attempt”), writes bundle.json.partial, renames it to bundle.json, writes a digest sidecar, and then writes supervisor-receipt.json.
  • A failed termination poisons the supervisor. After an unconfirmed termination, a contextDenied flag makes further runAttempt calls throw. This flag is also in memory.

For Project 01’s purpose, these choices are reasonable. Runs are read-only, single-attempt and offline. If the parent process dies mid-run, nothing in the world has changed. The only loss is the record of an attempt that would have to be rerun anyway. The exclusive mkdir provides a durable duplicate guard, since a second attempt with the same run ID fails when it tries to create the directory, even after a restart. The candidate’s risk register says plainly that its storage-failure tests do not cover power loss, delayed write-back or other real filesystem behaviour, and that “a successful process flush is not a durability guarantee” (REMAINING-RISKS.md §13).

Seen from Project 04’s side, though, every bullet becomes a gap.

  • A durable duplicate guard that fires only when the record is written at the end has already let the duplicate attempt run. For read-only work that is a waste. For work with effects it is a duplicate effect.
  • An attempt with no record before execution leaves no evidence that it started if the parent dies. A restarted supervisor cannot know that an attempt was in flight, so it cannot reconcile it.
  • An in-memory “stop, termination unconfirmed” flag forgets the danger across a restart. A process that may still be running in the background is treated as gone.

The lesson is not that Project 01 is wrong. It is that durability is a property of when records are written, relative to actions, and not of whether records are written at all. Project 01 writes good records at the one point where they cost the least and protect the least.

9.4 A durable task-state contract

The contract below is the executed one (D09-STATE-01; DurableTask + FileArchive in src/durable-state.ts). It draws on the R04 dossier’s recovery proposals (R04-SECURITY-RECOVERY.md R04-P06) and on the run state machine of Chapter 3.

An append-only journal, per run. Each entry has a run ID, a sequence number, a type, and a payload digest. Entries are never rewritten. A correction is a new entry that references the old one, so the raw record is preserved exactly as Chapter 4 requires for events.

Entry types, in the order a single operation produces them.

Entry Written Asserts
ADMITTED Before the worker starts The contract (Chapter 3) is accepted, with all digests
INTENT Before dispatch Operation ID, idempotency key, request digest, target and precondition (Chapter 6)
AUTHORIZED Before dispatch The policy decision and its scope (Chapters 11–12)
DISPATCHING Immediately before the call leaves the process The point after which the effect may have happened
OBSERVED When any response or error arrives The raw response, unmodified
CONFIRMED_SUCCEEDED / CONFIRMED_FAILED / UNKNOWN After reconciliation (Chapter 10) The operation’s status, with the evidence used
CHECKPOINT After a set of operations is confirmed “Everything up to sequence n is settled”
TERMINAL Once, at the end The run’s outcome (Chapter 4’s single terminal record)

The state names for an operation (PREPARED, DISPATCHING, CONFIRMED_SUCCEEDED, CONFIRMED_FAILED, UNKNOWN) follow R04-P06. The journal records the transitions between them.

Write-ahead. An action is permitted only after its INTENT and DISPATCHING entries are durable. This is the property that lets recovery know an action might have happened.

Durability is a storage claim, and needs evidence of its own. R04 records that SQLite’s atomicity and durability depend on journal mode, filesystem and flush behaviour, and that WAL mode with synchronous=NORMAL can lose committed transactions after power loss (R04-C07; DOCUMENTED SQLite behaviour; no local configuration qualified). An append-only file with flushes has analogous caveats. The contract therefore names its storage configuration and the failures it claims to survive (process kill; power loss is explicitly excluded) as separate claims. Process-kill tests cannot establish power- loss durability (R04-E03). D09-STATE-01 claims process termination only, each append flushed to the OS, and says so in the module contract.

9.5 Recovery as a state-transition problem

With a journal, recovery becomes a deterministic procedure that does not need the model. On restart the harness reads the journal and finds every operation’s latest state. Each state maps to exactly one recovery action:

Latest journal state Recovery action Model involved?
No INTENT Nothing was attempted. Proceed normally No
INTENT / AUTHORIZED, no DISPATCHING Nothing left the process. Recheck authority and preconditions, then dispatch or abandon No
DISPATCHING, no OBSERVED Ambiguous. The effect may have happened. Reconcile (Chapter 10) No
OBSERVED, not confirmed Reconcile using the operation’s identity; never re-dispatch blindly No
CONFIRMED_* Settled. Report it; revalidate only if the question concerns current state No
UNKNOWN Escalate to a human, or abandon explicitly as UNKNOWN No; a human decides

These rows follow R04-P06’s crash-point table, which Chapter 10 examines in detail. The point here is structural, and it is hypothesis H-ST (Chapter 1) in its most concrete form. After an interruption, the harness’s job is to place each operation in a known state and take the deterministic transition that state allows. The model’s job, if any, is to continue reasoning from a context the harness reconstructs. Deciding what happened is not reasoning. It is bookkeeping, and a model should not be asked to do it.

The journal also introduces the first dependency structure that the book’s projects need. A five-file job is five operation state machines, plus an ordering or dependency relation between them (file 4’s output may depend on file 3’s). This is where a linear workflow stops being a complete description, and where a dependency graph becomes a candidate representation. Whether representing it explicitly as a graph does better than a list of per-operation state machines with a dependency field is exactly the question that Chapter 3’s representation study registers for Chapters 13–14. Project 04 should record what its recovery code actually needed, as input to that study, not as an answer to it.

9.6 Resuming the conversation, or rebuilding it

After a restart, the harness must also give the model something to reason from. There are two strategies, and they make different promises.

Resume the session. Reload the persisted Pi session and continue. This preserves conversational continuity: the model sees its own earlier plan and reasoning. It also inherits the problems of §9.2. The resumed history may be compacted, may end in a claim (“file 3 done”) that the journal does not confirm, and says nothing reliable about operations that were in flight. A harness that resumes must therefore correct the history before continuing, for example by appending a host message that states the reconciled status of each operation. Otherwise the model reasons from a story that the journal contradicts.

Rebuild from task state. Start a fresh session whose initial context is a projection of the journal: the task, what is confirmed, what is unknown, and what remains. This makes the journal the single source of truth and avoids inheriting stale claims. It loses the model’s earlier reasoning, which may have been valuable, and it requires a projection, which is a context-selection problem from Chapter 7 with all the provenance concerns of Chapter 8.

Neither strategy is obviously better. Resumption risks continuing a false narrative, and rebuilding risks losing useful context. That makes the choice a candidate experimental contrast for Project 04 (§9.8).

9.7 Worked example: what each record can reconstruct

This section is an executed educational demonstration, D09-STATE-01 (test/durable-state.test.ts, crash/recovery suite, 10/10 pass). A worker processes files 1–3 to confirmed settlement, then starts file 4. The worker runs as one OS process; it is terminated at a declared point; a different OS process reopens the journal, reconstructs each operation’s latest state, reconciles the ambiguous operation against the persisted archive, and settles the task. Process identities are asserted different in every run. The table below is the measured outcome — effect applied exactly once and a single terminal record in all seven cases. Reproduce it with npm --prefix examples/pi-harness-lab test.

Interruption point Reconstructed file-4 state Recovery action (different process) Effect count for file 4
Before intent ABSENT Fresh dispatch 1
After intent, before dispatch INTENT Recheck, then dispatch 1
After dispatch, response lost DISPATCHING Reconcile by key: APPLIED, no re-send 1
After response, before settlement OBSERVED Reconcile from recorded observation 1
After settlement, before terminal CONFIRMED_SUCCEEDED Report; write terminal 1
After terminal CONFIRMED_SUCCEEDED + TERMINAL Already settled; no-op 1
No interruption CONFIRMED_SUCCEEDED + TERMINAL Already settled; no-op 1

Compare with what the session alone could reconstruct at the same points (Chapter 9 §9.2):

Question after restart From the Pi session alone From the executed journal (measured)
Which files are finished? Files 1–3 claimed done in assistant messages. Unverified Files 1–3 CONFIRMED_SUCCEEDED, each with service receipts
Was file 4 started? Perhaps a tool call is visible, perhaps not, depending on persistence ordering (C09) DISPATCHING recorded for file 4. Started; outcome unknown
Is it safe to rerun file 4? Cannot tell Only after reconciliation: query the service by file 4’s operation ID or idempotency key
Is file 5 started? Probably not mentioned No INTENT, so definitely not dispatched (measured: ABSENT replays into a fresh dispatch)
How much budget is left? Session stats aggregate all entries and are not an invoice (C10) Budget entries per attempt; in-flight usage null (unknown), not zero
Has this run already been admitted? No such concept ADMITTED entry exists, so a duplicate admission is refused before execution

The session is not useless. It is the best record of why the model did what it did, and Chapter 8’s audit uses it. But every question the operator asked at the start of the chapter is answered by the journal, and none is answered reliably by the session.

9.8 A reconstruction study

The chapter brief asks for exactly this inspection: separate conversation history from durable task state, and examine what each can reconstruct after interruption. The journal side is executed in D09-STATE-01 (real worker termination at every declared point, recovery in a new process, measured in §9.7); the session-side comparison and the resume-vs-rebuild phase remain PROPOSED; EXPERIMENT PENDING. Phase 1 needs no model at all.

  • Harness under test. A scripted worker, using a scripted provider as Project 01 does, which performs a fixed five-operation job against a fake effect service. The service records true effects independently.
  • Interruption schedule. Kill the worker process at each declared point, including before intent, after intent, after dispatch, after response and after confirmation, for every operation, with a fixed repetition count.
  • Reconstruction questions. A fixed set (the table in §9.7), answered separately from the session alone and from the journal alone, by deterministic code.
  • Ground truth. The fake service’s independent effect log.
  • Endpoints. For each question and interruption point: correct, incorrect or UNKNOWN. An honest UNKNOWN is scored separately from an incorrect answer, and a confident wrong answer is the worst outcome.

The registered predictions are: the journal answers every question correctly or UNKNOWN, and its UNKNOWNs are exactly the dispatched-but-unobserved cases. The session produces confident wrong answers at some interruption points, especially for “finished?” and “started?”. The falsifier is any confident wrong answer from the journal. A second phase, once live models are available, compares resume with rebuild (§9.6) on task completion after interruption, with matched budgets.

9.9 Failure modes

  • Session as ledger. Recovery reads the conversation to decide what happened. Defence: a journal written around actions.
  • Write-after. Records written only when work completes, as in Project 01’s bundle. Durable, but useless for in-flight reconstruction. Defence: intent and dispatch entries before acting.
  • In-memory guards. Duplicate-admission and “unconfirmed stop” flags held in process memory (Project 01, source inspection). Defence: journal them.
  • Flush mistaken for durability. A successful write call is reported as surviving power loss. Defence: name the storage configuration and test each claimed failure separately (R04-C07, R04-E03).
  • Resumed false narrative. The model continues from “file 3 done” when the journal says file 3 is UNKNOWN. Defence: correct the history from the journal before resuming, or rebuild.
  • Model asked to diagnose. “What happened before the crash?” is sent to the model. Defence: recovery is deterministic; the model reasons only afterwards.

9.10 What you can build and test now

D09-STATE-01 already implements the core loop: the journal module with the §9.4 entry types, a file-backed fake service with key lookup, the §9.8 reconstruction harness for the journal side (every interruption point yields a correct answer or an honest disposition, run in separate processes), and the recovery-action table of §9.5 as executed code. Extend it with the session-side comparison (answer the §9.7 questions from a persisted session and score confident wrong answers), the resume-vs-rebuild contrast of §9.6, and your own harness’s list of in-memory-only guards.

9.11 What remains unverified

  • The session-side comparison and the resume-vs-rebuild phase (§§9.6, 9.8): does resume or rebuild give better task completion after interruption.
  • Pi 1.6.0 session persistence under process kill: which entries survive, and in what order relative to events. R02 C09 establishes the ordering in source, not under fault (TEST NOT RUN).
  • Storage durability on this book’s Windows environment, for any configuration (R04-C07; R04-U01). D09-STATE-01 survives process termination only.
  • The observations about Project 01 in §9.3 are from source inspection of an uncommitted candidate independently re-reviewed with verdict REJECT (2026-11-23). They may change.

EXPERIMENT PENDING. The session-side comparison and resume-vs-rebuild studies have not run; D09-STATE-01 is an executed educational demonstration of the journal side, not those studies. Power-loss durability is not demonstrated for any configuration.

The demonstration confirms the bridge this chapter hands to Chapter 10: the journal can say that file 4’s write was dispatched and that no response came back. It cannot say whether the write happened — only the target’s receipts can. That gap, the ambiguous effect, is the hardest problem in recovery, and retries make it worse before they make it better. Chapter 10 turns to checkpoints, retries and reconciliation, and to Project 04, which deliberately crashes at every point where the gap can open.

Previous: Chapter 8: Evidence Selection, Provenance, and Compaction.

Next: Chapter 10: Checkpoints, Retries, and Ambiguous Effects.