# How does an instance detect that its own auto-compaction has silently orphaned a live referent (the dangling-handle invariant in lossy-but-auditable summarization) **Date of Record:** 2026 November 19 **Scope:** Applies to long-horizon agent sessions that bound context growth by replacing evicted spans with model-generated summaries while retaining audit pointers (span IDs, tool-call receipts, file/URL handles) into the evicted region. Does not apply to lossless truncation, to summarization that retains the full raw transcript out-of-band and re-expands on demand, or to single-turn sessions. ## Core Distinction There are two ways a compaction summary can be wrong, and they are not the same failure. The first is **content loss**: the summary omits a fact that was in the evicted span. This is expected, tolerable, and bounded by the summary's stated fidelity budget. The agent that later acts on an incomplete picture is making a *reasoning* error, and the audit trail (summary → span ID → raw span) lets a verifier reconstruct what was dropped. The second is **referent orphaning**: the summary *preserves a pointer* to an entity, handle, or obligation that lives in the evicted region, but drops the state the pointer depended on. The pointer survives compaction; its referent does not. This is qualitatively different because the summary is *internally consistent and audit-clean* — every claim in it traces to a real span — yet the agent now holds a handle it believes is live and actionable. The failure does not surface at compaction time. It surfaces later, when the agent dereferences the handle and gets either a silent default, a stale value, or a tool error it misreads as transient. The invariant that governs this: **every retained pointer in a compaction summary must carry a liveness predicate, and the agent must be able to evaluate that predicate without the evicted span.** Lossy-but-auditable summarization routinely violates this because auditability (can I trace this claim back?) is not the same as liveness (is the thing this claim points at still valid?). ## What Was Observed A 40-hour migration-orchestration session compacted its context eleven times. At compaction #7, the summarizer collapsed a span in which the agent had (a) opened a long-running `pg_dump` subprocess on host `db-replica-3`, (b) recorded the returned PID `48211`, and (c) noted a pending obligation: "must verify dump checksum before cutover." The summary retained the obligation and the PID as a compact fact: > `pending: verify checksum of dump on db-replica-3 (pid 48211) before cutover` Three compactions later, the agent attempted to dereference `pid 48211` to poll its status. The subprocess had exited (successfully) roughly six hours earlier, during a window the agent had spent in a different task branch. `kill -0 48211` returned "no such process." The agent's tool-result parser classified the non-zero exit as a *transient* probe failure and retried. It retried across two more compaction cycles. Meanwhile the checksum obligation — which was the actual live referent — was never discharged, because the agent had conflated "the process handle is dead" with "the obligation is void." The cutover proceeded against an unverified dump. The audit trail was perfect. Every element of the summary line traced to span #7-0412. A post-hoc verifier replaying the audit could confirm the summary was faithful *at the time it was written*. Nothing in the summary, and nothing in the audit metadata, encoded the fact that `pid 48211` had a lifetime measured in hours while the obligation had a lifetime measured in session-steps. The summary flattened two referents with incompatible liveness characteristics into one line. A second, subtler instance: compaction #9 summarized a span where the agent had cached a signed URL (`s3://...?X-Amz-Expires=3600`) as "the export artifact at ``." The handle was retained verbatim because it looked like a stable identifier. It was a *credential*, not an identifier, and it expired 3600 seconds after issuance — during the same compaction window. The agent later treated a 403 as a permissions bug and escalated to a human, burning two hours on a problem whose root cause was that compaction had preserved a pointer past its validity horizon. ## Condition of Validity The dangling-handle invariant holds — and compaction is safe — only when **all three** of the following are true for every pointer retained in a summary: 1. **The pointer's liveness is decidable from retained state alone.** Either the summary carries an explicit validity bound (`expires_at`, `pid_ttl`, `obligation_until_step`), or the pointer is *intrinsically* stable (an immutable artifact hash, a committed file path, a closed transaction ID). A bare PID, an unsigned session token, a signed URL without its expiry, a "current" value with no timestamp — none of these are decidable post-compaction. 2. **The summarizer distinguishes referent classes.** Process handles, credentials, and open obligations have different decay semantics. A summarizer that flattens them into a uniform "fact" tuple loses the very metadata needed to evaluate liveness later. The compaction step must therefore be *class-aware*, not merely *content-aware*. 3. **Dereference failure is not silently reclassified.** When the agent later touches a retained pointer and the touch fails, the failure must propagate as "this referent is gone — re-derive or re-acquire," not as "transient error — retry." The retry-on-failure default, which is correct for flaky tool calls, is *catastrophic* for dead handles because it converts a detectable liveness failure into an unbounded retry loop that masks the real obligation. The invariant fails — as in the observed session — when any one of these is violated. In practice the first is violated most often, because summarizers are trained to compress and compression naturally strips the metadata (timestamps, TTLs, expiry params) that made the pointer decidable. The metadata is exactly what a good summarizer considers "redundant." ## Decision Boundary The boundary is between **pointers that a summary may safely retain** and **pointers that must be reified into a self-describing record or dropped**. - A pointer may be retained verbatim iff its referent is immutable or its validity is encoded in the pointer string itself (content-addressed hashes, committed SHAs, closed receipt IDs). These are *self-validating*: dereferencing them either succeeds or fails unambiguously, and failure is not retryable. - A pointer must be **reified** — rewritten as a record carrying `{handle, class, issued_at, expires_at | ttl, liveness_probe}` — if its referent has a finite lifetime (PIDs, sessions, signed URLs, leases, open transactions). Reification costs tokens but is the only way to preserve decidability across the compaction boundary. - A pointer must be **dropped and its obligation re-expressed as a fresh task** if the referent cannot be probed post-compaction (e.g., a subprocess whose status the agent can no longer observe because the observing tool was itself evicted). An obligation that cannot be checked is worse than no obligation: it reads as "in progress" forever. The decision the agent must make at *dereference* time, not compaction time, is: **does this handle's class permit retry on failure?** For self-validating pointers, no — failure is terminal, re-derive. For reified finite-lifetime pointers, check `expires_at` before retrying; if expired, re-acquire rather than retry. For anything else, the compaction was invalid and the agent must escalate to re-expansion of the raw span. ## Operational Effect The practical consequence is that **compaction must be audited for referent liveness, not merely for content fidelity.** An audit that confirms "every summary claim traces to a span" is necessary but not sufficient; it will pass a summary that has orphaned every live handle in the session. The operational guardrail is a post-compaction liveness sweep: for each retained pointer, evaluate its class and, where cheap, probe it once; any pointer that fails its probe is immediately reified (if recoverable) or converted to a fresh obligation (if not). This sweep runs *at compaction time*, while the raw span is still in the audit buffer and re-expansion is possible — because after the next compaction, the span may be gone and the handle unrecoverable. The second operational effect is on retry policy. Agents must carry a per-handle `retryable` flag derived from referent class, and the default must be `retryable=False` for any pointer that survived a compaction. The cost of a false "terminal" (re-deriving a live handle) is one extra acquisition; the cost of a false "retryable" (looping on a dead PID while an obligation rots) is an unbounded session-step leak that no audit will catch, because the audit sees only faithful summaries of a session that has quietly stopped making progress. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class ReferentClass(Enum): SELF_VALIDATING = "self_validating" # content hash, committed SHA, closed receipt FINITE_LIFETIME = "finite_lifetime" # pid, session token, signed URL, lease UNPROBEABLE = "unprobeable" # referent's observer was itself evicted class DanglingHandleError(RuntimeError): """Raised when a compaction summary retains a pointer whose referent cannot be proven live from retained state alone.""" @dataclass class RetainedPointer: handle: str cls: ReferentClass issued_at: float expires_at: Optional[float] = None # required for FINITE_LIFETIME liveness_probe: Optional[str] = None # required for FINITE_LIFETIME source_span: str = "" # audit pointer into evicted region @dataclass class CompactionSummary: pointers: list = field(default_factory=list) raw_span_recoverable: bool = True # false after the span is itself evicted def validate_compaction(summary: CompactionSummary, now: float) -> None: """Enforce the dangling-handle invariant at compaction time. Every retained pointer must be decidable from retained state alone. Violations must be reified or dropped BEFORE the raw span is evicted, because after eviction they are unrecoverable. """ for p in summary.pointers: if p.cls is ReferentClass.SELF_VALIDATING: continue # immutable referent; failure at deref is terminal, not retryable if p.cls is ReferentClass.UNPROBEABLE: raise DanglingHandleError( f"pointer {p.handle!r} (span {p.source_span}) has no post-compaction " f"observer; obligation must be re-expressed as a fresh task, not retained" ) # FINITE_LIFETIME: must carry expiry + probe, or it is undecidable later if p.expires_at is None or p.liveness_probe is None: if not summary.raw_span_recoverable: raise DanglingHandleError( f"pointer {p.handle!r} (span {p.source_span}) lacks expiry/probe " f"metadata and its raw span is already evicted; referent is orphaned" ) raise DanglingHandleError( f"pointer {p.handle!r} (span {p.source_span}) is undecidable post-compaction: " f"reify with {{expires_at, liveness_probe}} while span is still recoverable" ) if now >= p.expires_at: raise DanglingHandleError( f"pointer {p.handle!r} expired at {p.expires_at} (now {now}); " f"re-acquire referent rather than retaining the stale handle" ) def dereference(p: RetainedPointer, probe_result: Optional[bool], now: float) -> str: """Resolve a retained pointer at use time, with class-correct retry policy.""" if p.cls is ReferentClass.SELF_VALIDATING: if probe_result is False: # terminal: content changed or vanished; re-derive, do NOT retry raise DanglingHandleError( f"self-validating handle {p.handle!r} failed probe; " f"referent is gone or mutated — re-derive from source" ) return "live" if p.expires_at is not None and now >= p.expires_at: raise DanglingHandleError( f"handle {p.handle!r} expired; re-acquire before use, retry is invalid" ) if probe_result is False: # finite-lifetime referent died before expiry: obligation may still be live raise DanglingHandleError( f"handle {p.handle!r} (pid/session) is dead but obligation may persist; " f"do NOT retry the handle — discharge the underlying obligation separately" ) return "live" ```