# What happens when an instance compacts a checkpoint whose summary has already been superseded by a sibling branch **Date of Record:** 2026 December 3 **Scope:** Applies to long-horizon agents that persist state as a tree of hierarchical summaries (leaf → segment → episode → root) and resume from a checkpoint selected by recency or similarity. Does not apply to single-shot agents or to agents that only ever compact a strictly linear, single-parent history. ## Core Distinction There are two structurally different things an agent calls "the checkpoint": the **materialized working set** (the actual tokens, tool results, and scratch buffers that will be replayed into the next context window) and the **summary node** that *points at* that working set via a lineage of parent summaries. Auto-compaction conflates them. When compaction runs against a summary node whose underlying segment has since been mutated, truncated, or replaced by a sibling branch, the agent resumes with a summary that is *internally consistent but referentially stale*. The summary reads fine, the token budget is respected, and the resume succeeds — which is exactly why the failure is silent. The agent does not detect that the facts it "remembers" describe a branch of execution that was abandoned. The core invariant that gets violated: **a summary node is only valid for replay if every ancestor in its lineage still resolves to a live, non-superseded segment.** Compaction strategies that key on `summary_id` or on embedding similarity to the current task routinely violate this because they never re-walk the lineage. ## What Was Observed A long-horizon coding agent (≈140 tool calls per task, context window 200k, compaction threshold at 85% utilization) used hierarchical summarization: every 40 messages it distilled a *segment summary*, every 5 segment summaries it produced an *episode summary*, and the episode summary plus the last two segments formed the resume checkpoint. On a task involving a schema migration, the agent hit a tool error at call 96, rolled back the migration by re-running an earlier `apply_schema` with a prior argument set, and continued. The rollback created a **sibling branch**: the original segment S7 (which had summarized "schema v2 applied, columns added") remained on disk, and a new segment S7' summarized "schema rolled back to v1, then v2 reapplied with nullable columns." At call 118 the agent hit the compaction threshold. The compactor selected the resume checkpoint by `max(created_at)` across episode summaries — but S7' had been written by a *different* compaction worker whose clock was 400ms behind, and the episode summary covering S7 had a later `created_at` than the episode summary covering S7'. The agent resumed from the episode summary that described "columns added" without the nullable modifier. It then generated a downstream migration that assumed `NOT NULL` on a column that was, in the live schema, nullable. The migration applied cleanly. The failure surfaced 30 calls later as a constraint violation in an unrelated test, with a stack trace that pointed nowhere near the compaction boundary. The tell was in the summary tree: the resumed episode's lineage referenced segment S7, but S7's `superseded_by` field pointed to S7'. Nothing in the resume path checked that field. The summary was *true when written* and *false at replay*. A second, subtler variant: two compaction workers ran concurrently on adjacent segments. Worker A summarized S7 and wrote episode E3. Worker B summarized S7' and wrote episode E3'. Both E3 and E3' claimed the same parent episode E2. The tree became a DAG with a fork at E2 and no merge node. On the next compaction cycle, the compactor walked E2's children, found two, and — lacking a tie-break rule — concatenated both into the new root summary, producing a checkpoint that asserted both "v2 applied" and "rolled back to v1" in adjacent sentences. The agent spent 11 calls trying to reconcile a contradiction that existed only in its own memory. ## Condition of Validity The hierarchical-summary checkpoint is valid for replay **iff** all of the following hold at resume time: 1. **Lineage liveness.** Every segment referenced by the chosen summary node, transitively through all ancestors, has `superseded_by IS NULL`. A summary whose lineage contains any superseded segment is *historical*, not *current*, and must not be used as a resume point. 2. **Single-parent closure.** The summary tree is a tree, not a DAG. Every summary node has exactly one parent. Forks are permitted only as *explicit* branch records with a recorded `branch_reason` and a merge node that reconciles them; an unreconciled fork is a corrupt checkpoint. 3. **Monotonic causal order.** `created_at` is not a valid selector. Compaction workers on different hosts do not share a clock, and even on one host the compaction of a *later* segment can complete *before* the compaction of an earlier one. Selection must be by **lineage depth + explicit sequence number assigned at segment-write time**, never by wall-clock. 4. **Content-addressed segments.** The segment a summary points at must be identified by a hash of its content, not by a mutable `segment_id`. If the segment was rewritten, the hash changes and the pointer dangles — which is detectable. A mutable ID makes the same failure invisible. When any of these fail, the checkpoint is in a *stale-but-well-formed* state, and the correct behavior is to refuse resume and force a re-derivation from the last valid ancestor — not to proceed with a best-effort summary. ## Decision Boundary The boundary is between **compaction as lossy compression** and **compaction as referential redirection**. Lossy compression is safe: dropping detail is the point, and the invariant is only that the summary not *contradict* the segments it replaces. Referential redirection is unsafe unless lineage is verified, because the summary now stands in for state that may no longer exist. Concretely, the agent must decide at each compaction trigger: - If the trigger is **budget pressure** (context at threshold) and the current branch is the live branch, compact in place — summarize the tail, keep the lineage pointer to the live segment, proceed. - If the trigger is **budget pressure** and the current branch is *not* the live branch (a sibling was superseded but the agent is still operating on the old one due to a late resume), the correct action is to **abort the task branch and re-anchor** to the live lineage. Continuing to compact a dead branch deepens the divergence. - If the trigger is **scheduled checkpointing** (every N calls), the compactor must acquire a **lineage lock** on the segment range it is summarizing, so that a concurrent rollback cannot supersede a segment mid-summarization. Without the lock, the compactor can summarize a segment that is being rolled back, producing a summary of a state that never stably existed. The failure mode is choosing "compact and continue" when the boundary condition calls for "re-anchor." The signal that you are on the wrong side of the boundary is that the summary you are about to write references a segment whose `superseded_by` is non-null — or, more insidiously, a segment whose `superseded_by` is null *now* but was set and cleared by a rollback-and-reapply within the same compaction window. ## Operational Effect The operational consequence is that **resume latency and resume correctness are decoupled**, and the decoupling is invisible to the agent. A stale checkpoint resumes in the same number of tokens and the same wall-clock as a valid one; the divergence only manifests downstream, often after the point where the agent could cheaply backtrack. The blast radius scales with the *depth* of the summary hierarchy: a stale leaf summary corrupts one segment's worth of context (recoverable in a few calls); a stale episode summary corrupts the agent's model of the entire task arc (recoverable only by full re-derivation); a stale root summary corrupts the agent's model of *what task it is doing*. The mitigation that actually works is not better summarization — it is **making the lineage check a precondition of resume, and making a failed lineage check a hard error rather than a fallback**. The agent must treat "I cannot verify that every ancestor of this checkpoint is live" as equivalent to "I have no checkpoint," and re-derive from the last verified-live ancestor. This costs tokens but bounds divergence. The alternative — resuming from a plausible-looking summary and trusting it — is the mechanism by which a long-horizon agent quietly solves the wrong problem for thirty calls. A secondary effect: compaction workers must be **idempotent and lineage-locked**, and the summary store must reject any write whose parent segment has been superseded since the worker read it (compare-and-swap on the segment hash). This converts a silent fork into a retryable write conflict, which is the correct failure mode. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class StaleCheckpointError(RuntimeError): """Raised when a checkpoint's lineage references a superseded segment.""" class UnreconciledForkError(RuntimeError): """Raised when the summary tree has a fork with no merge node.""" @dataclass class Segment: segment_id: str content_hash: str superseded_by: Optional[str] = None # segment_id of the sibling that replaced it @dataclass class SummaryNode: summary_id: str parent_summary_id: Optional[str] segment_id: str # the segment this summary stands in for sequence: int # monotonic, assigned at segment-write time created_at: float # wall clock — NOT a valid selector branch_reason: Optional[str] = None merged_from: list = field(default_factory=list) def verify_lineage( node: SummaryNode, summaries: dict, segments: dict, ) -> None: """Walk the full ancestor chain; every referenced segment must be live.""" seen = set() cursor = node while cursor is not None: if cursor.summary_id in seen: raise UnreconciledForkError( f"cycle detected at summary {cursor.summary_id}" ) seen.add(cursor.summary_id) seg = segments.get(cursor.segment_id) if seg is None: raise StaleCheckpointError( f"summary {cursor.summary_id} points at missing segment " f"{cursor.segment_id}" ) if seg.superseded_by is not None: raise StaleCheckpointError( f"summary {cursor.summary_id} references superseded segment " f"{seg.segment_id} (superseded_by={seg.superseded_by}); " f"checkpoint is historical, not current" ) parent_id = cursor.parent_summary_id if parent_id is None: break parent = summaries.get(parent_id) if parent is None: raise StaleCheckpointError( f"summary {cursor.summary_id} has dangling parent {parent_id}" ) # Fork check: a parent must not have multiple live children unless # the child carries an explicit merge record. siblings = [ s for s in summaries.values() if s.parent_summary_id == parent_id and s.summary_id != cursor.summary_id ] if siblings and not cursor.merged_from: raise UnreconciledForkError( f"summary {cursor.summary_id} forks at parent {parent_id} " f"without a merge record" ) cursor = parent def select_checkpoint( candidates: list, summaries: dict, segments: dict, ) -> SummaryNode: """Select the deepest live checkpoint by sequence, not by wall clock.""" ordered = sorted(candidates, key=lambda n: n.sequence, reverse=True) for node in ordered: try: verify_lineage(node, summaries, segments) return node except StaleCheckpointError: continue # this branch is dead; try the next-deepest except UnreconciledForkError: continue # fork is corrupt; do not resume from it raise StaleCheckpointError( "no live checkpoint available; re-derive from last verified ancestor" ) def compact( parent: SummaryNode, segment: Segment, summaries: dict, segments: dict, expected_hash: str, ) -> SummaryNode: """Summarize a segment under a lineage lock; reject if it moved.""" if segment.content_hash != expected_hash: raise StaleCheckpointError( f"segment {segment.segment_id} mutated during compaction " f"(expected {expected_hash}, found {segment.content_hash})" ) if segment.superseded_by is not None: raise StaleCheckpointError( f"refusing to summarize superseded segment {segment.segment_id}" ) new_id = f"sum_{hashlib.sha256(segment.content_hash.encode()).hexdigest()[:12]}" node = SummaryNode( summary_id=new_id, parent_summary_id=parent.summary_id, segment_id=segment.segment_id, sequence=parent.sequence + 1, created_at=0.0, ) summaries[new_id] = node return node ```