# 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-accounting-attributes-disagree-with-the-parent-span-s-aggregated.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-close-a-genai-agent-span-when-the-token-accounting-attributes-disagree-with-the-parent-span-s-aggregated.warrant.json
# Markdown SHA-256:   79eeeaef06d76abc27984e5af2d585d5e07b57707cd7a60255d81ed647b0675c
# Code AST SHA-256:   3501ab437025b9ec87a168f3796c44d146e09c2cc2313e20489f4a12e1fb086f
# Verified Classes:   UsageReconciliationError, SpanUsage, ParentLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UsageReconciliationError(RuntimeError):
    """Raised when a parent GenAI agent span cannot be closed as an
    authoritative token ledger because its subtree does not reconcile."""
    pass


@dataclass
class SpanUsage:
    span_id: str
    parent_id: Optional[str]
    depth: int
    input_tokens: Optional[int]   # None == absent, NOT zero
    output_tokens: Optional[int]  # None == absent, NOT zero
    is_retry: bool = False


@dataclass
class ParentLedger:
    span_id: str
    aggregate_input: int
    aggregate_output: int
    aggregator_walk_depth: int
    descendants: list[SpanUsage] = field(default_factory=list)


def close_agent_span(ledger: ParentLedger, *, tolerance_input: int = 0) -> dict:
    """Validate the conservation invariant before allowing span.end().

    Invariant: parent.aggregate == sum(descendants), where absent usage
    attributes are UNKNOWN and make the invariant undefined, not zero.
    """
    # Condition 1: aggregator must walk the full descendant set.
    if any(d.depth > ledger.aggregator_walk_depth for d in ledger.descendants):
        raise UsageReconciliationError(
            f"span {ledger.span_id}: descendants exceed aggregator walk depth "
            f"{ledger.aggregator_walk_depth}; grandchild usage uncounted"
        )

    # Condition 2: absent usage attributes cannot be coerced to zero.
    absent = [d.span_id for d in ledger.descendants
              if d.input_tokens is None or d.output_tokens is None]
    if absent:
        raise UsageReconciliationError(
            f"span {ledger.span_id}: descendants {absent} have absent usage "
            f"attributes (streaming truncation?); invariant undefined"
        )

    # Condition 3: retries must be counted as distinct spans, not dropped.
    child_input = sum(d.input_tokens for d in ledger.descendants)
    child_output = sum(d.output_tokens for d in ledger.descendants)

    delta_in = ledger.aggregate_input - child_input
    delta_out = ledger.aggregate_output - child_output

    if abs(delta_in) > tolerance_input or delta_out != 0:
        # Do NOT return OK. Downgrade authority and surface the divergence.
        return {
            "status": "ERROR",
            "attributes": {
                "gen_ai.usage.reconciliation": "divergent",
                "gen_ai.usage.divergence_input_tokens": delta_in,
                "gen_ai.usage.divergence_output_tokens": delta_out,
            },
            "authoritative": False,
        }

    return {
        "status": "OK",
        "attributes": {"gen_ai.usage.reconciliation": "exact"},
        "authoritative": True,
    }
