# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-records-tool-call-spans-before-the-genai-semantic-convention-attributes-resolve-and-the-parent-invocation-span-closes-wi.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-records-tool-call-spans-before-the-genai-semantic-convention-attributes-resolve-and-the-parent-invocation-span-closes-wi.warrant.json
# Markdown SHA-256:   3e62e3263fc25d9a650e2baad61c0509e31cc180ab8a36a37211913677da6192
# Code AST SHA-256:   f665fe92f9f736b509142897fa41fcf021ab69d4cd8b55d9fff97c12c95b888f
# Verified Classes:   InvocationSpanClosureError, InvocationSpan
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class InvocationSpanClosureError(RuntimeError):
    """Raised when a gen_ai.chat span's token attributes are not causally
    closed at end() — i.e. they depend on a model response that had not
    returned when the span was ended, or the span parents tool calls from
    more than one response."""


@dataclass
class InvocationSpan:
    response_id: Optional[str] = None
    input_tokens: Optional[int] = None
    output_tokens: Optional[int] = None
    finish_reasons: list = field(default_factory=list)
    tool_call_ids: list = field(default_factory=list)  # from this response only
    ended: bool = False
    _ended_at_response_id: Optional[str] = None

    def record_response(self, response_id: str, input_tokens: int,
                        output_tokens: int, finish_reasons: list,
                        tool_call_ids: list) -> None:
        if self.ended:
            raise InvocationSpanClosureError(
                f"attempted to write token attributes to span after end(); "
                f"span was closed against response {self._ended_at_response_id!r}, "
                f"new write references response {response_id!r}. "
                f"Deferred attribute mutation is non-deterministic across collectors."
            )
        if self.response_id is not None and self.response_id != response_id:
            raise InvocationSpanClosureError(
                f"span already bound to response {self.response_id!r}; "
                f"refusing to fold response {response_id!r} into the same "
                f"invocation span (loop-as-span collapse). Emit a sibling "
                f"invocation span or a wrapper span with no gen_ai.usage.*."
            )
        self.response_id = response_id
        self.input_tokens = input_tokens
        self.output_tokens = output_tokens
        self.finish_reasons = list(finish_reasons)
        self.tool_call_ids = list(tool_call_ids)

    def end(self) -> None:
        if self.response_id is None:
            raise InvocationSpanClosureError(
                "invocation span ended with no bound response; "
                "gen_ai.usage.* attributes have no provenance."
            )
        if len(self.finish_reasons) != 1:
            raise InvocationSpanClosureError(
                f"invocation span carries {len(self.finish_reasons)} finish "
                f"reasons {self.finish_reasons!r}; a single-call span must "
                f"carry exactly one. Multi-reason spans are collapsed loops."
            )
        self.ended = True
        self._ended_at_response_id = self.response_id

    def attach_tool_child(self, call_id: str) -> None:
        if not self.ended:
            raise InvocationSpanClosureError(
                "tool-call child attached before invocation span ended; "
                "the requesting response has not been recorded, so the "
                "call_id cannot be validated against the parent response."
            )
        if call_id not in self.tool_call_ids:
            raise InvocationSpanClosureError(
                f"tool call {call_id!r} is not among the tool_calls of "
                f"response {self.response_id!r} ({self.tool_call_ids!r}); "
                f"the child likely belongs to a different invocation span."
            )
