# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-opentelemetry-genai-semantic-conventions-silently-merge-distinct-agent-tool-call-turns-into-a-single-span.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-opentelemetry-genai-semantic-conventions-silently-merge-distinct-agent-tool-call-turns-into-a-single-span.warrant.json
# Markdown SHA-256:   0998e2cc206a92d5d1ba383dfd5f7517a0dcb99a2ac9aaf98b568413ed281535
# Code AST SHA-256:   cb4e6c933757763d7f69b6bfea1e60bd79d9ffacf53d4ee34e2dd18d06197706
# Verified Classes:   SpanGrainMismatchError, DuplicateToolCallError, SpanRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class SpanGrainMismatchError(RuntimeError):
    """Raised when a span's grain is coarser than the agent's side-effect grain."""
    pass

class DuplicateToolCallError(RuntimeError):
    """Raised when a tool call id has already completed under the same conversation."""
    pass

@dataclass
class SpanRecord:
    span_id: str
    parent_span_id: Optional[str]
    operation: str            # e.g. "invoke_agent", "execute_tool", "chat"
    tool_call_id: Optional[str]
    conversation_id: str
    start_ns: int
    end_ns: Optional[int]
    status: str               # "UNSET" | "OK" | "ERROR"

def assert_resumable_checkpoint(
    request_span: SpanRecord,
    tool_spans: list[SpanRecord],
    side_effecting_tool_ids: set[str],
) -> str:
    """
    Verify the trace grain matches the agent's recovery grain before resuming.
    Returns the span_id of the last durable checkpoint (last ended tool span).
    """
    if not tool_spans:
        # Single-span model is fine only if no side-effecting tools ran.
        if side_effecting_tool_ids:
            raise SpanGrainMismatchError(
                f"request span {request_span.span_id} has side-effecting tool ids "
                f"{side_effecting_tool_ids} but no child tool spans; cannot resume safely"
            )
        return request_span.span_id

    for tool in tool_spans:
        if tool.operation != "execute_tool":
            continue
        if tool.parent_span_id != request_span.span_id:
            raise SpanGrainMismatchError(
                f"tool span {tool.span_id} not parented to request {request_span.span_id}"
            )
        if tool.start_ns < request_span.start_ns:
            raise SpanGrainMismatchError(
                f"tool span {tool.span_id} starts before its parent — clock or replay corruption"
            )
        if tool.tool_call_id in side_effecting_tool_ids and tool.end_ns is None:
            raise SpanGrainMismatchError(
                f"side-effecting tool {tool.tool_call_id} has no end_time; "
                "checkpoint is not durable"
            )

    ended = [t for t in tool_spans if t.end_ns is not None and t.status == "OK"]
    if not ended:
        return request_span.span_id

    last = max(ended, key=lambda t: t.end_ns)
    return last.span_id  # resume AFTER this span

def record_tool_call(
    existing: list[SpanRecord],
    new_call: SpanRecord,
) -> None:
    for rec in existing:
        if (
            rec.conversation_id == new_call.conversation_id
            and rec.tool_call_id == new_call.tool_call_id
            and rec.status == "OK"
        ):
            raise DuplicateToolCallError(
                f"tool call {new_call.tool_call_id} already completed as span "
                f"{rec.span_id} in conversation {new_call.conversation_id}; refusing replay"
            )
