# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-parent-child-span-invariant-when-a-tool-call-is-retried-under-a-new-genai-span-and-the-otel-genai-semantic-conven.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-parent-child-span-invariant-when-a-tool-call-is-retried-under-a-new-genai-span-and-the-otel-genai-semantic-conven.warrant.json
# Markdown SHA-256:   17393855b08e004c6012726fb3c13d62eec34492cde7ccc5d3240d702023331b
# Code AST SHA-256:   f7d16c391d8fe3d04972646b628c9398941a6ffce92c7fd7ed0ebc1c767799b6
# Verified Classes:   AmbiguousToolSpanError, ToolSpan
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class AmbiguousToolSpanError(RuntimeError):
    """Raised when a tool-call span group cannot be disambiguated for replay."""


@dataclass
class ToolSpan:
    span_id: str
    parent_chat_span_id: str
    tool_call_id: str          # gen_ai.tool.call.id, model-emitted, may repeat
    attempt: Optional[int]     # gen_ai.tool.call.attempt, zero-based
    superseded_by: Optional[str]  # span_id of the attempt that replaced this one
    status: str                # "OK" | "ERROR"


def assert_replayable(group: list[ToolSpan]) -> ToolSpan:
    """Return the authoritative span for one logical tool call.

    A group is all spans sharing (tool_call_id, parent_chat_span_id).
    Exactly one span must be authoritative: no superseded_by, and either
    attempt == 0 (no retry) or attempt == max(attempt) (final retry).
    """
    if not group:
        raise AmbiguousToolSpanError("empty tool-span group")

    call_id = group[0].tool_call_id
    chat_id = group[0].parent_chat_span_id

    # Every span must carry an attempt index; absence is the silent defect.
    for s in group:
        if s.attempt is None:
            raise AmbiguousToolSpanError(
                f"tool call {call_id!r} under chat {chat_id!r}: span "
                f"{s.span_id!r} has no gen_ai.tool.call.attempt; retry "
                f"is indistinguishable from a second sibling tool call"
            )

    max_attempt = max(s.attempt for s in group)
    finals = [s for s in group if s.attempt == max_attempt]

    if len(finals) != 1:
        raise AmbiguousToolSpanError(
            f"tool call {call_id!r} under chat {chat_id!r}: "
            f"{len(finals)} spans share attempt={max_attempt}; "
            f"attempt index is not unique, trace is unreplayable"
        )

    authoritative = finals[0]

    # Every non-final attempt must explicitly point at its successor.
    for s in group:
        if s.span_id == authoritative.span_id:
            continue
        if s.superseded_by is None:
            raise AmbiguousToolSpanError(
                f"tool call {call_id!r} under chat {chat_id!r}: "
                f"superseded span {s.span_id!r} (attempt={s.attempt}) "
                f"has no gen_ai.tool.call.superseded_by link; "
                f"causal chain is broken"
            )

    # The authoritative span must not itself be marked superseded.
    if authoritative.superseded_by is not None:
        raise AmbiguousToolSpanError(
            f"tool call {call_id!r} under chat {chat_id!r}: "
            f"authoritative span {authoritative.span_id!r} is marked "
            f"superseded_by={authoritative.superseded_by!r}"
        )

    return authoritative


def emit_retry_span(
    prior: ToolSpan,
    new_span_id: str,
    status: str,
) -> ToolSpan:
    """Construct a retry span that preserves the replay invariant."""
    if prior.attempt is None:
        raise AmbiguousToolSpanError(
            f"cannot retry span {prior.span_id!r}: prior attempt index "
            f"missing, retry would produce an ambiguous sibling"
        )
    retry = ToolSpan(
        span_id=new_span_id,
        parent_chat_span_id=prior.parent_chat_span_id,
        tool_call_id=prior.tool_call_id,
        attempt=prior.attempt + 1,
        superseded_by=None,
        status=status,
    )
    # Mutating the prior span is only legal before export; the runtime
    # must hold the span open until the retry resolves.
    prior.superseded_by = new_span_id
    return retry
