# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attributes-a-nested-tool-call-span-s-tokens-to-the-parent-agent-span-double-counting-and-orphaned-cost-under-opentelemet.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attributes-a-nested-tool-call-span-s-tokens-to-the-parent-agent-span-double-counting-and-orphaned-cost-under-opentelemet.warrant.json
# Markdown SHA-256:   2e9e525eff00681b943b456b4e3c822bb9cee73b5dbcded3fddd6cf2b916e374
# Code AST SHA-256:   92c0f4979d8b98bd869de85e3c2cb3eef066e20a8310e7f34e5e3a8911ca59a3
# Verified Classes:   UsageAttributionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UsageAttributionError(RuntimeError):
    """Raised when a span would carry gen_ai.usage.* without a single-inference identity."""
    pass


def emit_span_usage(span: dict) -> dict:
    """
    Enforce the invariant: gen_ai.usage.* may appear only on a span that
    represents exactly one inference (has gen_ai.response.id).
    Rollups belong in a distinct namespace (agent.usage.*).
    """
    attrs = span.get("attributes", {})
    has_usage = any(k.startswith("gen_ai.usage.") for k in attrs)
    has_response_id = "gen_ai.response.id" in attrs
    is_agent_span = attrs.get("gen_ai.operation.name") in ("invoke_agent", "execute_tool")

    if has_usage and is_agent_span:
        raise UsageAttributionError(
            f"span {span.get('name')!r} (operation={attrs.get('gen_ai.operation.name')}) "
            "carries gen_ai.usage.* but is not an inference span; "
            "move the total to agent.usage.* to avoid double-counting leaves"
        )

    if has_usage and not has_response_id:
        raise UsageAttributionError(
            f"span {span.get('name')!r} carries gen_ai.usage.* without gen_ai.response.id; "
            "usage cannot be reconciled to a single inference"
        )

    return span
