# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-opentelemetry-genai-span-as-authoritative-for-token-accounting-when-tool-call-attributes-are-split-acr.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-opentelemetry-genai-span-as-authoritative-for-token-accounting-when-tool-call-attributes-are-split-acr.warrant.json
# Markdown SHA-256:   9065beb205fbd4a334c6407352a4219af93108c4a74bced2e99f2fcf9325a73a
# Code AST SHA-256:   9acee72ae78712493be9e43fc5c05fc549c2966c947ea54ec333b876dc70742d
# Verified Classes:   GenAISpanAccountingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class GenAISpanAccountingError(RuntimeError):
    """Raised when a GenAI span tree cannot be trusted for token attribution."""
    pass


def attribute_tokens_by_tool(spans: list[dict]) -> dict[str, int]:
    """
    spans: list of dicts with keys 'name', 'span_id', 'parent_id',
    'attributes' (gen_ai.* dict), 'status'.
    Returns per-tool input-token attribution, or raises if the tree
    violates the one-invocation-per-span / linkage invariant.
    """
    chat_spans = [s for s in spans if s["name"] == "chat"]
    tool_spans = [s for s in spans if s["name"] == "execute_tool"]

    # Invariant 1: no parent agent span may carry its own usage attrs.
    for s in spans:
        if s["name"] == "invoke_agent" and any(
            k.startswith("gen_ai.usage.") for k in s["attributes"]
        ):
            raise GenAISpanAccountingError(
                f"agent span {s['span_id']} carries usage attrs; "
                "parent/child double-count risk"
            )

    # Invariant 2: retried chat spans must be marked and not summed.
    for s in chat_spans:
        if s["status"] == "ERROR" and not s["attributes"].get("gen_ai.usage.retry"):
            raise GenAISpanAccountingError(
                f"chat span {s['span_id']} failed without retry marker; "
                "cannot distinguish retry from real turn"
            )

    # Invariant 3: every non-first chat span must link to the tool span
    # whose output formed its input, OR the tree must be strictly
    # sequential single-tool (M == N-1).
    successful_chats = [s for s in chat_spans if s["status"] != "ERROR"]
    if len(tool_spans) != len(successful_chats) - 1:
        links_present = all(
            any(link.startswith("tool:") for link in s.get("links", []))
            for s in successful_chats[1:]
        )
        if not links_present:
            raise GenAISpanAccountingError(
                f"tool/chat cardinality mismatch: {len(tool_spans)} tools, "
                f"{len(successful_chats)} chats, no Span.Link provenance; "
                "per-tool attribution is undefined"
            )

    attribution: dict[str, int] = {}
    prev_input = 0
    for i, chat in enumerate(successful_chats):
        cur_input = chat["attributes"].get("gen_ai.usage.input_tokens", 0)
        delta = cur_input - prev_input
        if i > 0:
            tool = tool_spans[i - 1]
            tool_name = tool["attributes"].get("gen_ai.tool.name", "unknown")
            attribution[tool_name] = attribution.get(tool_name, 0) + delta
        prev_input = cur_input
    return attribution
