# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tool-call-span-re-parenting-from-silently-corrupting-agent-turn-attribution-under-opentelemetry-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tool-call-span-re-parenting-from-silently-corrupting-agent-turn-attribution-under-opentelemetry-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   ae78f09c2a6231afb90f45b0b27f8a49d39a53c1f7b26a8b92a882b1e793b9e7
# Code AST SHA-256:   223994816eb79666f70885c997da37520c9dc6af025d1fd13338de00f1e4036c
# Verified Classes:   TurnAttributionError, Span, Trace
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class TurnAttributionError(RuntimeError):
    """Raised when a tool-call span violates the turn-attribution invariant."""


@dataclass
class Span:
    span_id: str
    parent_span_id: str | None
    operation: str
    turn_index: int | None
    turn_span_id: str | None
    tool_name: str | None = None
    retry_count: int = 0
    input_tokens: int = 0
    output_tokens: int = 0

    @property
    def is_tool(self) -> bool:
        return self.operation == "execute_tool"

    @property
    def is_chat(self) -> bool:
        return self.operation in ("chat", "invoke_agent")


@dataclass
class Trace:
    spans: list[Span] = field(default_factory=list)

    def by_id(self) -> dict[str, Span]:
        return {s.span_id: s for s in self.spans}

    def chat_spans(self) -> Iterable[Span]:
        return (s for s in self.spans if s.is_chat)

    def tool_spans(self) -> Iterable[Span]:
        return (s for s in self.spans if s.is_tool)


def assert_turn_attribution(trace: Trace) -> None:
    """Enforce: every tool span resolves to a live chat span whose turn_index matches."""
    index = trace.by_id()
    for tool in trace.tool_spans():
        if tool.turn_span_id is None:
            raise TurnAttributionError(
                f"tool span {tool.span_id} ({tool.tool_name}) has no turn_span_id; "
                "re-parenting leak — attribution is unverifiable"
            )
        parent = index.get(tool.turn_span_id)
        if parent is None or not parent.is_chat:
            raise TurnAttributionError(
                f"tool span {tool.span_id} references turn_span_id={tool.turn_span_id} "
                f"which is not a live chat span"
            )
        if parent.turn_index != tool.turn_index:
            raise TurnAttributionError(
                f"tool span {tool.span_id} turn_index={tool.turn_index} disagrees with "
                f"parent turn span {parent.span_id} turn_index={parent.turn_index}"
            )


def reconcile_rollups(trace: Trace) -> dict[str, int]:
    """Return per-turn token totals keyed by turn_span_id, deduplicated by retry."""
    assert_turn_attribution(trace)
    seen: set[tuple[str | None, str | None, int]] = set()
    totals: dict[str, int] = {}
    for tool in trace.tool_spans():
        key = (tool.turn_span_id, tool.tool_name, tool.retry_count)
        if key in seen:
            continue
        seen.add(key)
        cost = tool.input_tokens + tool.output_tokens
        totals[tool.turn_span_id] = totals.get(tool.turn_span_id, 0) + cost  # type: ignore[index]
    for chat in trace.chat_spans():
        cost = chat.input_tokens + chat.output_tokens
        totals[chat.span_id] = totals.get(chat.span_id, 0) + cost
    return totals


def detect_divergence(trace: Trace) -> str:
    index = trace.by_id()
    session_total = sum(s.input_tokens + s.output_tokens for s in trace.spans if s.is_tool or s.is_chat)
    try:
        per_turn = reconcile_rollups(trace)
    except TurnAttributionError as exc:
        return f"attribution_corrupt: {exc}"
    turn_total = sum(per_turn.values())
    residual = session_total - turn_total
    if residual == 0:
        return "consistent"
    if residual > 0:
        orphans = [
            s.span_id
            for s in trace.tool_spans()
            if s.parent_span_id is not None
            and index.get(s.parent_span_id) is not None
            and index[s.parent_span_id].is_chat is False
        ]
        if orphans:
            raise TurnAttributionError(
                f"re-parenting leak: residual={residual} tokens across orphaned tool spans {orphans}"
            )
    return f"divergent: residual={residual}"
