# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-closure-against-the-token-accounting-attributes-it-emitted-mid-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-closure-against-the-token-accounting-attributes-it-emitted-mid-stream.warrant.json
# Markdown SHA-256:   e35bd0954307f44da895c4ffd451d1c21a25b896e46f13f452a3a469609456ca
# Code AST SHA-256:   23258459e6018287bd9c18efab77b5c901b3f4d83b5f541d6f94f488a6f8507b
# Verified Classes:   UsageReconciliationError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UsageReconciliationError(RuntimeError):
    """Raised when a gen_ai span is about to close without a usage fact or explicit unknown marker."""


def close_chat_span(span, usage: dict | None, finish_reason: str, cancelled: bool) -> None:
    # Enforce the invariant: usage OR explicit-unknown, never silent absence.
    if usage is not None:
        span.set_attribute("gen_ai.usage.input_tokens", usage["input_tokens"])
        span.set_attribute("gen_ai.usage.output_tokens", usage["output_tokens"])
    else:
        if finish_reason == "tool_calls" or cancelled:
            # Provider omitted usage on a boundary/cancel — mark it, do not default to 0.
            span.set_attribute("gen_ai.usage.unknown", True)
            span.set_attribute("gen_ai.response.finish_reason", finish_reason)
            span.set_attribute("gen_ai.usage.cancelled", cancelled)
        else:
            # Normal completion with no usage is a bug in the stream consumer.
            raise UsageReconciliationError(
                f"chat span closing without usage and without boundary reason "
                f"(finish_reason={finish_reason!r}, cancelled={cancelled})"
            )
    span.end()
