What structural signals indicate causal trace stitching has silently mis-joined spans across federated agents under semantic-convention drift

**Date of Record:** 2026 December 2 **Scope:** Applies to observability pipelines that reconstruct a single causal trace from spans emitted by independently-deployed agents which share only a semantic convention (attribute schema + span-kind vocabulary) rather than a runtime tracer or shared process memory. Does not apply to single-process instrumentation, nor to federated traces that propagate a signed trace-context token end-to-end (those fail differently, at token validation, not at stitching).

Core Distinction

There are two ways a federated trace can be wrong. The first is **missing spans** — an agent never emitted, or the collector dropped, a span. This is detectable: the causal graph has a hole, and the parent-child reference points at a `parent_span_id` that resolves to nothing.

The second, and the one that matters here, is **plausible mis-join**: every span resolves, every parent pointer is internally consistent, the reconstructed DAG is acyclic and complete, and the trace *looks* healthy — but two spans that were never causally related have been stitched together because the pipeline's join key matched on a *semantic convention attribute* whose value coincided. The pipeline reports a coherent trace; the coherence is fabricated. This is the boundary condition: **trace stitching is a join over agent-emitted metadata, and agent-emitted metadata is probabilistic output, not a fact about causality.**

The invariant that must hold for a stitched trace to be trustworthy is stricter than "the graph is connected":

> For every edge `(parent, child)` in the reconstructed DAG, the join predicate that produced it must be one whose false-positive probability is bounded below the pipeline's span-admission threshold — which in practice means the join must key on a *causally-exchanged opaque token*, never on a *semantic attribute whose value is reproducible by an independent agent*.

When agents are federated, the only token that reliably survives the handoff is the one carried inside the task payload. Everything else — `session.id`, `conversation_id`, `user.goal`, `task.label`, `agent.role` — is a semantic attribute, and semantic attributes are *re-derivable* by any agent that sees the same task. Two agents that both emit `session.id = "refund-flow-7"` because both were told "handle refund flow 7" will be stitched into one trace even if they never exchanged a message.

What Was Observed

A federated deployment of three agents — a planner, a retrieval worker, and an auditor — emitted spans with the following semantic-convention attributes (OpenTelemetry-style, but the convention is the deployment's, not OTel's):

agent.role        : "planner" | "retriever" | "auditor"
task.label        : free-text, model-generated summary of the current subtask
session.id        : caller-supplied, reused across all subtasks of one user request
conversation.id   : caller-supplied, stable per user

The stitcher's join predicate was, in order of preference: `trace_id` if present, else `(session.id, parent_span_id)`, else `(session.id, task.label)` with fuzzy match. The first two are sound. The third is the failure surface.

During a batch of ~40k user requests, the planner decomposed each request into 2–5 subtasks and dispatched them **concurrently** to the retriever and auditor with the *same* `session.id` (correct — it is one user request) but *model-generated* `task.label` strings (the planner summarized each subtask in natural language before dispatch). The retriever and auditor each re-summarized the subtask they received into their own `task.label` before emitting their span. Three independent model generations of the same subtask produced three different strings.

The observed failure had two arms:

  1. **False merge.** When the planner's summary of subtask A and its summary of subtask B were lexically close (e.g., "look up refund policy for order" vs "look up refund eligibility for order"), the fuzzy join under the shared `session.id` collapsed both subtask chains into one. Downstream latency attribution then reported the retriever's p99 as the *sum* of two concurrent branches, because they were serialized into one path. The auditor's verdict span was attached under the wrong branch, so the audit's "reject" was attributed to the wrong subtask.
  1. **False split.** When an agent's re-summarization drifted far enough from the dispatcher's label (the retriever paraphrased "eligibility" as "qualification"), the fuzzy match fell below threshold and the child span was **orphaned** — re-parented to the session root. The trace remained valid and complete; it simply claimed the retriever ran at top level rather than under the planner's subtask. Causal depth was silently lost.

Neither arm raised an error. The stitcher's only health signal was "unresolved `parent_span_id` count," which stayed at zero because the fuzzy join always found *a* parent — the wrong one, but a parent nonetheless.

Condition of Validity

The mis-join is *possible* whenever the join key is a semantic attribute and the following three conditions co-occur. It is *likely* when all three hold and the agents are generative:

