# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-child-agent-span-token-counts-when-a-tool-call-span-is-retried-across-a-transport-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-child-agent-span-token-counts-when-a-tool-call-span-is-retried-across-a-transport-boundary.warrant.json
# Markdown SHA-256:   4551aac66c8f1c2ddea124d7b1f5bb488e0a36d1baa46625659699bfdcf0da3f
# Code AST SHA-256:   135f016a77556cece2d4c507453a6ee32b591ccad5a53dc1c911aac5f34f131d
# Verified Classes:   UsageReconciliationError, AttemptOutcome, ToolAttempt, AgentSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class UsageReconciliationError(RuntimeError):
    """Raised when a parent agent span's summed child usage cannot be
    treated as a point estimate because a retried tool-call attempt
    has an unresolvable token cost."""


class AttemptOutcome(Enum):
    OK = "ok"
    FAIL_BEFORE_EXECUTE = "fail_before_execute"   # zero tokens is truthful
    FAIL_AFTER_EXECUTE = "fail_after_execute"     # zero tokens is a lie of omission
    UNKNOWN = "unknown"                           # cannot classify from client side


@dataclass
class ToolAttempt:
    tool_name: str
    attempt: int
    outcome: AttemptOutcome
    input_tokens: Optional[int]
    output_tokens: Optional[int]
    usage_unknown: bool = False

    def truthful_usage(self) -> Optional[int]:
        if self.usage_unknown or self.input_tokens is None:
            return None
        if self.outcome is AttemptOutcome.FAIL_AFTER_EXECUTE:
            # client-observed zero is not the backend's truth
            return None
        return self.input_tokens


@dataclass
class AgentSpan:
    agent_name: str
    tool_attempts: list[ToolAttempt] = field(default_factory=list)

    def reconcile_input_tokens(self) -> tuple[int, bool]:
        """Return (best_estimate, is_partial). is_partial=True means the
        figure is a lower bound and must not drive budget compaction."""
        by_tool: dict[str, list[ToolAttempt]] = {}
        for a in self.tool_attempts:
            by_tool.setdefault(a.tool_name, []).append(a)

        total = 0
        partial = False
        for tool, attempts in by_tool.items():
            attempts.sort(key=lambda a: a.attempt)
            ok = [a for a in attempts if a.outcome is AttemptOutcome.OK]
            if not ok:
                raise UsageReconciliationError(
                    f"tool {tool!r}: no successful attempt; cannot account usage"
                )
            # only the highest-attempt OK span represents resident context
            total += ok[-1].truthful_usage() or 0
            # every failed attempt may have consumed backend tokens
            for a in attempts:
                if a.outcome is AttemptOutcome.OK:
                    continue
                if a.truthful_usage() is None:
                    partial = True
        return total, partial


def enforce_budget(span: AgentSpan, context_budget: int) -> None:
    used, partial = span.reconcile_input_tokens()
    if partial and used >= context_budget:
        raise UsageReconciliationError(
            f"agent {span.agent_name!r}: budget {context_budget} reached at "
            f"lower-bound usage {used}, but a retried attempt has unknown cost; "
            f"refusing to compact on an undercount"
        )
    if not partial and used >= context_budget:
        raise UsageReconciliationError(
            f"agent {span.agent_name!r}: budget {context_budget} exceeded "
            f"(exact usage {used})"
        )
