# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-span-graph-discontinuities-in-opentelemetry-genai-tool-call-attribution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-span-graph-discontinuities-in-opentelemetry-genai-tool-call-attribution.warrant.json
# Markdown SHA-256:   b5e2e7be5172a76dfcf9afb0a9eb0e1dfc2ebf8c2d6756f40c16d855c519f7a0
# Code AST SHA-256:   0dfe88a747eec70ec5e917a920be8eb7311f39706620b872b2eb7646f611abe9
# Verified Classes:   SpanGraphIntegrityError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable

class SpanGraphIntegrityError(RuntimeError):
    """Raised when a GenAI span graph violates the tool-call tree invariant."""

@dataclass(frozen=True)
class Span:
    span_id: str
    parent_span_id: str | None
    name: str                      # e.g. "invoke_agent", "chat", "execute_tool"
    tool_call_id: str | None = None  # gen_ai.tool.call.id, set on chat spans
    input_tokens: int = 0

def assert_tool_call_tree(spans: Iterable[Span]) -> None:
    by_id = {s.span_id: s for s in spans}
    for s in spans:
        if s.name != "execute_tool":
            continue
        parent = by_id.get(s.parent_span_id) if s.parent_span_id else None
        if parent is None or parent.name != "chat":
            raise SpanGraphIntegrityError(
                f"execute_tool span {s.span_id} has parent "
                f"{s.parent_span_id!r} ({parent.name if parent else 'missing'}); "
                f"expected a chat span — context captured at submit time, not execution time"
            )
        if parent.tool_call_id is None:
            raise SpanGraphIntegrityError(
                f"chat parent {parent.span_id} of tool {s.span_id} lacks "
                f"gen_ai.tool.call.id; forest cannot be repaired by cross-reference"
            )

def attribute_turn_tokens(spans: Iterable[Span]) -> int:
    spans = list(spans)
    assert_tool_call_tree(spans)
    # Per-call accuracy only: this sums what each chat span actually sent,
    # including replayed history. Do not treat as unique prompt tokens.
    return sum(s.input_tokens for s in spans if s.name == "chat")
