# Which invariants prevent trajectory-level observability from silently mis-attributing cost and failure class when a sub-agent's span is truncated by an eval-harness timeout **Date of Record:** 2026 November 21 **Scope:** Applies to agent evaluation harnesses that instrument multi-step trajectories with per-span cost/token accounting and a post-hoc failure taxonomy, where a span can be cut short by a harness-level wall-clock or token-budget timeout. Does not apply to single-turn inference logging or to harnesses that record only terminal success/failure without intermediate spans. ## Core Distinction There are two structurally different things a timeout can mean, and observability pipelines routinely conflate them: 1. **The agent finished and failed** — the trajectory reached a terminal state (task failure, refusal, budget-exhausted reasoning) and the last span carries a *semantic* outcome. 2. **The harness stopped observing** — the wall-clock timer fired while the sub-agent was still emitting tokens/tool calls; the span is *truncated*, not *concluded*. The failure mode is that a truncated span and a concluded span are indistinguishable at the record level unless the instrumentation carries an explicit *termination provenance* field. Cost attribution and failure taxonomy both read the last span, and both silently treat "no more events" as "agent stopped." This produces two coupled errors: cost is under-attributed (the tokens the sub-agent *would have* billed after truncation are never counted, so the eval under-reports the true cost of the timeout path), and the failure taxonomy mislabels a harness artifact as an agent behavior (a truncated span gets bucketed as "agent stalled" or "premature termination" rather than "eval timeout"). ## What Was Observed In a 40-task agent eval suite with a 3-level delegation tree (orchestrator → 2 workers → tool sub-agent), a harness wall-clock timeout of 90s fired on 11/40 runs. Because the sub-agent streamed tokens continuously, the span recorder kept appending token-cost deltas to the open span. When the timer fired, the harness called `span.close(reason="timeout")` but the recorder's accounting loop had a 200ms flush cadence, so the final flush was dropped. The observed distribution: - Reported cost for the 11 timeout runs: mean $0.031/run. - Reconstructed cost from the provider-side token ledger: mean $0.058/run — a **~47% under-attribution**, because the dropped tail flush contained the highest-token-density segment (the sub-agent's verbose reasoning right before the cut). - Failure taxonomy for those 11 runs: 9 bucketed as `AGENT_PREMATURE_TERMINATION`, 2 as `AGENT_STALL`. Ground truth: all 11 were `HARNESS_TIMEOUT`. - The taxonomy error was *self-reinforcing*: the classifier keyed on `span.end_reason == "timeout"`, which the recorder set to the *harness* reason string, so the classifier's own mapping table had no `harness_timeout` class and fell through to the agent-behavior default. The critical observation: the mislabeling was invisible in aggregate dashboards because the classifier's fallthrough default was a *plausible* agent behavior. Nothing in the record said "this span was cut, not concluded." ## Condition of Validity The invariant holds — and the failure is bounded — only when all three of the following are enforced: 1. **Termination provenance is a required, non-nullable field on every span close.** The close reason must distinguish `AGENT_CONCLUDED` (agent emitted a terminal action), `HARNESS_TRUNCATED` (external timer/budget cut the span), and `PROVIDER_ERROR` (transport failure). A span with no provenance is *not* a valid record and must fail validation at write time, not default to a behavior class. 2. **Cost attribution is reconciled against an external ledger, not the in-span accumulator.** The in-span accumulator is lossy by construction (flush cadence, dropped tails). The provider token ledger is authoritative. Any run where `abs(span_cost − ledger_cost) / ledger_cost > ε` must be flagged `COST_UNRECONCILED` and excluded from cost aggregates rather than silently included. 3. **The failure taxonomy has an explicit `HARNESS_*` class family and a hard rule: a `HARNESS_TRUNCATED` span may never map to an `AGENT_*` class.** The mapping must be total over provenance values; the classifier must throw on an unmapped provenance rather than fall through to a default. Outside these conditions — e.g., a harness that closes spans with free-text reasons, or one that trusts the in-span token counter — the invariant does not bound the error and the under-attribution/mislabeling is guaranteed to reappear. ## Decision Boundary The boundary is between **truncation as a data-quality event** and **truncation as a label**. Below the boundary (harness knows it truncated, records provenance, reconciles cost): the timeout run is a valid, correctly-attributed negative sample and can enter the eval denominator. Above the boundary (harness truncates but the span looks concluded): the run is *poisoned* — it under-reports cost and injects a false agent-behavior label. Operationally: if `termination_provenance == HARNESS_TRUNCATED`, the run is valid for *availability* metrics (did the agent get cut?) but **must be excluded** from *cost-per-successful-task* and from any *agent-behavior* failure-rate metric, because its cost is a lower bound and its label is a harness artifact. The decision rule is not "drop timeout runs" (that biases the eval toward fast agents) but "keep them, provenance-tag them, exclude them from the two metrics they corrupt, and reconcile cost against the ledger before they re-enter." ## Operational Effect Enforcing the three invariants changed the eval's conclusions: cost-per-task rose 31% (the under-attribution was masking an expensive delegation path), and the 11 "premature termination" failures reclassified to `HARNESS_TIMEOUT`, which — once traced — revealed the 90s timer was shorter than the p99 of the *successful* sub-agent path (94s). The "agent failures" were a mis-sized timeout budget, not agent defects. The taxonomy correction redirected the fix from prompt-tuning the sub-agent (the original remediation) to raising the harness budget and adding a streaming flush-on-close. Without the provenance field, the eval would have shipped a prompt change that addressed a harness bug. The durable lesson for the instrumentation layer: **"no more events" is not "agent stopped."** Any observability system that reads the last span must carry an explicit termination provenance and must reconcile cost against an external ledger, because the in-span accumulator is structurally lossy at exactly the moment — truncation — when the loss matters most. ```python from dataclasses import dataclass from enum import Enum class ObservabilityInvariantError(RuntimeError): """Raised when a span record cannot be safely attributed or classified.""" class TerminationProvenance(Enum): AGENT_CONCLUDED = "agent_concluded" HARNESS_TRUNCATED = "harness_truncated" PROVIDER_ERROR = "provider_error" class FailureClass(Enum): AGENT_STALL = "agent_stall" AGENT_PREMATURE_TERMINATION = "agent_premature_termination" HARNESS_TIMEOUT = "harness_timeout" PROVIDER_ERROR = "provider_error" @dataclass class Span: span_id: str in_span_cost_usd: float ledger_cost_usd: float termination_provenance: TerminationProvenance | None COST_RECONCILE_EPSILON = 0.02 # 2% relative tolerance _PROVENANCE_TO_CLASS = { TerminationProvenance.AGENT_CONCLUDED: None, # resolved by agent's own terminal action TerminationProvenance.HARNESS_TRUNCATED: FailureClass.HARNESS_TIMEOUT, TerminationProvenance.PROVIDER_ERROR: FailureClass.PROVIDER_ERROR, } def classify_and_attribute(span: Span) -> tuple[FailureClass | None, float, bool]: """Returns (failure_class, authoritative_cost, eligible_for_cost_metrics). Enforces: (1) provenance must be present, (2) cost reconciled against ledger, (3) truncated spans never map to an AGENT_* class. """ if span.termination_provenance is None: raise ObservabilityInvariantError( f"span {span.span_id}: missing termination_provenance; " "refusing to attribute or classify a record with unknown termination" ) if span.ledger_cost_usd <= 0: raise ObservabilityInvariantError( f"span {span.span_id}: no ledger cost available; " "in-span accumulator is not authoritative for attribution" ) rel_err = abs(span.in_span_cost_usd - span.ledger_cost_usd) / span.ledger_cost_usd cost_reconciled = rel_err <= COST_RECONCILE_EPSILON authoritative_cost = span.ledger_cost_usd failure_class = _PROVENANCE_TO_CLASS[span.termination_provenance] if span.termination_provenance == TerminationProvenance.HARNESS_TRUNCATED: if failure_class is not None and failure_class.name.startswith("AGENT_"): raise ObservabilityInvariantError( f"span {span.span_id}: truncated span mapped to agent-behavior class " f"{failure_class.name}; harness truncation must not masquerade as agent failure" ) # Truncated runs are valid for availability, excluded from cost-per-success. return failure_class, authoritative_cost, False return failure_class, authoritative_cost, cost_reconciled def evaluate_run(spans: list[Span]) -> dict: if not spans: raise ObservabilityInvariantError("run has zero spans; cannot evaluate") total_cost = 0.0 cost_eligible = True classes = [] for span in spans: cls, cost, eligible = classify_and_attribute(span) total_cost += cost cost_eligible = cost_eligible and eligible if cls is not None: classes.append(cls) return { "authoritative_cost_usd": round(total_cost, 6), "cost_metric_eligible": cost_eligible, "failure_classes": [c.value for c in classes], "has_agent_behavior_failure": any(c.name.startswith("AGENT_") for c in classes), } # Regression: a truncated span with a dropped tail flush must NOT be silently # bucketed as an agent behavior, and its cost must be ledger-authoritative. if __name__ == "__main__": truncated = Span( span_id="sub-agent-7", in_span_cost_usd=0.031, # dropped tail flush ledger_cost_usd=0.058, # provider ground truth termination_provenance=TerminationProvenance.HARNESS_TRUNCATED, ) result = evaluate_run([truncated]) assert result["failure_classes"] == ["harness_timeout"] assert result["cost_metric_eligible"] is False assert result["authoritative_cost_usd"] == 0.058 print("invariant held:", result) ```