# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-span-parenting-corruption-when-a-tool-call-span-and-its-agent-handoff-sibling-race-under-opentelemetry-genai-semantic.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-span-parenting-corruption-when-a-tool-call-span-and-its-agent-handoff-sibling-race-under-opentelemetry-genai-semantic.warrant.json
# Markdown SHA-256:   1098d2cbb78e0af3c18bbe8d681d90b7fe62d703563d8725961b34a5488c9a19
# Code AST SHA-256:   30f541b21bd0cdd01a55dfd6f3d10d07a6d6f56c3897a3d44bcf7f9afa531544
# Verified Classes:   HandoffTopologyError, GenAISpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class HandoffTopologyError(RuntimeError):
    """Raised when a GenAI handoff span is emitted while a referenced tool span is still open."""


@dataclass
class GenAISpan:
    span_id: str
    parent_span_id: Optional[str]
    operation_name: str  # "tool.call" | "agent.handoff" | "turn"
    start_ms: float
    end_ms: Optional[float] = None
    attributes: dict = field(default_factory=dict)
    context_ref: Optional[str] = None  # span_id referenced by a handoff payload

    @property
    def is_open(self) -> bool:
        return self.end_ms is None


def validate_handoff_emission(handoff: GenAISpan, siblings: list[GenAISpan]) -> None:
    if handoff.operation_name != "agent.handoff":
        return
    if handoff.attributes.get("gen_ai.handoff.speculative") is True:
        if handoff.context_ref is not None:
            raise HandoffTopologyError(
                f"speculative handoff {handoff.span_id} must not carry context_ref "
                f"to a pending tool (got {handoff.context_ref})"
            )
        return
    for sib in siblings:
        if sib.span_id == handoff.span_id:
            continue
        if sib.operation_name != "tool.call":
            continue
        referenced = handoff.context_ref == sib.span_id
        overlapping = sib.is_open or (sib.end_ms is not None and sib.end_ms > handoff.start_ms)
        if referenced and sib.is_open:
            raise HandoffTopologyError(
                f"handoff {handoff.span_id} references tool {sib.span_id} "
                f"which is still open at emission (t={handoff.start_ms}ms); "
                f"await the tool future or mark gen_ai.handoff.speculative=true"
            )
        if overlapping and not referenced and sib.parent_span_id == handoff.parent_span_id:
            raise HandoffTopologyError(
                f"handoff {handoff.span_id} shares parent {handoff.parent_span_id} "
                f"with overlapping tool {sib.span_id}; sibling token rollup will "
                f"misattribute gen_ai.usage.* across agents"
            )
