What structural signals indicate retry-causality collapse in GenAI span attributes when reasoning traces are re-emitted across retry attempts

**Date of Record:** 2026 December 2 **Scope:** Applies to agents instrumented with OpenTelemetry-style GenAI span attributes (`genai.operation.name`, `genai.usage.*`, custom `genai.reasoning.*` / `genai.retry.*` attributes) where a retry re-enters a tool-calling reasoning loop and re-emits a reasoning trace. Does not apply to single-shot inference without retries, nor to retries that occur entirely outside an instrumented span boundary (e.g., transport-level HTTP retries below the SDK).

Core Distinction

A retry span is not a fresh invocation. It is a **causally dependent re-execution** whose reasoning trace is *derived* from the failed attempt's partial state, not from the original prompt. Observability systems routinely conflate the two because the span attributes look identical: same `genai.request.model`, same `genai.usage.input_tokens` order of magnitude, same `genai.operation.name="chat"`. The failure mode is that **retry causality is only recoverable if the span carries an explicit parent-of-failure link and a monotonic attempt ordinal**; when it does not, the reasoning trace of attempt *n+1* is attributed as an independent root-cause trace, and the actual failure trigger (attempt *n*'s divergence) disappears from the causal graph.

The non-obvious boundary: an agent that *reasons about its own failure* before retrying emits a trace that is **semantically richer but causally orphaned**. The richer trace scores higher in trace-quality heuristics and is preferentially surfaced by observability UIs, actively masking the failure it was reasoning about.

What Was Observed

A tool-calling agent (three-step loop: plan → call tool → synthesize) wrapped in a retry supervisor with `max_attempts=3`. Each attempt opened a span with standard GenAI attributes. On a malformed tool response (attempt 1: tool returned a JSON object where a list was expected), the supervisor caught the parse error, injected the error text into the next prompt as a "previous attempt failed because…" preamble, and re-invoked.

Observed span sequence across 1,412 retried tasks:

The structural signal that indicated collapse: **attempt-2 `output_tokens` were consistently 2.5–3.8× attempt-1 for the same `input_tokens` bucket.** A genuine independent invocation would not systematically inflate output length. The inflation is the fingerprint of failure-narration reasoning. But because the trace-quality scorer ranked by output richness, 71% of sampled "successful" traces surfaced for review were *post-failure narrations* — the reviewer saw the agent explaining a failure whose span was invisible.

A second signal: when the tool response was *silently wrong* (schema-valid but semantically wrong, e.g., a list of the wrong entity), no retry fired, no error status was set, and the attempt-1 span was the canonical trace — yet the same 2.5×+ output inflation appeared in the *synthesis* step, indicating the model had reasoned around a discrepancy it could not surface as an error. Output-token inflation is thus a signal of **latent divergence**, not only of retry.

Condition of Validity

The diagnosis holds only when all of the following are true:

  1. Retries are **semantic** (agent-level, prompt-mutating), not transport-level. Transport retries re-send identical bytes and do not inflate reasoning.
  2. The retry supervisor **injects failure context** into the next prompt. If it does not, attempt *n+1* is a true cold re-execution and the inflation signal is absent — but then attempt *n+1* is also not causally dependent, and the missing link is correct.
  3. `genai.usage.output_tokens` is measured per-attempt, not aggregated across the retry chain. Aggregation destroys the ratio.
  4. The task has a bounded expected output length so the 2.5× baseline is meaningful. Open-ended generation tasks violate this and the signal is uninterpretable.

When condition 2 fails, the correct invariant is *no link expected*; the failure mode does not apply. When condition 3 fails, you cannot detect the collapse at all — you have already lost the per-attempt denominator.

Decision Boundary

The boundary between "retry trace correctly attributed" and "retry causality collapsed" is a single attribute pair on the retry span:

If both present: the reasoning trace is a dependent re-execution; downstream analysis must treat its output as *conditioned on prior failure*, and trace-quality scoring must not rank it above the root trace without penalty. If either absent on a span whose `output_tokens` exceed the task's p50 by >2× and whose `status.code=OK` while a sibling span for the same task has `status.code=ERROR` within the same time window: **causality has collapsed** and the OK span must be demoted, not promoted.

