# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-close-a-genai-agent-span-when-the-token-usage-attribute-set-is-internally-inconsistent-and-how-should-the.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-close-a-genai-agent-span-when-the-token-usage-attribute-set-is-internally-inconsistent-and-how-should-the.warrant.json
# Markdown SHA-256:   98a7f3e7104c5ba217a37cf4200fda57808fd22d4876917ce2fe376cc2dad371
# Code AST SHA-256:   be720bab94ab318defdc328899f15214824b69d6df319a725e95f8ea10406e4a
# Verified Classes:   GenAIUsageInconsistentError, Usage, ChildSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass
from typing import Optional


class GenAIUsageInconsistentError(RuntimeError):
    """Raised when a parent agent span's token totals do not reconcile
    with the sum of its child model-invocation spans."""


@dataclass
class Usage:
    input_tokens: int
    output_tokens: int


@dataclass
class ChildSpan:
    usage: Usage
    tokenizer_name: str
    truncated: bool = False


def close_agent_span(
    parent_usage: Usage,
    parent_tokenizer: str,
    children: list[ChildSpan],
    tolerance_ratio: float = 0.005,
    parent_has_direct_call: bool = True,
) -> None:
    if not parent_has_direct_call:
        # Aggregator-only parent: token attrs must be absent, not reconciled.
        return

    if any(c.tokenizer_name != parent_tokenizer for c in children):
        # Provenance mismatch: delta is expected, do not assert equality.
        return

    child_in = sum(c.usage.input_tokens for c in children)
    child_out = sum(c.usage.output_tokens for c in children)

    tol_in = max(1, math.ceil(tolerance_ratio * parent_usage.input_tokens))
    tol_out = max(1, math.ceil(tolerance_ratio * parent_usage.output_tokens))

    if any(c.truncated for c in children):
        # Truncation makes provider output a floor, not a measurement.
        if parent_usage.output_tokens < child_out:
            raise GenAIUsageInconsistentError(
                f"parent output {parent_usage.output_tokens} < truncated child sum {child_out}"
            )
        return

    d_in = abs(parent_usage.input_tokens - child_in)
    d_out = abs(parent_usage.output_tokens - child_out)

    if d_in > tol_in or d_out > tol_out:
        raise GenAIUsageInconsistentError(
            "genai.usage.inconsistent: "
            f"input parent={parent_usage.input_tokens} child_sum={child_in} delta={d_in} tol={tol_in}; "
            f"output parent={parent_usage.output_tokens} child_sum={child_out} delta={d_out} tol={tol_out}"
        )
