# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-tool-call-spans-whose-token-accounting-collapses-parent-and-child-spans-into-a-single-non-idempotent-counter.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-tool-call-spans-whose-token-accounting-collapses-parent-and-child-spans-into-a-single-non-idempotent-counter.warrant.json
# Markdown SHA-256:   c98f91527eb0125ed2f9105aacad5da726a4cc47d7a85e608cff4088c68226f8
# Code AST SHA-256:   adb8f6619458a69a0e30933e59896d6a60406aaa80e9c49590e03b2ab2f3a3a0
# Verified Classes:   GenAIUsageDoubleCountError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class GenAIUsageDoubleCountError(RuntimeError):
    """Raised when a span carries gen_ai.usage.* while a descendant carries the same key,
    making delta vs. cumulative readings indistinguishable to a sum-over-trace rollup."""
    pass


DELTA_OPERATIONS = {"chat"}


def validate_usage_span(span: dict, descendant_usage_keys: set[str]) -> None:
    op = span.get("attributes", {}).get("gen_ai.operation.name")
    has_usage = any(
        k.startswith("gen_ai.usage.") for k in span.get("attributes", {})
    )
    if not has_usage:
        return
    if op in DELTA_OPERATIONS:
        return
    # Non-delta span (invoke_agent / execute_tool) carrying usage while a child
    # also carries usage => this span is a rollup, not a delta. Reject it from
    # the aggregation set; summing it double-counts every descendant invocation.
    overlapping = {
        k for k in span["attributes"]
        if k.startswith("gen_ai.usage.") and k in descendant_usage_keys
    }
    if overlapping:
        raise GenAIUsageDoubleCountError(
            f"span {span.get('span_id')} op={op} re-emits {sorted(overlapping)} "
            f"already present on a descendant; sum-over-trace will inflate cost "
            f"by tool-call fan-out. Route to gen_ai.agent.cumulative_* namespace."
        )


def rollup_trace(spans: list[dict]) -> int:
    descendant_keys: set[str] = set()
    for s in spans:
        if s.get("attributes", {}).get("gen_ai.operation.name") in DELTA_OPERATIONS:
            descendant_keys |= {
                k for k in s["attributes"] if k.startswith("gen_ai.usage.")
            }
    total = 0
    for s in spans:
        validate_usage_span(s, descendant_keys)
        if s.get("attributes", {}).get("gen_ai.operation.name") in DELTA_OPERATIONS:
            total += s["attributes"].get("gen_ai.usage.input_tokens", 0)
    return total
