# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-emit-orphaned-tool-call-spans-when-genai-token-accounting-crosses-a-retry-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-emit-orphaned-tool-call-spans-when-genai-token-accounting-crosses-a-retry-boundary.warrant.json
# Markdown SHA-256:   88f973c3fbe174bf3290e6e9b094ed4f35a4cb1990a57871d2d3da55523d4fd2
# Code AST SHA-256:   bb77d9078f0aa3e2f35d2d9dd23dee52f497b8de2225e6332173f72d5221745f
# Verified Classes:   OrphanedToolCallError, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class OrphanedToolCallError(RuntimeError):
    """Raised when a chat span's tool_calls have no matching execute_tool descendant,
    or when an execute_tool span's parent chat span carries zero usage."""


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    operation: str                 # "chat" | "execute_tool"
    finish_reasons: list[str] = field(default_factory=list)
    output_tokens: int = 0
    tool_call_id: str | None = None
    exported: bool = True


def reconcile_tool_lineage(spans: list[Span]) -> None:
    """Enforce parent-child usage consistency across a retry boundary.

    Invariant: every chat span reporting finish_reason 'tool_calls' must own at
    least one execute_tool descendant with a matching call id, and every
    execute_tool span must have an exported, non-zero-usage chat parent.
    """
    by_id = {s.span_id: s for s in spans if s.exported}
    chat_spans = [s for s in spans if s.operation == "chat" and s.exported]
    tool_spans = [s for s in spans if s.operation == "execute_tool"]

    # 1. Every tool call must resolve to an exported chat parent with real usage.
    for tool in tool_spans:
        parent = by_id.get(tool.parent_id) if tool.parent_id else None
        if parent is None:
            raise OrphanedToolCallError(
                f"execute_tool span {tool.span_id} (call_id={tool.tool_call_id}) "
                f"parents to unexported/failed chat span {tool.parent_id}; "
                f"token lineage is broken and replay would fabricate a tool call"
            )
        if parent.operation != "chat":
            raise OrphanedToolCallError(
                f"execute_tool span {tool.span_id} parent {parent.span_id} "
                f"is not a chat span (op={parent.operation})"
            )
        if parent.output_tokens <= 0:
            raise OrphanedToolCallError(
                f"execute_tool span {tool.span_id} parent chat {parent.span_id} "
                f"reports zero output tokens; tokens were likely paid on a dropped retry"
            )

    # 2. Every chat span that requested tool calls must own a matching tool descendant.
    for chat in chat_spans:
        if "tool_calls" not in chat.finish_reasons:
            continue
        owned = [t for t in tool_spans if t.parent_id == chat.span_id]
        if not owned:
            raise OrphanedToolCallError(
                f"chat span {chat.span_id} reports finish_reasons={chat.finish_reasons} "
                f"but has no execute_tool descendant; tool call was orphaned to a "
                f"retry attempt that was never exported"
            )


def emit_reconciled_trace(spans: list[Span]) -> None:
    try:
        reconcile_tool_lineage(spans)
    except OrphanedToolCallError as exc:
        # Quarantine: do not repair lineage, do not fabricate a token/tool pairing.
        raise OrphanedToolCallError(
            f"trace quarantined as incomplete_lineage: {exc}"
        ) from exc
