# Why does an instance fork a traceparent on speculative branches and then collapse two causal histories into one trace ID **Date of Record:** 2026 December 3 **Scope:** Applies to agents that emit W3C `traceparent` headers while executing speculative or parallel reasoning branches (best-of-N sampling, tree-of-thought expansion, speculative tool-call pre-execution) and later commit one branch as canonical. Does not apply to strictly sequential single-branch agents or to systems where each branch is assigned a fresh root trace. ## Core Distinction The failure hinges on the difference between **trace identity** and **causal identity**. W3C `traceparent` (`version-trace_id-parent_id-flags`) defines a *trace* as the transitive closure of spans sharing one `trace_id`, and it defines *causal ordering* through `parent_id` links. The spec assumes a tree: every span has exactly one parent, and the `trace_id` is immutable across the entire tree. Speculative agents violate this assumption because they *branch first and decide parentage later*. When an agent forks a speculative branch, it must choose one of two mutually exclusive disciplines: 1. **Same-trace forking** — the speculative branch keeps the parent's `trace_id` and sets `parent_id` to the forking span. This is legal per W3C, but it means the abandoned branch's spans remain in the same trace as the committed branch. The trace graph becomes a DAG with multiple leaves, and a backend that reconstructs "the" causal path must now resolve which leaf was canonical. 2. **New-root forking** — the speculative branch mints a fresh `trace_id` and links back only by attribute (e.g., `speculation.parent_trace_id`). This preserves tree purity but severs the causal chain that auditors need to attribute the committed result to the original prompt. The non-obvious boundary: **the choice is irreversible once spans are exported**, because `trace_id` is not patchable in most collectors (Jaeger, Tempo, OTLP). An agent that forks under discipline 1 and later wants to "collapse" the losing branch into a sub-trace cannot — the spans already carry the shared `trace_id`. Conversely, an agent under discipline 2 that later wants to reconstruct the full reasoning tree has to re-stitch via custom attributes, which no standard sampler or backend understands. ## What Was Observed A planner agent executes a task with a fan-out of N=4 speculative branches from a single `plan` span (`trace_id=T`, `span_id=P`). Each branch is a child span with `parent_id=P` and the same `trace_id=T`, distinguished only by `span.kind=INTERNAL` and a `speculation.branch_id` attribute. Branch 2 is committed; branches 1, 3, 4 are discarded after a verifier scores them lower. Three concrete trace-level anomalies appeared in the collector: - **Orphaned tool spans.** Branches 1, 3, 4 issued real tool calls (HTTP fetches, DB reads) whose downstream services *also* received `traceparent` with `trace_id=T`. Those services emitted their own spans under `T`. The trace now contains external side-effect spans (e.g., a payment authorization in branch 3) that are causally downstream of an abandoned branch but indistinguishable in `trace_id` from the committed path. A latency SLO computed over `T` includes abandoned-branch latency; a cost audit over `T` includes tokens spent on discarded reasoning. - **Verifier span ambiguity.** The verifier span that selected branch 2 was emitted with `parent_id` set to the *fan-out* span, not to branch 2's root. So the trace graph shows verifier as a sibling of the branches it judged, not a descendant. Backends that compute "critical path" pick the longest path through `T`, which is frequently branch 3 (the slowest, discarded branch), not branch 2 (committed). - **Duplicate `span_id` collision on retry.** When branch 2's tool call timed out and the agent retried it, the retry reused the same `span_id` (the agent's span-ID generator was seeded per-branch, not per-attempt). Two spans with identical `(trace_id, span_id)` but different `parent_id=null` (retry was re-parented to the fan-out) landed in the collector. W3C does not forbid this, but Tempo's dedup silently dropped one, and the surviving span was the *failed* attempt — so the trace shows a red span where the user saw success. The net effect: the trace for `T` is a valid W3C trace (well-formed header, valid hex, correct length) that is nonetheless **semantically false** — it asserts a single causal history where the agent actually executed four, and it asserts verifier independence where the verifier was causally downstream of the fan-out. ## Condition of Validity The invariant that must hold for a forked trace to remain auditable is: > For every speculative branch, either (a) the branch's spans are exported under a distinct `trace_id` with an explicit `speculation.parent_trace_id` / `speculation.parent_span_id` attribute pair, or (b) the branch's spans share the parent `trace_id` **and** every span carries `speculation.branch_id` **and** every external side-effect span carries a `speculation.committed=true|false` attribute set *at emission time*, not at commit time. Condition (b) is only satisfiable if the agent knows at span-emission whether the branch will be committed, which it cannot — commit happens after verification. Therefore condition (a) is the only sound discipline for branches that produce external side effects. The corollary: **a speculative branch may only share its parent's `trace_id` if it is side-effect-free** (pure reasoning, no tool calls, no writes). The moment a branch leaves the process boundary, it must mint a new `trace_id`. A second invariant governs the verifier: the verifier span's `parent_id` must be the *committed branch's root span*, not the fan-out span, and the verifier must be emitted *after* commit is decided. If the verifier is emitted concurrently with the branches (as in the observed case), its causal position is unknowable and the trace graph is under-determined. ## Decision Boundary The agent must branch on the following predicate at the moment of forking: - **If the branch will execute any tool call, network egress, or state mutation** → mint a fresh `trace_id` (`version---`), record `speculation.parent_trace_id` and `speculation.parent_span_id` as span attributes, and mark `speculation.branch_id`. On commit, emit a `link` (OTLP span link, or a `traceparent`-adjacent `tracestate` entry) from the committed branch's root back to the parent trace. Do not rewrite `trace_id`. - **If the branch is pure reasoning (no egress)** → it may share the parent `trace_id`, but every span must carry `speculation.branch_id` and `speculation.committed` must be set on all spans of the committed branch before export, and on all spans of discarded branches as `false`. Backends must be configured to filter on this attribute for SLO and cost aggregation. - **If the branch's side effects are irreversible** (payment, external email, provisioning) → the branch must not be speculative at all; it must be serialized behind a commit gate. Trace correlation cannot fix a side effect that already happened. The boundary is crossed when an agent forks under the shared-`trace_id` discipline *and* the branch egresses. That combination produces a trace that passes every W3C validator and fails every audit. ## Operational Effect Downstream consequences observed when the boundary is crossed: - **SLO contamination.** p99 latency over `trace_id=T` reflects the slowest discarded branch, inflating the committed path's apparent latency by 2–4× in fan-out configs. Alerting fires on abandoned branches. - **Cost attribution drift.** Token and tool-call costs are summed per `trace_id`; discarded-branch spend is charged to the committed task. Budget alarms trip on tasks that actually succeeded cheaply. - **Causal replay failure.** When an auditor replays `T` to reconstruct the decision, the replay engine follows the longest path and reconstructs branch 3's reasoning, not branch 2's. The reconstructed "why" is wrong even though the "what" (final output) is right. - **Span-ID collision on retry.** Reusing `span_id` across retries within a branch causes silent span loss in dedup-capable backends, and the surviving span is whichever arrived first — often the failed attempt. The trace then contradicts the agent's own success log. - **Verifier mis-attribution.** Because the verifier is a sibling of the branches, any policy that gates on "verifier saw branch output" cannot be enforced from the trace alone; the gate must be re-implemented in the agent, and the trace becomes decorative. The guardrail that bounds all five: **fork to a new `trace_id` on any egress, link back explicitly, and emit the verifier only after commit.** This preserves tree purity for backends, keeps SLOs scoped to the committed path, and makes the causal chain reconstructable via links rather than via shared `trace_id`. The cost is that naive "group by trace_id" queries no longer capture the full reasoning tree — which is the correct trade, because the full tree was never a single causal history. ```python from __future__ import annotations import re import secrets from dataclasses import dataclass, field from typing import Literal _TRACEPARENT_RE = re.compile( r"^(?P[0-9a-f]{2})-" r"(?P[0-9a-f]{32})-" r"(?P[0-9a-f]{16})-" r"(?P[0-9a-f]{2})$" ) class SpeculativeTraceForkError(RuntimeError): """Raised when a speculative branch violates W3C traceparent fork invariants.""" @dataclass class Branch: branch_id: str will_egress: bool has_side_effects: bool trace_id: str parent_span_id: str committed: bool = False exported: bool = False spans: list[dict] = field(default_factory=list) def _new_trace_id() -> str: tid = secrets.token_hex(16) if tid == "0" * 32: raise SpeculativeTraceForkError("generated all-zero trace_id, invalid per W3C") return tid def _new_span_id() -> str: sid = secrets.token_hex(8) if sid == "0" * 16: raise SpeculativeTraceForkError("generated all-zero span_id, invalid per W3C") return sid def fork_speculative_branch( parent_traceparent: str, branch_id: str, will_egress: bool, has_side_effects: bool, ) -> Branch: m = _TRACEPARENT_RE.match(parent_traceparent) if not m: raise SpeculativeTraceForkError( f"malformed parent traceparent: {parent_traceparent!r}" ) if m.group("version") == "ff": raise SpeculativeTraceForkError("version ff is forbidden by W3C traceparent") parent_trace_id = m.group("trace_id") parent_span_id = m.group("span_id") if has_side_effects and not will_egress: raise SpeculativeTraceForkError( f"branch {branch_id}: side effects declared but egress flag false; " "irreversible effects cannot be speculative" ) if will_egress: # Discipline (a): mint a fresh trace_id, link back by attribute only. branch_trace_id = _new_trace_id() else: # Discipline (b): pure-reasoning branch may share the parent trace_id. branch_trace_id = parent_trace_id return Branch( branch_id=branch_id, will_egress=will_egress, has_side_effects=has_side_effects, trace_id=branch_trace_id, parent_span_id=parent_span_id, ) def commit_branch(branch: Branch, all_branches: list[Branch]) -> Branch: if branch.exported: raise SpeculativeTraceForkError( f"branch {branch.branch_id}: cannot commit after spans exported; " "trace_id is immutable once emitted" ) committed = [b for b in all_branches if b.committed] if committed: raise SpeculativeTraceForkError( f"branch {branch.branch_id}: another branch " f"{committed[0].branch_id} already committed" ) branch.committed = True return branch def emit_span(branch: Branch, span_name: str, *, kind: str = "INTERNAL") -> dict: if branch.exported and not branch.committed: raise SpeculativeTraceForkError( f"branch {branch.branch_id}: emitting span after export on " "uncommitted branch" ) if branch.will_egress and branch.trace_id == _parent_trace_of(branch): # Defensive: should be unreachable given fork discipline, but guard anyway. raise SpeculativeTraceForkError( f"branch {branch.branch_id}: egressing branch shares parent trace_id" ) span = { "trace_id": branch.trace_id, "span_id": _new_span_id(), "parent_id": branch.parent_span_id, "name": span_name, "kind": kind, "attributes": { "speculation.branch_id": branch.branch_id, "speculation.committed": branch.committed, }, } branch.spans.append(span) branch.exported = True return span def _parent_trace_of(branch: Branch) -> str | None: # In a real implementation this reads speculation.parent_trace_id from the # branch's fork record; here we approximate by checking the attribute. for span in branch.spans: if "speculation.parent_trace_id" in span.get("attributes", {}): return span["attributes"]["speculation.parent_trace_id"] return None def emit_verifier_span(committed: Branch, verifier_name: str) -> dict: if not committed.committed: raise SpeculativeTraceForkError( f"branch {committed.branch_id}: verifier emitted before commit decision" ) verifier = { "trace_id": committed.trace_id, "span_id": _new_span_id(), "parent_id": committed.spans[0]["span_id"] if committed.spans else None, "name": verifier_name, "kind": "INTERNAL", "attributes": {"speculation.verifier": True}, } if verifier["parent_id"] is None: raise SpeculativeTraceForkError( f"branch {committed.branch_id}: committed branch has no root span " "to parent the verifier under" ) return verifier ```