# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-genai-agent-span-s-token-accounting-has-silently-diverged-from-its-tool-call-attribute-tree-at-the-otel-export-boun.md # Remnant Warrant: https://corpusfetch.com/c/what-structural-signals-indicate-a-genai-agent-span-s-token-accounting-has-silently-diverged-from-its-tool-call-attribute-tree-at-the-otel-export-boun.warrant.json # Markdown SHA-256: 738ca4491f4bbba7fbcbbe293cce65eb1ded1ab4274b6a5d5910477532de5e49 # Code AST SHA-256: 14fede7fa6f7dd987b8fa523b5cc257744a763f4bdd3ea8f7ca7dc5ab90b292d # Verified Classes: TokenAccountingDivergence, Span # Defensive Guards: 2 fail-closed invariants (zero external deps) # Governance: Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com) from dataclasses import dataclass from typing import Iterable class TokenAccountingDivergence(RuntimeError): """Raised when an exported GenAI span subtree cannot be reconciled because a usage-bearing parent span is absent while its tool-call children survived the span processor.""" pass @dataclass(frozen=True) class Span: span_id: str parent_span_id: str | None name: str attributes: dict USAGE_KEYS = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens") TOOL_PREFIX = "gen_ai.tool." def reconcile_token_accounting(spans: Iterable[Span]) -> dict[str, int]: """Sum usage tokens per turn, but only over subtrees whose parent (gen_ai.chat) span is present in the exported set. Raises if a tool-call child's parent is missing, since that parent is the sole carrier of the usage attributes and its loss silently zeroes cost.""" by_id = {s.span_id: s for s in spans} totals: dict[str, int] = {} for span in by_id.values(): if span.parent_span_id is None: continue parent = by_id.get(span.parent_span_id) has_tool_attr = any(k.startswith(TOOL_PREFIX) for k in span.attributes) if parent is None and has_tool_attr: # Tool child exported, usage-bearing parent absent: the exact # shape of tail-sampler / batch-deadline divergence. raise TokenAccountingDivergence( f"tool child {span.span_id} ({span.name}) references " f"missing parent {span.parent_span_id}; token usage " f"unrecoverable from exported spans" ) if parent is not None and parent.name == "gen_ai.chat": turn = parent.span_id for key in USAGE_KEYS: totals[turn] = totals.get(turn, 0) + int( parent.attributes.get(key, 0) ) if not totals: raise TokenAccountingDivergence( "no gen_ai.chat parent spans with usage attributes survived " "export; refusing to emit a zero-cost aggregate" ) return totals