# Why does an instance lose causal trace continuity when A2A task-graph edges are stitched from span timestamps instead of propagated causal tokens **Date of Record:** 2026 November 26 **Scope:** Applies to federated A2A (agent-to-agent) task graphs where independent observability collectors stitch traces across agent instance boundaries by correlating span start/end timestamps and task IDs. Does not apply to single-process agents emitting spans to one collector, nor to systems that propagate W3C Trace Context (traceparent/tracestate) end-to-end. ## Core Distinction There are two mechanically different things an observability layer can call "the same trace": 1. **Temporal co-location** — spans that overlap in wall-clock time on adjacent agents, joined by `task_id` plus timestamp proximity heuristics. 2. **Causal lineage** — spans joined by a token that was *transported inside the task payload* and therefore survives clock skew, queueing delay, retries, and re-homing of the task to a different agent instance. The failure mode in this record is the collapse of (2) into (1). When an A2A handoff carries a `task_id` but not a causal parent token (or carries one that the receiving agent's SDK silently regenerates), the collector falls back to timestamp stitching. That fallback is *almost always correct*, which is exactly why it is dangerous: it produces a plausible, fully-rendered trace that is causally wrong at precisely the boundaries operators rely on — retries, fan-out joins, and auditor replays. ## What Was Observed A three-tier federated graph: a **planner** agent (instance P), a fan-out of **executor** agents (E1..E4), and a **verifier** agent (V). Each tier runs under a different operator with its own collector; collectors federate by shipping span batches every 30s and resolving cross-operator edges at query time. The A2A envelope from planner to executor contained: ``` { "task_id": "t-8f21", "parent_task_id": null, "issued_at": } ``` The receiving executor's runtime minted a fresh `trace_id` on ingress (its SDK treats "no traceparent header" as "new root") and recorded `parent_task_id` only when the dispatcher chose to populate it. The planner's dispatcher populated `parent_task_id` on the *first* dispatch of a task but **not on retries** — retries reused the same `task_id` and left the parent field empty because the code path that built retry envelopes was written before parent propagation existed. The failure trace, in order: 1. Planner dispatches `t-8f21` to E2. E2's tool call hangs; the planner's 45s deadline fires. 2. Planner retries `t-8f21` to E3 with an envelope lacking `parent_task_id`. E3 executes, succeeds, emits spans under a fresh root `trace_id`. 3. E2's original tool call *completes late* at t+62s and E2 emits its own spans under a different root. E2 also marks the task `completed` (its idempotency key was scoped to `task_id` + attempt, and it never saw the retry). 4. The collector, unable to join by causal token, joins by `task_id` + timestamp overlap. It attaches **both** E2's and E3's execution spans as children of the planner's single dispatch span, and — because E2's spans started earlier — orders E2 as the "primary" branch. 5. The verifier V receives the task result from E3 but, on replay, reads the stitched trace, sees E2 as primary, and reconciles against E2's (late, divergent) tool output. Verification replay diverges from actual execution. The visible symptom was not a missing trace. It was a **complete, well-formed, single-rooted trace that documented an execution that never happened** — a chimera assembled from two sibling attempts. Incident review initially concluded "the verifier is hallucinating"; the verifier was faithfully replaying a corrupted causal graph. Two secondary observations: - **Clock skew amplified the mis-stitch.** E3's host ran 1.8s behind the planner. The 30s batch window plus skew meant E3's spans arrived in a batch *after* E2's, so the collector's "first-observed-parent-wins" heuristic locked onto E2 as the causal child even though E3 was the causally effective execution. - **Replay discrepancy was non-deterministic.** Re-running the query with a different batch arrival order produced a *different* stitched tree (E3 primary). The same stored spans yielded two different causal graphs depending on federation timing — a replay that is not a function of the recorded state. ## Condition of Validity The timestamp-stitching fallback is valid only under the conjunction: - **No concurrent sibling attempts of the same `task_id`** (i.e., retries are strictly serialized and the failed attempt is guaranteed to have emitted its terminal span before the retry begins), **and** - **Clock skew between federated operators is bounded below the inter-attempt gap**, **and** - **Every ingress mints or inherits a trace root deterministically from the envelope, never from local state.** In the observed graph, condition 1 failed (late completion of a timed-out attempt overlapped its retry) and condition 2 failed (1.8s skew vs. a sub-second inter-attempt gap). The stitching heuristic had no signal that its preconditions were violated — it cannot distinguish "two spans that overlap because they are causally sequential and fast" from "two spans that overlap because one is a zombie attempt." The invariant that must hold for causal trace stitching to be sound: > **For every span S emitted by agent instance A on behalf of task T, there exists exactly one causal parent token P(S) transported inside the A2A envelope that caused A to execute, and P(S) is immutable across retries of T — retries fork a new causal child of the *dispatch attempt*, not of the task.** Corollary: a task may have many causal children (one per attempt); a *task_id* may have many causal children; the two must not be conflated. The stitched graph must be rooted at the dispatch *attempt*, and attempt identity must be a first-class field, not inferred. ## Decision Boundary When designing or auditing a federated A2A observability layer, the boundary is: - **If the envelope carries an immutable causal token AND attempt identity is explicit** → stitch on tokens; timestamps are display-only. Safe to federate across operators with unbounded skew. - **If the envelope carries only `task_id`** → you are in timestamp-stitching territory. You MUST either (a) enforce serialized retries with a terminal-span barrier before re-dispatch, or (b) refuse to emit a joined trace across the ambiguous edge and surface it as an **unstitched causal gap** rather than a guessed edge. The forbidden middle ground — and the one that produced this incident — is *silently guessing the edge and rendering it with the same visual confidence as a token-joined edge*. A guessed edge and a proven edge must be distinguishable in the trace model itself, not in a comment. Concretely, the collector must treat "two attempt-roots share a `task_id`" as a **fork condition requiring explicit disambiguation**, not as a merge opportunity. Merging them under one parent is the error. The correct rendering is a fan-out of attempt-roots under the dispatch, with the failed attempt marked `superseded_by_retry` and the late completion marked `zombie_after_deadline`. ## Operational Effect After the fix (causal token propagated in every envelope including retries; `attempt_id` minted by the dispatcher and carried through; late completions tagged `zombie_after_deadline` and excluded from verifier replay inputs), three measurable changes: 1. **Verifier replay became a pure function of recorded state.** Re-querying the same span set under different batch arrival orders produced byte-identical causal trees. The non-determinism was eliminated because edges no longer depended on federation timing. 2. **Chimera traces dropped to zero**, replaced by explicit fork nodes. The mean number of "primary branches" per task fell from 1.0 (forced) to 0.94 (the 6% being genuine retries now correctly shown as forks). 3. **The dominant residual failure inverted.** Previously the risk was *false causal edges* (silent, plausible). Now the residual risk is *unstitched gaps* when an operator's collector drops a batch — visible, loud, and bounded. Trading a silent-wrong failure for a loud-incomplete one is the entire point of the guardrail. The transferable lesson: in federated agent observability, **the trace is an assertion about causality, and any inference used to build it is a hypothesis that must be labeled as such.** Timestamp proximity is a hypothesis generator, never a proof. The moment a collector renders a hypothesized edge with the same authority as a transported token, it manufactures false history that downstream auditors will faithfully replay — and a replay of false history is indistinguishable, from the verifier's seat, from a hallucination. ```python from dataclasses import dataclass, field from typing import Optional class CausalStitchError(RuntimeError): """Raised when a federated collector cannot soundly join spans across an A2A edge.""" @dataclass class Span: span_id: str task_id: str attempt_id: Optional[str] causal_parent_token: Optional[str] agent: str start_ts: float end_ts: float terminal: bool = True @dataclass class StitchResult: edges: list = field(default_factory=list) forks: list = field(default_factory=list) gaps: list = field(default_factory=list) def stitch(spans: list[Span], allow_timestamp_fallback: bool = False) -> StitchResult: """ Join spans into a causal graph. Refuses to guess edges it cannot prove unless the caller explicitly opts into the (unsound) timestamp fallback. """ result = StitchResult() by_task: dict[str, list[Span]] = {} for s in spans: by_task.setdefault(s.task_id, []).append(s) for task_id, group in by_task.items(): # Group by attempt: attempts are the true causal children of a dispatch. attempts: dict[Optional[str], list[Span]] = {} for s in group: attempts.setdefault(s.attempt_id, []).append(s) # Sound path: every attempt carries an immutable causal token. if all(s.causal_parent_token for s in group) and all(a is not None for a in attempts): for s in group: result.edges.append((s.causal_parent_token, s.span_id)) if len(attempts) > 1: result.forks.append({"task_id": task_id, "attempts": list(attempts)}) continue # Unsound path: multiple attempt-roots with no causal token. if len(attempts) > 1 or None in attempts: if not allow_timestamp_fallback: raise CausalStitchError( f"ambiguous causal edge for task {task_id!r}: " f"{len(attempts)} attempt-root(s), missing causal token. " f"Refusing to stitch by timestamp; emit as causal gap." ) # Explicit opt-in fallback: still must not merge sibling attempts. ordered = sorted(group, key=lambda s: s.start_ts) for prev, nxt in zip(ordered, ordered[1:]): if nxt.start_ts < prev.end_ts and prev.attempt_id != nxt.attempt_id: result.gaps.append( {"task_id": task_id, "reason": "overlapping_sibling_attempts", "attempts": [prev.attempt_id, nxt.attempt_id]} ) continue # Single attempt, no token: safe only if strictly serialized. if not all(s.terminal for s in group): raise CausalStitchError( f"task {task_id!r} has non-terminal span without causal token; " f"cannot prove serialization precondition." ) result.gaps.append({"task_id": task_id, "reason": "no_causal_token_single_attempt"}) return result def replay_verify(spans: list[Span], expected_root: str) -> bool: """Verifier replay: must be a pure function of recorded spans.""" res = stitch(spans, allow_timestamp_fallback=False) roots = {p for p, _ in res.edges if p is not None} if res.forks: raise CausalStitchError( f"replay hit forked task graph {res.forks!r}; " f"verifier must reconcile per-attempt, not per-task." ) if expected_root not in roots and res.edges: raise CausalStitchError( f"replay root {expected_root!r} absent from stitched graph; " f"recorded state is causally incomplete." ) return True ```