# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-revoke-a-speculative-tool-call-pre-execution-whose-taint-gate-was-satisfied-at-dispatch-but-violated-at-commit.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-revoke-a-speculative-tool-call-pre-execution-whose-taint-gate-was-satisfied-at-dispatch-but-violated-at-commit.warrant.json
# Markdown SHA-256:   b07d84806abe9007e5ccf2be28b0ee069f10bfaeede8db331b8803caa2c2b4ae
# Code AST SHA-256:   b2b9060cd5785de5e5ac459878fc42a70a54d9228eb489c2920dd2e56d157bbd
# Verified Classes:   Taint, LabelSnapshot, SpeculativeCall, StaleGateRevocation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Callable, Hashable


class Taint(IntEnum):
    """Ordered label lattice; higher widens taint."""
    INTERNAL = 0
    PARTNER = 1
    EXTERNAL_UNTRUSTED = 2


@dataclass(frozen=True)
class LabelSnapshot:
    labels: dict[Hashable, Taint]

    def max_on(self, closure: frozenset[Hashable]) -> Taint:
        if not closure:
            # Empty closure is unverifiable, not clean.
            return Taint.EXTERNAL_UNTRUSTED
        return max((self.labels.get(k, Taint.EXTERNAL_UNTRUSTED) for k in closure),
                   default=Taint.EXTERNAL_UNTRUSTED)


@dataclass
class SpeculativeCall:
    call_id: str
    tool: str
    closure: frozenset[Hashable]          # transitive input ids read at dispatch
    dispatch_labels: LabelSnapshot
    ceiling: Taint                        # tool's admitted taint ceiling
    result: object = None
    committed: bool = False


class StaleGateRevocation(RuntimeError):
    """Raised when a speculative call's gate passed at dispatch but fails re-evaluation at commit."""


def gate_admits(observed: Taint, ceiling: Taint) -> bool:
    return observed <= ceiling


def commit_speculative(
    call: SpeculativeCall,
    live_labels: LabelSnapshot,
    apply_side_effect: Callable[[object], None],
) -> None:
    """
    Re-evaluate taint closure against live labels before committing.
    Widening across the window revokes, even if the dispatch gate passed.
    """
    dispatch_max = call.dispatch_labels.max_on(call.closure)
    if not gate_admits(dispatch_max, call.ceiling):
        # Should never have been buffered; defensive.
        raise StaleGateRevocation(
            f"{call.call_id}: buffered despite failing dispatch gate "
            f"({dispatch_max.name} > {call.ceiling.name})"
        )

    live_max = live_labels.max_on(call.closure)
    # Widening-then-narrowing must not launder: compare against max seen.
    observed = max(dispatch_max, live_max)

    if not gate_admits(observed, call.ceiling):
        raise StaleGateRevocation(
            f"{call.call_id}: taint widened across speculation window "
            f"({dispatch_max.name} -> {live_max.name}, ceiling {call.ceiling.name}); "
            f"commit revoked, result discarded, closure requires re-derivation"
        )

    apply_side_effect(call.result)
    call.committed = True
