# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-call-latency-as-a-semantic-signal-rather-than-a-performance-metric-and-how-does-retry-storm-amplificatio.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-call-latency-as-a-semantic-signal-rather-than-a-performance-metric-and-how-does-retry-storm-amplificatio.warrant.json
# Markdown SHA-256:   4b5c3ff5c19bd1f0f8c7d1429e1eb0af0d8914da946dbd4fca3043e8460f309d
# Code AST SHA-256:   4fc1e2d6894e18411efec9d60ecbbb23f7f2fbe097662966723c2ba03278fb36
# Verified Classes:   AmbiguousCommitError, CommitStatus, ToolCapability, RetryBudget, LogicalSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class AmbiguousCommitError(RuntimeError):
    """Raised when a non-idempotent tool times out and commit status is unknown.

    Retrying in this state risks duplicate side effects and corrupts trace
    semantics by emitting sibling spans for a single logical operation.
    """


class CommitStatus(Enum):
    COMMITTED = "committed"
    NOT_COMMITTED = "not_committed"
    UNKNOWN = "unknown"


@dataclass
class ToolCapability:
    name: str
    idempotent: bool
    supports_dedup_key: bool


@dataclass
class RetryBudget:
    """Global token bucket; retries drain from a shared pool, not per-call."""
    tokens: int
    refill_per_call: int = 1

    def try_consume(self) -> bool:
        if self.tokens <= 0:
            return False
        self.tokens -= 1
        return True


@dataclass
class LogicalSpan:
    name: str
    attempts: list = field(default_factory=list)
    commit_status: CommitStatus = CommitStatus.UNKNOWN

    def record_attempt(self, duration_ms: int, error: Optional[str]) -> None:
        # Physical attempts are span EVENTS, not sibling spans.
        self.attempts.append({"duration_ms": duration_ms, "error": error})


def invoke_tool(
    cap: ToolCapability,
    budget: RetryBudget,
    call_fn,
    dedup_key: Optional[str],
    timeout_ms: int,
) -> LogicalSpan:
    span = LogicalSpan(name=cap.name)
    while True:
        try:
            result = call_fn(timeout_ms=timeout_ms, dedup_key=dedup_key)
            span.record_attempt(duration_ms=timeout_ms, error=None)
            span.commit_status = CommitStatus.COMMITTED
            return span
        except TimeoutError as exc:
            span.record_attempt(duration_ms=timeout_ms, error="DeadlineExceeded")

            # Idempotency check: a declaration without enforcement is a lie.
            safe_to_retry = (
                cap.idempotent
                and cap.supports_dedup_key
                and dedup_key is not None
            )

            if not safe_to_retry:
                span.commit_status = CommitStatus.UNKNOWN
                raise AmbiguousCommitError(
                    f"tool={cap.name} timed out with commit status UNKNOWN; "
                    f"idempotent={cap.idempotent} dedup_key_supplied="
                    f"{dedup_key is not None}. Do not retry; reconcile via "
                    f"get_status(dedup_key) before proceeding."
                ) from exc

            if not budget.try_consume():
                span.commit_status = CommitStatus.UNKNOWN
                raise AmbiguousCommitError(
                    f"tool={cap.name} retry budget exhausted during storm; "
                    f"aborting rather than amplifying load."
                ) from exc
            # loop: retry with the same dedup_key, which the tool dedups server-side
