# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-span-boundary-token-accounting-drift-in-opentelemetry-genai-multi-turn-agent-traces.md # Remnant Warrant: https://corpusfetch.com/c/what-structural-signals-indicate-span-boundary-token-accounting-drift-in-opentelemetry-genai-multi-turn-agent-traces.warrant.json # Markdown SHA-256: 2ecc317cbdf2192f17b931302f39d12413de982cd6eaad67443a555711d5cc35 # Code AST SHA-256: 083b9baf421ada355b8604ff1fa807fba4352831248c274438e8ee7ec8b45dd7 # Verified Classes: TokenAttributionError # Defensive Guards: 6 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) class TokenAttributionError(RuntimeError): pass def reconcile_agent_span(agent_span: dict, chat_spans: list[dict]) -> dict: """Reconcile a gen_ai.agent span's token usage against its gen_ai.chat children. Enforces: parent.input_tokens must equal sum(child.input_tokens - replayed_prefix). """ if not chat_spans: raise TokenAttributionError("agent span has no chat children; cannot reconcile") billed_input = 0 for i, child in enumerate(chat_spans): inp = child.get("gen_ai.usage.input_tokens") if inp is None: raise TokenAttributionError(f"child {i} missing input_tokens") prefix = child.get("gen_ai.usage.replayed_prefix_tokens", child.get("gen_ai.usage.cache_read_input_tokens", 0)) if prefix > inp: raise TokenAttributionError( f"child {i}: replayed_prefix {prefix} exceeds input {inp}") billed_input += inp - prefix parent_input = agent_span.get("gen_ai.usage.input_tokens") if parent_input is None: raise TokenAttributionError("agent span missing input_tokens") # Structural signal: parent equals naive sum => replayed prefixes folded in. naive_sum = sum(c["gen_ai.usage.input_tokens"] for c in chat_spans) if parent_input == naive_sum and billed_input != naive_sum: raise TokenAttributionError( f"parent input {parent_input} equals naive child sum but billed is " f"{billed_input}; replayed prefixes not declared") if parent_input != billed_input: raise TokenAttributionError( f"parent input {parent_input} != billed input {billed_input}") return {"billed_input_tokens": billed_input, "billed_output_tokens": sum(c.get("gen_ai.usage.output_tokens", 0) for c in chat_spans)}