# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-spans-when-a-tool-call-chain-fragments-token-usage-across-nested-retried-and-re-entrant-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-spans-when-a-tool-call-chain-fragments-token-usage-across-nested-retried-and-re-entrant-spans.warrant.json
# Markdown SHA-256:   b84bdac279cc75edcfbf0da826b4c8f6ae7bbdccb4b04a6e39c2c3340476f756
# Code AST SHA-256:   214e444a55f4bf29e29688fdbb37bfd658edded8ea750d10fceac327d725587d
# Verified Classes:   CostAttributionError, GenAISpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable

LLM_OPS = {"chat", "text_completion", "embeddings"}


class CostAttributionError(RuntimeError):
    """Raised when a GenAI span cannot be attributed to a billed work unit."""


@dataclass(frozen=True)
class GenAISpan:
    span_id: str
    parent_id: str | None
    operation_name: str          # gen_ai.operation.name
    work_key: str | None         # stable across retries; unique per logical call
    attempt: int | None          # monotonic retry counter
    input_tokens: int | None
    output_tokens: int | None


def attribute_cost(spans: Iterable[GenAISpan]) -> dict[tuple[str, int], int]:
    """
    Aggregate tokens by (work_key, attempt) across ALL LLM spans,
    regardless of parent span kind. Re-entrant LLM calls under tool
    spans are included; retries are counted per attempt, never deduped.
    """
    totals: dict[tuple[str, int], int] = {}
    for s in spans:
        if s.operation_name not in LLM_OPS:
            continue
        if s.work_key is None or s.attempt is None:
            raise CostAttributionError(
                f"LLM span {s.span_id} ({s.operation_name}) lacks work_key/attempt; "
                "unattributable and would corrupt subtree sums"
            )
        if s.input_tokens is None or s.output_tokens is None:
            raise CostAttributionError(
                f"LLM span {s.span_id} missing usage tokens; "
                "streaming close-before-usage would under-count"
            )
        key = (s.work_key, s.attempt)
        totals[key] = totals.get(key, 0) + s.input_tokens + s.output_tokens
    return totals


def enforce_no_reentrant_gap(spans: list[GenAISpan]) -> None:
    """Fail loudly if an LLM span hides beneath a tool span without a work_key lineage."""
    by_id = {s.span_id: s for s in spans}
    for s in spans:
        if s.operation_name not in LLM_OPS:
            continue
        parent = by_id.get(s.parent_id) if s.parent_id else None
        if parent and parent.operation_name == "tool.execute" and s.work_key is None:
            raise CostAttributionError(
                f"re-entrant LLM span {s.span_id} under tool {parent.span_id} "
                "has no inherited work_key; budget enforcer would orphan it"
            )
