# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-genai-agent-spans-from-silently-losing-tool-call-causality-across-retries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-genai-agent-spans-from-silently-losing-tool-call-causality-across-retries.warrant.json
# Markdown SHA-256:   8b71b51977ca63a23e4ca19281298c88d88582bf2490982bb74391abbb7e7ff1
# Code AST SHA-256:   410fc9e5b863f4f16f90cab34c2c6974e1b696136d1ecc64f52f8cc2b194f04d
# Verified Classes:   ToolCallCausalityError, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ToolCallCausalityError(RuntimeError):
    """Raised when a gen_ai.tool.call.id does not resolve to exactly one
    terminal tool-execution span, violating the retry correlation invariant."""
    pass


@dataclass
class Span:
    name: str
    attributes: dict = field(default_factory=dict)
    status: str = "UNSET"
    parent: Optional["Span"] = None
    children: list = field(default_factory=list)


def record_tool_attempt(
    parent_model_span: Span,
    call_id: str,
    attempt: int,
    outcome: str,
    replacement_id: Optional[str] = None,
) -> Span:
    """Emit a tool-execution span under a model span, enforcing that the
    logical call id is immutable across retries.

    The parent's gen_ai.tool.call.id must equal call_id. On a regenerated
    retry (new id), the caller must pass replacement_id and the prior id
    must already be closed as abandoned.
    """
    parent_call_id = parent_model_span.attributes.get("gen_ai.tool.call.id")

    if parent_call_id is None:
        raise ToolCallCausalityError(
            f"parent span {parent_model_span.name!r} has no gen_ai.tool.call.id; "
            "cannot attribute tool execution"
        )

    if replacement_id is not None:
        # Regenerated retry: the logical call id changed. The parent must
        # carry the abandoned marker or the trace is causally broken.
        abandoned = parent_model_span.attributes.get("gen_ai.tool.call.abandoned")
        if abandoned != parent_call_id:
            raise ToolCallCausalityError(
                f"retry with replacement_id={replacement_id!r} but parent call id "
                f"{parent_call_id!r} was not marked abandoned; "
                "downstream joins will double-count or orphan"
            )
        if call_id == parent_call_id:
            raise ToolCallCausalityError(
                "replacement retry must carry a new call id, not the original"
            )
    else:
        if call_id != parent_call_id:
            raise ToolCallCausalityError(
                f"tool attempt call_id={call_id!r} does not match parent "
                f"gen_ai.tool.call.id={parent_call_id!r}; "
                "replay retries must reuse the logical id"
            )

    span = Span(
        name=f"execute_tool {parent_model_span.attributes.get('gen_ai.tool.name', '?')}",
        attributes={
            "gen_ai.tool.call.id": call_id,
            "gen_ai.tool.attempt": attempt,
            "gen_ai.tool.replacement_id": replacement_id,
        },
        status=outcome,
        parent=parent_model_span,
    )
    parent_model_span.children.append(span)
    return span


def resolve_call(spans: list, call_id: str) -> Span:
    """Exactly one terminal tool span must resolve for a call id."""
    matches = [
        s for s in spans
        if s.attributes.get("gen_ai.tool.call.id") == call_id
        and s.status in ("OK", "ERROR")
    ]
    if len(matches) != 1:
        raise ToolCallCausalityError(
            f"call id {call_id!r} resolved to {len(matches)} terminal spans; "
            "invariant requires exactly one"
        )
    return matches[0]
