# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-opentelemetry-genai-span-attributes-when-tool-call-lineage-and-token-accounting-diverge-across-a-resu.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-opentelemetry-genai-span-attributes-when-tool-call-lineage-and-token-accounting-diverge-across-a-resu.warrant.json
# Markdown SHA-256:   1bfe7de365587a1058d05150d20424247dbd207527934f9258ee6c81c9ef0182
# Code AST SHA-256:   3d1ef71fc5f963e611b90871cbdf9b7e4ebe815dea17284aef225008d6833e5b
# Verified Classes:   LineageAccountingDivergence, GenAISpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class LineageAccountingDivergence(RuntimeError):
    """Raised when a trace's terminal-span cardinality or token sum violates the resume invariant."""
    pass


@dataclass
class GenAISpan:
    trace_id: str
    span_id: str
    operation: str                       # "chat" | "execute_tool"
    tool_call_id: Optional[str] = None   # gen_ai.tool.call.id
    ended: bool = True
    input_tokens: int = 0                # gen_ai.usage.input_tokens
    output_tokens: int = 0               # gen_ai.usage.output_tokens


def reconcile_trace(spans: list[GenAISpan], billed_input_tokens: int) -> dict:
    """
    Enforce: exactly one terminal span per (trace_id, tool_call_id);
    orphan chat spans (tool call with no terminal tool span) excluded from sums.
    """
    terminal_tool: dict[str, GenAISpan] = {}
    for s in spans:
        if s.operation == "execute_tool" and s.tool_call_id is not None:
            if not s.ended:
                continue  # abandoned span; never counted
            if s.tool_call_id in terminal_tool:
                raise LineageAccountingDivergence(
                    f"duplicate terminal tool span for call_id={s.tool_call_id} "
                    f"in trace={s.trace_id}: {terminal_tool[s.tool_call_id].span_id} "
                    f"vs {s.span_id}"
                )
            terminal_tool[s.tool_call_id] = s

    total_in = total_out = 0
    orphans = 0
    for s in spans:
        if not s.ended:
            continue
        if s.operation == "chat":
            # orphan: model span whose declared tool call has no terminal tool span
            if s.tool_call_id is not None and s.tool_call_id not in terminal_tool:
                orphans += 1
                continue
        total_in += s.input_tokens
        total_out += s.output_tokens

    if total_in != billed_input_tokens:
        raise LineageAccountingDivergence(
            f"reconciled input tokens {total_in} != billed {billed_input_tokens} "
            f"for trace {spans[0].trace_id if spans else '?'} (orphans dropped: {orphans})"
        )
    return {"input_tokens": total_in, "output_tokens": total_out, "orphans_dropped": orphans}
