# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-authorizes-a-tool-call-against-a-policy-snapshot-that-was-refreshed-mid-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-authorizes-a-tool-call-against-a-policy-snapshot-that-was-refreshed-mid-invocation.warrant.json
# Markdown SHA-256:   ca22977770ca8da220cfa422a10894b1f9a72b5b788fb8f679e37eb8f7f56e78
# Code AST SHA-256:   8bcfc6f0780f33e562181f8fc79e34eed1eccd64d23caf5d84f1fdc0de7879d7
# Verified Classes:   StalePolicySnapshotError, PolicySnapshot, Decision, PolicyEnforcementPoint
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Callable, Optional


class StalePolicySnapshotError(RuntimeError):
    """Raised when a tool invocation would commit under a policy version
    older than the version in force at commit time."""
    pass


@dataclass
class PolicySnapshot:
    version: int
    permits: dict  # tool_name -> bool
    fetched_at: float


@dataclass
class Decision:
    tool: str
    permit: bool
    policy_version: int
    commit_ts: float = 0.0


class PolicyEnforcementPoint:
    def __init__(self, pdp: Callable[[str], PolicySnapshot], max_staleness_s: float = 0.0):
        self._pdp = pdp
        self._max_staleness_s = max_staleness_s

    def _fetch(self) -> PolicySnapshot:
        # Fail-closed: no fallback to last-known-good on error.
        snap = self._pdp("principal")
        if snap is None:
            raise StalePolicySnapshotError("PDP returned no snapshot; refusing to authorize")
        return snap

    def authorize_at_commit(self, tool: str, step_snapshot: PolicySnapshot) -> Decision:
        now = time.time()
        # 1. Re-fetch at commit; do not trust the step-scoped snapshot.
        current = self._fetch()
        # 2. Monotonic version assertion: commit-time version must not be older.
        if current.version < step_snapshot.version:
            raise StalePolicySnapshotError(
                f"policy version regressed: commit={current.version} "
                f"step={step_snapshot.version}"
            )
        # 3. Staleness bound on the snapshot actually used for the decision.
        age = now - current.fetched_at
        if self._max_staleness_s >= 0 and age > self._max_staleness_s:
            raise StalePolicySnapshotError(
                f"snapshot age {age:.3f}s exceeds bound {self._max_staleness_s}s"
            )
        permit = bool(current.permits.get(tool, False))
        return Decision(tool=tool, permit=permit,
                        policy_version=current.version, commit_ts=now)


def invoke_tool(pep: PolicyEnforcementPoint, tool: str,
                step_snapshot: PolicySnapshot,
                effect: Callable[[], None]) -> Decision:
    decision = pep.authorize_at_commit(tool, step_snapshot)
    if not decision.permit:
        raise StalePolicySnapshotError(
            f"tool {tool!r} denied at commit under policy v{decision.policy_version}"
        )
    effect()
    return decision
