# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-tool-call-spans-against-token-accounting-before-emitting-a-parent-agent-span.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-tool-call-spans-against-token-accounting-before-emitting-a-parent-agent-span.warrant.json
# Markdown SHA-256:   d131501fe3e17c30902a0a1ffb31408e118d3ade15503d6091cd6ffd83f9c58d
# Code AST SHA-256:   d7a9279ebf6e9f48aea2bff0352decc0e675594e11381e5de913a282a4b80f85
# Verified Classes:   TokenReconciliationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TokenReconciliationError(RuntimeError):
    """Raised when an agent span's descendant usage cannot be validly rolled up."""
    pass


def rollup_agent_usage(agent_span, child_llm_spans, child_tool_spans):
    referenced_ids = set()
    for llm in child_llm_spans:
        referenced_ids.update(llm.get("request_tool_call_ids", []))
    emitted_ids = {t["gen_ai.tool.call.id"] for t in child_tool_spans}

    if not emitted_ids.issubset(referenced_ids):
        missing = emitted_ids - referenced_ids
        raise TokenReconciliationError(
            f"tool calls {sorted(missing)} emitted but absent from any LLM request; "
            f"rollup invalid for agent span {agent_span.get('span_id')}"
        )

    if any(llm.get("gen_ai.usage.cache_read_input_tokens", 0) > 0
           for llm in child_llm_spans) and len(child_llm_spans) > 1:
        raise TokenReconciliationError(
            "shared cached prefix across sibling LLM spans; summing input_tokens "
            "double-counts cache reads"
        )

    return {
        "gen_ai.usage.input_tokens": sum(
            l["gen_ai.usage.input_tokens"] for l in child_llm_spans),
        "gen_ai.usage.output_tokens": sum(
            l["gen_ai.usage.output_tokens"] for l in child_llm_spans),
        "reconciliation.mode": "sum",
    }
