# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-accounting-spans-when-a-tool-call-span-s-gen-ai-usage-attributes-are-re-emitted-after-a-ret.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-accounting-spans-when-a-tool-call-span-s-gen-ai-usage-attributes-are-re-emitted-after-a-ret.warrant.json
# Markdown SHA-256:   77d4e4c442ff1902cc23faff94e5559a8e65e4716e897a5ee3c66d4acaa99375
# Code AST SHA-256:   4d9f6abada6f82a562374c77cf4c2b340a9f4ac8e4c42e061d76a930c1d95c83
# Verified Classes:   AmbiguousTokenAccounting, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AmbiguousTokenAccounting(RuntimeError):
    """Raised when a span tree cannot be reduced to a defensible token total."""


@dataclass
class Span:
    name: str
    operation: str
    request_id: Optional[str] = None
    attempt: Optional[int] = None
    input_tokens: int = 0
    output_tokens: int = 0
    children: list["Span"] = field(default_factory=list)

    def has_usage(self) -> bool:
        return self.input_tokens > 0 or self.output_tokens > 0


def reconcile_agent_tokens(root: Span) -> tuple[int, int]:
    """
    Reduce an invoke_agent span tree to (input_tokens, output_tokens).

    Invariant: input tokens are billed per attempt (sum across all attempts
    sharing a request_id); output tokens are billed once per logical request
    (terminal attempt only). Requires an attempt discriminator whenever a
    request_id repeats among descendants.
    """
    by_request: dict[str, list[Span]] = {}
    for child in _walk(root):
        if child.request_id is None or not child.has_usage():
            continue
        by_request.setdefault(child.request_id, []).append(child)

    total_input = 0
    total_output = 0
    for req_id, spans in by_request.items():
        if len(spans) > 1 and any(s.attempt is None for s in spans):
            raise AmbiguousTokenAccounting(
                f"request_id={req_id!r} appears on {len(spans)} spans but at "
                f"least one lacks gen_ai.request.attempt; cannot distinguish "
                f"retries from distinct calls. Refusing to emit cost metric."
            )
        total_input += sum(s.input_tokens for s in spans)
        terminal = max(spans, key=lambda s: s.attempt or 0)
        total_output += terminal.output_tokens

    if root.has_usage() and by_request:
        raise AmbiguousTokenAccounting(
            "parent span sets gen_ai.usage.* while children also set it; "
            "aggregation ownership is undefined (authoritative vs derived)."
        )
    if root.has_usage():
        return root.input_tokens, root.output_tokens
    return total_input, total_output


def _walk(span: Span):
    for child in span.children:
        yield child
        yield from _walk(child)


# Reproduces the observed billing-reconciler trace: three tool attempts sharing
# one request_id, no attempt discriminator -> must raise, not emit 7660.
lookup_attempts = [
    Span("execute_tool", "execute_tool", request_id="req-77", input_tokens=1180)
    for _ in range(3)
]
root = Span(
    "invoke_agent",
    "invoke_agent",
    request_id="req-77",
    input_tokens=4120,
    output_tokens=2047,
    children=lookup_attempts
    + [Span("chat", "chat", request_id="req-77", attempt=3,
            input_tokens=0, output_tokens=2047)],
)
try:
    reconcile_agent_tokens(root)
except AmbiguousTokenAccounting as exc:
    # Quarantine the span tree; do not publish gen_ai.client.token.usage.
    print(f"quarantined: {exc}")
