# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-token-usage-spans-when-a-streaming-completion-terminates-without-a-terminal-finish-reason.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-token-usage-spans-when-a-streaming-completion-terminates-without-a-terminal-finish-reason.warrant.json
# Markdown SHA-256:   69d2a0120277223a729a24e7855e2b02f4c2b4f8d37773f073311cdfe39645a5
# Code AST SHA-256:   c6edc1d0d6523a3b8ae8b85acd7523412de45f804a25ebf879af428da36d77e9
# Verified Classes:   IncompleteStreamError, GenAISpanState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class IncompleteStreamError(RuntimeError):
    """Raised when a streaming completion ends without a terminal finish_reason."""
    pass


@dataclass
class GenAISpanState:
    saw_terminal_event: bool = False
    finish_reason: Optional[str] = None
    input_tokens: Optional[int] = None
    output_tokens: Optional[int] = None
    content_buffer: str = ""
    tool_call_buffer: str = ""
    attributes: dict = field(default_factory=dict)

    def observe_chunk(self, chunk: dict) -> None:
        choice = chunk["choices"][0]
        delta = choice.get("delta", {})
        self.content_buffer += delta.get("content") or ""
        self.tool_call_buffer += (delta.get("tool_calls") or [{}])[0].get("function", {}).get("arguments", "") or ""
        reason = choice.get("finish_reason")
        if reason is not None:
            self.saw_terminal_event = True
            self.finish_reason = reason
            usage = chunk.get("usage") or {}
            # Only trust usage that arrives alongside a terminal event.
            self.input_tokens = usage.get("prompt_tokens")
            self.output_tokens = usage.get("completion_tokens")

    def finalize_span(self) -> dict:
        if not self.saw_terminal_event:
            # Do NOT default usage to 0; leave absent and mark incomplete.
            self.attributes["gen_ai.response.incomplete"] = True
            self.attributes["span.status"] = "ERROR"
            self.attributes["span.status_description"] = (
                "stream_terminated_without_finish_reason"
            )
            raise IncompleteStreamError(
                "stream closed after "
                f"{len(self.content_buffer)} content chars and "
                f"{len(self.tool_call_buffer)} tool-call chars "
                "with no finish_reason; refusing to write usage attributes"
            )
        self.attributes["gen_ai.response.finish_reasons"] = [self.finish_reason]
        self.attributes["gen_ai.usage.input_tokens"] = self.input_tokens
        self.attributes["gen_ai.usage.output_tokens"] = self.output_tokens
        self.attributes["gen_ai.response.incomplete"] = False
        self.attributes["span.status"] = "OK"
        return self.attributes


def run_streaming_turn(stream, span_state: GenAISpanState) -> dict:
    try:
        for chunk in stream:
            span_state.observe_chunk(chunk)
    except (ConnectionResetError, TimeoutError):
        # Transport termination without semantic termination.
        pass  # fall through to finalize, which will raise
    return span_state.finalize_span()
