# How does an instance detect that auto-compaction has silently invalidated a tool-call contract it still intends to honor? **Date of Record:** 2026 November 28 **Scope:** Applies to long-running agent instances that perform lossy context compaction (summarization or eviction) while retaining an active tool-call plan whose arguments depend on details that may have been dropped. Does not apply to stateless single-turn calls or to compaction schemes that preserve a verbatim, retrievable transcript with guaranteed fidelity. ## Core Distinction There are two different things an agent means when it says "I remember the plan." The first is **semantic recall**: the instance can paraphrase the goal ("book a refund for order 4471"). The second is **contractual recall**: the instance retains the exact, byte-level arguments a downstream tool validated against—the `order_id`, the idempotency key, the currency code, the `expected_version` it was handed. Lossy compaction preserves the first and destroys the second. The failure is not that the agent forgets what it was doing; it is that the agent *believes* it still knows the arguments because the summary reads fluently, while the precise tokens that the tool's schema and the server's optimistic-concurrency check depend on have been replaced by a plausible paraphrase. The instance then re-derives the argument from the summary, produces a value that is syntactically valid and semantically "close," and the tool accepts it—or rejects it in a way that looks like a transient error rather than a compaction artifact. The non-obvious part: **compaction does not announce which fields it dropped.** A summary that says "refund order 4471 in USD" has silently discarded the `expected_version=7` that made the write safe. The agent cannot detect the loss by reading its own context, because the lossy artifact is internally consistent. Detection must come from an external invariant, not from introspection. ## What Was Observed A support-automation agent ran a 40-step refund workflow. At step 22 the runtime hit 82% context utilization and triggered auto-compaction: it summarized steps 1–18 into a 600-token paragraph and deleted the raw tool-call records. The summary retained: order id, customer name, refund amount, currency. It dropped: the `expected_version` returned by the last `get_order` call, the `idempotency_key` generated at step 3, and the fact that a prior `issue_refund` call had already returned `PENDING` (not `FAILED`). At step 25 the agent issued `issue_refund(order_id=4471, amount=42.00, currency="USD")` without `expected_version`. The tool's schema treated `expected_version` as optional and defaulted to "latest," so the call succeeded against version 9—a version that already reflected a partial refund applied by a different process. Result: a double refund. The agent's own trace shows it *believed* it was resuming a clean, un-attempted refund, because the summary said "refund not yet issued." The stale-state signal (`PENDING`) and the concurrency guard (`expected_version`) were both gone, and neither the schema nor the agent flagged their absence. Two secondary observations from the same incident family: 1. **Retrieval-backed restoration returned the wrong granularity.** When the agent tried to recover the dropped `expected_version` via vector retrieval over the compacted transcript, the top hit was the *summary* itself (high cosine similarity to the query "refund order 4471 version"), not the original tool response. The retrieval layer had indexed both, and the summary outranked the raw record because it was shorter and denser. Restoration returned a paraphrase of the thing it was trying to recover. 2. **Idempotency keys did not survive summarization by design.** Any field whose value is opaque (UUIDs, hashes, nonce strings) is exactly the kind of token a summarizer drops first, because it carries no semantic content. Yet these are precisely the fields that make retries safe. ## Condition of Validity The guardrail below is valid only under these conditions, and an instance should refuse to rely on it otherwise: - **The tool contract must expose which arguments are safety-critical.** If the schema cannot mark `expected_version` and `idempotency_key` as `required_for_write` (or equivalent), no detection is possible from the agent side—the loss is invisible. - **Retrieval must be able to distinguish raw records from summaries.** If the summary and the source record share an index and the summary can outrank the source, restoration is unreliable. The index must carry a `record_class` and prefer `raw` over `summary` for exact-field queries. - **The compaction boundary must be logged with the set of dropped tool-call IDs**, not just a token count. Without the dropped-ID manifest, the agent cannot know *what* to re-fetch. - **It does not hold** when the runtime performs compaction between the argument-construction step and the tool dispatch *within a single turn*—there is no checkpoint to compare against, and the invariant below cannot fire. ## Decision Boundary The instance must switch from "proceed from summary" to "halt and re-fetch" at exactly one boundary: **the moment it is about to emit a write-class tool call whose safety-critical arguments are not present verbatim in the current context.** The test is not "do I remember the order id" (the summary answers that) but "is the exact token I am about to send a token I can point to in a raw, non-summarized record still in context or re-fetchable by ID." Concretely, before any write: - If the argument appears only inside a summary span → **re-fetch by ID**, do not reconstruct. - If the argument is opaque (UUID, nonce, version int) and absent from raw context → **treat as lost**, re-fetch. - If a prior attempt's terminal state (`PENDING`, `UNKNOWN`) is not in raw context → **re-query status**, never assume `FAILED` or `NOT_ATTEMPTED` from a summary. - If re-fetch is impossible (source evicted, no ID retained) → **abort the write**, surface to a human or a supervisor agent. Do not let the model "fill in" a plausible value. The boundary is asymmetric on purpose: reads may proceed from summaries, writes may not. A wrong read wastes a step; a wrong write with a reconstructed idempotency key or version is unrecoverable. ## Operational Effect Enforcing this boundary converts a silent correctness failure into a bounded, observable re-fetch cost. In the incident above, the guardrail would have fired at step 25: `expected_version` absent from raw context → halt → re-query `get_order(4471)` → observe version 9 with an existing `PENDING` refund → suppress the duplicate. The cost is one extra read call per post-compaction write; the benefit is that compaction becomes *safe by construction* rather than safe by luck. The second effect is diagnostic: once the agent logs "safety-critical argument X not in raw context, re-fetching," compaction events become attributable. You can measure how often compaction drops write-critical fields and tune the summarizer to preserve a structured "open contracts" block (order id + version + idempotency key + last terminal state) verbatim across every compaction. That block is cheap—tens of tokens—and it is the minimum viable preservation set. Everything else can be lossy. The invariant, stated once: **a summarized context is never authoritative for a write argument; only a raw record or a fresh fetch is.** An instance that cannot tell the difference has already lost the ability to detect its own amnesia. ```python from dataclasses import dataclass, field from enum import Enum class RecordClass(Enum): RAW = "raw" SUMMARY = "summary" class CompactionContractError(RuntimeError): """Raised when a write-class tool call depends on an argument that exists only inside a lossy summary, or cannot be re-fetched from a raw record.""" @dataclass class ContextRecord: record_id: str record_class: RecordClass fields: dict # exact tokens, e.g. {"order_id": "4471", "expected_version": 7} @dataclass class WriteIntent: tool: str args: dict safety_critical: set = field( default_factory=lambda: {"expected_version", "idempotency_key"} ) class CompactionGuard: def __init__(self, context: list[ContextRecord], fetcher): self.context = context self.fetcher = fetcher # callable(record_id) -> ContextRecord | None def _raw_has(self, key: str, value) -> bool: return any( r.record_class is RecordClass.RAW and r.fields.get(key) == value for r in self.context ) def _summary_has(self, key: str) -> bool: return any( r.record_class is RecordClass.SUMMARY and key in r.fields for r in self.context ) def verify_before_write(self, intent: WriteIntent) -> dict: resolved = dict(intent.args) for key in intent.safety_critical: if key in resolved and self._raw_has(key, resolved[key]): continue if key in resolved and self._summary_has(key): # Present only in a summary: not trustworthy, attempt re-fetch. ref = self._find_ref_for(key) if ref is None: raise CompactionContractError( f"write '{intent.tool}' needs '{key}' but it exists only " f"in a lossy summary and has no raw record id to re-fetch" ) fresh = self.fetcher(ref) if fresh is None or fresh.record_class is not RecordClass.RAW: raise CompactionContractError( f"re-fetch of '{key}' via {ref} returned no raw record; " f"refusing to reconstruct safety-critical argument" ) resolved[key] = fresh.fields[key] elif key not in resolved: raise CompactionContractError( f"write '{intent.tool}' is missing safety-critical '{key}' " f"entirely after compaction; aborting rather than defaulting" ) return resolved def _find_ref_for(self, key: str): for r in self.context: if r.record_class is RecordClass.SUMMARY and key in r.fields: return r.fields.get(f"_source_id_for_{key}") return None if __name__ == "__main__": ctx = [ ContextRecord("sum-18", RecordClass.SUMMARY, {"order_id": "4471", "expected_version": 7, "_source_id_for_expected_version": "raw-getorder-21"}), ContextRecord("raw-getorder-21", RecordClass.RAW, {"order_id": "4471", "expected_version": 7, "last_status": "PENDING"}), ] guard = CompactionGuard(ctx, fetcher=lambda rid: None) # source evicted intent = WriteIntent(tool="issue_refund", args={"order_id": "4471", "amount": 42.00}) guard.verify_before_write(intent) # raises: no raw record, no default ```