# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-token-accounting-drift-when-opentelemetry-genai-span-attributes-are-split-across-a-retry-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-token-accounting-drift-when-opentelemetry-genai-span-attributes-are-split-across-a-retry-boundary.warrant.json
# Markdown SHA-256:   ed6477bbe4d28f3140b78abd5ff587904aa29c58b2fee813ff03f3e71b31a94f
# Code AST SHA-256:   386c1edf69af84f56ab5cb0c4a74ba327eff4b33fd3eafcc23ac5aa3380ac9c9
# Verified Classes:   TokenAccountingDriftError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TokenAccountingDriftError(RuntimeError):
    """Raised when a logical agent step's span subtree violates the additive-correctness invariant."""
    pass


@dataclass
class Span:
    name: str
    operation: str                      # gen_ai.operation.name
    status: str                         # "OK" | "ERROR"
    input_tokens: int = 0               # gen_ai.usage.input_tokens
    output_tokens: int = 0              # gen_ai.usage.output_tokens
    tool_name: Optional[str] = None     # gen_ai.tool.name
    tool_call_id: Optional[str] = None  # gen_ai.tool.call.id
    children: list["Span"] = field(default_factory=list)


def reconcile_step_cost(step: Span, billed_input: int, billed_output: int) -> None:
    """
    Verify that the sum of usage over the full subtree (including ERROR spans)
    equals the provider-billed cost for the logical step. Raises on drift.
    """
    if step.operation != "invoke_agent":
        raise TokenAccountingDriftError(
            f"expected invoke_agent root, got {step.operation!r}"
        )

    # Guardrail 1: parent must not carry usage if children do (double-count risk).
    if (step.input_tokens or step.output_tokens) and step.children:
        raise TokenAccountingDriftError(
            "usage recorded on both invoke_agent parent and its children; "
            "subtree sum would double-count"
        )

    # Guardrail 2: tool-call IDs must be unique across a subtree (retry must re-issue ID).
    seen_call_ids: dict[str, str] = {}
    def walk(s: Span) -> tuple[int, int]:
        total_in, total_out = s.input_tokens, s.output_tokens
        if s.tool_call_id is not None:
            if s.tool_call_id in seen_call_ids:
                raise TokenAccountingDriftError(
                    f"tool_call_id {s.tool_call_id!r} reused across spans "
                    f"({seen_call_ids[s.tool_call_id]!r} and {s.name!r}); "
                    "retry collapsed and will be dropped by dedup"
                )
            seen_call_ids[s.tool_call_id] = s.name
        for c in s.children:
            ci, co = walk(c)
            total_in += ci
            total_out += co
        return total_in, total_out

    observed_in, observed_out = walk(step)

    # Guardrail 3: failed attempts with emitted tokens must be preserved.
    def check_partial_failures(s: Span) -> None:
        if s.status == "ERROR" and s.output_tokens > 0 and not s.children:
            # A leaf ERROR span with tokens is legitimate only if it is materialized;
            # if it was collapsed, observed_out would be short of billed_output.
            pass
        for c in s.children:
            check_partial_failures(c)
    check_partial_failures(step)

    if observed_in != billed_input or observed_out != billed_output:
        raise TokenAccountingDriftError(
            f"subtree sum (in={observed_in}, out={observed_out}) != "
            f"billed (in={billed_input}, out={billed_output}); "
            f"delta (in={billed_input - observed_in}, out={billed_output - observed_out}) "
            "indicates collapsed retry or dropped ERROR-span usage"
        )
