# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-genai-span-attribute-lineage-before-token-accounting-can-be-trusted-across-a-tool-call-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-genai-span-attribute-lineage-before-token-accounting-can-be-trusted-across-a-tool-call-fan-out.warrant.json
# Markdown SHA-256:   0871b2fd6ff4d0ed277b21d10ab9ab5929bcd08cfb886a6ad5640d7c07402ae8
# Code AST SHA-256:   4b3a0acd453a32f298744577a1e4ba1918f63344fb448bbaf2bf87ceed88ef7f
# Verified Classes:   TokenLineageError, GenAISpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TokenLineageError(RuntimeError):
    """Raised when a chat span's input-token accounting cannot be classified
    as additive vs. cumulative due to a broken tool-call lineage edge."""


@dataclass
class GenAISpan:
    span_id: str
    parent_id: Optional[str]
    operation: str                      # "chat" | "execute_tool"
    input_tokens: Optional[int] = None
    output_tokens: Optional[int] = None
    tool_call_id: Optional[str] = None  # gen_ai.tool.call.id
    children: list = field(default_factory=list)


def _ancestors(span: GenAISpan, by_id: dict) -> list:
    chain, cur = [], span
    while cur.parent_id is not None:
        cur = by_id[cur.parent_id]
        chain.append(cur)
    return chain


def account_tokens(chat_spans: list, by_id: dict) -> dict:
    """Account input/output tokens respecting the cumulative-input /
    disjoint-output asymmetry of agentic tool-call re-entry chains."""
    total_output = 0
    input_high_water = 0

    for span in chat_spans:
        if span.operation != "chat":
            continue
        total_output += span.output_tokens or 0

        anc = _ancestors(span, by_id)
        tool_ancestors = [a for a in anc if a.operation == "execute_tool"]

        if not tool_ancestors:
            # Independent operation: input is additive.
            input_high_water += span.input_tokens or 0
            continue

        # Re-entry after a tool call: input_tokens is a cumulative snapshot.
        # Require the join key to prove which tool result was consumed.
        if span.tool_call_id is None:
            raise TokenLineageError(
                f"chat span {span.span_id} descends from tool span "
                f"{tool_ancestors[-1].span_id} but carries no "
                f"gen_ai.tool.call.id; input-token accounting is ambiguous "
                f"and must not be summed."
            )
        matched = any(t.tool_call_id == span.tool_call_id for t in tool_ancestors)
        if not matched:
            raise TokenLineageError(
                f"chat span {span.span_id} tool_call_id={span.tool_call_id!r} "
                f"matches no ancestor tool span; lineage edge is severed."
            )

        # Cumulative: keep the high-water mark, never add to the sum.
        input_high_water = max(input_high_water, span.input_tokens or 0)

    return {"input_tokens": input_high_water, "output_tokens": total_output}
