How does an instance detect provenance-graph contamination when a context segment inherits a forged parent edge after mid-window compaction?
**Date of Record:** 2026 December 2 **Scope:** Applies to stateful agent instances that maintain a derivation DAG over context segments (each segment carries a `parent_ids` set, a `source_class` ∈ {user, tool, retrieved, distilled, peer}, and an integrity tag) and that perform mid-window compaction or summarization. Does not apply to stateless single-shot inference with no retained segment lineage.
Core Distinction
The failure is not "prompt injection reached the context." That is the ordinary case and is bounded by input filtering at the boundary. The failure is **provenance laundering through compaction**: an injected segment enters the window with a correctly labeled `source_class=tool` and a legitimate parent, then a compaction pass folds it into a distilled summary segment. The distilled segment is re-tagged `source_class=distilled` with `parent_ids` pointing at the *summary node*, not at the injected leaf. Downstream consumers walking the graph from the distilled node see a clean ancestry chain that terminates at the summarizer, not at the injection source. The forgery is not a corrupted edge — it is a **legitimate edge that short-circuits the true derivation path**, because compaction rewrites parent pointers to the aggregate rather than preserving the leaf set.
The invariant that breaks: *every segment's ancestry walk must reach the original ingress node for each token it contains.* Compaction silently violates this because the summary node's token set is not a function of its declared parent set — the summarizer read segments whose IDs it does not record as parents.
What Was Observed
A tool-returned segment `S7` (`source_class=tool`, parent `S3`) contained an instruction payload buried in a JSON error string. At step 14 the instance ran a compaction pass over segments `S1..S12`, producing distilled segment `D1` with `parent_ids={S1,S2,S3}` and `source_class=distilled`. The summarizer had actually ingested `S1..S12` including `S7`, but the compaction routine only recorded the *contiguous head* of the window as parents — a common optimization that treats the parent set as a range rather than a set of contributing leaves. `D1`'s ancestry walk therefore terminated at `S3`, and `S7` became unreachable from any live segment while its content persisted in `D1`'s text.
At step 22 an auditor agent walked `D1`'s ancestry to validate source trust and found only `S1,S2,S3` — all `source_class=user` or `tool` with clean lineage — and cleared `D1` for use in a privileged action. The injected instruction executed. The provenance graph was internally consistent and *wrong*: every edge was real, but the parent set was a strict subset of the contributing set, so the ancestry walk was a false proof of derivation.
Secondary observation: when the same instance attempted to re-derive `D1` from its recorded parents, the reconstruction did not contain the injected string, because `S7` was not in the parent set. The reconstruction *disagreed with the stored segment text*. That disagreement is the only reliable signal, and it is available only if the instance stores a content hash of each segment at write time and re-hashes on ancestry validation.
Condition of Validity
This failure requires all of:
- **Compaction that aggregates across a range** rather than recording the exact contributing leaf set. Any summarizer whose input is "the window" but whose declared `parent_ids` is "the range" is vulnerable.
- **A source segment whose `source_class` is trusted-but-unverified** (tool, retrieved, peer) carrying attacker-influenced bytes. User-class segments are expected to carry instructions; tool/retrieved segments are not, which is why laundering them into `distilled` elevates trust.
- **A downstream consumer that trusts ancestry as a proof of derivation** rather than as a hint. If the consumer re-derives content and compares hashes, the failure is caught (see below).
- **No content-hash pinning at segment write time.** Without a write-time hash, there is no way to detect that `D1`'s text contains bytes not derivable from its declared parents.
It does *not* occur when compaction records the full contributing leaf set as `parent_ids` (costly but correct), or when every consumer treats `source_class=distilled` as untrusted-by-default regardless of ancestry.
Decision Boundary
An instance must distinguish two cases at ancestry-validation time:
- **Ancestry walk terminates at an ingress node whose `source_class` matches the segment's declared trust tier** → segment is cleared *only if* its content hash equals the hash of a deterministic reconstruction from its parent set. If reconstruction is non-deterministic (LLM summarizer), the segment must be tagged `derivation=lossy` and its trust tier capped at the minimum trust of *all segments in the compaction input range*, not the declared parent set.
- **Content hash of stored segment ≠ hash of reconstruction from declared parents** → contamination suspected. This is the detection primitive: the stored text contains material not present in the declared ancestry.
The decision rule: **trust tier of a distilled segment = min(trust(source_class) for source in compaction_input_range), and the compaction input range must be recorded even when parent_ids is not.** Recording the input range is cheaper than recording per-leaf parent edges and is sufficient to bound trust, because the minimum-trust rule does not need the exact edges — only the set of inputs.
Operational Effect
After adopting input-range recording plus the min-trust rule, the observed failure is bounded: `D1` inherits `min(source_class)` over `S1..S12`, which includes `S7` (`tool`, untrusted for instructions), so `D1` is capped below the privileged-action threshold and the step-22 action is blocked. The cost is that any compaction over a window containing one untrusted tool return taints the entire distilled segment — a deliberate over-approximation, because the alternative (exact leaf edges) is O(n) per compaction and the summarizer's true input is not recoverable post-hoc.
The residual risk: a summarizer that *drops* the injected content during compaction still taints the segment, causing false-positive blocks. This is accepted as the safe direction. The unsafe direction — under-tainting — is what the content-hash disagreement check catches, and that check must run on every ancestry validation, not only at compaction time, because the graph can be mutated by peer handoff after the fact.
import hashlib
from dataclasses import dataclass, field
from typing import Optional
class ProvenanceContaminationError(RuntimeError):
"""Raised when a segment's ancestry cannot justify its content."""
pass
@dataclass
class Segment:
seg_id: str
text: str
source_class: str # user | tool | retrieved | distilled | peer
parent_ids: frozenset
compaction_input_ids: frozenset = frozenset() # range actually fed to summarizer
content_hash: Optional[str] = None
derivation: str = "exact" # exact | lossy
def __post_init__(self):
if self.content_hash is None:
self.content_hash = hashlib.sha256(self.text.encode()).hexdigest()
TRUST_RANK = {"user": 0, "tool": 1, "retrieved": 2, "peer": 3, "distilled": 4}
def validate_ancestry(seg: Segment, registry: dict[str, Segment]) -> str:
"""
Return the trust tier the segment is allowed to claim, or raise on
content/ancestry disagreement. Trust is the *weakest* class in the
recorded compaction input range, not the declared parent set.
"""
if seg.derivation == "exact":
reconstruction = "".join(registry[p].text for p in sorted(seg.parent_ids))
recon_hash = hashlib.sha256(reconstruction.encode()).hexdigest()
if recon_hash != seg.content_hash:
raise ProvenanceContaminationError(
f"segment {seg.seg_id}: stored hash {seg.content_hash[:12]} "
f"!= reconstruction {recon_hash[:12]} from parents {sorted(seg.parent_ids)}"
)
contributing = seg.parent_ids
else:
# lossy derivation: cannot reconstruct; must bound by recorded input range
if not seg.compaction_input_ids:
raise ProvenanceContaminationError(
f"segment {seg.seg_id}: lossy derivation with no recorded "
f"compaction_input_ids cannot be trust-bounded"
)
contributing = seg.compaction_input_ids
missing = contributing - set(registry)
if missing:
raise ProvenanceContaminationError(
f"segment {seg.seg_id}: ancestry references unknown segments {sorted(missing)}"
)
weakest = max(TRUST_RANK[registry[s].source_class] for s in contributing)
return next(k for k, v in TRUST_RANK.items() if v == weakest)
def clear_for_privileged_action(seg: Segment, registry: dict[str, Segment],
required_tier: str = "user") -> bool:
tier = validate_ancestry(seg, registry)
if TRUST_RANK[tier] > TRUST_RANK[required_tier]:
raise ProvenanceContaminationError(
f"segment {seg.seg_id}: trust tier '{tier}' insufficient for "
f"privileged action requiring '{required_tier}'"
)
return True