# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-closure-when-a-tool-call-child-span-outlives-its-parent-agent-span.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-closure-when-a-tool-call-child-span-outlives-its-parent-agent-span.warrant.json
# Markdown SHA-256:   faf434a3697a9054f6d8ef97f94b8c48732d0fe69c4ef909ed46e227ee341c99
# Code AST SHA-256:   4766a165fd89ca876073a30ee486cccd83a0e5a77e8c8d006972152397b11a58
# Verified Classes:   SpanContainmentViolation, GenAISpan, ContainmentEnforcingTracer
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class SpanContainmentViolation(RuntimeError):
    """Raised when an operation span is ended while a dependency tool span it
    spawned is still open, breaking the GenAI containment invariant."""
    pass


@dataclass
class GenAISpan:
    name: str
    operation: str                      # gen_ai.operation.name
    parent_id: Optional[str] = None
    span_id: str = ""
    end_time: Optional[float] = None
    is_dependency_tool: bool = False
    input_tokens: int = 0
    output_tokens: int = 0
    open_children: set = field(default_factory=set)


class ContainmentEnforcingTracer:
    def __init__(self):
        self._spans: dict[str, GenAISpan] = {}
        self._seq = 0

    def start_operation(self, name: str, parent_id: Optional[str] = None) -> GenAISpan:
        self._seq += 1
        span = GenAISpan(name=name, operation="chat",
                         parent_id=parent_id, span_id=f"s{self._seq}")
        self._spans[span.span_id] = span
        if parent_id and parent_id in self._spans:
            self._spans[parent_id].open_children.add(span.span_id)
        return span

    def start_tool(self, parent: GenAISpan, tool_name: str,
                   dependency: bool = True) -> GenAISpan:
        self._seq += 1
        span = GenAISpan(name=f"execute_tool:{tool_name}",
                         operation="execute_tool",
                         parent_id=parent.span_id,
                         span_id=f"s{self._seq}",
                         is_dependency_tool=dependency)
        self._spans[span.span_id] = span
        parent.open_children.add(span.span_id)
        return span

    def end_tool(self, span: GenAISpan) -> None:
        span.end_time = time.time()
        if span.parent_id:
            self._spans[span.parent_id].open_children.discard(span.span_id)

    def end_operation(self, span: GenAISpan) -> None:
        # Invariant: no dependency-child may remain open at parent end.
        still_open = [
            cid for cid in span.open_children
            if self._spans[cid].is_dependency_tool and self._spans[cid].end_time is None
        ]
        if still_open:
            raise SpanContainmentViolation(
                f"operation span {span.span_id} ({span.name}) ended with "
                f"{len(still_open)} open dependency tool spans: {still_open}. "
                f"Either hold the parent open, or re-parent tools under a task "
                f"span and mark gen_ai.operation.status=incomplete."
            )
        span.end_time = time.time()


# --- trigger trace: the misconfiguration observed in production ---
tracer = ContainmentEnforcingTracer()
op = tracer.start_operation("step-1")
tool = tracer.start_tool(op, "search_index", dependency=True)

# Runtime closes the operation as soon as the model returns the tool request,
# before the MCP round-trip has completed:
try:
    tracer.end_operation(op)
except SpanContainmentViolation as e:
    print("BLOCKED:", e)
    # Correct remediation: do not end op; wait for tool, then fold tokens.
    tracer.end_tool(tool)
    op.output_tokens += 0  # tool-result tokens attributed on next turn
    tracer.end_operation(op)
    print("contained: op closed after tool, tree single-rooted")
