# 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-span-when-token-usage-attributes-disagree-with-the-provider-s-billed-counts-across-a-tool-c.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-close-a-genai-span-when-token-usage-attributes-disagree-with-the-provider-s-billed-counts-across-a-tool-c.warrant.json
# Markdown SHA-256:   15ddc3aea73ee1e70699f3c430322f6ca74c343387c6b0984ceb8301bcbc7eda
# Code AST SHA-256:   d243fe76026d46062038fd081d0b75d53673ae95c87f1a80736ed4622309cff0
# Verified Classes:   UnverifiedUsageError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class UnverifiedUsageError(RuntimeError):
    """Raised when a GenAI span would close with usage attributes that
    cannot be reconciled to a provider request or to its chat descendants."""


@dataclass
class Span:
    name: str
    operation: str                      # gen_ai.operation.name
    request_id: Optional[str] = None    # provider request id, if any
    input_tokens: Optional[int] = None  # gen_ai.usage.input_tokens
    output_tokens: Optional[int] = None
    usage_verified: bool = False        # reconciled against provider response
    children: list["Span"] = field(default_factory=list)

    def chat_descendant_usage(self) -> tuple[int, int]:
        """Sum verified usage across all descendant chat spans."""
        inp = out = 0
        for child in self.children:
            if child.operation == "chat":
                if not child.usage_verified:
                    raise UnverifiedUsageError(
                        f"descendant chat span {child.name!r} closed without "
                        f"verified usage; cannot aggregate parent {self.name!r}"
                    )
                inp += child.input_tokens or 0
                out += child.output_tokens or 0
            ci, co = child.chat_descendant_usage()
            inp += ci
            out += co
        return inp, out


def close_span(span: Span, aggregate_verified: bool) -> None:
    """Enforce the invariant at span-close time.

    A parent span may close only if either (a) it has no chat descendants,
    or (b) its usage attributes equal the verified sum of its own request
    plus all descendant chat spans, or (c) the caller explicitly marks the
    span as aggregate-unverified so the ledger walks descendants instead.
    """
    desc_in, desc_out = span.chat_descendant_usage()

    if desc_in == 0 and desc_out == 0:
        # Leaf-equivalent: no chat descendants, local usage is authoritative.
        if span.operation == "chat" and span.input_tokens is None:
            raise UnverifiedUsageError(
                f"chat span {span.name!r} closing with no usage and no "
                f"descendants; usage object was lost (stream truncated?)"
            )
        return

    if aggregate_verified:
        local_in = span.input_tokens or 0
        local_out = span.output_tokens or 0
        if local_in != desc_in and local_in + (span.input_tokens or 0) != desc_in:
            # The parent's own usage does not account for descendants.
            raise UnverifiedUsageError(
                f"span {span.name!r} claims input_tokens={local_in} but "
                f"descendant chat spans account for {desc_in}; "
                f"aggregate_verified=True requires equality"
            )
        return

    # aggregate_verified=False: caller has acknowledged the span's usage is
    # local-only. The ledger must walk descendants. Nothing to enforce here,
    # but the marker must be recorded by the exporter (checked elsewhere).
    if span.operation == "chat" and span.input_tokens is None:
        raise UnverifiedUsageError(
            f"span {span.name!r} has chat descendants but no local usage "
            f"and no aggregate marker; trace is unattributable"
        )


# Reproduces the observed incident:
root = Span(name="planner", operation="chat", request_id="req_1",
            input_tokens=1200, output_tokens=340, usage_verified=True)
nested = Span(name="synthesize", operation="chat", request_id="req_2",
              input_tokens=41200, output_tokens=520, usage_verified=True)
root.children.append(nested)

try:
    close_span(root, aggregate_verified=True)   # would have blocked the incident
except UnverifiedUsageError as exc:
    print(f"BLOCKED: {exc}")
