# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-the-causal-chain-when-opentelemetry-genai-spans-are-emitted-per-turn-but-the-agent-loop-re-enters-a-tool-call-after-a-retry.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-the-causal-chain-when-opentelemetry-genai-spans-are-emitted-per-turn-but-the-agent-loop-re-enters-a-tool-call-after-a-retry.warrant.json
# Markdown SHA-256:   8c3f244b2fa4af17bde29e05529a9a17e094f1e2c0d6a8d46d0ad436bcaed3c7
# Code AST SHA-256:   6e7ac7cce1b5d4b6e987b26813ca4344bb8ce0476879b54fcfbf8d4885a1ffda
# Verified Classes:   CausalParentInversion, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CausalParentInversion(RuntimeError):
    """Raised when a GenAI tool-call span's parent is not the chat span that requested it,
    or when a retry is indistinguishable from a first attempt under the same parent."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    operation: str            # "chat" | "execute_tool"
    tool_name: Optional[str] = None
    retry_count: Optional[int] = None
    tool_call_id: Optional[str] = None


def assert_genai_causal_integrity(spans: list[Span]) -> None:
    by_id = {s.span_id: s for s in spans}
    # Rule 1: every execute_tool span's parent must be a chat span.
    for s in spans:
        if s.operation != "execute_tool":
            continue
        parent = by_id.get(s.parent_span_id)
        if parent is None:
            raise CausalParentInversion(
                f"tool span {s.span_id} has dangling parent {s.parent_span_id}"
            )
        if parent.operation != "chat":
            raise CausalParentInversion(
                f"tool span {s.span_id} (tool={s.tool_name}) parented to "
                f"{parent.operation} span {parent.span_id}; expected a chat span. "
                f"This is the retry-wrapper context-capture defect."
            )
    # Rule 2: siblings under one chat span must be distinguishable as retries.
    siblings: dict[str, list[Span]] = {}
    for s in spans:
        if s.operation == "execute_tool":
            siblings.setdefault(s.parent_span_id, []).append(s)
    for parent_id, group in siblings.items():
        if len(group) < 2:
            continue
        seen: set[tuple] = set()
        for s in group:
            key = (s.tool_name, s.retry_count, s.tool_call_id)
            if key in seen:
                raise CausalParentInversion(
                    f"two execute_tool spans under chat {parent_id} share "
                    f"identity {key}; retry_count/tool_call_id missing, so the "
                    f"retry is causally indistinguishable from a first attempt."
                )
            seen.add(key)


def emit_tool_span(turn_ctx_parent: str, attempt: int, tool: str,
                   tool_call_id: str, retry_ctx_parent: Optional[str]) -> Span:
    # Guardrail: never trust the wrapper's captured parent on retries.
    parent = retry_ctx_parent if retry_ctx_parent is not None else turn_ctx_parent
    if attempt > 0 and parent != turn_ctx_parent:
        raise CausalParentInversion(
            f"retry attempt {attempt} for {tool} re-parented away from turn "
            f"{turn_ctx_parent} to {parent}; retries must remain children of the "
            f"requesting chat span and carry retry_count."
        )
    return Span(
        span_id=f"{turn_ctx_parent}-{tool}-{attempt}",
        parent_span_id=parent,
        operation="execute_tool",
        tool_name=tool,
        retry_count=attempt if attempt > 0 else None,
        tool_call_id=tool_call_id,
    )
