# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-token-accounting-drift-when-an-opentelemetry-genai-agent-span-is-closed-by-a-different-process-than-the-one-that-opened-it.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-token-accounting-drift-when-an-opentelemetry-genai-agent-span-is-closed-by-a-different-process-than-the-one-that-opened-it.warrant.json
# Markdown SHA-256:   6913f08e4145baf347de00ed304224e150748db914dc0368ecf7453b7f385901
# Code AST SHA-256:   fd8d1a1969b12775e908adec191ec05ec84faabbb14c9aa9081df9b5e32994c0
# Verified Classes:   NonAuthoritativeUsageError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class NonAuthoritativeUsageError(RuntimeError):
    """Raised when a GenAI agent span is about to be closed with usage
    attributes that were not observed by the closing process."""
    pass


AUTHORITATIVE_SOURCES = frozenset({"provider_response", "structured_handoff"})


def close_agent_span(span, usage_block, observed_source, tool_call_id=None):
    """
    Finalize a gen_ai agent span. Refuses to attach usage attributes
    unless the closing process can prove it observed the token counts.

    usage_block: dict with input_tokens/output_tokens, or None.
    observed_source: one of AUTHORITATIVE_SOURCES, or "estimate"/"none".
    tool_call_id: required when usage arrives via structured handoff,
                  so a fanned-out span can correlate to the right child.
    """
    if usage_block is None or observed_source not in AUTHORITATIVE_SOURCES:
        # Do NOT fabricate. Leave usage absent and mark non-authoritative.
        span.set_attribute("agent.usage.authoritative", False)
        span.set_attribute("agent.usage.source", observed_source or "none")
        span.end()
        return

    if observed_source == "structured_handoff" and not tool_call_id:
        # We have numbers but cannot prove they belong to THIS span.
        raise NonAuthoritativeUsageError(
            "structured handoff usage arrived without gen_ai.tool.call.id; "
            "cannot attribute tokens to a specific agent span"
        )

    span.set_attribute("gen_ai.usage.input_tokens", int(usage_block["input_tokens"]))
    span.set_attribute("gen_ai.usage.output_tokens", int(usage_block["output_tokens"]))
    span.set_attribute("agent.usage.authoritative", True)
    span.set_attribute("agent.usage.source", observed_source)
    if tool_call_id:
        span.set_attribute("gen_ai.tool.call.id", tool_call_id)
    span.end()


def reconcile_trace_usage(trace_spans, provider_usage_log):
    """
    Invariant test: authoritative trace token sums must match the
    provider's billed usage. Non-authoritative spans are excluded,
    not silently zeroed.
    """
    authoritative = [
        s for s in trace_spans
        if s.attributes.get("agent.usage.authoritative") is True
    ]
    trace_input = sum(
        s.attributes.get("gen_ai.usage.input_tokens", 0) for s in authoritative
    )
    billed_input = sum(u["input_tokens"] for u in provider_usage_log)

    if trace_input != billed_input:
        raise NonAuthoritativeUsageError(
            f"token-accounting drift: trace authoritative input={trace_input} "
            f"vs provider billed input={billed_input}; "
            f"{len(trace_spans) - len(authoritative)} span(s) were "
            f"non-authoritative and must be reconciled out-of-band"
        )
    return trace_input
