# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-token-usage-double-counting-when-genai-agent-spans-are-re-parented-across-a-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-token-usage-double-counting-when-genai-agent-spans-are-re-parented-across-a-tool-call-boundary.warrant.json
# Markdown SHA-256:   97ebaede835d8f6873b820ce17132ececdbe63e1b2dced2fd97ef094cf9e83c1
# Code AST SHA-256:   390382e71d79f94fb565b2aa5877453ec97dc45755f3d9af81ed2f4063207ae0
# Verified Classes:   GenAiUsageInvariantError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class GenAiUsageInvariantError(RuntimeError):
    """Raised when a trace violates single-recording ownership of genai.usage.* attributes."""
    pass


LEAF_OPERATIONS = {"chat", "embeddings", "generate_content"}


def aggregate_trace_usage(spans: list[dict]) -> dict:
    """
    Sum genai.usage.* across a trace under the single-recording invariant.
    `spans` is a list of OTel span dicts with at least:
      span_id, trace_id, parent_span_id, attributes.
    Raises GenAiUsageInvariantError if ownership is ambiguous.
    """
    by_id = {s["span_id"]: s for s in spans}
    trace_ids = {s["trace_id"] for s in spans}
    if len(trace_ids) != 1:
        raise GenAiUsageInvariantError(
            f"expected one trace_id, got {sorted(trace_ids)}"
        )

    def descendants(span_id: str) -> list[dict]:
        out, stack = [], [span_id]
        while stack:
            cur = stack.pop()
            for s in spans:
                if s.get("parent_span_id") == cur:
                    out.append(s)
                    stack.append(s["span_id"])
        return out

    totals = {"input_tokens": 0, "output_tokens": 0}
    rollup_owners: list[str] = []

    for s in spans:
        attrs = s.get("attributes", {})
        op = attrs.get("genai.operation.name")
        carries_usage = (
            "genai.usage.input_tokens" in attrs
            or "genai.usage.output_tokens" in attrs
        )
        if not carries_usage:
            continue

        if op in LEAF_OPERATIONS:
            totals["input_tokens"] += attrs.get("genai.usage.input_tokens", 0)
            totals["output_tokens"] += attrs.get("genai.usage.output_tokens", 0)
            continue

        # Ancestor carrying usage: only valid as a fallback when it has
        # no leaf descendants in this trace, and is not marked as aggregate.
        leaves = [d for d in descendants(s["span_id"])
                  if d.get("attributes", {}).get("genai.operation.name") in LEAF_OPERATIONS]
        if leaves:
            if not attrs.get("genai.usage.aggregate"):
                raise GenAiUsageInvariantError(
                    f"span {s['span_id']} (op={op}) carries genai.usage.* "
                    f"but has {len(leaves)} leaf descendants; "
                    f"rollup must be tagged genai.usage.aggregate=true"
                )
            rollup_owners.append(s["span_id"])
            continue

        # No leaf descendants: dangling rollup, admissible as fallback.
        totals["input_tokens"] += attrs.get("genai.usage.input_tokens", 0)
        totals["output_tokens"] += attrs.get("genai.usage.output_tokens", 0)

    if len(rollup_owners) > 1:
        raise GenAiUsageInvariantError(
            f"multiple aggregate rollups in trace: {rollup_owners}; "
            f"re-parenting duplicated an ancestor usage attribute"
        )
    return totals
