# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-tool-call-span-whose-gen-ai-usage-attributes-were-attributed-to-the-wrong-agent-turn-during-mcp-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-tool-call-span-whose-gen-ai-usage-attributes-were-attributed-to-the-wrong-agent-turn-during-mcp-handoff.warrant.json
# Markdown SHA-256:   561656c3409d86dc6f7fa50f52a65ef64e21bf5a118784e4bb1a0bcb98a40cbe
# Code AST SHA-256:   891431f5484065e707913999708dfb285aa098cf4e8bf7f1f0a015068d62752b
# Verified Classes:   ParentageMismatchError, TurnSpan, ToolSpan, GenAITraceReconciler
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import uuid
from dataclasses import dataclass, field
from typing import Dict, Set


class ParentageMismatchError(RuntimeError):
    """Raised when a tool-call span's parent turn does not match the issuing turn."""


@dataclass
class TurnSpan:
    span_id: str
    issued_tool_call_ids: Set[str] = field(default_factory=set)
    input_tokens: int = 0
    output_tokens: int = 0
    ended: bool = False


@dataclass
class ToolSpan:
    span_id: str
    parent_span_id: str
    tool_call_id: str
    tool_input_tokens: int = 0
    tool_output_tokens: int = 0


class GenAITraceReconciler:
    def __init__(self) -> None:
        self.turns: Dict[str, TurnSpan] = {}
        self.tool_calls: Dict[str, ToolSpan] = {}

    def register_turn(self, span_id: str) -> TurnSpan:
        turn = TurnSpan(span_id=span_id)
        self.turns[span_id] = turn
        return turn

    def issue_tool_call(self, turn_span_id: str) -> str:
        call_id = str(uuid.uuid4())
        turn = self.turns[turn_span_id]
        if turn.ended:
            raise ParentageMismatchError(
                f"turn {turn_span_id} already ended; cannot issue tool call {call_id}"
            )
        turn.issued_tool_call_ids.add(call_id)
        return call_id

    def record_tool_span(self, tool: ToolSpan) -> None:
        parent = self.turns.get(tool.parent_span_id)
        if parent is None:
            raise ParentageMismatchError(
                f"tool span {tool.span_id} references unknown parent {tool.parent_span_id}"
            )
        if tool.tool_call_id not in parent.issued_tool_call_ids:
            # The critical boundary: parentage edge disagrees with issued-call identity.
            raise ParentageMismatchError(
                f"tool span {tool.span_id} (call {tool.tool_call_id}) "
                f"claims parent {tool.parent_span_id}, but that turn never issued it. "
                f"Issued set: {sorted(parent.issued_tool_call_ids)}"
            )
        self.tool_calls[tool.tool_call_id] = tool

    def reconcile_usage(self) -> Dict[str, int]:
        """Join usage by tool_call_id, not by span-tree parentage."""
        totals: Dict[str, int] = {}
        for call_id, tool in self.tool_calls.items():
            totals[call_id] = tool.tool_input_tokens + tool.tool_output_tokens
        return totals


# Failure trace: turn 1 issues a retrieval; MCP server returns after turn 1 ended,
# and the client's span processor re-parents the tool span onto turn 2.
r = GenAITraceReconciler()
t1 = r.register_turn("A1")
call = r.issue_tool_call("A1")
t1.ended = True            # turn 1 closes before the tool result returns
t2 = r.register_turn("A3") # turn 2 is now active

try:
    r.record_tool_span(
        ToolSpan(span_id="C4", parent_span_id="A3", tool_call_id=call,
                 tool_input_tokens=1200, tool_output_tokens=0)
    )
except ParentageMismatchError as e:
    # Correct behavior: refuse to attribute; emit synthetic resumed-turn span instead.
    print(f"detected: {e}")
    r.record_tool_span(
        ToolSpan(span_id="C4", parent_span_id="A1", tool_call_id=call,
                 tool_input_tokens=1200, tool_output_tokens=0)
    )
