# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-genai-tool-call-span-as-non-terminal-when-the-agent-loop-has-already-advanced.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-genai-tool-call-span-as-non-terminal-when-the-agent-loop-has-already-advanced.warrant.json
# Markdown SHA-256:   3b51472db4921e0e961a3b782b360870b7eb93bc25e0789450b09dc442eebb9c
# Code AST SHA-256:   1c8a52f1347351f328cedd67745807a16a328e1ec135954e7a2ba19e711dbd5e
# Verified Classes:   SpanLifecycleViolation, ExecutorState, ToolCallSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class SpanLifecycleViolation(RuntimeError):
    """Raised when the agent loop attempts to terminate a tool-call span
    whose executor has not reached a confirmed terminal state."""


class ExecutorState(Enum):
    RUNNING = "running"
    RETURNED = "returned"
    CANCELLED_CONFIRMED = "cancelled_confirmed"


@dataclass
class ToolCallSpan:
    call_id: str
    tool_name: str
    executor_state: ExecutorState = ExecutorState.RUNNING
    closed: bool = False
    status: str = "UNSET"
    error_type: Optional[str] = None
    superseded_by: Optional[str] = None
    attributes: dict = field(default_factory=dict)


def close_span_on_loop_advance(
    span: ToolCallSpan, superseding_call_id: Optional[str] = None
) -> None:
    """Called when the loop times out, retries, or otherwise advances past a
    call. Enforces the boundary: the loop may not close a span whose executor
    is still running unless it is explicitly reclassified as abandoned."""
    if span.closed:
        raise SpanLifecycleViolation(
            f"span {span.call_id} already closed; double-close would corrupt trace"
        )

    if span.executor_state is ExecutorState.RETURNED:
        span.status = "OK"
        span.closed = True
        return

    if span.executor_state is ExecutorState.CANCELLED_CONFIRMED:
        span.status = "ERROR"
        span.error_type = "cancelled"
        span.closed = True
        return

    # Executor still running. The loop has abandoned interest, not the work.
    if superseding_call_id is None:
        raise SpanLifecycleViolation(
            f"span {span.call_id} abandoned by loop with no superseding call id; "
            "cannot record supersession and refuse to close silently"
        )

    span.status = "ERROR"
    span.error_type = "abandoned_by_loop"
    span.superseded_by = superseding_call_id
    span.attributes["gen_ai.tool.call.superseded_by"] = superseding_call_id
    # Deliberately NOT closed: executor is live. The span stays open until the
    # executor returns or cancellation is confirmed, at which point a resolver
    # finalizes it with the true outcome.
    span.closed = False


def resolve_late_result(span: ToolCallSpan, returned_ok: bool) -> None:
    """Executor finally returned. Finalize the abandoned span honestly."""
    if span.executor_state is not ExecutorState.RETURNED:
        raise SpanLifecycleViolation(
            f"resolve_late_result on span {span.call_id} whose executor "
            f"state is {span.executor_state.value}, not returned"
        )
    if span.closed:
        raise SpanLifecycleViolation(
            f"span {span.call_id} closed before late result arrived; "
            "result would be dropped silently"
        )
    span.attributes["gen_ai.tool.call.late_result"] = True
    span.attributes["gen_ai.tool.call.late_result_ok"] = returned_ok
    span.status = "ERROR"  # abandoned calls remain errors even if they returned
    span.closed = True
