# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-token-accounting-divergence-between-opentelemetry-genai-agent-spans-and-their-child-tool-call-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-token-accounting-divergence-between-opentelemetry-genai-agent-spans-and-their-child-tool-call-spans.warrant.json
# Markdown SHA-256:   5626f457c3ab3740402db3dae7aea5395eaa2475165a1ace9faa3c471c68c974
# Code AST SHA-256:   07aa3d4fe1d0f26e4ed26b7e70dc3a6b074ac2ad873ec9c51a65fd1dbf32bd4a
# Verified Classes:   TokenAggregationInvariantError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TokenAggregationInvariantError(RuntimeError):
    """Raised when a trace's span shape cannot support per-invocation token aggregation."""
    pass


def reconcile_token_usage(spans: list[dict]) -> dict:
    """
    spans: exported OTel spans for one trace, each a dict with
      'name', 'operation' ('chat' | 'execute_tool' | 'invoke_agent'), and
      optional 'input_tokens' / 'output_tokens'.
    Returns a reconciled accounting dict or raises if the shape is un-attributable.
    """
    chat = [s for s in spans if s.get("operation") == "chat"]
    tools = [s for s in spans if s.get("operation") == "execute_tool"]
    agents = [s for s in spans if s.get("operation") == "invoke_agent"]

    if not agents:
        raise TokenAggregationInvariantError(
            "no invoke_agent span: cannot establish billed total"
        )

    # Structural signal: a well-formed agent trace has one chat span per
    # tool round-trip plus a terminal response.
    if len(chat) < len(tools):
        raise TokenAggregationInvariantError(
            f"hoisted accounting detected: {len(chat)} chat spans for "
            f"{len(tools)} tool calls; per-invocation aggregation is void. "
            f"Read totals from invoke_agent span only."
        )

    # Missing usage on a chat span means 'unknown', not 'zero'.
    for s in chat:
        if "input_tokens" not in s or "output_tokens" not in s:
            raise TokenAggregationInvariantError(
                f"chat span {s.get('name')!r} closed before usage finalized; "
                f"refusing to aggregate unknown as zero"
            )

    # Cache reads are reported separately and must not inflate billable input.
    per_invocation_input = sum(
        s["input_tokens"] - s.get("cache_read_input_tokens", 0) for s in chat
    )
    per_invocation_output = sum(s["output_tokens"] for s in chat)

    agent_total_input = sum(a.get("input_tokens", 0) for a in agents)
    agent_total_output = sum(a.get("output_tokens", 0) for a in agents)

    return {
        "billed_input": agent_total_input,
        "billed_output": agent_total_output,
        "attributed_input": per_invocation_input,
        "attributed_output": per_invocation_output,
        "decomposable": True,
    }
