# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-otel-genai-agent-spans-when-tool-call-lineage-token-accounting-and-model-provenance-disagree-across-a-res.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-otel-genai-agent-spans-when-tool-call-lineage-token-accounting-and-model-provenance-disagree-across-a-res.warrant.json
# Markdown SHA-256:   4238ce9a3ef13c42f1169688ccb743e505ad12b4fbbc75b80eee765de23f7753
# Code AST SHA-256:   f70e6a3d020beb0011d74e47f93aad753112d9bbe518d29f21631abebe355b87
# Verified Classes:   LineageReconciliationError, GenAISpan
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class LineageReconciliationError(RuntimeError):
    """Raised when a GenAI trace cannot be reconciled under resume semantics."""

@dataclass
class GenAISpan:
    span_id: str
    trace_id: str
    parent_span_id: Optional[str]
    operation: str
    tool_call_id: Optional[str] = None
    retry_of: Optional[str] = None
    resume_of: Optional[str] = None
    input_tokens: int = 0
    output_tokens: int = 0
    model: Optional[str] = None

def reconcile_trace(spans: list[GenAISpan]) -> dict:
    """Sum token usage over a resumed GenAI trace, honoring retry/resume edges.

    Raises LineageReconciliationError if the trace is not reconcilable.
    """
    by_id = {s.span_id: s for s in spans}
    if len(by_id) != len(spans):
        raise LineageReconciliationError("duplicate span_id in trace")

    roots = [s for s in spans if s.parent_span_id is None and s.operation == "invoke_agent"]
    if not roots:
        raise LineageReconciliationError("no invoke_agent root span")

    # Every non-primary root must declare a resume edge to a known span.
    primary = [r for r in roots if r.resume_of is None]
    if len(primary) != 1:
        raise LineageReconciliationError(
            f"expected exactly one primary root, found {len(primary)}"
        )
    for r in roots:
        if r.resume_of is not None and r.resume_of not in by_id:
            raise LineageReconciliationError(
                f"resume_of points to unknown span {r.resume_of}"
            )

    # Any retry_of must reference a known, distinct span.
    for s in spans:
        if s.retry_of is not None and s.retry_of not in by_id:
            raise LineageReconciliationError(
                f"retry_of points to unknown span {s.retry_of}"
            )

    # Model provenance must be pinned (no alias) on every span that counts tokens.
    for s in spans:
        if (s.input_tokens or s.output_tokens) and s.model is None:
            raise LineageReconciliationError(
                f"span {s.span_id} counts tokens without gen_ai.request.model"
            )
        if s.model is not None and s.model.count("-") < 2:
            raise LineageReconciliationError(
                f"span {s.span_id} model {s.model!r} is an unpinned alias"
            )

    retried_ids = {s.retry_of for s in spans if s.retry_of is not None}
    total_in = total_out = 0
    for s in spans:
        if s.tool_call_id is not None and s.tool_call_id in retried_ids:
            continue  # superseded by a retry; do not double-count
        total_in += s.input_tokens
        total_out += s.output_tokens

    return {"trace_id": spans[0].trace_id, "input_tokens": total_in, "output_tokens": total_out}
