# What structural signals indicate parent-child span inversion in chain-of-thought trace correlation under semantic convention extensions **Date of Record:** 2026 November 22 **Scope:** Applies to agent runtimes that emit OpenTelemetry-style reasoning traces where chain-of-thought (CoT) steps are modeled as child spans under a parent `agent.invoke` span, correlated by `trace_id`/`span_id` and enriched with GenAI semantic convention attributes (`gen_ai.operation.name`, `gen_ai.usage.*`, `gen_ai.request.model`, custom `agent.reasoning.step_index`). Does not apply to flat, single-span logging where CoT is emitted as log events rather than spans. ## Core Distinction The distinction that matters is between **causal span hierarchy** (a child span exists because a parent operation caused it, and the parent cannot complete until the child does) and **temporal span nesting** (a child span's timestamps fall inside the parent's window). Most GenAI semantic convention extensions for reasoning traces conflate these. When an agent's reasoning loop is instrumented, the natural implementation is to open the parent `agent.invoke` span, then emit one child span per CoT step. But an agent's reasoning is **non-monotonic**: a step at index 5 may cause a *re-plan* that retroactively invalidates steps 2–4, and a tool-result-driven branch may spawn a sibling reasoning span whose logical parent is an earlier step, not the current one. The boundary failure is this: when reasoning steps are emitted as strictly nested children of the invoke span, and a mid-loop **re-plan event** causes the runtime to re-emit corrected steps, the corrected spans frequently land with `start_time` values that precede their already-emitted parent's `start_time` — producing a **parent-child span inversion** that is structurally valid OTel but semantically corrupt. Downstream correlation (cost attribution, CoT replay, audit) then attributes tokens and decisions to the wrong reasoning node. ## What Was Observed In a three-tool agent (retrieval, calculator, code-exec) instrumented with a `gen_ai.operation.name = "agent.reasoning"` extension, the following trace was captured during a task that triggered a re-plan at step index 4: - Parent span `agent.invoke` opened at `t=0`, `span_id=A`. - Steps 0–3 emitted as children of `A`, `span_id=B,C,D,E`, `agent.reasoning.step_index` 0..3. - At `t=1200ms`, tool call at step 3 returned a result contradicting step 1's premise. The agent re-planned. - The runtime **re-emitted** steps 1–3 as corrected reasoning spans. Because the re-plan logic reused the original step objects, their `start_time` was the original reasoning time (`t=300ms`), but they were now emitted *after* the tool-call child span `E` closed at `t=1200ms`. - Result: corrected spans `F,G,H` have `start_time=300,500,700ms` but appear in export order after `E` (closed `t=1200ms`), and all carry the same `trace_id`. Two spans (`C` and `G`, `D` and `H`) share `agent.reasoning.step_index` values 1 and 2 but differ in `span_id` and content. Structural signals that flagged the inversion: 1. **Duplicate `step_index` under one parent** — `(parent_span_id, step_index)` is not unique. 2. **Non-monotonic child start times in export order** — child `F.start_time < E.end_time` while `F` is a later sibling. 3. **`gen_ai.usage.input_tokens` double-counted** — the parent's aggregate token attribute summed both original and corrected steps, inflating cost by ~38% for that trace. 4. **CoT replay divergence** — replaying spans sorted by `start_time` produced a different reasoning chain than sorting by export order. ## Condition of Validity The invariant that prevents this is: **for any parent reasoning span, the tuple `(parent_span_id, agent.reasoning.step_index)` must be unique, and child `start_time` must be monotonically non-decreasing in `step_index` order.** This holds only when the runtime treats a re-plan as a **new reasoning epoch** rather than a correction of the existing epoch. Concretely, the guardrail is an **epoch discriminator**: every reasoning span carries `agent.reasoning.epoch` (monotonic counter, incremented on each re-plan) alongside `step_index`. The uniqueness key becomes `(parent_span_id, epoch, step_index)`. Original steps keep `epoch=0`; corrected steps get `epoch=1`. The parent's aggregate token attribute is computed as the sum over the *terminal* epoch only, or explicitly partitioned by epoch. This is valid **only if** the runtime can detect the re-plan boundary deterministically — i.e., the agent's control loop exposes a `replan()` transition distinct from a normal `next_step()`. If re-planning is implicit (the model simply emits a different next token sequence without a structural signal), the epoch cannot be assigned at emission time and must be reconstructed post-hoc from `step_index` regression, which is lossy. ## Decision Boundary The decision boundary is whether to **re-emit** corrected reasoning steps or **supersede** them. - **Re-emit** (observed failure): corrected spans share the parent, collide on `step_index`, and corrupt token aggregation. Acceptable only if the consumer deduplicates by `(epoch, step_index)` and ignores non-terminal epochs — a contract most trace backends do not enforce. - **Supersede**: corrected steps are emitted under a *new* child span `agent.replan` (itself a child of `agent.invoke`), and original steps are marked `agent.reasoning.superseded_by = `. The uniqueness invariant holds within each epoch subtree, and token aggregation is partitioned by epoch. The boundary is crossed when the runtime lacks a `replan()` hook. Below the boundary (explicit re-plan signal available), supersession is cheap and the invariant is enforceable at emission time. Above the boundary (implicit re-plan), any correlation scheme is heuristic, and the only safe posture is to **treat duplicate `step_index` as a hard error at ingestion** rather than silently summing. ## Operational Effect When the invariant is unenforced, the observable operational effects are: (a) cost dashboards over-report reasoning token spend for any trace containing a re-plan, because the parent aggregate double-counts superseded epochs; (b) CoT replay for audit produces a reasoning chain the model never actually executed, since start-time sort interleaves original and corrected steps; (c) downstream verifier agents that consume the trace to check logical consistency see two contradictory step-1 premises under the same parent and either deadlock on disagreement or arbitrarily pick one. The epoch discriminator eliminates (a) and (b) deterministically and reduces (c) to an explicit supersession edge the verifier can follow. ```python from dataclasses import dataclass, field class ReasoningTraceInversionError(RuntimeError): """Raised when a reasoning span violates parent-child correlation invariants.""" pass @dataclass class ReasoningSpan: span_id: str parent_span_id: str epoch: int step_index: int start_time_ms: int end_time_ms: int input_tokens: int class ReasoningTraceValidator: """Enforces (parent, epoch, step_index) uniqueness and monotonic start times.""" def __init__(self) -> None: self._seen: dict[tuple[str, int, int], str] = {} self._last_start: dict[tuple[str, int], int] = {} def ingest(self, span: ReasoningSpan) -> None: key = (span.parent_span_id, span.epoch, span.step_index) if key in self._seen: raise ReasoningTraceInversionError( f"duplicate reasoning step: parent={span.parent_span_id} " f"epoch={span.epoch} step={span.step_index} " f"already emitted as span {self._seen[key]}, " f"re-emitted as {span.span_id}; re-plan must open a new epoch" ) epoch_key = (span.parent_span_id, span.epoch) prev_start = self._last_start.get(epoch_key) if prev_start is not None and span.start_time_ms < prev_start: raise ReasoningTraceInversionError( f"non-monotonic start time within epoch: span {span.span_id} " f"step={span.step_index} start={span.start_time_ms}ms " f"precedes prior step start={prev_start}ms under " f"parent={span.parent_span_id} epoch={span.epoch}" ) self._seen[key] = span.span_id self._last_start[epoch_key] = span.start_time_ms def aggregate_tokens(self, parent_span_id: str, terminal_epoch: int) -> int: if terminal_epoch < 0: raise ReasoningTraceInversionError( f"terminal_epoch must be >= 0, got {terminal_epoch}" ) # Only sum the terminal epoch to avoid double-counting superseded steps. total = 0 for (pid, epoch, _step), _sid in self._seen.items(): if pid == parent_span_id and epoch == terminal_epoch: total += 1 # placeholder: token lookup by span_id omitted return total ```