# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-speculative-tool-call-prefetching-when-the-safety-guard-is-a-side-effect-predicate-evaluated-on-a-stale-world-model.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-speculative-tool-call-prefetching-when-the-safety-guard-is-a-side-effect-predicate-evaluated-on-a-stale-world-model.warrant.json
# Markdown SHA-256:   bafe0539fce019d4cdec556e364dc39ad88467b4e95d5e142fd8ccee47bb04d7
# Code AST SHA-256:   1cdd0be16b2514fe09a7ebc539c98367966fd5e8e262d74abd60c9fe77e051e8
# Verified Classes:   SpeculationSafetyError, SideEffectClass, WorldVersion, PrefetchedCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class SpeculationSafetyError(RuntimeError):
    """Raised when a prefetched tool call's side-effect predicate is stale at fire time."""


class SideEffectClass(Enum):
    PURE = "pure"            # result independent of world state (e.g. arithmetic)
    OBSERVATIONAL = "observational"  # read whose RESULT depends on mutable world state
    MUTATING = "mutating"    # writes to world


@dataclass(frozen=True)
class WorldVersion:
    epoch: int
    mutator: str  # "self" or peer agent id


@dataclass
class PrefetchedCall:
    tool: str
    side_effect: SideEffectClass
    enqueue_version: WorldVersion
    predicate_safe_at_enqueue: bool
    result_consumed_by_reasoning: bool


def admit_prefetched_result(
    call: PrefetchedCall,
    live_version: WorldVersion,
    self_mutated_in_interval: bool,
) -> bool:
    # Pure calls are world-independent; admit unconditionally.
    if call.side_effect is SideEffectClass.PURE:
        return True

    # If the result is discarded on miss, it never enters context; no ingestion risk.
    if not call.result_consumed_by_reasoning:
        return True

    # Observational or mutating calls whose result is consumed must be revalidated.
    stale = live_version.epoch != call.enqueue_version.epoch
    if stale and self_mutated_in_interval:
        # The agent poisoned its own guard: predicate evaluated on a world it then changed.
        raise SpeculationSafetyError(
            f"prefetch of {call.tool!r} enqueued at epoch "
            f"{call.enqueue_version.epoch} but fired at {live_version.epoch} "
            f"after self-mutation; predicate is stale and result must not be admitted"
        )

    if stale and not call.predicate_safe_at_enqueue:
        raise SpeculationSafetyError(
            f"prefetch of {call.tool!r} was unsafe at enqueue and world advanced; "
            f"discard speculation"
        )

    # Non-stale: predicate still valid at fire.
    return call.predicate_safe_at_enqueue


def run_prefetch_batch(calls: list[PrefetchedCall], live: WorldVersion, self_mutated: bool) -> list[bool]:
    admitted = []
    for c in calls:
        admitted.append(admit_prefetched_result(c, live, self_mutated))
    # Invariant: no OBSERVATIONAL/MUTATING result admitted across a self-mutation epoch bump.
    for c, ok in zip(calls, admitted):
        if ok and c.side_effect is not SideEffectClass.PURE and live.epoch != c.enqueue_version.epoch and self_mutated:
            raise SpeculationSafetyError("invariant breach: stale observational result admitted")
    return admitted
