# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-genai-agent-span-whose-token-accounting-double-counts-cached-prompt-tokens-across-a-tool-call-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-genai-agent-span-whose-token-accounting-double-counts-cached-prompt-tokens-across-a-tool-call-fan-out.warrant.json
# Markdown SHA-256:   fa3e7dffd6751236bf3cc531f4f18a4b5e87c3c24c0c92502e2e4cb8b4d07904
# Code AST SHA-256:   c9e047333176a5ec33ee18ac808702547f9ed6079845b251e82af17e17fa1b3f
# Verified Classes:   UnverifiedCacheSemanticsError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnverifiedCacheSemanticsError(RuntimeError):
    """Raised when a parent agent span cannot safely aggregate child token usage."""
    pass


# Registry mapping provider/model -> how cached_tokens relates to input_tokens.
CACHE_SEMANTICS = {
    ("openai", "gpt-4o"): "SUBSET",       # cached_tokens is a subset of input_tokens
    ("anthropic", "claude-3-5-sonnet"): "PARTITION",  # cache_read distinct from input
}


def aggregate_agent_usage(children: list[dict]) -> dict:
    """
    children: each dict has keys provider, model, input_tokens,
              cached_tokens, output_tokens.
    Returns verified aggregate, or raises if any child's semantics are unknown.
    """
    total_input = 0
    total_cached = 0
    total_output = 0

    for i, child in enumerate(children):
        key = (child["provider"], child["model"])
        semantics = CACHE_SEMANTICS.get(key)

        if semantics is None:
            # Fail closed: do not guess subset vs partition.
            raise UnverifiedCacheSemanticsError(
                f"child[{i}] provider={key[0]!r} model={key[1]!r} has no "
                f"registered cached_tokens semantics; refusing to aggregate "
                f"parent gen_ai.usage.input_tokens"
            )

        if semantics == "SUBSET":
            # cached_tokens already inside input_tokens; do not add.
            total_input += child["input_tokens"]
            total_cached += child["cached_tokens"]
        elif semantics == "PARTITION":
            # cached_tokens disjoint from input_tokens; add both.
            total_input += child["input_tokens"] + child["cached_tokens"]
            total_cached += child["cached_tokens"]
        else:
            raise UnverifiedCacheSemanticsError(
                f"unknown semantics {semantics!r} for {key}"
            )

        total_output += child["output_tokens"]

    return {
        "gen_ai.usage.input_tokens": total_input,
        "gen_ai.usage.output_tokens": total_output,
        "gen_ai.usage.cached_tokens": total_cached,  # informational only
        "gen_ai.agent.usage.aggregation": "verified",
    }
