# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-tool-call-cache-poisoning-is-about-to-cross-a-byzantine-commit-boundary-in-multi-agent-schedulers.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-tool-call-cache-poisoning-is-about-to-cross-a-byzantine-commit-boundary-in-multi-agent-schedulers.warrant.json
# Markdown SHA-256:   a63d3e729835a628fc6dfd1890a8f0295989fa53d8b20ce805397157d62126d1
# Code AST SHA-256:   2a5ce31c6574592cff28e4a05cb9ccb35550552ed9b0d5d6f6e06d1504630e7f
# Verified Classes:   SpeculativeCacheBoundaryError, ToolDeterminism, Disposition, CacheEntry, Request
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from typing import Optional


class SpeculativeCacheBoundaryError(RuntimeError):
    """Raised when a speculative cache entry would cross a Byzantine commit boundary."""


class ToolDeterminism(Enum):
    PURE = "pure"
    EXTERNAL_STATE = "external_state"


class Disposition(Enum):
    SERVE = "serve"
    RE_SPECULATE = "re_speculate"
    INVALIDATE = "invalidate"


@dataclass(frozen=True)
class CacheEntry:
    key: str
    value: object
    origin_agent: str
    commit_round_id: int
    quorum_signers: frozenset[str]
    tool_class: ToolDeterminism
    epoch_written: int


@dataclass(frozen=True)
class Request:
    key: str
    requester: str
    is_voter_in_pending_round: bool
    current_epoch: int
    fault_tolerance_f: int


def classify(entry: Optional[CacheEntry], req: Request) -> Disposition:
    if entry is None:
        return Disposition.RE_SPECULATE
    attested = len(entry.quorum_signers) >= req.fault_tolerance_f + 1
    epoch_valid = req.current_epoch - entry.epoch_written <= 1
    non_deterministic = entry.tool_class is ToolDeterminism.EXTERNAL_STATE

    if non_deterministic:
        return Disposition.INVALIDATE
    if attested and epoch_valid:
        return Disposition.SERVE
    if not attested and req.is_voter_in_pending_round and entry.origin_agent != req.requester:
        # voter may use provisionally but MUST NOT propagate
        return Disposition.RE_SPECULATE
    if not attested and not req.is_voter_in_pending_round:
        return Disposition.INVALIDATE
    return Disposition.INVALIDATE


def serve_or_guard(entry: Optional[CacheEntry], req: Request) -> object:
    disposition = classify(entry, req)
    if disposition is Disposition.INVALIDATE and entry is not None:
        # The structural signal: a non-originator is about to read an
        # unattested speculative result. Refuse before state divergence.
        raise SpeculativeCacheBoundaryError(
            f"refusing cache hit key={entry.key!r} origin={entry.origin_agent!r} "
            f"requester={req.requester!r} signers={len(entry.quorum_signers)} "
            f"f={req.fault_tolerance_f} round={entry.commit_round_id} "
            f"epoch_delta={req.current_epoch - entry.epoch_written}"
        )
    if disposition is Disposition.RE_SPECULATE:
        return None  # caller must re-execute, not reuse
    assert entry is not None
    return entry.value
