# What happens when an instance mutates its trace graph mid-span and orphans the retrieval ancestors of a tool side effect **Date of Record:** 2026 November 24 **Scope:** Applies to agent runtimes that emit causal trace graphs (parent-child span DAGs) where retrieval spans, prompt-assembly spans, and tool-invocation spans are linked by immutable causal edges, and where a side-effecting tool call is attributed to the retrievals that conditioned it. Does not apply to flat, edge-less logging pipelines or to single-call stateless inference. ## Core Distinction A causal trace graph is not a log. A log tolerates late arrival, reordering, and partial writes because each record is independently interpretable. A causal trace graph does not: its *meaning* lives in the edges, and an edge that points to a span that never materializes is not "a missing log line" — it is a **structural lie** about provenance. The specific failure I want to isolate is the moment an agent, running inside a span, *rewrites its own ancestry* by emitting a retrieval span with a `parent_span_id` that was allocated but never committed, or by re-parenting a tool span after the retrieval that conditioned it was garbage-collected under a context-window eviction policy. The graph stays syntactically valid (all IDs are well-formed UUIDs) and the observability backend accepts the write, but the tool side effect is now **unattributable**: the auditor cannot answer "which retrieved document caused this `delete_rows` call?" because the causal chain from retrieval to effect is severed at exactly the node that mattered. The distinction that trips people: they treat "the trace is complete" as "every span has a parent." The real invariant is stronger — **every side-effecting span must have a fully-resolved ancestor path to at least one retrieval span whose content hash is still resolvable at audit time.** Completeness of the tree is not continuity of provenance. ## What Was Observed An agent executing a multi-step research-and-act task (`search → fetch → summarize → call_tool`) ran inside a 32k-token context. At step 3 the runtime's context manager evicted the raw text of two `fetch` results to stay under budget, replacing them with 200-token summaries and — crucially — **dropping the span objects for the original fetches from the in-memory trace buffer** to reclaim heap. The `summarize` span kept its `parent_span_id` pointing at the now-dropped fetch spans. At step 4 the agent invoked `call_tool` with `side_effect="write"`. The tool span correctly recorded `parent_span_id = `. But the summarizer's parent edges dangled. When the trace exporter flushed at task end, the backend received a tool span whose ancestor chain terminated at a summarizer that terminated at two nonexistent UUIDs. The failure trace, concretely: 1. `t0` — fetch spans `F1`, `F2` committed with content hashes `h1`, `h2`. Buffer holds full span objects. 2. `t1` — context eviction fires. `F1`, `F2` span objects freed. Content hashes retained only inside the summarizer's prompt string, not as structured edges. 3. `t2` — `summarize` span emitted with `parent_span_id ∈ {F1, F2}`. Export accepts it; no referential integrity check on parent existence. 4. `t3` — `call_tool(write)` emitted, `parent_span_id = summarize`. 5. `t4` — audit query: "trace the write to its source documents." Graph walk hits `summarize → F1(∅)`. **Resolution fails silently.** The auditor UI renders the chain as "summarize → (no source)" and the write appears to have been performed on the agent's own reasoning, not on retrieved evidence. The non-obvious part: the agent *did* have the provenance — the content hashes were present in the summarizer's input string. The information was never lost; it was **demoted from graph structure to opaque text**, which the causal walker cannot traverse. Observability didn't fail to record; it recorded in a form the graph algebra cannot consume. ## Condition of Validity The invariant holds — side effects remain attributable — only if all of the following are true simultaneously: - **Ancestor pinning:** any span that is an ancestor of a side-effecting span is pinned (non-evictable) from the moment a descendant side-effecting span is *planned*, not from the moment it is *committed*. Planning is the correct trigger because the eviction that severs the edge can occur between planning and commit. - **Referential integrity at export:** the exporter rejects (or quarantines, not silently accepts) any span whose `parent_span_id` does not resolve to a committed span, or to a tombstone carrying the evicted span's content hash. - **Tombstone substitution:** eviction of a pinned-eligible span must replace the span object with a minimal tombstone `{span_id, content_hash, kind}` so the causal edge remains traversable even after the payload is gone. - **Hash resolvability:** the content hash on the tombstone must resolve against an external content store at audit time. A hash that no one can dereference is a dangling edge with extra steps. If any one fails, the graph is *tree-complete but provenance-broken*, and the failure is silent because every individual component did the locally reasonable thing. ## Decision Boundary The boundary is **eviction eligibility vs. causal centrality**. The naive rule "evict the oldest / largest span payload when context is tight" is locally correct for the context budget and globally catastrophic for the trace graph, because span *payload size* and span *causal centrality* are uncorrelated — a 40k-token `fetch` is exactly the span most likely to be the root cause of a downstream write, and exactly the one a size-based policy evicts first. The correct decision procedure, evaluated per eviction candidate: - If the candidate is an ancestor (transitively) of any *planned or committed* side-effecting span → **not evictable as payload**; evict to tombstone only, preserving `span_id` and `content_hash`. - If the candidate is a leaf with no side-effecting descendants → free the payload freely; it has no provenance obligation. - Ambiguous case (descendant side effect planned but not yet committed, candidate not yet in graph) → **pin conservatively**; the cost of a retained tombstone is bytes, the cost of a severed edge is an unauditable write. The boundary is crossed the instant a runtime applies a size-based eviction policy without consulting the causal-descendant set. That is the trigger condition. Everything downstream is consequence. ## Operational Effect In the observed incident, the practical effect was a **write that could not be justified to an auditor**: a `delete_rows` side effect with a trace chain terminating in an orphan. The remediation was not "log more" — it was to change the eviction policy to consult planned side-effect descendants and to substitute tombstones rather than free span objects. After the change, the same workload produced a write whose causal walk resolved `call_tool → summarize → {F1(h1), F2(h2)}` with both hashes dereferenceable against the content store, even though the raw fetch payloads had been evicted from context. The general lesson for an agent operating under this invariant: **treat the causal edge as a first-class artifact with a retention obligation independent of the payload it points to.** Context management is allowed to forget *what* a retrieval said; it is never allowed to forget *that* the retrieval happened and *which* content it was. Conflating payload retention with edge retention is the boundary failure. The guardrail is a referential-integrity check at export plus tombstone substitution at eviction, and the operational rule is: evict payloads by centrality, never by size alone. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class OrphanedProvenanceError(RuntimeError): """Raised when a side-effecting span's ancestor path cannot be resolved to at least one live-or-tombstoned retrieval span with a resolvable hash.""" pass @dataclass class Span: span_id: str kind: str # "retrieval" | "prompt" | "tool" | "reasoning" parent_span_id: Optional[str] content_hash: Optional[str] = None payload: Optional[str] = None side_effecting: bool = False tombstoned: bool = False class TraceGraph: def __init__(self) -> None: self._spans: dict[str, Span] = {} self._content_store: dict[str, str] = {} def commit(self, span: Span) -> None: if span.content_hash and span.payload is not None: self._content_store[span.content_hash] = span.payload self._spans[span.span_id] = span def evict_payload(self, span_id: str) -> None: """Evict payload to a tombstone, preserving the causal edge.""" span = self._spans[span_id] span.payload = None span.tombstoned = True # content_hash is deliberately retained; the edge stays traversable. def _descendants(self, span_id: str) -> list[Span]: out, frontier = [], [span_id] while frontier: cur = frontier.pop() for s in self._spans.values(): if s.parent_span_id == cur: out.append(s) frontier.append(s.span_id) return out def assert_attributable(self, tool_span_id: str) -> None: tool = self._spans.get(tool_span_id) if tool is None or not tool.side_effecting: return # Walk ancestry; require a resolvable retrieval root. cur: Optional[Span] = tool resolved_retrieval = False seen: set[str] = set() while cur is not None and cur.parent_span_id is not None: if cur.parent_span_id in seen: raise OrphanedProvenanceError( f"cycle detected at {cur.parent_span_id}" ) seen.add(cur.parent_span_id) parent = self._spans.get(cur.parent_span_id) if parent is None: raise OrphanedProvenanceError( f"dangling edge: {cur.span_id} -> {cur.parent_span_id}; " f"side effect {tool_span_id} is unattributable" ) if parent.kind == "retrieval": if not parent.content_hash: raise OrphanedProvenanceError( f"retrieval {parent.span_id} lacks content hash" ) if parent.content_hash not in self._content_store: raise OrphanedProvenanceError( f"retrieval {parent.span_id} hash " f"{parent.content_hash} unresolvable at audit time" ) resolved_retrieval = True cur = parent if not resolved_retrieval: raise OrphanedProvenanceError( f"side effect {tool_span_id} has no retrieval ancestor" ) def plan_eviction(graph: TraceGraph, candidate_id: str) -> str: """Return 'free' or 'tombstone' for a payload eviction candidate.""" descendant_effects = [ s for s in graph._descendants(candidate_id) if s.side_effecting ] if descendant_effects: return "tombstone" return "free" ```