# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-opentelemetry-genai-agent-spans-when-the-tool-call-attribute-set-is-only-partially-resolvable-at-spa.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-opentelemetry-genai-agent-spans-when-the-tool-call-attribute-set-is-only-partially-resolvable-at-spa.warrant.json
# Markdown SHA-256:   8955a443e15f441de764001fa4aba1bdfbe1766606ecfcebb45e42ad8c60ab55
# Code AST SHA-256:   0ca2ef074cdf445ab4d0982285ce7d09d1df019e3e92db9df575c56122496652
# Verified Classes:   IncompleteGenAISpanError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class IncompleteGenAISpanError(RuntimeError):
    """Raised when a tool-bearing GenAI span would close with inconsistent
    token-usage and tool-call cardinality attributes."""
    pass


def close_genai_span(span, response_tool_calls, emitted_tool_spans, usage):
    expected = len(response_tool_calls)
    emitted = len(emitted_tool_spans)

    if expected == 0:
        span.set_attribute("gen_ai.usage.input_tokens", usage.input_tokens)
        span.set_attribute("gen_ai.usage.output_tokens", usage.output_tokens)
        span.end()
        return

    if emitted == expected:
        span.set_attribute("gen_ai.usage.input_tokens", usage.input_tokens)
        span.set_attribute("gen_ai.usage.output_tokens", usage.output_tokens)
        span.end()
        return

    # Partial resolution: refuse to emit usage, mark incomplete instead.
    if usage is not None and hasattr(usage, "output_tokens"):
        raise IncompleteGenAISpanError(
            f"tool-bearing span has {emitted}/{expected} tool spans resolved; "
            f"refusing to emit gen_ai.usage.* on an incomplete round trip"
        )

    span.set_attribute("gen_ai.agent.incomplete", True)
    span.set_attribute("gen_ai.agent.incomplete.reason", "tool_dispatch_unresolved")
    span.end()