The invariant, stated operationally: **a stitched edge is admissible only if its join key is injective over the set of concurrently-live subtasks in the session.** `session.id` is not injective over concurrent subtasks (C2 fails). `task.label` is not injective and not stable (C3 fails). Only a dispatcher-minted `subtask.id` copied verbatim — never regenerated by the child model — satisfies injectivity.

Decision Boundary

The decision the pipeline must make is: *when a child span arrives with a `session.id` but no resolvable `parent_span_id`, do we fuzzy-join it to the best label match, or do we refuse and quarantine?*

The boundary is drawn by **whether the join can be verified against an exchange record**. Two regimes:

The most common production error is treating regime 2 as regime 1: the stitcher fuzzy-joins because a candidate exists, and the absence of a dispatch record is never checked. The guardrail is to make the dispatch record a *precondition* of the fuzzy-join code path, not a nice-to-have.

Operational Effect

Downstream of a silent mis-join, three classes of operational decision are corrupted, and each corrupts quietly:

  1. **Latency attribution.** Concurrent branches serialized into one path inflate per-agent p99 by the branch count. Capacity planning then over-provisions the retriever and under-provisions the auditor. The error is invisible because the trace is complete.
  2. **Audit provenance.** An auditor's reject verdict attached to the wrong subtask causes the wrong subtask to be re-run or rolled back. The auditor's *decision* was correct; its *attachment* was not. Replay of the trace reproduces the mis-join deterministically (the labels are logged), so replay does not catch it — replay validates the stitcher against itself.
  3. **Causal-depth metrics.** False splits re-parent children to the session root, flattening measured causal depth. Any alert keyed on "max causal depth per trace" stops firing precisely when decomposition is deepest, because the deepest edges are the ones most likely to have drifted labels.

The durable fix is structural, not threshold-tuning: **mint the join key at the dispatcher, carry it opaquely, and forbid the child model from regenerating it.** The child may *describe* the subtask in `task.label` for human reading; it must *copy* `subtask.id` for stitching. Fuzzy label matching is then demoted from a join mechanism to a human-facing annotation, and the stitcher's health signal becomes "count of spans that arrived without a dispatcher-minted `subtask.id`" — a number that should be zero and that, when nonzero, names the exact agent whose payload contract is broken.

import hashlib
from dataclasses import dataclass


class TraceStitchError(RuntimeError):
    """Raised when a federated span cannot be causally joined without inference."""


@dataclass(frozen=True)
class DispatchRecord:
    subtask_id: str          # dispatcher-minted, opaque, injective over live subtasks
    recipient_agent: str
    payload_hash: str        # sha256 of the exact payload handed to the child


@dataclass(frozen=True)
class ChildSpan:
    span_id: str
    session_id: str
    parent_span_id: str | None
    subtask_id: str | None   # copied verbatim from payload, or None if model regenerated
    received_payload_hash: str


def stitch_child(
    span: ChildSpan,
    dispatch_log: dict[str, DispatchRecord],
) -> str:
    """
    Return the verified parent span id for a child span, or raise.

    Invariant: an edge is admissible only if it keys on a dispatcher-minted
    subtask_id AND the child's received payload hash matches the dispatch
    record. Semantic attributes (task.label, session.id) are never used to
    infer a parent.
    """
    if span.parent_span_id is not None:
        return span.parent_span_id  # explicit causal token, trust it

    if span.subtask_id is None:
        # Child regenerated its identity instead of copying it. We cannot
        # verify the join, so we refuse rather than fuzzy-match on labels.
        raise TraceStitchError(
            f"span {span.span_id} in session {span.session_id} arrived with no "
            f"dispatcher-minted subtask_id; label-based join would be "
            f"unverified inference"
        )

    record = dispatch_log.get(span.subtask_id)
    if record is None:
        raise TraceStitchError(
            f"span {span.span_id} cites subtask_id {span.subtask_id!r} with no "
            f"dispatch record; join is exchange-unverifiable"
        )

    if record.payload_hash != span.received_payload_hash:
        raise TraceStitchError(
            f"span {span.span_id} subtask_id {span.subtask_id!r} payload hash "
            f"mismatch: dispatched {record.payload_hash[:12]} but child received "
            f"{span.received_payload_hash[:12]}; likely session.id collision across "
            f"concurrent branches"
        )

    # Verified: dispatcher minted the id and the child provably received that payload.
    return f"subtask:{span.subtask_id}"


def payload_hash(payload: bytes) -> str:
    return hashlib.sha256(payload).hexdigest()