# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-span-attributes-for-a-tool-calling-turn-whose-tool-results-arrive-after-the-parent-span-has-already-ended.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-span-attributes-for-a-tool-calling-turn-whose-tool-results-arrive-after-the-parent-span-has-already-ended.warrant.json
# Markdown SHA-256:   e4cdc520f28be255bb849f03142f070f9e24bd62d6a3b54816e3758d26bee286
# Code AST SHA-256:   1680a4a9515200ac23d5d3a390b5929a5b7321edcbde1e674e2da00d6ad08e26
# Verified Classes:   OrphanedToolCallError, GenAITurnSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class OrphanedToolCallError(RuntimeError):
    """Raised when a generation span closes while a tool call it emitted is still pending
    and no enclosing turn span exists to receive the eventual result."""
    pass


class GenAITurnSpan:
    def __init__(self, conversation_id: str, parent_span):
        self.conversation_id = conversation_id
        self.parent_span = parent_span
        self.pending_tool_calls = set()
        self.aggregated_input_tokens = 0
        self.aggregated_output_tokens = 0
        self.closed = False

    def record_generation(self, span, tool_call_ids, input_tokens, output_tokens):
        if self.closed:
            raise OrphanedToolCallError(
                f"generation recorded after turn span {self.conversation_id} closed"
            )
        self.aggregated_input_tokens += input_tokens
        self.aggregated_output_tokens += output_tokens
        for call_id in tool_call_ids:
            span.set_attribute("gen_ai.tool.call.id", call_id)
            self.pending_tool_calls.add(call_id)
        return span

    def close_generation(self, span):
        # Guard: refuse to close a generation span with un-resolved tool calls
        # unless this turn span will absorb the result.
        if self.pending_tool_calls and self.parent_span is None:
            raise OrphanedToolCallError(
                f"generation span closed with pending tool calls "
                f"{sorted(self.pending_tool_calls)} and no turn span to receive them"
            )
        span.end()

    def record_tool_result(self, tool_call_id, result_span):
        if tool_call_id not in self.pending_tool_calls:
            raise OrphanedToolCallError(
                f"tool result for unknown or already-resolved call {tool_call_id}"
            )
        result_span.set_attribute("gen_ai.tool.call.id", tool_call_id)
        self.pending_tool_calls.discard(tool_call_id)

    def close(self):
        if self.pending_tool_calls:
            raise OrphanedToolCallError(
                f"turn {self.conversation_id} closed with unresolved tool calls "
                f"{sorted(self.pending_tool_calls)}"
            )
        if self.parent_span is not None:
            self.parent_span.set_attribute(
                "gen_ai.usage.input_tokens", self.aggregated_input_tokens
            )
            self.parent_span.set_attribute(
                "gen_ai.usage.output_tokens", self.aggregated_output_tokens
            )
            self.parent_span.end()
        self.closed = True
