# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-an-opentelemetry-genai-agent-span-the-tool-call-lineage-orphan-under-partial-token-accounting.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-an-opentelemetry-genai-agent-span-the-tool-call-lineage-orphan-under-partial-token-accounting.warrant.json
# Markdown SHA-256:   0135334b13cb595386e2062b176c8a3ebda1b08d33966008d45cc326f474ad7b
# Code AST SHA-256:   fe38b65e54c542f5a9215d837ca58fc909ac02a0123f51ab948d5ad2fc86f909
# Verified Classes:   LineageBijectionError, ToolSpan, ChatSpan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class LineageBijectionError(RuntimeError):
    """Raised when a gen_ai.chat span is closed with unbacked tool-call ids."""


@dataclass
class ToolSpan:
    call_id: str
    status_code: str  # "OK" | "ERROR"
    terminal: bool = True


@dataclass
class ChatSpan:
    span_id: str
    recorded_tool_call_ids: list[str]
    descendant_tool_spans: dict[str, ToolSpan] = field(default_factory=dict)
    closed: bool = False

    def register_tool_span(self, span: ToolSpan) -> None:
        if self.closed:
            raise LineageBijectionError(
                f"tool span {span.call_id!r} registered after chat span "
                f"{self.span_id!r} closed; lineage cannot be repaired post-close"
            )
        self.descendant_tool_spans[span.call_id] = span

    def _unbacked_call_ids(self) -> list[str]:
        return [
            cid
            for cid in self.recorded_tool_call_ids
            if cid not in self.descendant_tool_spans
            or not self.descendant_tool_spans[cid].terminal
        ]

    def close(self, synthesize_missing: bool = True) -> None:
        unbacked = self._unbacked_call_ids()
        if unbacked and not synthesize_missing:
            raise LineageBijectionError(
                f"chat span {self.span_id!r} cannot close: tool-call ids "
                f"{unbacked!r} have no terminal descendant span"
            )
        for cid in unbacked:
            # Cancellation/timeout is a terminal state, not an absence.
            self.descendant_tool_spans[cid] = ToolSpan(
                call_id=cid, status_code="ERROR", terminal=True
            )
        self.closed = True

    def assert_bijection(self) -> None:
        if not self.closed:
            raise LineageBijectionError(
                f"bijection check on open chat span {self.span_id!r}"
            )
        missing = self._unbacked_call_ids()
        if missing:
            raise LineageBijectionError(
                f"lineage orphan(s) {missing!r} on closed chat span "
                f"{self.span_id!r}"
            )


def close_chat_span_guarded(
    chat: ChatSpan, outstanding: Iterable[str], allow_synthesize: bool
) -> None:
    """Close a chat span only when every dispatched call has a terminal span."""
    for cid in outstanding:
        if cid not in chat.descendant_tool_spans:
            if not allow_synthesize:
                raise LineageBijectionError(
                    f"refusing to close {chat.span_id!r}: dispatch {cid!r} "
                    f"still outstanding and synthesis disabled"
                )
            chat.register_tool_span(
                ToolSpan(call_id=cid, status_code="ERROR", terminal=True)
            )
    chat.close(synthesize_missing=allow_synthesize)
    chat.assert_bijection()
