# 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-on-token-accounting-reconciliation-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-close-a-genai-agent-span-on-token-accounting-reconciliation-failure.warrant.json
# Markdown SHA-256:   12c93c9e03f52f3880a5ea15dbb80b790a782704b74a27f076c3072c3f39ede5
# Code AST SHA-256:   f96fb6aff95889f36f13262cd6b96a9e5799a1a87254c39cbba6139e79faca73
# Verified Classes:   TokenAccountingReconciliationError, ChildUsage, ParentAggregate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TokenAccountingReconciliationError(RuntimeError):
    """Raised when a usage-aggregating GenAI parent span cannot be closed
    consistently with its committed child spans."""
    pass


@dataclass
class ChildUsage:
    span_id: str
    input_tokens: int          # non-cached, per gen_ai.usage.input_tokens
    cached_input_tokens: int   # gen_ai.usage.input_tokens_details.cached_tokens
    output_tokens: int


@dataclass
class ParentAggregate:
    input_tokens: int
    output_tokens: int
    provenance: str            # "child_ledger" | "unverified" | "omitted"


def reconcile_parent_usage(
    parent_span_id: str,
    counter_input: int,
    counter_output: int,
    children: list[ChildUsage],
    attributable_residual: Optional[str] = None,
) -> ParentAggregate:
    """
    Decide whether a usage-aggregating parent span may close OK.

    Invariant: parent aggregate must be >= sum(child non-cached input) and
    >= sum(child output), with any positive residual attributable to a named
    cause (retry, cache, estimation). A negative residual is a hard failure.
    """
    if not children:
        # No committed child ledger: cannot reconcile. Be honest, do not fabricate.
        return ParentAggregate(counter_input, counter_output, provenance="unverified")

    child_input = sum(c.input_tokens for c in children)
    child_output = sum(c.output_tokens for c in children)

    input_residual = counter_input - child_input
    output_residual = counter_output - child_output

    if input_residual < 0 or output_residual < 0:
        offenders = [
            c.span_id for c in children
            if c.input_tokens < 0 or c.output_tokens < 0
        ]
        raise TokenAccountingReconciliationError(
            f"parent span {parent_span_id}: negative usage residual "
            f"(input_residual={input_residual}, output_residual={output_residual}); "
            f"children claim more than parent counter. Offending children: {offenders}. "
            f"Span must close ERROR with error.type="
            f"'token_accounting_reconciliation_failure'."
        )

    if (input_residual > 0 or output_residual > 0) and attributable_residual is None:
        # Positive residual but no named cause: emit unverified, never claim OK-with-ledger.
        return ParentAggregate(counter_input, counter_output, provenance="unverified")

    return ParentAggregate(counter_input, counter_output, provenance="child_ledger")
