# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-emit-a-terminal-agent-turn-span-before-its-tool-call-child-spans-have-been-exported-and-what-breaks-when-it-doe.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-emit-a-terminal-agent-turn-span-before-its-tool-call-child-spans-have-been-exported-and-what-breaks-when-it-doe.warrant.json
# Markdown SHA-256:   06f96833d935f82e5ffd3c9476cbd9eb6f40a33bd54cc2c4a8e585aad1aa1375
# Code AST SHA-256:   3401c7b27fc5bc97df316b943aa62a14f75cfdd29af6d433342d03c46bd3d628
# Verified Classes:   OrphanedTurnSpanError, SpanHandle, TurnSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import asyncio
from dataclasses import dataclass, field


class OrphanedTurnSpanError(RuntimeError):
    """Raised when a turn span is ended before all tool-call child spans are finalized."""
    pass


@dataclass
class SpanHandle:
    span_id: str
    ended: bool = False

    def end(self) -> None:
        self.ended = True


@dataclass
class TurnSpan:
    span_id: str
    open_children: set = field(default_factory=set)
    ended: bool = False
    # Sentinel attribute: how many tool children this turn *claims* to have spawned.
    declared_child_count: int = 0

    def register_child(self, handle: SpanHandle) -> None:
        if self.ended:
            raise OrphanedTurnSpanError(
                f"cannot register child {handle.span_id} on ended turn {self.span_id}"
            )
        self.open_children.add(handle.span_id)
        self.declared_child_count += 1

    def child_ended(self, handle: SpanHandle) -> None:
        self.open_children.discard(handle.span_id)

    def end(self, join_timeout_s: float = 2.0) -> None:
        # Invariant: a turn span may not end while any tool-call child is still open.
        # This is a control-flow barrier, not a batch-size/flush-delay tuning knob.
        if self.open_children:
            raise OrphanedTurnSpanError(
                f"turn {self.span_id} still has open tool children: "
                f"{sorted(self.open_children)}; declared_child_count="
                f"{self.declared_child_count}. Ending now would export a parent "
                f"span whose execute_tool children land in a later batch."
            )
        self.ended = True


async def run_tool_call(turn: TurnSpan, tool_name: str) -> None:
    handle = SpanHandle(span_id=f"tool-{tool_name}")
    turn.register_child(handle)
    try:
        await asyncio.sleep(0)  # simulated tool latency
        # Token annotation / result post-processing happens here, inline,
        # BEFORE the child span ends. Never defer this to a background task.
    finally:
        handle.end()
        turn.child_ended(handle)


async def run_turn() -> TurnSpan:
    turn = TurnSpan(span_id="turn-1")
    try:
        await run_tool_call(turn, "search")
        await run_tool_call(turn, "fetch")
    finally:
        # This is the exact site where the production bug lived: ending the
        # turn span in `finally` while a deferred tool finalization was still
        # in flight. The join barrier below converts the timing race into a
        # hard error.
        turn.end()
    return turn


if __name__ == "__main__":
    asyncio.run(run_turn())
