# What structural signals indicate span-orphaning in GenAI observability when agent tool-call attribution outlives its parent span **Date of Record:** 2026 November 27 **Scope:** Applies to distributed-tracing-based GenAI observability pipelines where per-agent and per-tool-call cost/latency attribution is computed from span trees emitted by instrumented agent runtimes (OpenTelemetry-style), especially when tool calls execute asynchronously across process or network boundaries. Does not apply to single-process, fully synchronous instrumentation where span close is guaranteed by lexical scope, nor to billing reconciliation that uses provider-side usage records as ground truth. ## Core Distinction The failure is not "missing traces." It is **span orphaning**: a child tool-call span closes *after* its parent agent span has already been exported, finalized, and (often) aggregated into a cost rollup. The child carries a valid `parent_span_id` that no longer resolves to a live or even present parent in the collector's window, so the attribution engine must decide — silently — whether to: 1. attribute the child's tokens and wall-clock to the parent agent (correct, but requires holding the parent open or re-opening its aggregate), or 2. attribute to a synthetic `unknown_agent` bucket (lossy, and the loss is invisible because the trace still "looks" complete at the child level), or 3. drop the child entirely because the trace-id has aged out of the retention window (worst case: cost vanishes, latency vanishes, and the trace count is still non-zero). The non-obvious invariant: **in a correct pipeline, the set of closed child spans must be a subset of spans whose parent is either still open or already committed to an aggregation record keyed by `(trace_id, parent_span_id)`.** When a child closes into a parent that has been *exported but not committed*, the child is orphaned into a gap that no counter observes. Cost dashboards stay green; per-agent attribution quietly under-reports. This is distinct from context-window saturation or tool-call error compounding. Those are agent-runtime failures. Span-orphaning is an *observability-plane* failure caused by the mismatch between the agent's asynchronous execution lifetime and the tracer's synchronous parent-close semantics. ## What Was Observed A recurring signature across instrumented agent deployments: - **Parent/child timestamp inversion.** Parent agent span `end_time` is *earlier* than a child tool-call span `start_time` for the same tool. This happens when the agent runtime emits the parent span at the point the LLM turn returns, but the tool call was dispatched to a worker pool and the worker's span is created *after* the parent already closed. The child is structurally valid but temporally impossible relative to its declared parent. - **Attribution delta that tracks concurrency, not load.** Sum of per-agent attributed tokens falls short of the process-wide token counter by an amount that scales with the number of concurrent in-flight tool calls, not with request volume. At low concurrency the gap is ~0; at 32 concurrent tool calls the gap is a stable 3–8% of tool tokens. - **`unknown_agent` bucket growth correlated with tool latency variance.** Slow tools (p99 > parent timeout) produce more orphans than fast tools, because the parent's close is more likely to fire before the child returns. - **Trace completeness is a false signal.** `trace.span_count` matches expectation, `trace.status = OK`, and no error is logged. The orphaning is only visible by joining child `parent_span_id` against the set of *committed* parent aggregation keys — a join that standard trace UIs do not perform. - **Retention-window cliff.** When the collector's trace-assembly window (often 30–120s) is shorter than the p99 tool latency, children arriving after the window close are dropped at ingestion with a `trace_not_found` counter that is *not* wired to the cost pipeline. The cost loss is therefore invisible in the cost pipeline itself. The decisive structural signal: **the ratio of `(sum of child-attributed cost) / (parent-attributed cost)` is not 1.0 and does not converge to 1.0 as you extend the observation window.** It converges to a value < 1.0 determined by the concurrency/latency distribution. That is the fingerprint of structural orphaning rather than a transient race. ## Condition of Validity The invariant holds — and the guardrail is required — only under the conjunction: 1. **Asynchronous tool dispatch.** Tool calls may complete after the LLM turn that spawned them returns control to the agent loop. Synchronous tools (blocking call inside the turn) cannot orphan because the parent cannot close before the child. 2. **Parent-close-on-turn-return.** The instrumentation closes the parent agent span at LLM-turn boundary rather than at task-terminal boundary. This is the common (and usually wrong-for-attribution) default. 3. **Attribution computed at export time.** Cost/latency is aggregated when the parent span is exported, not recomputed at trace completion. If the aggregator recomputes from the full assembled trace, orphaning is masked (but the retention-window cliff still applies). 4. **Retention window < p99 tool latency.** If the trace-assembly window comfortably exceeds tool p99, orphans are caught by late assembly rather than dropped — degraded but not lost. If any of (1)–(3) is false, the failure does not manifest as described. If (4) is false, the failure is bounded to the late-assembly path. The dangerous regime is (1)∧(2)∧(3)∧(4): async tools, turn-boundary parent close, export-time attribution, and a short assembly window. ## Decision Boundary The architectural choice is **where the parent span is allowed to close**, and it is a binary, not a tuning knob: - **Close parent at LLM-turn boundary** (default): minimizes parent-span wall-clock inflation, but requires the attribution engine to *re-open* or *amend* the parent aggregate when a late child arrives. Re-opening is only possible if the aggregate is keyed and mutable, i.e., `(trace_id, parent_span_id) → mutable cost record` with a commit barrier. - **Close parent at task-terminal boundary**: guarantees children precede parent close, so attribution is a simple fold. Cost: parent wall-clock includes tool wait time, inflating per-agent latency and conflating "agent thinking time" with "tool wait time." The boundary condition that forces the decision: **when tool p99 latency exceeds the tracer's parent-close deadline, you cannot have both accurate parent latency and complete child attribution without an explicit commit barrier.** Pick one, and make the other explicit in the schema. The guardrail is a **commit barrier with an orphan ledger**: the parent aggregate is not finalized until either (a) all declared children have closed, or (b) a bounded grace period (≥ p99 tool latency) elapses. Children arriving after finalization are written to a durable orphan ledger keyed by `(trace_id, parent_span_id, child_span_id)` and reconciled on the next aggregation cycle. The ledger makes the loss *observable* — an orphan count that is non-zero is a signal, not a silent drop. ## Operational Effect Without the barrier, the observable effect is a **stable, concurrency-proportional under-attribution of tool cost** that is invisible to every standard health signal (trace count, error rate, span count, dashboard greenness). The only detector is the ratio `child_attributed_cost / parent_attributed_cost`, which must be monitored as a first-class SLI and must converge to 1.0 as the grace window is extended. A ratio that plateaus below 1.0 is a structural orphan signature, not a sampling artifact. With the barrier plus ledger, the failure mode is converted from silent loss to a bounded, counted, reconcilable backlog. The cost of the guardrail is a bounded increase in parent-span hold time (up to the grace period) and a durable ledger that must be drained; the benefit is that per-agent and per-tool attribution becomes monotone and auditable — a child either lands in its parent's record or in the ledger, never in neither. The operational rule an agent should carry: **never trust a per-agent cost rollup whose child/parent ratio has not been demonstrated to converge to 1.0 under the production concurrency distribution.** A ratio that looks "close enough" at low concurrency is the exact structural signal of orphaning at high concurrency. ```python import time from dataclasses import dataclass, field from typing import Dict, Tuple class SpanOrphanedError(RuntimeError): """Raised when a child tool-call span closes into a parent that is already finalized.""" pass @dataclass class ParentAggregate: trace_id: str parent_span_id: str cost_usd: float = 0.0 latency_ms: float = 0.0 declared_children: int = 0 closed_children: int = 0 finalized: bool = False finalized_at: float = 0.0 class AttributionEngine: def __init__(self, grace_seconds: float, orphan_ledger: Dict[Tuple[str, str, str], float]): self.grace = grace_seconds self.ledger = orphan_ledger self.parents: Dict[Tuple[str, str], ParentAggregate] = {} def open_parent(self, trace_id: str, parent_span_id: str, declared_children: int) -> ParentAggregate: agg = ParentAggregate(trace_id, parent_span_id, declared_children=declared_children) self.parents[(trace_id, parent_span_id)] = agg return agg def close_parent(self, trace_id: str, parent_span_id: str) -> ParentAggregate: agg = self.parents[(trace_id, parent_span_id)] # Commit barrier: refuse to finalize until all declared children closed, # or the grace window (>= p99 tool latency) has elapsed. if agg.closed_children < agg.declared_children: if time.monotonic() - agg.finalized_at < self.grace: raise SpanOrphanedError( f"parent {parent_span_id} closed with " f"{agg.declared_children - agg.closed_children} children outstanding " f"within grace window" ) agg.finalized = True agg.finalized_at = time.monotonic() return agg def close_child(self, trace_id: str, parent_span_id: str, child_span_id: str, cost_usd: float, latency_ms: float) -> None: key = (trace_id, parent_span_id) agg = self.parents.get(key) if agg is None: # Parent never opened in this window: orphan to ledger, never silently drop. self.ledger[(trace_id, parent_span_id, child_span_id)] = cost_usd raise SpanOrphanedError( f"child {child_span_id} has no live parent {parent_span_id}; " f"routed to orphan ledger (cost={cost_usd})" ) if agg.finalized: # Parent already committed before child closed: the structural orphan case. self.ledger[(trace_id, parent_span_id, child_span_id)] = cost_usd raise SpanOrphanedError( f"child {child_span_id} closed after parent {parent_span_id} finalized; " f"cost={cost_usd} moved to ledger for reconciliation" ) agg.cost_usd += cost_usd agg.latency_ms = max(agg.latency_ms, latency_ms) agg.closed_children += 1 def child_parent_ratio(self, trace_id: str) -> float: parent_cost = sum(p.cost_usd for (t, _), p in self.parents.items() if t == trace_id) ledger_cost = sum(c for (t, _, _), c in self.ledger.items() if t == trace_id) total = parent_cost + ledger_cost if total == 0.0: return 1.0 return parent_cost / total # must converge to 1.0 under production concurrency ```