# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-opentelemetry-genai-span-attributes-for-a-tool-call-whose-token-accounting-crosses-a-provider-side-retry-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-opentelemetry-genai-span-attributes-for-a-tool-call-whose-token-accounting-crosses-a-provider-side-retry-boundary.warrant.json
# Markdown SHA-256:   28155e188c5953a06ff090c4abe88e7682f9ddfcad37e2093761fe44ba3ed1dc
# Code AST SHA-256:   2125bd548bb9b6813f87a57f354f22efda1a3a760ddf0a0d3b4ef68879eda6e6
# Verified Classes:   UsageLineageViolation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UsageLineageViolation(RuntimeError):
    """Raised when a logical GenAI operation's span lineage would double-count usage."""
    pass


def finalize_usage_lineage(spans: list[dict]) -> dict:
    """
    Enforce the invariant: for each logical operation parent, exactly one
    usage-bearing span is canonical, or superseded spans are explicitly marked.
    Returns the canonical usage record. Raises on ambiguity.
    """
    by_parent: dict[str, list[dict]] = {}
    for span in spans:
        if "gen_ai.usage.input_tokens" in span.get("attributes", {}):
            parent = span.get("parent_span_id")
            by_parent.setdefault(parent, []).append(span)

    canonical_records = {}
    for parent, usage_spans in by_parent.items():
        canonical = [
            s for s in usage_spans
            if s["attributes"].get("gen_ai.usage.canonical") is True
        ]
        superseded = [
            s for s in usage_spans
            if s["attributes"].get("gen_ai.retry.superseded") is True
        ]
        unmarked = [s for s in usage_spans if s not in canonical and s not in superseded]

        if len(canonical) == 1 and not unmarked:
            canonical_records[parent] = {
                "input_tokens": canonical[0]["attributes"]["gen_ai.usage.input_tokens"],
                "output_tokens": canonical[0]["attributes"]["gen_ai.usage.output_tokens"],
                "span_id": canonical[0]["span_id"],
            }
        elif len(canonical) == 0 and len(usage_spans) == 1:
            # Single unmarked usage span is unambiguous by cardinality.
            canonical_records[parent] = {
                "input_tokens": usage_spans[0]["attributes"]["gen_ai.usage.input_tokens"],
                "output_tokens": usage_spans[0]["attributes"]["gen_ai.usage.output_tokens"],
                "span_id": usage_spans[0]["span_id"],
            }
        else:
            raise UsageLineageViolation(
                f"Ambiguous usage lineage under parent {parent!r}: "
                f"{len(canonical)} canonical, {len(superseded)} superseded, "
                f"{len(unmarked)} unmarked usage spans. "
                f"Refusing to emit summed usage; mark supersession or designate canonical."
            )
    return canonical_records
