# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-genai-span-tree-has-silently-orphaned-a-tool-call-child-before-the-parent-reasoning-span-closes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-genai-span-tree-has-silently-orphaned-a-tool-call-child-before-the-parent-reasoning-span-closes.warrant.json
# Markdown SHA-256:   9192d980f3198c3dabc738af4585a0cf1f0abca57ad69c4e97507231845b1852
# Code AST SHA-256:   412584c5b99a2e4ce146f734006f89dbd254a9bf5efeca56e0f855461ff4dcba
# Verified Classes:   OrphanedToolSpanError, SpanRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class OrphanedToolSpanError(RuntimeError):
    """Raised when a GenAI chat span closes with tool_calls but no linked tool child."""

    def __init__(self, span_name: str, finish_reasons: list[str], child_count: int):
        self.span_name = span_name
        self.finish_reasons = finish_reasons
        self.child_count = child_count
        super().__init__(
            f"chat span {span_name!r} closed with finish_reasons={finish_reasons!r} "
            f"but linked execute_tool children={child_count}"
        )


@dataclass
class SpanRecord:
    name: str
    operation: str
    parent_id: Optional[str]
    finish_reasons: list[str] = field(default_factory=list)
    linked_children: int = 0


def close_chat_span(span: SpanRecord) -> None:
    """Enforce containment invariant before a chat span is ended.

    A chat span that reports tool_calls MUST have at least one linked
    execute_tool child. Otherwise the tool span has been orphaned by an
    ambient-context exit and the causal edge is lost.
    """
    if span.operation != "chat":
        return

    requests_tool = "tool_calls" in span.finish_reasons
    if requests_tool and span.linked_children == 0:
        raise OrphanedToolSpanError(
            span_name=span.name,
            finish_reasons=list(span.finish_reasons),
            child_count=span.linked_children,
        )
