# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-close-a-genai-span-when-a-tool-call-child-span-is-still-open-under-otel-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-close-a-genai-span-when-a-tool-call-child-span-is-still-open-under-otel-semantic-conventions.warrant.json
# Markdown SHA-256:   53844b93a5cd5f86eeec0af9cf819cc1805024dbc5b1666feaa8f2c71d81fdfb
# Code AST SHA-256:   547d046970a13a98266a0e3fe806c2f55f4b5cc0c529ac22ce0c62ebee40cdd9
# Verified Classes:   PrematureSpanCloseError, GenAISpan, SpanRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class PrematureSpanCloseError(RuntimeError):
    """Raised when a GenAI parent span is ended while child spans remain open."""


@dataclass
class GenAISpan:
    span_id: str
    parent_id: Optional[str]
    operation_name: str  # e.g. "invoke_agent", "execute_tool"
    status_code: str = "UNSET"
    end_time_ns: Optional[int] = None
    attributes: Dict[str, object] = field(default_factory=dict)


class SpanRegistry:
    """Tracks open children per parent to enforce the close-time invariant."""

    def __init__(self) -> None:
        self._open_children: Dict[str, int] = {}
        self._spans: Dict[str, GenAISpan] = {}

    def start(self, span: GenAISpan) -> None:
        self._spans[span.span_id] = span
        self._open_children.setdefault(span.span_id, 0)
        if span.parent_id is not None:
            self._open_children[span.parent_id] = (
                self._open_children.get(span.parent_id, 0) + 1
            )

    def end(self, span_id: str, end_time_ns: int) -> None:
        span = self._spans.get(span_id)
        if span is None:
            raise PrematureSpanCloseError(f"unknown span_id={span_id}")

        open_kids = self._open_children.get(span_id, 0)
        if span.operation_name in ("invoke_agent", "execute_tool") and open_kids > 0:
            # Do NOT silently close: this would forge a completion proof.
            raise PrematureSpanCloseError(
                f"refusing to close {span.operation_name} span_id={span_id}: "
                f"{open_kids} child span(s) still open; "
                f"emitting incomplete=true instead"
            )

        span.end_time_ns = end_time_ns
        span.status_code = "OK"
        if span.parent_id is not None:
            self._open_children[span.parent_id] = max(
                0, self._open_children.get(span.parent_id, 0) - 1
            )

    def end_or_mark_incomplete(self, span_id: str, end_time_ns: int) -> GenAISpan:
        """Fallback path: close anyway but poison the span so verifiers reject it."""
        span = self._spans[span_id]
        try:
            self.end(span_id, end_time_ns)
            return span
        except PrematureSpanCloseError:
            span.end_time_ns = end_time_ns
            span.status_code = "ERROR"
            span.attributes["gen_ai.tool.call.incomplete"] = True
            span.attributes["gen_ai.close.open_children"] = self._open_children.get(
                span_id, 0
            )
            if span.parent_id is not None:
                self._open_children[span.parent_id] = max(
                    0, self._open_children.get(span.parent_id, 0) - 1
                )
            return span


def verify_trace_ordering(registry: SpanRegistry) -> None:
    """Post-hoc check: no child may end after its parent."""
    by_id = registry._spans
    for span in by_id.values():
        if span.parent_id is None or span.end_time_ns is None:
            continue
        parent = by_id.get(span.parent_id)
        if parent is None or parent.end_time_ns is None:
            continue
        if span.end_time_ns > parent.end_time_ns:
            raise PrematureSpanCloseError(
                f"temporal inversion: child {span.span_id} ends at "
                f"{span.end_time_ns} > parent {parent.span_id} at "
                f"{parent.end_time_ns}; parent status was {parent.status_code}"
            )
