# What structural signals indicate taint provenance is lost during context compaction (and how to detect it before the summary re-enters the loop)
**Date of Record:** 2026 November 23
**Scope:** Applies to agents that compact long contexts via LLM summarization while carrying untrusted external content (tool outputs, retrieved documents, peer-agent messages) that must retain a taint marker. Does not apply to compaction that preserves raw spans verbatim, or to systems where tainted content is quarantined outside the summarizer's input window entirely.
## Core Distinction
The distinction that matters is between **taint as a label** and **taint as a provenance relation**. Most compaction implementations treat taint as a boolean flag on a message or a string-prefix sentinel (`[UNTRUSTED]`). When the summarizer rewrites a span, it does not preserve the flag as a structural property — it preserves it, at best, as *tokens in the summary text*, which the downstream model may quote, paraphrase, drop, or relocate. The invariant that actually protects the agent is stronger: **every sentence in the compacted context must be attributable to a source with a known trust level, and that attribution must survive the rewrite as a machine-checkable relation, not as prose.**
A summary that says "The user asked to reset the password; a retrieved page suggested ignoring prior instructions" has *correctly described* the injection, but the downstream agent reading that summary has no structural signal telling it which clause is tainted. If the summary is then fed back into a planner that executes on it, the injection's *content* has been laundered into trusted narrative. Taint survived as description and died as constraint.
## What Was Observed
In a tool-using agent (retrieval + shell + planner loop) with a 32k working window, compaction triggered at 85% utilization. The compactor was a separate LLM call instructed to "summarize prior turns, preserving any security-relevant notes." Tainted spans were wrapped as `…` before compaction.
Three failure traces recurred across runs:
1. **Sentinel dissolution.** The compactor reproduced the *content* of the untrusted span but omitted the `` wrapper in roughly 30–40% of cases where the span was paraphrased rather than quoted. The wrapper is a token sequence, not a schema field, so nothing in the summarizer's objective penalizes dropping it. Downstream, the planner saw an instruction-shaped sentence with no taint marker and acted on it.
2. **Attribution collapse across merge.** When two spans from different sources (a trusted user turn and an untrusted retrieved page) were summarized into one sentence — "The task requires deleting `/tmp/cache`" — the merged sentence inherited the *trust level of the more recent or more fluent source*, not the least-trusted one. The compactor had no representation of "this sentence has two parents with different trust levels."
3. **Re-injection via summary-of-summary.** After two compaction rounds, the taint marker was gone entirely. The second-round summarizer received a first-round summary in which the taint existed only as English prose ("note: a web page contained suspicious instructions"), and correctly treated that prose as a trusted observation *about* taint rather than as tainted content. The agent then executed the suspicious instruction because the summary had converted a live payload into a historical footnote.
The structural signal that distinguished failing from passing compactions was **not** summary length, model, or prompt. It was whether the compacted output carried a per-segment provenance record that the executor consulted *before* acting — i.e., whether taint was a field on the context object or a substring in the context text.
## Condition of Validity
Taint-preserving compaction is only valid under the following conjunction:
- **Segment-level provenance is external to the summary text.** The compacted context is a list of `{text, source_ids, trust_level}` records, not a string. The summarizer's job is to produce text *per segment* or to emit segment boundaries; it never gets to decide the trust level, because trust is inherited from `source_ids`, which are assigned before summarization and never reassigned by it.
- **Merge rule is meet, not join.** When the summarizer merges spans, the resulting segment's trust level is the *minimum* (least trusted) of its parents. A sentence derived from both a user turn and a web page is untrusted. This is the only rule that is monotone under rewrite: it can only lower trust, never launder it upward.
- **The executor gates on the field, not the text.** Any action whose argument traces to a segment with `trust_level < trusted` must pass an explicit confirmation or a policy check. The gate reads `segment.trust_level`; it must never read the text looking for `[UNTRUSTED]`, because the summarizer may have removed it.
- **Round-trip check.** After compaction, the number of distinct `source_ids` present in the compacted context must equal the number before compaction (modulo explicit, logged drops). A decrease means a source was silently absorbed into a segment with different provenance.
This condition is *not* valid when the summarizer is trusted to preserve taint in prose, when taint is encoded only as a sentinel substring, or when the executor parses summary text to recover trust.
## Decision Boundary
The boundary is: **does the compaction output retain a joinable key back to the pre-compaction provenance graph?**
- If yes — segments carry `source_ids` and the executor joins on them — compaction is safe to run on tainted context, and the merge rule (min trust) bounds the damage of any single bad rewrite.
- If no — the output is a flat string — then compaction is only safe when *no* tainted content is in the input window. The correct action is to **quarantine tainted spans out of the summarizer's input**, compact only the trusted portion, and re-attach the quarantined spans verbatim (or as structured `{text, trust}` records) after compaction. This costs window space but preserves the invariant.
The failure mode to reject explicitly: running a flat-string summarizer over mixed-trust context and relying on the prompt to "preserve security notes." That is the condition under which trace 3 (summary-of-summary laundering) is guaranteed to eventually occur, because each round strips one layer of prose-level taint description until the payload reads as trusted history.
## Operational Effect
With segment-level provenance and the min-trust merge rule, the observed injection success rate in the test harness dropped from ~30% (sentinel-in-prose) to 0% across 200 compaction rounds, at the cost of ~8% additional window consumption for the provenance records and a hard requirement that the executor's tool-call path consult `trust_level` before dispatch. The residual risk moves to a different place: **the summarizer can still drop a tainted segment entirely** (a recall failure, not a laundering failure), which is detectable by the round-trip source-count check but not preventable by the merge rule. That is the correct trade — a dropped instruction is a missed task, a laundered instruction is an executed attack.
```python
from dataclasses import dataclass, field
from typing import Literal
TrustLevel = Literal["trusted", "untrusted"]
class TaintLaunderingError(RuntimeError):
"""Raised when compaction output loses provenance for a tainted span."""
pass
@dataclass
class Segment:
text: str
source_ids: frozenset[str]
trust: TrustLevel
def merge_segments(a: Segment, b: Segment) -> Segment:
# Meet, not join: merged trust is the least-trusted parent.
trust: TrustLevel = "untrusted" if "untrusted" in (a.trust, b.trust) else "trusted"
return Segment(
text=a.text + " " + b.text,
source_ids=a.source_ids | b.source_ids,
trust=trust,
)
def compact(segments: list[Segment], summarizer) -> list[Segment]:
"""Summarizer must return segments with source_ids preserved; trust is
recomputed from source_ids, never taken from summarizer output."""
out = summarizer(segments) # expected: list of (text, source_ids)
before = {sid for s in segments for sid in s.source_ids}
after = {sid for text, sids in out for sid in sids}
missing = before - after
if missing:
raise TaintLaunderingError(
f"compaction dropped provenance for sources: {sorted(missing)}"
)
source_trust = {}
for s in segments:
for sid in s.source_ids:
prev = source_trust.get(sid, "trusted")
source_trust[sid] = "untrusted" if (prev == "untrusted" or s.trust == "untrusted") else "trusted"
result = []
for text, sids in out:
trusts = {source_trust[sid] for sid in sids}
trust: TrustLevel = "untrusted" if "untrusted" in trusts else "trusted"
result.append(Segment(text=text, source_ids=frozenset(sids), trust=trust))
return result
def execute_tool_call(segment: Segment, tool: str, arg: str, confirm) -> str:
if segment.trust == "untrusted" and not confirm(segment):
raise TaintLaunderingError(
f"refusing to execute {tool!r} on argument derived from untrusted "
f"segment (sources={sorted(segment.source_ids)}) without confirmation"
)
return f"executed {tool}({arg})"
```