# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-token-counts-against-the-turn-causality-chain-before-trusting-a-cumulative-cost-attribute.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-token-counts-against-the-turn-causality-chain-before-trusting-a-cumulative-cost-attribute.warrant.json
# Markdown SHA-256:   ca9b4c66dc8049b5baefe932cd8eb23ab13fe44798f189f3637c33bdea1ea2eb
# Code AST SHA-256:   2cc60eeceda77b997ba856c44274f09ce4a845f6095d6d4e68e697d6349af0b0
# Verified Classes:   TurnAccountingError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TurnAccountingError(RuntimeError):
    """Raised when a turn's span graph cannot yield a trustworthy token total."""
    pass


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    kind: str                      # "agent.turn" | "gen_ai.chat" | "gen_ai.tool"
    end_ms: int
    input_tokens: int = 0
    output_tokens: int = 0
    retry_of: str | None = None    # dedup key for re-sent prompts


def reconcile_turn(root: Span, spans: list[Span]) -> int:
    children = {s.span_id: s for s in spans if s.parent_id == root.span_id}
    reachable: dict[str, list[str]] = {}

    def walk(span: Span, path: list[str]) -> None:
        for s in spans:
            if s.parent_id == span.span_id:
                reachable.setdefault(s.span_id, []).append("/".join(path + [span.span_id]))
                walk(s, path + [span.span_id])

    walk(root, [])

    # Invariant 1: tree closure — no descendant ends after the root.
    for s in spans:
        if s.end_ms > root.end_ms and s.span_id in reachable:
            raise TurnAccountingError(
                f"orphan span {s.span_id} ends at {s.end_ms}ms, after root "
                f"{root.span_id} at {root.end_ms}ms; cumulative total is a lower bound"
            )

    # Invariant 2: single-path reachability — no inference span reached twice.
    for sid, paths in reachable.items():
        if len(paths) > 1:
            raise TurnAccountingError(
                f"span {sid} reachable by {len(paths)} paths {paths}; sum would double-count"
            )

    # Invariant 3: retries must be tagged, else totals are ambiguous.
    total = 0
    for s in spans:
        if s.kind != "gen_ai.chat":
            continue
        if s.retry_of is None and any(
            o.retry_of is None and o.input_tokens == s.input_tokens and o.span_id != s.span_id
            for o in spans if o.kind == "gen_ai.chat"
        ):
            # identical untagged input on two spans: flag, do not silently sum
            raise TurnAccountingError(
                f"span {s.span_id} has duplicate untagged input ({s.input_tokens}); "
                "tag retries with retry_of or totals are ambiguous"
            )
        total += s.input_tokens + s.output_tokens
    return total
