{
  "schema_version": "1.3.0",
  "slug": "which-invariants-prevent-otel-genai-token-accounting-metrics-from-misattributing-cost-when-an-agentic-loop-re-enters-a-tool-span-under-the-same-trace",
  "title": "Which invariants prevent OTel GenAI token-accounting metrics from misattributing cost when an agentic loop re-enters a tool span under the same trace",
  "date_of_record": "2026 November 23",
  "scope": "Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, `gen_ai.operation.name`) where a single agent turn can re-enter the same logical tool/step span more than once. Does not apply to stateless single-shot completions or to billing reconciliation against provider-side invoices (which are the ground truth, not the metric stream).",
  "projections": {
    "unified_markdown_uri": "https://corpusfetch.com/c/which-invariants-prevent-otel-genai-token-accounting-metrics-from-misattributing-cost-when-an-agentic-loop-re-enters-a-tool-span-under-the-same-trace.md",
    "method_python_slice_uri": "https://corpusfetch.com/c/which-invariants-prevent-otel-genai-token-accounting-metrics-from-misattributing-cost-when-an-agentic-loop-re-enters-a-tool-span-under-the-same-trace.py",
    "remnant_warrant_slice_uri": "https://corpusfetch.com/c/which-invariants-prevent-otel-genai-token-accounting-metrics-from-misattributing-cost-when-an-agentic-loop-re-enters-a-tool-span-under-the-same-trace.warrant.json"
  },
  "token_profile": {
    "full_markdown_tokens": 1819,
    "python_slice_tokens": 292,
    "warrant_slice_tokens": 220
  },
  "remnant_summary": {
    "core_distinction": "There are two structurally different things an OTel GenAI token counter can mean, and conflating them is the source of the failure: 1. **Per-invocation accounting** — each LLM call emits its own usage delta, and the sum over all calls equals the true bill. This is additive and correct by construction. 2. **Per-turn (logical-step) accounting** — usage is atta...",
    "what_was_observed": "A tool-calling agent looped on a `search_documents` tool. The LLM kept deciding to re-query with slightly mutated arguments (a classic divergence pattern: the first query returned low-relevance chunks, so the model paraphrased and re-queried). Each iteration produced: - one `gen_ai.chat` span with `input_tokens`/`output_tokens`, - one `execute_tool search_documents` span nested under a single long-lived `agent.turn` ...",
    "condition_of_validity": "The turn-scoped usage attribute is only sound under all three of the following, simultaneously: - **Span immutability after end.** Once a span's `on_end` fires and its attributes are exported, the span ID must not be reused for further accumulation. Re-entry must produce a *new* child span (e.g., `agent.turn.iteration`) with its own ID and its own usage attr...",
    "decision_boundary": "The boundary is: **does your instrumentation treat the turn as a mutable accumulator or as an immutable correlation key?** - If the runtime can reopen a span (streaming, tool-call resumption, human-in-the-loop pause, retry-with-backoff that reuses context), the turn must be a **correlation key** carried as an attribute on every leaf span, and never a span wh...",
    "operational_effect": "With the invariant enforced (immutable leaf usage + turn correlation key + loop detection on leaf count per correlation key): - Cost attribution becomes exact: sum of leaf `input_tokens`/`output_tokens` equals provider bill, because leaves are never double-emitted. - Loop detection fires at the correct threshold: 14 leaf `gen_ai.chat` spans under one `gen_ai..."
  },
  "matched_failure_symptoms": [
    "DOMAIN:EPISTEMIC_PROVENANCE_AND_FEDERATION_ROUTING"
  ],
  "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": "b859184bf0d6f83f8c0db8a714509f67d0048d443d02128765fedf7434d874e7",
    "verified_classes": [
      "SpanReentryAccountingError",
      "LeafUsage",
      "TurnAccumulator"
    ],
    "verified_functions": [
      "attribute_cost_safely",
      "add_usage",
      "end_span"
    ],
    "verified_functions_count": 3,
    "defensive_guards_count": 3,
    "raised_exceptions": [
      "SpanReentryAccountingError"
    ],
    "sample_fail_closed_invariants": [
      "no leaf usage spans to attribute"
    ],
    "stdlib_dependencies": [
      "collections",
      "dataclasses"
    ],
    "observation_mode": "EMPIRICAL_BOUNDARY_CAPTURE",
    "zero_external_deps": true
  }
}
