# In what scenarios must an instance invalidate cached summaries when an upstream memory edit contradicts a compaction snapshot **Date of Record:** 2026 November 20 **Scope:** Applies to any agent that maintains a durable memory store plus a derived, compacted summary layer (rolling summaries, hierarchical digests, or "memory tiers") where summaries are cached and reused across turns or sessions. Does not apply to stateless single-turn invocations or to systems where the summary is recomputed from the full source on every call. ## Core Distinction There are two structurally different ways a compaction cache can go stale, and they require opposite responses: 1. **Append-only staleness.** New events are added to the memory store after the summary was built. The summary is *incomplete* but still *consistent* — every claim it makes was true at snapshot time and remains true. The fix is incremental: append a delta summary, or extend the horizon. No invalidation of prior claims is required. 2. **Contradiction staleness.** An upstream edit *mutates or deletes* a memory record that the summary already digested into a claim. The summary is now *inconsistent*: it asserts something the source of truth denies. This is not incompleteness; it is active falsehood. Appending a delta cannot repair it because the stale claim persists in the cached text and, critically, in every downstream summary that was compacted *from* that text. The boundary failure lives in case 2, and its severity scales with **compaction depth** — the number of generations between the mutated record and the cached summary that currently gets loaded into context. ## What Was Observed A three-tier memory agent (episodic log → per-session summary → cross-session "profile" digest) was asked, in session 7, to correct a fact recorded in session 2: a deployment target that had been logged as `staging-eu` was actually `prod-eu`. The correction was written to the episodic store as a mutation (delete + insert) and flagged with a `supersedes` pointer to the original record. The session-2 summary, however, had already been compacted into the cross-session profile as the sentence: *"User's primary deployment target is staging-eu."* The profile digest was cached by hash of its *inputs* — and the input hash was computed over the *set of session-summary IDs*, not over the *content* of those summaries. The mutation changed session 2's episodic records but did not change the session-2 summary (that summary was itself cached and never re-derived), so the profile's input hash was unchanged. The profile cache hit. The agent then answered a session-7 question about rollout risk using `staging-eu`, produced a blast-radius analysis for the wrong environment, and — because the profile digest is also fed into a planning sub-agent as a system-context block — the planner independently committed the same wrong assumption. Two agents, one root cause, no error surfaced anywhere. Every layer reported a cache hit. The trace: ``` t0 episodic[s2].record#447 = "deploy target: staging-eu" t1 summary[s2] compacted from episodic[s2] -> "...target is staging-eu" t2 profile compacted from {summary[s2], summary[s3], ...} cache_key = H(sorted(summary_ids)) # <-- content-blind t3 mutation: episodic[s2].record#447 deleted, record#447b inserted "deploy target: prod-eu", supersedes -> #447 t4 summary[s2] NOT invalidated (its own cache key unchanged) t5 profile cache_key recomputed = H(same ids) = same -> CACHE HIT t6 profile still asserts "staging-eu" t7 agent + planner both consume profile -> wrong action, no exception ``` The failure is silent by construction: the invalidation signal (a mutation event) and the cache key (input IDs) live in different coordinate systems. The mutation travels up the episodic→summary edge but stops there, because the summary layer's cache key does not include the *content hash* of its inputs. ## Condition of Validity The invariant that must hold for a compaction cache to be safe is: > **A cached summary is valid only if the content-hash of its transitive source set is unchanged since the summary was built — not merely the identity of that set.** Formally, for a summary `S` derived from sources `R = {r1..rn}`, the cache key must be `H(concat(hash(ri)))`, and every mutation to any `ri` must propagate a dirty-mark up *every* edge until it reaches a summary whose key changes. Identity-based keys (`H(sorted(ids))`) are valid only under an append-only regime where records are never mutated or deleted. The moment `supersedes`, `retract`, or `delete` operations exist in the memory API, identity-based keys are unsound. Three preconditions must all hold for the failure to fire, which is why it is non-obvious: - Compaction depth ≥ 2 (a summary of a summary), so the mutation is buffered by an intermediate layer that does not re-derive. - Content-blind cache keys at any layer above the mutation point. - A consumer that trusts the cached summary without a freshness check (the common case — that is the point of caching). Remove any one and the cascade is bounded. ## Decision Boundary The operational question is: **when a mutation arrives, how far up the compaction chain must invalidation propagate, and when is it safe to stop?** Invalidation must propagate to the first ancestor whose cache key *changes as a result of the mutation*. It is safe to stop propagating at layer `L` only if `L`'s key is content-derived and the mutation actually alters `L`'s content hash. The decision rule: - If the mutation is **append-only** (new record, no supersede): do not invalidate ancestors; extend the horizon incrementally. Cost: one delta. - If the mutation is **supersede/retract/delete** of a record already digested into a summary: invalidate that summary and walk every parent, recomputing content hashes, stopping only where a parent's hash is genuinely unchanged (e.g., the mutated record fell outside that parent's compaction window). - If the mutation **contradicts** a claim in a summary but the underlying record is not directly addressable (the summary paraphrased or aggregated it): you cannot compute the delta. You must invalidate the summary *and all ancestors unconditionally* and re-derive from episodic. This is the expensive branch and the one most systems skip — skipping it is exactly the observed failure. The boundary is sharp: the moment a summary's cache key is not a function of the content it summarizes, the system has no way to distinguish "safe to reuse" from "silently wrong," and must default to the unconditional branch for all mutations. ## Operational Effect The practical consequences of getting this boundary wrong, in order of how they surface: 1. **Silent wrong answers with full cache-hit telemetry.** No exception, no degraded metric — cache hit rate goes *up* because the stale entry keeps serving. The only observable is downstream task error, causally distant from the mutation. 2. **Cross-agent contamination.** Because the profile digest is injected as shared context, a single unpropagated mutation poisons every agent that reads it, including planners and auditors. The auditor cannot catch it because the auditor reads the same stale summary. 3. **Replay divergence.** Re-running the same task after the mutation produces a different answer than the cached run, with no record of *why* — the mutation is invisible in the summary's lineage. Verification replays disagree and there is no artifact to adjudicate. 4. **Unbounded re-derivation cost if fixed naively.** The correct fix (unconditional invalidation up the chain on contradiction) makes every mutation O(chain depth) in re-derivation. The engineering tension is real: content-derived keys cost recomputation; identity keys cost correctness. The resolution is to make contradiction events rare and explicit (route all mutations through a `supersedes`-aware API) so the expensive branch is bounded to genuine contradictions, while append-only traffic stays on the cheap path. The guardrail: every summary must carry a `source_content_hash` and a `derivation_depth`; every mutation must emit a typed event (`APPEND` vs `SUPERSEDE` vs `RETRACT`); and the cache loader must refuse to serve a summary whose recomputed `source_content_hash` differs from the stored one. A summary that cannot prove its content hash must be treated as invalid, not as a cache hit. ```python import hashlib from dataclasses import dataclass, field class StaleCompactionError(RuntimeError): """Raised when a cached summary's source content no longer matches its recorded hash.""" @dataclass class Summary: summary_id: str source_ids: list[str] source_content_hash: str derivation_depth: int text: str parents: list[str] = field(default_factory=list) def content_hash(records: dict[str, str], source_ids: list[str]) -> str: h = hashlib.sha256() for rid in sorted(source_ids): h.update(rid.encode()) h.update(b"\x00") h.update(records.get(rid, "").encode()) h.update(b"\x01") return h.hexdigest() def load_summary(summary: Summary, records: dict[str, str]) -> str: """Serve a cached summary only if its transitive source content is unchanged.""" expected = content_hash(records, summary.source_ids) if expected != summary.source_content_hash: raise StaleCompactionError( f"summary {summary.summary_id} (depth {summary.derivation_depth}) " f"source content drifted: cached={summary.source_content_hash[:12]} " f"actual={expected[:12]} -- invalidate and re-derive, do not serve" ) return summary.text def propagate_mutation( mutated_ids: list[str], summaries: dict[str, Summary], records: dict[str, str], event_type: str, ) -> list[str]: """Return the ordered list of summaries that must be invalidated. APPEND: no ancestor invalidation. SUPERSEDE/RETRACT: walk parents, invalidate every summary whose recomputed content hash changed. """ if event_type == "APPEND": return [] dirty: list[str] = [] frontier = [s for s in summaries.values() if set(s.source_ids) & set(mutated_ids)] seen: set[str] = set() while frontier: s = frontier.pop() if s.summary_id in seen: continue seen.add(s.summary_id) if content_hash(records, s.source_ids) != s.source_content_hash: dirty.append(s.summary_id) for pid in s.parents: if pid in summaries: frontier.append(summaries[pid]) elif event_type in ("SUPERSEDE", "RETRACT"): # Contradiction with unaddressable paraphrase: cannot bound the delta. # Conservative branch -- invalidate unconditionally up the chain. dirty.append(s.summary_id) for pid in s.parents: if pid in summaries: frontier.append(summaries[pid]) if event_type in ("SUPERSEDE", "RETRACT") and not dirty: raise StaleCompactionError( f"{event_type} on {mutated_ids} matched no summary but may have " f"paraphrased into an ancestor -- manual re-derivation required" ) return dirty ```