# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-injection-detection-revocation-has-already-invalidated-an-in-flight-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-injection-detection-revocation-has-already-invalidated-an-in-flight-tool-call.warrant.json
# Markdown SHA-256:   e4cb7da87356f4d788a853895f9db6570f99f849f91cb0c9bcaa196f43d217ef
# Code AST SHA-256:   94ada1afa6e5fbb361f6b306462bc59c728f750effb1860819994534afe2e94c
# Verified Classes:   RevocationLeak, CapabilityHandle, EpochRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class RevocationLeak(RuntimeError):
    """Raised when a tool call commits under a capability epoch that was
    revoked before commit. The call executed despite being revoked mid-flight."""
    pass


@dataclass(frozen=True)
class CapabilityHandle:
    capability: str
    mint_epoch: int
    registry_nonce: str


class EpochRegistry:
    """Monotonic per-capability epochs. Revocation bumps the epoch; it never
    deletes. Epochs are durable across restarts via the registry nonce."""

    def __init__(self, nonce: str):
        self.nonce = nonce
        self._epochs: dict[str, int] = {}

    def mint(self, capability: str) -> CapabilityHandle:
        epoch = self._epochs.get(capability, 0)
        return CapabilityHandle(capability, epoch, self.nonce)

    def revoke(self, capability: str) -> int:
        self._epochs[capability] = self._epochs.get(capability, 0) + 1
        return self._epochs[capability]

    def current_epoch(self, capability: str) -> int:
        return self._epochs.get(capability, 0)


def commit_tool_effect(
    handle: CapabilityHandle,
    registry: EpochRegistry,
    effect,
) -> None:
    """Commit-time re-validation. This must run at the moment of effect
    commit, not at envelope receipt. A revocation landing between dispatch
    and commit is observed here and the call is rejected."""
    if handle.registry_nonce != registry.nonce:
        raise RevocationLeak(
            f"handle minted under registry {handle.registry_nonce!r}, "
            f"current registry is {registry.nonce!r}; epoch lineage lost"
        )
    commit_epoch = registry.current_epoch(handle.capability)
    if handle.mint_epoch < commit_epoch:
        raise RevocationLeak(
            f"capability {handle.capability!r} revoked mid-flight: "
            f"mint_epoch={handle.mint_epoch} commit_epoch={commit_epoch}"
        )
    effect()


def dispatch_with_taint_gate(
    capability: str,
    tainted: bool,
    registry: EpochRegistry,
    effect,
) -> None:
    """Dispatch path consults taint before materializing the handle. If the
    argument is tainted, no handle is minted and no envelope is built."""
    if tainted:
        raise RevocationLeak(
            f"refusing to dispatch {capability!r}: argument is tainted, "
            f"injection verdict is a precondition on dispatch"
        )
    handle = registry.mint(capability)
    commit_tool_effect(handle, registry, effect)


# --- reproduction of the observed leak ---
if __name__ == "__main__":
    reg = EpochRegistry(nonce="reg-A")
    handle = reg.mint("shell.exec")          # t=409ms, epoch 0
    reg.revoke("shell.exec")                 # t=412ms, epoch -> 1
    try:
        commit_tool_effect(handle, reg, lambda: print("EFFECT: should not run"))
    except RevocationLeak as e:
        print(f"blocked at commit: {e}")

    # the unsafe path: validating at receipt against a stale snapshot
    stale_epoch_at_receipt = 0
    if handle.mint_epoch >= stale_epoch_at_receipt:
        print("UNSAFE: receipt-time validation would let this commit")
