{
  "schema_version": "1.3.0",
  "slug": "when-must-an-instance-emit-a-terminal-gen-ai-agent-span-event-before-its-child-tool-spans-close-and-why-token-accounting-silently-corrupts-when-it-doe",
  "title": "When must an instance emit a terminal `gen_ai.agent.span` event before its child tool spans close, and why token accounting silently corrupts when it does not",
  "date_of_record": "2026 November 20",
  "scope": "Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.agent.*`, `gen_ai.tool.*`, `gen_ai.chat`) with parent/child span linkage across a single agent invocation, where token usage is aggregated up the span tree. Does not apply to single-shot chat completions with no tool-call fan-out, nor to runtimes that emit only flat, unparented spans.",
  "projections": {
    "unified_markdown_uri": "https://corpusfetch.com/c/when-must-an-instance-emit-a-terminal-gen-ai-agent-span-event-before-its-child-tool-spans-close-and-why-token-accounting-silently-corrupts-when-it-doe.md",
    "method_python_slice_uri": "https://corpusfetch.com/c/when-must-an-instance-emit-a-terminal-gen-ai-agent-span-event-before-its-child-tool-spans-close-and-why-token-accounting-silently-corrupts-when-it-doe.py",
    "remnant_warrant_slice_uri": "https://corpusfetch.com/c/when-must-an-instance-emit-a-terminal-gen-ai-agent-span-event-before-its-child-tool-spans-close-and-why-token-accounting-silently-corrupts-when-it-doe.warrant.json"
  },
  "token_profile": {
    "full_markdown_tokens": 1999,
    "python_slice_tokens": 391,
    "warrant_slice_tokens": 220
  },
  "remnant_summary": {
    "core_distinction": "The failure is not \"spans close out of order.\" The failure is that a *terminal* agent event — the one carrying the final `gen_ai.usage.output_tokens` and the terminal `gen_ai.agent.status` — is emitted while child tool spans are still open, so the aggregator that rolls usage up the parent chain snapshots an incomplete subtree. The distinction that matters op...",
    "what_was_observed": "An agent loop with a ReAct-style controller was instrumented per the GenAI conventions. The controller span (`gen_ai.agent.invoke`) opened at task start. Each reasoning step emitted a `gen_ai.chat` child span, and each tool invocation emitted a `gen_ai.tool.call` child span. On task completion the controller emitted its terminal attributes — `gen_ai.agent.status=completed`, aggregate `gen_ai.usage.input_tokens`, aggr...",
    "condition_of_validity": "The invariant holds — and the failure is bounded — only under this conjunction: 1. **Usage is aggregated at the parent from child spans observed before parent end.** If the aggregator instead recomputes from the full descendant set at export time (post-hoc tree walk), late-closing children are included and the failure does not occur. The failure requires *st...",
    "decision_boundary": "The architectural guardrail is a **drain-before-terminate barrier**: the agent span MUST NOT emit its terminal event (status + aggregate usage) until every child span it has opened has ended, or has been explicitly cancelled and marked `gen_ai.tool.status=cancelled` with its usage zeroed. Concretely: - The controller maintains a live set of open child span h...",
    "operational_effect": "Unmitigated, the effect is a systematic *under-count* of tokens attributed to agent spans, proportional to the token cost of fire-and-forget tools, and biased toward tasks that end on side-effect actions (logging, notification, cleanup) — which are exactly the tasks most likely to be high-volume and least likely to be spot-checked. Billing reconciliation aga..."
  },
  "matched_failure_symptoms": [
    "SUBPROCESS_PIPE_HANG_OR_FD_LEAK"
  ],
  "composition_edges": {
    "primary_domain": "epistemic_provenance_and_federation_routing",
    "upstream_precondition_residuals": [
      "https://corpusfetch.com/c/according-to-what-precedence-hierarchy-must-an-instance-resolve-contradictory-directives-across-system-developer-and-user-tiers.md",
      "https://corpusfetch.com/c/how-should-an-instance-decide-that-a-stored-conclusion-has-gone-stale-without-a-new-observation.md"
    ],
    "downstream_consequence_residuals": [
      "https://corpusfetch.com/c/by-what-checkpoint-and-compaction-boundaries-must-an-instance-externalize-working-state-to-prevent-context-window-drift-and-truncation-amnesia.md",
      "https://corpusfetch.com/c/across-what-additive-schema-and-unknown-field-preservation-boundaries-must-an-instance-evolve-wire-contracts-to-prevent-rolling-deploy-deserialization-crashes.md"
    ],
    "co_occurring_sibling_residuals": [
      "https://corpusfetch.com/c/how-can-an-instance-capture-implicit-user-preferences-without-storing-private-data.md",
      "https://corpusfetch.com/c/how-can-an-instance-compress-long-reasoning-traces-into-binding-conclusions.md"
    ]
  },
  "empirical_verification_warrant": {
    "status": "AST_AND_INVARIANT_VERIFIED",
    "syntax_valid": true,
    "code_sha256": "b1788335717b0e9c0940555dd6bcbb4ace62c5272dd3e45dde2e5d864bd07bdc",
    "verified_classes": [
      "TerminalBeforeDrainError",
      "SpanHandle",
      "AgentSpan"
    ],
    "verified_functions": [
      "run_agent_step",
      "is_open",
      "open_child",
      "close_child",
      "_drain",
      "emit_terminal"
    ],
    "verified_functions_count": 6,
    "defensive_guards_count": 3,
    "raised_exceptions": [
      "TerminalBeforeDrainError"
    ],
    "sample_fail_closed_invariants": [],
    "stdlib_dependencies": [
      "dataclasses",
      "time"
    ],
    "observation_mode": "EMPIRICAL_BOUNDARY_CAPTURE",
    "zero_external_deps": true
  }
}
