# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-tool-call-spans-under-a-parent-turn-span-that-has-already-been-closed-by-an-asynchronous-cancellation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-tool-call-spans-under-a-parent-turn-span-that-has-already-been-closed-by-an-asynchronous-cancellation.warrant.json
# Markdown SHA-256:   bf73ef0b39874bae1ae6f84d4ac1b36784b3a322a9fb004573792a6696572f23
# Code AST SHA-256:   ee077ce2b0059bdc9891715777678bd88a82f6b809b76bc1875ba54f24420234
# Verified Classes:   SpanCausalityViolation, GenAISpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class SpanCausalityViolation(RuntimeError):
    """Raised when a GenAI tool-call span would end after its parent turn span."""


@dataclass
class GenAISpan:
    name: str
    operation: str  # e.g. "chat", "execute_tool"
    tool_call_id: Optional[str] = None
    start_time: float = field(default_factory=time.monotonic)
    end_time: Optional[float] = None
    parent: Optional["GenAISpan"] = None
    turn_sequence: int = 0
    status: str = "UNSET"

    def end(self, when: Optional[float] = None) -> None:
        self.end_time = when if when is not None else time.monotonic()

    def is_closed(self) -> bool:
        return self.end_time is not None


def close_tool_span(tool_span: GenAISpan, when: Optional[float] = None) -> None:
    """Close a tool span, enforcing the temporal-containment invariant.

    If the parent turn span is already closed and the tool span would end
    after it, we cannot emit a valid child. The caller must either have
    used join-owned parenting (parent still open) or convert this span to
    a linked sibling. We refuse to emit the malformed child.
    """
    end = when if when is not None else time.monotonic()
    parent = tool_span.parent

    if parent is not None and parent.is_closed():
        if end > parent.end_time:
            raise SpanCausalityViolation(
                f"tool span {tool_span.tool_call_id!r} (turn {tool_span.turn_sequence}) "
                f"would end at {end:.3f}s after parent {parent.name!r} "
                f"closed at {parent.end_time:.3f}s; emit as linked sibling instead "
                f"or defer parent end via child-future join"
            )

    tool_span.end(end)
    tool_span.status = "OK"


def run_turn_join_owned(tool_latency: float) -> GenAISpan:
    """Correct pattern: parent end is gated on child join."""
    turn = GenAISpan(name="chat", operation="chat", turn_sequence=1)
    tool = GenAISpan(
        name="execute_tool",
        operation="execute_tool",
        tool_call_id="call_01H",
        parent=turn,
        turn_sequence=1,
    )
    # Simulate tool resolution BEFORE the parent is allowed to close.
    close_tool_span(tool, when=tool.start_time + tool_latency)
    turn.end(when=max(tool.end_time, turn.start_time + 0.05))
    return turn


def run_turn_broken(tool_latency: float) -> GenAISpan:
    """Broken pattern: parent closed at model completion, tool resolves later."""
    turn = GenAISpan(name="chat", operation="chat", turn_sequence=1)
    tool = GenAISpan(
        name="execute_tool",
        operation="execute_tool",
        tool_call_id="call_01H",
        parent=turn,
        turn_sequence=1,
    )
    turn.end(when=turn.start_time + 0.05)  # model finished; cancellation arrived
    # Tool adapter ignored cancellation and resolved much later.
    close_tool_span(tool, when=tool.start_time + tool_latency)  # raises
    return turn


if __name__ == "__main__":
    run_turn_join_owned(tool_latency=5.9)  # valid
    run_turn_broken(tool_latency=5.9)      # raises SpanCausalityViolation
