# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-token-accounting-across-a-genai-agent-span-when-tool-call-attributes-are-emitted-after-child-span-closure.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-token-accounting-across-a-genai-agent-span-when-tool-call-attributes-are-emitted-after-child-span-closure.warrant.json
# Markdown SHA-256:   a0bb957c608d24a5ec835b374a204a399e868a5f614243cdbbfab21fb531a06e
# Code AST SHA-256:   2d06667094aba7ede8f751e098816f4695e4e25131d04556639e14bc7bc7f778
# Verified Classes:   IncompleteTokenRollupError, AgentSpanRollup
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class IncompleteTokenRollupError(RuntimeError):
    """Raised when a parent agent span tries to emit an authoritative
    gen_ai.usage rollup while child tool/model work is still in flight."""
    pass


@dataclass
class AgentSpanRollup:
    trace_id: str
    outstanding_tool_futures: int = 0
    child_input_tokens: int = 0
    child_output_tokens: int = 0
    rollup_complete: bool = False
    _finalized: bool = False

    def dispatch_tool(self) -> None:
        if self._finalized:
            raise IncompleteTokenRollupError(
                f"tool dispatched after parent span {self.trace_id} finalized"
            )
        self.outstanding_tool_futures += 1

    def complete_tool(self, input_tokens: int = 0, output_tokens: int = 0) -> None:
        # A tool completion may trigger a follow-on chat span; its usage
        # must land here before the parent is allowed to finalize.
        if self.outstanding_tool_futures <= 0:
            raise IncompleteTokenRollupError(
                f"tool completion with no outstanding future on {self.trace_id}"
            )
        self.outstanding_tool_futures -= 1
        self.child_input_tokens += input_tokens
        self.child_output_tokens += output_tokens

    def finalize(self, deadline_exceeded: bool = False) -> dict:
        if self.outstanding_tool_futures > 0:
            # Do NOT fabricate an authoritative rollup. Emit a partial,
            # explicitly-flagged value and let the aggregator reconcile
            # against child chat spans by trace_id.
            if not deadline_exceeded:
                raise IncompleteTokenRollupError(
                    f"{self.outstanding_tool_futures} tool futures still live "
                    f"at parent end for {self.trace_id}; refusing authoritative rollup"
                )
            self._finalized = True
            return {
                "gen_ai.usage.input_tokens": self.child_input_tokens,
                "gen_ai.usage.output_tokens": self.child_output_tokens,
                "gen_ai.usage.rollup.complete": False,
            }

        self._finalized = True
        self.rollup_complete = True
        return {
            "gen_ai.usage.input_tokens": self.child_input_tokens,
            "gen_ai.usage.output_tokens": self.child_output_tokens,
            "gen_ai.usage.rollup.complete": True,
        }


def budget_guard(rollup_attrs: dict, ceiling: int) -> Optional[str]:
    """Fail closed: an incomplete rollup must never authorize more spend."""
    if not rollup_attrs.get("gen_ai.usage.rollup.complete", False):
        raise IncompleteTokenRollupError(
            "budget guard received a rollup without rollup.complete=true; "
            "reconcile against child chat spans before trusting it"
        )
    used = rollup_attrs["gen_ai.usage.input_tokens"] + rollup_attrs["gen_ai.usage.output_tokens"]
    if used > ceiling:
        return f"budget exceeded: {used} > {ceiling}"
    return None
