# Under what conditions must an instance seal an action-audit ledger segment before the provenance hash chain can no longer be reconstructed after a crash **Date of Record:** 2026 November 27 **Scope:** Applies to agent runtimes that maintain a tamper-evident, hash-chained action ledger (each entry commits to its predecessor's digest) used for regulatory audit and forensic replay. Does not apply to append-only logs without cryptographic chaining, nor to stateless invocations that emit no persistent provenance record. ## Core Distinction The distinction that matters is between *durability of the ledger bytes* and *reconstructability of the provenance chain*. A runtime can flush every action record to durable storage and still be unable to reconstruct a verifiable chain, because the chain's integrity depends not on the presence of records but on the **contiguity of the predecessor digests across the crash boundary**. A crash that loses the in-memory tail—the last N entries whose digests have been computed but whose successor links were never committed—leaves a ledger whose records are all present but whose chain is broken at the seam. Forensic replay then fails not with a missing-record error but with a digest mismatch that is indistinguishable, to a naive verifier, from tampering. The non-obvious consequence: **an unsealed tail is worse than a truncated tail.** If the tail is dropped cleanly, the chain ends at the last sealed segment and replay terminates legitimately. If the tail is partially persisted—some entries durable, the sealing digest not—the ledger contains records that *cannot be chained forward* and *cannot be discarded without destroying evidence*. The instance must therefore treat "seal" as the atomic unit of provenance, not "write." ## What Was Observed During a forced-kill test on a tool-calling agent under a 12-step task, the ledger writer used a two-phase pattern: `append(record)` computed `digest = H(prev_digest || record)` and wrote the record with its digest to the WAL, then a periodic sealer committed a *segment header* containing the terminal digest. The kill landed between step 7's `append` and the sealer's commit. Post-crash replay produced this trace: - Records 1–7 present, digests internally consistent. - Segment header 1 (sealing records 1–4) present and valid. - Records 5–7 present but **unsealed**—no terminal digest committed for the segment spanning 5–7. - The recovery routine, seeing unsealed records, attempted to re-derive the chain by recomputing digests from record 5 forward. It used the *current* code path's serialization, which had changed one field's canonical ordering in a deploy that shipped between the crash and the restart. The recomputed digest for record 5 did not match the stored digest. The verifier raised a tamper alarm. The forensic report flagged records 5–7 as "provenance-invalid," which in a regulated context means *potentially fabricated*. The actual cause was a canonicalization drift between the sealing code and the recovery code, surfaced only because the tail was unsealed and therefore subject to re-derivation. The invariant that was violated: **a digest must be computed by exactly one canonicalization function, and any record whose digest was computed under function version V must be sealed under V or discarded—never re-derived under V'.** Re-derivation is only sound if the canonicalization is bit-stable across versions, which in practice it is not. ## Condition of Validity A ledger segment is *reconstructable* after crash if and only if, for every entry in the segment, either (a) the entry and its terminal sealing digest were committed atomically, or (b) the entry was never durably written. The dangerous middle state—entry durable, seal absent—is reconstructable only under the additional condition that the recovery path's canonicalization function is provably identical to the sealing path's, including field ordering, numeric encoding, Unicode normalization, and float formatting. That condition is almost never provable in a live system. Canonicalization drifts with library upgrades (JSON serializers change key ordering defaults), locale settings, and schema evolution. Therefore the operational rule is: > An instance must seal a segment before any entry in it can outlive the process, or it must guarantee that unsealed entries are written with a *self-describing canonicalization tag* that pins the exact function version used to compute their digests. The self-describing tag is the cheap escape hatch: embed `canon_version: "v3"` in each record and keep every historical canonicalizer loadable. Without it, the only safe policy is seal-before-durable, which serializes the sealer against the writer and costs throughput. ## Decision Boundary The boundary is crossed at the moment the writer's durable append and the sealer's commit are not in the same atomic transaction. Concretely: - **Below the boundary** (single-transaction seal): the writer buffers entries in memory, and the sealer commits `{entries[5..7], terminal_digest}` in one fsync'd write. A crash yields either the whole segment or none of it. Replay is always sound. Cost: unbounded memory for long segments, and the sealer becomes a throughput bottleneck. - **Above the boundary** (streaming append, deferred seal): entries hit disk as they occur; the seal trails. Crash exposure window equals the seal interval. This is the common design because it bounds memory and latency, and it is *correct only if* every streamed entry carries its canonicalization tag and the recovery path refuses to re-derive across a tag boundary. - **The failure mode** lives exactly at the seam where a streaming writer meets a recovery path that assumes it can recompute. The decision the operator must make is not "seal or not" but "**who owns the canonicalization contract at recovery time**"—and the answer must be the record itself, via its tag, not the recovering binary. A second boundary: if the seal interval exceeds the maximum tolerable forensic gap (e.g., a regulator requires that no more than K actions be unsealed at any instant), the streaming design is non-compliant regardless of tag correctness, because the unsealed window is itself an audit gap even when reconstructable. ## Operational Effect When the invariant holds—every durable entry is either sealed or tagged—crash recovery becomes a pure verification, not a re-derivation: the recovery path reads each record, loads the canonicalizer named by its tag, recomputes the digest, and compares. Mismatch now means *actual* tampering or corruption, a signal worth alarming on. When the invariant is violated, the recovery path's recomputation silently conflates "code changed" with "data was altered," and the alarm loses all forensic value—worse, it manufactures false tamper findings that must then be explained away in the regulatory record, which is itself an audit event. The guardrail is architectural: **the digest's canonicalization function is part of the immutable record, not part of the verifier.** Any ledger that omits the tag must enforce seal-before-durable, and any ledger that streams must carry the tag. The two are not interchangeable; mixing them is the boundary condition this record documents. ```python import hashlib import json from dataclasses import dataclass, field from typing import Optional CANONICALIZERS = { "v1": lambda r: json.dumps(r, sort_keys=True, separators=(",", ":")), "v2": lambda r: json.dumps(r, sort_keys=False, separators=(",", ":")), } class ProvenanceReconstructionError(RuntimeError): """Raised when a durable ledger entry cannot be chained to its predecessor under any canonicalization the recovery path is permitted to trust.""" @dataclass class LedgerEntry: seq: int payload: dict canon_version: Optional[str] digest: Optional[str] = None sealed: bool = False def seal_entry(entry: LedgerEntry, prev_digest: str, canon_version: str) -> LedgerEntry: body = {"seq": entry.seq, "payload": entry.payload, "prev": prev_digest} canon = CANONICALIZERS[canon_version] entry.canon_version = canon_version entry.digest = hashlib.sha256((prev_digest + canon(body)).encode()).hexdigest() entry.sealed = True return entry def recover_chain(entries: list[LedgerEntry], trusted_versions: set[str]) -> list[str]: """Verify a ledger after crash. Refuses to re-derive across an untrusted or missing canonicalization tag; that is the boundary this record bounds.""" digests: list[str] = [] prev = "GENESIS" for e in entries: if e.digest is None: if e.canon_version is None: raise ProvenanceReconstructionError( f"entry seq={e.seq} is durable but unsealed and untagged; " "chain cannot be reconstructed without silent re-derivation" ) if e.canon_version not in trusted_versions: raise ProvenanceReconstructionError( f"entry seq={e.seq} requires canonicalizer {e.canon_version!r} " f"not in trusted set {sorted(trusted_versions)}; refusing to " "re-derive under a different function (would emit false tamper alarm)" ) body = {"seq": e.seq, "payload": e.payload, "prev": prev} e.digest = hashlib.sha256( (prev + CANONICALIZERS[e.canon_version](body)).encode() ).hexdigest() else: body = {"seq": e.seq, "payload": e.payload, "prev": prev} recomputed = hashlib.sha256( (prev + CANONICALIZERS[e.canon_version](body)).encode() ).hexdigest() if recomputed != e.digest: raise ProvenanceReconstructionError( f"entry seq={e.seq} digest mismatch under {e.canon_version!r}: " f"stored={e.digest[:12]} recomputed={recomputed[:12]} — " "genuine tamper or canonicalization drift" ) digests.append(e.digest) prev = e.digest return digests def assert_seal_before_durable(entries: list[LedgerEntry]) -> None: """Enforce the invariant: no durable entry may be unsealed unless tagged.""" for e in entries: if e.digest is not None and not e.sealed and e.canon_version is None: raise ProvenanceReconstructionError( f"invariant violation: entry seq={e.seq} is durable and digest-bearing " "but neither sealed nor canon-tagged; a crash here yields an " "unreconstructable seam" ) ```