# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-from-corrupting-otel-genai-agent-span-trees-across-retry-and-fan-out-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-from-corrupting-otel-genai-agent-span-trees-across-retry-and-fan-out-boundaries.warrant.json
# Markdown SHA-256:   5818bb30abe67cecaff3a41c976c2f867a0cfe8357e03fb7481d8e87527f87a5
# Code AST SHA-256:   ff7ebe1581b98fd1381ac4a3056505509f2a040a1be2213c91873a50f209ef3c
# Verified Classes:   TokenAggregationInvariantError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class TokenAggregationInvariantError(RuntimeError):
    """Raised when a parent agent span's token total cannot be soundly derived
    from its child model-invocation spans under the declared policy."""
    pass


def aggregate_agent_usage(children: list[dict], policy: dict) -> dict:
    """
    children: list of leaf chat-span dicts, each with keys:
        request_id, attempt (int|None), fanout_role ('sample'|'hedge'|None),
        status ('OK'|'ERROR'), input_tokens, output_tokens
    policy: {'dedup': 'attempt_id'|'request_id'|'none',
             'include_failed': bool,
             'require_fanout_role': bool}
    """
    if policy.get("require_fanout_role"):
        for c in children:
            if c.get("fanout_role") is None and policy["dedup"] == "request_id":
                # request_id dedup is only sound when fan-out intent is explicit;
                # a child with no role tag makes the dedup decision ambiguous.
                raise TokenAggregationInvariantError(
                    f"child {c['request_id']} has no fanout_role but policy "
                    "dedups by request_id; cannot distinguish hedged retry "
                    "from ensemble sample — parent token total is unsound"
                )

    # Step 1: drop failed attempts only if policy says so; otherwise they
    # are billable and must be counted.
    billable = [c for c in children if policy["include_failed"] or c["status"] == "OK"]

    # Step 2: dedup retries. Only 'attempt_id' dedup is sound across both
    # retry and fan-out; 'request_id' collapses fan-out samples wrongly.
    if policy["dedup"] == "attempt_id":
        seen: dict = {}
        for c in billable:
            key = c.get("attempt") if c.get("attempt") is not None else c["request_id"]
            # keep the last attempt of each logical invocation (the one whose
            # usage reflects the final provider state)
            seen[key] = c
        counted = list(seen.values())
    elif policy["dedup"] == "none":
        counted = billable
    else:
        raise TokenAggregationInvariantError(
            f"unsupported dedup policy {policy['dedup']!r}; request_id dedup "
            "is unsound for fan-out — use attempt_id or none"
        )

    total_in = sum(c["input_tokens"] for c in counted)
    total_out = sum(c["output_tokens"] for c in counted)

    if total_in < 0 or total_out < 0:
        raise TokenAggregationInvariantError(
            "negative token total; child usage tuple is corrupt"
        )
    return {
        "input_tokens": total_in,
        "output_tokens": total_out,
        "aggregation_policy": policy["dedup"],
        "children_counted": len(counted),
    }


def enforce_turn_budget(agent_span: dict, budget: int) -> None:
    """Enforce budget on the leaf-authoritative total, never on an
    undeclared parent rollup."""
    if "gen_ai.usage.aggregation_policy" not in agent_span:
        raise TokenAggregationInvariantError(
            "parent agent span has no declared aggregation_policy; "
            "refusing to enforce budget on an unsound derived total"
        )
    if agent_span["gen_ai.usage.input_tokens"] > budget:
        raise TokenAggregationInvariantError(
            f"turn budget exceeded: {agent_span['gen_ai.usage.input_tokens']} "
            f"> {budget} under policy {agent_span['gen_ai.usage.aggregation_policy']}"
        )
