# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-genai-tool-call-span-as-non-authoritative-for-token-accounting-during-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-genai-tool-call-span-as-non-authoritative-for-token-accounting-during-agent-handoffs.warrant.json
# Markdown SHA-256:   ebe5991aec95cd22d92d88abcac19d4d9efaea04601180de5a6a7fc1a73da821
# Code AST SHA-256:   2bb4a5702f9bd4e6bb78c552048758329865ef7e95ce59fc5d4d748ee69ff652
# Verified Classes:   FiscalAttributionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class FiscalAttributionError(RuntimeError):
    """Raised when a tool-call span cannot be safely attributed token usage."""
    pass


def attribute_usage(tool_span, descendant_chat_spans):
    """
    Attribute token usage to a GenAI execute_tool span.

    Returns (authoritative_usage, discarded_usage) where authoritative_usage
    is the usage of the successful attempt(s) and discarded_usage is the
    usage of failed attempts that were still billed by the provider.
    """
    if not descendant_chat_spans:
        # Tool span with no descendant chat spans: either a non-LLM tool
        # (fine, zero usage) or a sampling gap (not fine).
        if tool_span.attributes.get("gen_ai.usage.input_tokens", 0) > 0:
            raise FiscalAttributionError(
                f"tool span {tool_span.span_id} carries usage attributes "
                f"but has no descendant chat span; sampling gap or mis-emission"
            )
        return (0, 0)

    tool_service = tool_span.resource.get("service.name")
    call_ids = {s.attributes.get("gen_ai.tool.call.id") for s in descendant_chat_spans}
    if len(call_ids) > 1:
        raise FiscalAttributionError(
            f"tool span {tool_span.span_id} has descendant chat spans with "
            f"inconsistent gen_ai.tool.call.id values: {call_ids}; "
            f"fan-out must be attributed per sub-agent, not per tool call"
        )

    services = {s.resource.get("service.name") for s in descendant_chat_spans}
    if services != {tool_service}:
        # Delegated call: usage belongs to the sub-agent's budget line,
        # not the caller's tool call. Refuse to aggregate.
        raise FiscalAttributionError(
            f"tool span {tool_span.span_id} (service={tool_service}) has "
            f"descendant chat spans from services {services}; "
            f"delegated usage must not be summed into the caller's tool call"
        )

    authoritative = 0
    discarded = 0
    for span in descendant_chat_spans:
        usage = span.attributes.get("gen_ai.usage.input_tokens", 0) + \
                span.attributes.get("gen_ai.usage.output_tokens", 0)
        if span.attributes.get("otel.status_code") == "ERROR":
            discarded += usage
        else:
            authoritative += usage
    return (authoritative, discarded)