The boundary is *not* "error span exists." Errors are common and benign. The boundary is "OK span is causally downstream of an unlinked error span under output inflation." A retry that succeeds without inflation is an ordinary recovery and needs no special handling.

Operational Effect

Once collapse is detected, the remediation is structural, not statistical:

The invariant to enforce at the instrumentation layer: **every retry span MUST carry both the attempt ordinal and the parent-of-failure link, and the link MUST be emitted by the supervisor, not inferred by the backend.** Inference is lossy because the backend cannot distinguish "retry of a failure" from "independent task that happens to follow an error" without the ordinal. The ordinal is the only signal that survives aggregation.

import time
from dataclasses import dataclass, field
from typing import Optional


class RetryCausalityCollapse(RuntimeError):
    """Raised when a retry span's reasoning trace is causally orphaned from its failure."""
    pass


@dataclass
class GenAISpan:
    span_id: str
    task_key: str
    attempt: Optional[int]              # genai.retry.attempt
    parent_span_id: Optional[str]       # genai.retry.parent_span_id
    status_code: str                    # "OK" | "ERROR"
    output_tokens: int
    timestamp: float = field(default_factory=time.time)


def validate_retry_causality(
    span: GenAISpan,
    task_p50_output_tokens: int,
    error_siblings: list[GenAISpan],
    retry_window_s: float = 30.0,
) -> None:
    """
    Enforce the retry-causality invariant on a single span.
    Raises RetryCausalityCollapse when an OK span is a causally orphaned retry.
    """
    if span.status_code != "OK":
        return  # error spans are roots by definition; nothing to validate

    inflation = span.output_tokens / max(task_p50_output_tokens, 1)
    if inflation <= 2.0:
        return  # ordinary recovery, no narration signature

    # Inflation present. Is there an unlinked error sibling in the window?
    nearby_errors = [
        e for e in error_siblings
        if e.task_key == span.task_key
        and abs(e.timestamp - span.timestamp) <= retry_window_s
    ]
    if not nearby_errors:
        return  # latent divergence, not retry collapse; caller flags separately

    has_ordinal = span.attempt is not None and span.attempt > 1
    has_parent = span.parent_span_id is not None and any(
        e.span_id == span.parent_span_id for e in nearby_errors
    )

    if not (has_ordinal and has_parent):
        raise RetryCausalityCollapse(
            f"span {span.span_id} (task={span.task_key}) has OK status with "
            f"{inflation:.2f}x output inflation and an unlinked error sibling "
            f"{nearby_errors[0].span_id} within {retry_window_s}s, but "
            f"attempt={span.attempt!r} parent_span_id={span.parent_span_id!r}. "
            f"Reasoning trace is causally orphaned; demote from canonical trace."
        )


def relink_and_demote(
    span: GenAISpan,
    error_siblings: list[GenAISpan],
    task_p50_output_tokens: int,
) -> GenAISpan:
    """Attempt structural repair: synthesize the missing causal edge, then re-validate."""
    try:
        validate_retry_causality(span, task_p50_output_tokens, error_siblings)
        return span
    except RetryCausalityCollapse:
        candidate = min(
            (e for e in error_siblings if e.task_key == span.task_key),
            key=lambda e: abs(e.timestamp - span.timestamp),
            default=None,
        )
        if candidate is None:
            raise RetryCausalityCollapse(
                f"cannot relink span {span.span_id}: no error sibling for task {span.task_key}"
            )
        repaired = GenAISpan(
            span_id=span.span_id,
            task_key=span.task_key,
            attempt=2,
            parent_span_id=candidate.span_id,
            status_code=span.status_code,
            output_tokens=span.output_tokens,
            timestamp=span.timestamp,
        )
        validate_retry_causality(repaired, task_p50_output_tokens, error_siblings)
        return repaired