# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-genai-spans-have-silently-lost-token-accounting-lineage-across-a-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-genai-spans-have-silently-lost-token-accounting-lineage-across-a-tool-call-boundary.warrant.json
# Markdown SHA-256:   a6d54dc3de3808a2b32518e165c1c5281f8a3c6a58e21409e53f825944d77ca0
# Code AST SHA-256:   b57881bc9ea832a56408786de526e30ed4201285d5acf574eeeaf185810ec3f8
# Verified Classes:   GenAiLineageError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class GenAiLineageError(RuntimeError):
    """Raised when a nested chat span cannot be assigned a unique billing owner."""
    pass

@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    operation: str                       # "chat" | "execute_tool" | ...
    tool_call_id: Optional[str] = None
    input_tokens: int = 0
    output_tokens: int = 0
    billing_owner_span_id: Optional[str] = None
    children: list = field(default_factory=list)

def assign_billing_owner(span: Span, ancestors: list[Span]) -> None:
    # A chat span nested under execute_tool under chat must name the
    # ancestor chat span that will re-ingest its output as billing owner.
    if span.operation != "chat":
        return
    chat_ancestors = [a for a in ancestors if a.operation == "chat"]
    tool_between = any(a.operation == "execute_tool" for a in ancestors)
    if not chat_ancestors:
        span.billing_owner_span_id = span.span_id  # top-level: owns itself
        return
    if not tool_between:
        # nested chat without a tool boundary: ambiguous, cannot assign
        raise GenAiLineageError(
            f"chat span {span.span_id} nested under chat without tool boundary; "
            f"billing owner undefined"
        )
    owner = chat_ancestors[-1]  # nearest enclosing chat is the re-ingester
    span.billing_owner_span_id = owner.span_id

def aggregate_billed_tokens(root: Span) -> int:
    total = 0
    stack = [(root, [])]
    while stack:
        node, ancestors = stack.pop()
        assign_billing_owner(node, ancestors)
        if node.operation == "chat":
            # Count only self-owned spans; relayed children are excluded
            # here and will be counted when the owner re-ingests them.
            if node.billing_owner_span_id == node.span_id:
                total += node.input_tokens + node.output_tokens
        for child in node.children:
            stack.append((child, ancestors + [node]))
    return total

def verify_against_provider(root: Span, provider_billed: int) -> None:
    computed = aggregate_billed_tokens(root)
    if computed != provider_billed:
        raise GenAiLineageError(
            f"token lineage broken: trace sums to {computed} but provider "
            f"billed {provider_billed}; nested chat span lacks a resolvable "
            f"billing_owner_span_id"
        )
