# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-close-a-genai-agent-span-when-the-token-accounting-child-spans-disagree-with-the-parent-s-gen-ai-usag.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-close-a-genai-agent-span-when-the-token-accounting-child-spans-disagree-with-the-parent-s-gen-ai-usag.warrant.json
# Markdown SHA-256:   e630b05bbb66b1ed162319bd40100e8c31b9faec85f4196517dc02f18922d300
# Code AST SHA-256:   04a0d418dd77ba8763a46700cc1e114ad89caec2c5d06edc845251317181bae5
# Verified Classes:   TokenAccountingInvariantError, SpanNode
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a GenAI agent span closes with usage that cannot equal
    the sum of its descendant inference spans."""


@dataclass
class SpanNode:
    span_id: str
    operation_name: str
    input_tokens: Optional[int] = None
    output_tokens: Optional[int] = None
    children: list["SpanNode"] = field(default_factory=list)
    aggregate_complete: bool = True


def _descendant_usage(node: SpanNode) -> tuple[int, int]:
    """Sum input/output tokens over all descendants that carry usage."""
    total_in = total_out = 0
    for child in node.children:
        if child.input_tokens is not None:
            total_in += child.input_tokens
        if child.output_tokens is not None:
            total_out += child.output_tokens
        sub_in, sub_out = _descendant_usage(child)
        total_in += sub_in
        total_out += sub_out
    return total_in, total_out


def close_agent_span(node: SpanNode, performs_own_inference: bool) -> None:
    """Validate the GenAI aggregate invariant before allowing the span to close.

    - Pure aggregator (performs_own_inference=False): parent usage MUST equal
      descendant sum exactly.
    - Self-inferring parent: parent usage MUST be >= descendant sum.
    - Asynchronous runtimes that cannot join descendants MUST set
      aggregate_complete=False; the invariant is then skipped but the trace is
      marked non-authoritative for accounting.
    """
    if node.operation_name != "invoke_agent":
        return
    if not node.aggregate_complete:
        # Honest uncertainty: caller declared descendants may be outstanding.
        return

    desc_in, desc_out = _descendant_usage(node)
    parent_in = node.input_tokens or 0
    parent_out = node.output_tokens or 0

    if performs_own_inference:
        if parent_in < desc_in or parent_out < desc_out:
            raise TokenAccountingInvariantError(
                f"span {node.span_id}: self-inferring parent reports "
                f"in={parent_in}/out={parent_out} but descendants sum to "
                f"in={desc_in}/out={desc_out}; parent under-reports. "
                f"Likely depth truncation or identity collapse in aggregator."
            )
    else:
        if parent_in != desc_in or parent_out != desc_out:
            raise TokenAccountingInvariantError(
                f"span {node.span_id}: pure-aggregator parent reports "
                f"in={parent_in}/out={parent_out} but descendants sum to "
                f"in={desc_in}/out={desc_out}; equality violated by "
                f"delta_in={parent_in - desc_in}, delta_out={parent_out - desc_out}. "
                f"Check for deduplication keyed on gen_ai.operation.name, "
                f"direct-children-only summation, or post-close descendant spans."
            )
