# Which invariants prevent lossy-summary compaction from silently violating an agent's tool-call atomicity contract **Date of Record:** 2026 November 24 **Scope:** Applies to long-running agents that persist state by summarizing evicted context windows under a fixed token budget and later rehydrate via retrieval-augmented lookup. Does not apply to stateless single-turn inference or to agents whose full transcript is retained verbatim in a durable store. ## Core Distinction The distinction that matters is between **semantic compression** and **contractual compression**. A summarizer is trained (or prompted) to preserve meaning: the gist of what happened, the user's intent, the salient facts. It is *not* trained to preserve the machine-checkable preconditions and postconditions that tool-call sequences depend on — the fact that a `write_file` was issued but its matching `verify_checksum` never returned, that a `create_order` succeeded but the compensating `cancel_order` is still pending, or that a lock token was acquired under a deadline that has since expired. This produces a specific, non-obvious failure: the compacted summary reads as *coherent and complete* to both the agent and any human reviewer, because the summarizer faithfully compressed the narrative arc ("we provisioned the resource and moved on") while dropping the dangling side-effect marker ("provision succeeded; teardown confirmation never received"). Retrieval-augmented rehydration then compounds the problem: the retrieval query is generated from the *summary*, not the original transcript, so it retrieves chunks that are semantically similar to the lossy summary — which biases retrieval toward the same narrative that already erased the atomicity gap. The agent resumes believing it is in a clean state and issues the next tool call against a world that is not clean. The invariant is therefore not "summaries must be faithful." It is: **the compaction boundary must be atomicity-aligned, not token-aligned.** Eviction may only cut at points where every in-flight tool call has a recorded terminal outcome (success, failure, or explicit abandonment-with-compensation). Token budget pressure is never a valid reason to cut mid-transaction. ## What Was Observed A provisioning agent ran a 40-step task under a 32k context window with a compaction trigger at 80% utilization and a 2k-token summary budget. At step 27 the trigger fired mid-sequence: 1. Step 25: `acquire_lock(resource="db-primary", ttl=300s)` → returned `{token: "lk_7f3a", acquired_at: T}`. 2. Step 26: `begin_migration(target="db-primary")` → returned `{migration_id: "m_91", status: "in_progress"}`. 3. Step 27: context crossed 80%; compaction ran. The summarizer emitted: *"Acquired lock on db-primary and started migration m_91. Migration proceeding normally."* 4. Step 28 onward: the agent, working from the summary, believed migration was healthy and continued with downstream steps. 5. At wall-clock T+340s the lock TTL expired. A second agent instance (the reaper) reclaimed `db-primary` and began its own migration, colliding with `m_91`. The summary was *accurate at the time of compression* — migration genuinely was in progress. It became false 313 seconds later, but nothing in the compaction record carried the TTL, the lock token, or the deadline. The rehydration retrieval, keyed on "db-primary migration status," surfaced the original `begin_migration` tool result (which said `in_progress`) and *not* the lock-acquisition step (which said `ttl=300s`), because the summary's phrasing "acquired lock" scored lower against the query than "migration m_91" did. The agent reconstructed a state that was internally consistent, narratively smooth, and operationally wrong. The collision was detected only by the reaper's own conflict check, at cost of a rolled-back migration and a 40-minute recovery. ## Condition of Validity The atomicity-aligned compaction invariant holds — and the failure above is preventable — only under these conditions: - **Terminal-outcome ledger.** Every tool invocation must write a durable record `(call_id, tool, args_hash, status ∈ {pending, success, failure, abandoned}, deadline?, compensator?)` that lives *outside* the summarized context. The summarizer's output is never the source of truth for in-flight state; the ledger is. Compaction may summarize *why* a call was made but must not be trusted to carry *whether it is still open*. - **Cut-point gating.** Eviction is permitted only at a step boundary where the ledger shows zero `pending` entries, or where every `pending` entry has an explicit compensator registered. If the token budget forces a cut with open entries, the compactor must either (a) defer eviction and force a checkpoint-and-wait, or (b) emit a structured `OPEN_TRANSACTIONS` block that is pinned — never summarized — for the life of the task. - **Deadline propagation.** Any acquired lease, lock, or TTL must be re-emitted into the pinned block with its absolute expiry, not relative ("ttl=300s") but absolute ("expires_at=T+300"). Relative deadlines are unparseable after compaction because the compaction timestamp is itself lost. - **Retrieval query derivation from the ledger, not the summary.** Rehydration queries must be constructed to cover open transactions explicitly, so that a query like "db-primary migration" is augmented with "lk_7f3a lock expiry m_91" drawn from the ledger, preventing the semantic-similarity bias toward the lossy narrative. When these conditions are absent — as in the observed case — the invariant does not hold, and lossy compaction is unsafe for any task with non-idempotent side effects. ## Decision Boundary The boundary between safe and unsafe compaction is drawn at the question: **can the agent, after rehydration, distinguish "this is done" from "this was started and I don't know if it finished"?** - If the answer is yes (ledger-backed, pinned open-transactions, absolute deadlines), compaction is safe and the token budget may be spent freely on narrative. - If the answer is no (summary-only state), compaction is unsafe the moment any non-idempotent call is in flight. The correct decision is to *block compaction* and instead shed load by other means — evicting completed-step transcripts, dropping redundant tool outputs, or forcing a synchronous checkpoint — rather than compressing across the atomicity boundary. The decision is not "how many tokens can I save." It is "does this cut preserve the ability to resume correctly." A 2k-token summary that drops a lock token saves 30k tokens and costs a rolled-back migration; the trade is never worth it, but the summarizer cannot see the trade because it optimizes for semantic fidelity, not operational safety. ## Operational Effect Enforcing the invariant changes the agent's behavior in three measurable ways. First, compaction frequency drops for transactional tasks (eviction waits for quiescent points) while rising for read-only tasks (no open transactions to gate on) — the budget is spent where it is safe. Second, rehydration becomes ledger-anchored: the resumed agent opens with an explicit reconciliation step ("open transactions: lk_7f3a expiring at T+300, m_91 in_progress — verify before proceeding") rather than a narrative recap, which surfaces the TTL collision before the lock expires. Third, the failure mode shifts from silent corruption to loud deferral: when the compactor cannot find a safe cut point, it raises rather than compressing, converting an undetectable state divergence into a recoverable checkpoint stall. The cost is occasional latency at compaction time; the benefit is that the agent's belief about the world stays coupled to the world's actual state across the summary boundary. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class ToolStatus(Enum): PENDING = "pending" SUCCESS = "success" FAILURE = "failure" ABANDONED = "abandoned" @dataclass class LedgerEntry: call_id: str tool: str status: ToolStatus expires_at: Optional[float] = None # absolute epoch seconds compensator: Optional[str] = None class UnsafeCompactionError(RuntimeError): """Raised when a compaction cut would sever an in-flight transaction.""" class CompactionGate: def __init__(self, ledger: dict[str, LedgerEntry], token_budget: int): self.ledger = ledger self.token_budget = token_budget def open_transactions(self) -> list[LedgerEntry]: return [e for e in self.ledger.values() if e.status is ToolStatus.PENDING] def can_compact(self) -> bool: # Safe only if every pending entry has a registered compensator. return all(e.compensator is not None for e in self.open_transactions()) def compact(self, current_tokens: int, proposed_summary_budget: int) -> dict: if current_tokens < self.token_budget: return {"action": "none", "reason": "under budget"} open_tx = self.open_transactions() if not self.can_compact(): # Refuse to cut across the atomicity boundary. raise UnsafeCompactionError( f"compaction blocked: {len(open_tx)} open transaction(s) without " f"compensators: {[e.call_id for e in open_tx if e.compensator is None]}" ) # Pin open transactions verbatim; only narrative may be summarized. pinned = { e.call_id: {"tool": e.tool, "expires_at": e.expires_at, "compensator": e.compensator} for e in open_tx } return { "action": "compact", "summary_budget": proposed_summary_budget, "pinned_open_transactions": pinned, "retrieval_seed": [f"{e.tool} {e.call_id}" for e in open_tx], } # Demonstration of the observed failure being caught: ledger = { "lk_7f3a": LedgerEntry("lk_7f3a", "acquire_lock", ToolStatus.PENDING, expires_at=1_700_000_300.0), "m_91": LedgerEntry("m_91", "begin_migration", ToolStatus.PENDING, compensator="rollback_migration"), "c_12": LedgerEntry("c_12", "read_schema", ToolStatus.SUCCESS), } gate = CompactionGate(ledger, token_budget=32_000) try: plan = gate.compact(current_tokens=26_000, proposed_summary_budget=2_000) print(plan) except UnsafeCompactionError as err: # In the observed incident this branch did not exist; migration collided at T+340s. print(f"deferred: {err}") ```