# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-tool-call-before-the-policy-decision-is-durably-acknowledged.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-tool-call-before-the-policy-decision-is-durably-acknowledged.warrant.json
# Markdown SHA-256:   0f20545a1ec4997861f3c0e5bfa3e49b4e751a8b2f11847c26ba60c1b7600862
# Code AST SHA-256:   c5f416e0aec0ca63e3426f7ecd47f6165f428f55075e56c6cf442a580be6c497
# Verified Classes:   PolicyWarrantUnrecorded, WarrantStore, ToolCallIntent
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class PolicyWarrantUnrecorded(RuntimeError):
    """Raised when a tool call would dispatch without a durably recorded allow-decision."""
    pass


class WarrantStore:
    """Durable store for (intent_hash -> decision record). Must be transactional with checkpoints."""
    def __init__(self):
        self._records = {}

    def persist(self, intent_hash: str, decision_id: str, policy_revision: str) -> bool:
        # In production: same transaction as checkpoint write; fsync before returning True.
        self._records[intent_hash] = (decision_id, policy_revision)
        return True

    def lookup(self, intent_hash: str) -> Optional[tuple]:
        return self._records.get(intent_hash)


@dataclass
class ToolCallIntent:
    tool: str
    args: dict
    intent_hash: str


def dispatch_tool_call(intent: ToolCallIntent, pdp, store: WarrantStore, tool_server) -> dict:
    # On resume: prefer an existing durable warrant over a fresh PDP consultation.
    existing = store.lookup(intent.intent_hash)
    if existing is not None:
        decision_id, _rev = existing
        # Idempotent replay: tool server must no-op on a seen decision_id.
        return tool_server.invoke(intent, idempotency_key=decision_id)

    decision = pdp.evaluate(intent.tool, intent.args)
    if decision.effect != "allow":
        raise PolicyWarrantUnrecorded(
            f"PDP denied {intent.tool} (rev={decision.revision}); no dispatch."
        )

    # The authorization event is the durable record, not the in-memory Allow.
    if not store.persist(intent.intent_hash, decision.decision_id, decision.revision):
        raise PolicyWarrantUnrecorded(
            f"Could not durably record allow-decision {decision.decision_id} for "
            f"{intent.tool}; failing closed rather than dispatching on an unpersisted warrant."
        )

    return tool_server.invoke(intent, idempotency_key=decision.decision_id)
