# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-tool-call-spans-before-the-model-span-closes-orphaned-token-accounting-and-the-parent-span-ordering-invarian.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-tool-call-spans-before-the-model-span-closes-orphaned-token-accounting-and-the-parent-span-ordering-invarian.warrant.json
# Markdown SHA-256:   67dddc37cad3655b2af58472a26180ed7b124df26ffc1079634a5061ead1adbe
# Code AST SHA-256:   cc085fb95f33bb80c5a285dd4d45462da2163a6e2d624079c56f650a08fce63a
# Verified Classes:   OrphanedGenAISpanError, SpanRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class OrphanedGenAISpanError(RuntimeError):
    """Raised when a GenAI tool-call span cannot be attributed to a turn."""


@dataclass(frozen=True)
class SpanRecord:
    span_id: str
    parent_span_id: str | None
    operation: str
    turn_id: str | None
    input_tokens: int
    output_tokens: int


def attribute_turn_tokens(spans: list[SpanRecord]) -> dict[str, int]:
    """Sum tokens per turn, keyed on the turn-correlation attribute.

    Refuses to attribute any span whose turn_id is absent, rather than
    falling back to a parent-span join that may not resolve.
    """
    totals: dict[str, int] = {}
    orphans: list[SpanRecord] = []

    for span in spans:
        if span.turn_id is None:
            orphans.append(span)
            continue
        totals[span.turn_id] = (
            totals.get(span.turn_id, 0) + span.input_tokens + span.output_tokens
        )

    if orphans:
        # Fail closed: an unattributable token-bearing span must not be
        # silently dropped into an "unknown" bucket, because that is the
        # exact deficit the parent-edge join produces.
        raise OrphanedGenAISpanError(
            f"{len(orphans)} span(s) lack a turn_id and cannot be attributed; "
            f"first offender span_id={orphans[0].span_id} "
            f"op={orphans[0].operation} parent={orphans[0].parent_span_id}"
        )

    return totals
