# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-parent-span-token-laundering-when-genai-tool-call-spans-are-re-parented-across-mcp-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-parent-span-token-laundering-when-genai-tool-call-spans-are-re-parented-across-mcp-handoffs.warrant.json
# Markdown SHA-256:   95c2668ae3a94e095cdf3c384c0dad9569aca559912aba65807d9e7f78446508
# Code AST SHA-256:   393ebdf75c78e3d3c40a75a53cb78187dc9d22264a31f33836623d45292087a2
# Verified Classes:   TokenAttributionLaunderingError, GenAiSpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable

class TokenAttributionLaunderingError(RuntimeError):
    """Raised when a tool-call span relays a descendant chat span's usage,
    making the same inference appear attributed to the tool-call parent."""
    pass

@dataclass(frozen=True)
class GenAiSpan:
    span_id: str
    parent_span_id: str | None
    operation_name: str          # gen_ai.operation.name
    input_tokens: int | None     # gen_ai.usage.input_tokens
    output_tokens: int | None    # gen_ai.usage.output_tokens

def _usage(span: GenAiSpan) -> tuple[int, int] | None:
    if span.input_tokens is None and span.output_tokens is None:
        return None
    return (span.input_tokens or 0, span.output_tokens or 0)

def _descendants(root: GenAiSpan, spans: Iterable[GenAiSpan]) -> list[GenAiSpan]:
    by_parent: dict[str | None, list[GenAiSpan]] = {}
    for s in spans:
        by_parent.setdefault(s.parent_span_id, []).append(s)
    out, stack = [], list(by_parent.get(root.span_id, []))
    while stack:
        cur = stack.pop()
        out.append(cur)
        stack.extend(by_parent.get(cur.span_id, []))
    return out

def audit_tool_span_attribution(spans: list[GenAiSpan], rounding: int = 0) -> None:
    """Enforce: an execute_tool span carrying usage must not have a descendant
    chat span with usage equal (within `rounding`) to its own. Equality is the
    fingerprint of a relayed (laundered) attribution."""
    for span in spans:
        if span.operation_name != "execute_tool":
            continue
        tool_usage = _usage(span)
        if tool_usage is None:
            continue  # tool did not report usage; nothing to launder
        for desc in _descendants(span, spans):
            if desc.operation_name != "chat":
                continue
            chat_usage = _usage(desc)
            if chat_usage is None:
                continue
            if (abs(tool_usage[0] - chat_usage[0]) <= rounding
                    and abs(tool_usage[1] - chat_usage[1]) <= rounding):
                raise TokenAttributionLaunderingError(
                    f"tool span {span.span_id} relays usage {tool_usage} "
                    f"identical to descendant chat span {desc.span_id} "
                    f"(usage {chat_usage}); re-parented at handoff boundary. "
                    f"Exclude tool span from cost/budget rollups and debit "
                    f"budget once on {desc.span_id}."
                )

def accountable_tokens(spans: list[GenAiSpan]) -> dict[str, tuple[int, int]]:
    """Per-agent accountable tokens: sum only chat spans, keyed by span,
    after laundering audit passes. Tool spans with usage are counted only
    if they have no descendant chat span (unspanned inference)."""
    audit_tool_span_attribution(spans)
    totals: dict[str, tuple[int, int]] = {}
    for span in spans:
        usage = _usage(span)
        if usage is None:
            continue
        if span.operation_name == "chat":
            totals[span.span_id] = usage
        elif span.operation_name == "execute_tool":
            if not any(d.operation_name == "chat" for d in _descendants(span, spans)):
                totals[span.span_id] = usage  # unspanned inference, legitimate
            # else: relayed usage, excluded
    return totals
