# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-genai-semantic-convention-token-accounting-with-the-actual-tool-call-span-tree-before-emitting-a-pare.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-genai-semantic-convention-token-accounting-with-the-actual-tool-call-span-tree-before-emitting-a-pare.warrant.json
# Markdown SHA-256:   4416c98dd7603550afb56a73e83f9113322a649f3c7dc698eedeba0dc36d8ecf
# Code AST SHA-256:   e9627a73d424543a975f039290d31ea540b8851ab5e1cfbc783f1f3a4c0a4226
# Verified Classes:   UsageReconciliationError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class UsageReconciliationError(RuntimeError):
    """Raised when a parent agent span's aggregate usage cannot be
    reconciled against its owned model-call children under the declared
    GenAI semantic-convention posture."""
    pass

@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    kind: str                      # "agent" | "chat" | "tool"
    status: str                    # "ok" | "cancelled" | "speculative"
    input_tokens: int = 0
    output_tokens: int = 0
    cache_read_tokens: int = 0
    attempt: int = 1
    logical_call_id: Optional[str] = None

def fold_owned_usage(parent: Span, all_spans: list[Span], posture: str) -> tuple[int, int]:
    if posture not in ("semantic", "billing"):
        raise UsageReconciliationError(f"unknown posture {posture!r} on span {parent.span_id}")

    owned = [s for s in all_spans if s.parent_span_id == parent.span_id and s.kind == "chat"]

    if posture == "semantic":
        # Collapse retries to the final attempt of each logical call; drop
        # cancelled/speculative calls entirely.
        by_call: dict[str, Span] = {}
        for s in owned:
            if s.status != "ok":
                continue
            key = s.logical_call_id or s.span_id
            prev = by_call.get(key)
            if prev is None or s.attempt > prev.attempt:
                by_call[key] = s
        chosen = list(by_call.values())
    else:  # billing: include every attempt, including cancelled speculative
        chosen = owned

    # Cache reads must never be folded into input_tokens.
    for s in chosen:
        if s.cache_read_tokens and s.cache_read_tokens > s.input_tokens:
            raise UsageReconciliationError(
                f"span {s.span_id}: cache_read_tokens {s.cache_read_tokens} "
                f"exceeds input_tokens {s.input_tokens}"
            )

    return (
        sum(s.input_tokens for s in chosen),
        sum(s.output_tokens for s in chosen),
    )

def close_parent(parent: Span, all_spans: list[Span], posture: str,
                 reported_input: int, reported_output: int) -> None:
    expected_in, expected_out = fold_owned_usage(parent, all_spans, posture)
    if (reported_input, reported_output) != (expected_in, expected_out):
        raise UsageReconciliationError(
            f"parent {parent.span_id} reported "
            f"({reported_input},{reported_output}) but owned fold under "
            f"posture={posture!r} yields ({expected_in},{expected_out})"
        )
