# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-span-attribute-lineage-collapse-in-opentelemetry-genai-tool-call-chains-under-retry.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-span-attribute-lineage-collapse-in-opentelemetry-genai-tool-call-chains-under-retry.warrant.json
# Markdown SHA-256:   9dd27b0dfbfa423aede8261770134721805c996a8c668dd788ba11aaf48bfefe
# Code AST SHA-256:   9fcb74b1bbc1ce8564253efa237974359587756cee9ae303c77ab2d2fa01e87b
# Verified Classes:   LineageCollapseError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class LineageCollapseError(RuntimeError):
    """Raised when GenAI span attributes cannot distinguish retry from resume."""
    pass


def aggregate_tool_usage(spans: list[dict]) -> dict:
    """
    Sum token usage across a logical tool call, refusing to guess
    when retry/resume is ambiguous.

    Each span is expected to carry:
      gen_ai.tool.call.id        (str)  lineage key
      gen_ai.tool.attempt        (int)  1-indexed attempt ordinal
      gen_ai.usage.input_tokens  (int)  per-attempt delta
      gen_ai.usage.output_tokens (int)  per-attempt delta
      status.code                (str)  OK | ERROR | UNSET
    """
    if not spans:
        return {"input_tokens": 0, "output_tokens": 0, "attempts": 0}

    lineage_keys = {s.get("gen_ai.tool.call.id") for s in spans}
    if len(lineage_keys) > 1:
        raise LineageCollapseError(
            f"spans span multiple lineage keys {lineage_keys}; "
            "cannot aggregate across logical calls"
        )

    attempts = [s.get("gen_ai.tool.attempt") for s in spans]
    if any(a is None for a in attempts):
        raise LineageCollapseError(
            f"lineage key {lineage_keys.pop()!r} has spans without "
            "gen_ai.tool.attempt; retry vs resume is unresolvable — "
            "refusing to sum, route to reconciliation"
        )

    if sorted(attempts) != list(range(1, len(attempts) + 1)):
        raise LineageCollapseError(
            f"attempt ordinals {sorted(attempts)} are not a contiguous "
            "1..N sequence; a resume likely minted a fresh lineage key "
            "or a retry skipped an ordinal"
        )

    # Supersede rule: an ERROR attempt followed by a higher-ordinal sibling
    # is discarded. UNSET (checkpoint) attempts are summed with continuation.
    kept = []
    for s in spans:
        higher_exists = any(
            o.get("gen_ai.tool.attempt") > s["gen_ai.tool.attempt"]
            for o in spans
        )
        if s.get("status.code") == "ERROR" and higher_exists:
            continue  # superseded retry — discard its usage
        kept.append(s)

    return {
        "input_tokens": sum(s.get("gen_ai.usage.input_tokens", 0) for s in kept),
        "output_tokens": sum(s.get("gen_ai.usage.output_tokens", 0) for s in kept),
        "attempts": len(kept),
    }
