# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-tool-call-cache-has-silently-diverged-from-byzantine-validated-ground-truth.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-tool-call-cache-has-silently-diverged-from-byzantine-validated-ground-truth.warrant.json
# Markdown SHA-256:   d58747870914ebb3b859dd8e0f3eb17d2ade472b8b2b16367ea78651b1a7bfe3
# Code AST SHA-256:   7aff4698eef2e21bec0d1d06b59587460a541e9b111258af72ff3e2ec26fdfdd
# Verified Classes:   CacheConsumptionError, Status, CacheEntry, QuorumConfig
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, FrozenSet, Iterable, List, Optional


class CacheConsumptionError(RuntimeError):
    """Raised when a cache hit is consumed in violation of the commit barrier
    or the correlated-stale invariant."""


class Status(Enum):
    PROVISIONAL = "provisional"
    CONFIRMED = "confirmed"


@dataclass(frozen=True)
class CacheEntry:
    key: str
    payload_hash: str
    produced_at: float
    footprint: FrozenSet[str]          # external resource ids read to produce this
    status: Status


@dataclass
class QuorumConfig:
    confirmation_lag: float            # max validator->attestation latency, not median
    f: int                             # Byzantine tolerance; quorum = 2f+1


def _footprint_closed(entry: CacheEntry, mutated: Dict[str, float]) -> bool:
    # closed iff no resource in footprint mutated after entry.produced_at
    return all(mutated.get(r, float("-inf")) <= entry.produced_at for r in entry.footprint)


def _shares_provisional_footprint(entry: CacheEntry, siblings: Iterable[CacheEntry]) -> bool:
    for s in siblings:
        if s.key == entry.key or s.status is Status.CONFIRMED:
            continue
        if entry.footprint & s.footprint:
            return True
    return False


def consume(
    entry: CacheEntry,
    now: float,
    quorum: QuorumConfig,
    mutated: Dict[str, float],
    siblings: List[CacheEntry],
    committing: bool,
) -> str:
    """Decide whether a cache hit may be consumed. Returns the payload_hash on
    success; raises CacheConsumptionError on any invariant violation."""

    # Recompute effective status: a CONFIRMED entry whose footprint mutated
    # after production is no longer confirmed, regardless of stored status.
    effective = entry.status
    if effective is Status.CONFIRMED and not _footprint_closed(entry, mutated):
        effective = Status.PROVISIONAL

    # Provisional entries older than the confirmation horizon are stale bets.
    if effective is Status.PROVISIONAL and (now - entry.produced_at) > quorum.confirmation_lag:
        # Not fatal on its own, but must never feed a commit.
        if committing:
            raise CacheConsumptionError(
                f"stale provisional hit {entry.key!r} (age "
                f"{now - entry.produced_at:.1f}s > lag {quorum.confirmation_lag:.1f}s) "
                f"cannot feed a committing step; block or re-derive"
            )

    # Commit barrier: provisional hits may not feed committing steps.
    if committing and effective is Status.PROVISIONAL:
        raise CacheConsumptionError(
            f"provisional cache hit {entry.key!r} cannot feed a committing step; "
            f"defer past quorum horizon or re-derive directly"
        )

    # Correlated-stale check: a provisional hit that shares a footprint with
    # another provisional hit is not independent evidence. If the caller is
    # treating it as corroboration (committing on agreement), reject.
    if committing and _shares_provisional_footprint(entry, siblings):
        raise CacheConsumptionError(
            f"cache hit {entry.key!r} shares a footprint with a provisional sibling; "
            f"mutual agreement is a shared-ancestor artifact, not independent evidence"
        )

    return entry.payload_hash


def reconcile_attestation(
    entry: CacheEntry,
    attested_hash: str,
    attesting_validators: int,
    quorum: QuorumConfig,
) -> str:
    """Apply a Byzantine attestation to a cache entry. Returns 'match',
    'cache_diverged', or 'sub_quorum_ignored'. Never mutates the cache on a
    sub-quorum attestation."""
    if attesting_validators < 2 * quorum.f + 1:
        return "sub_quorum_ignored"
    if attested_hash == entry.payload_hash:
        return "match"
    # Quorum disagrees: cache diverged. Caller must roll back committed
    # consumers; this function only classifies.
    return "cache_diverged"


def assert_attestation_applicable(
    entry: CacheEntry,
    attested_hash: str,
    attesting_validators: int,
    quorum: QuorumConfig,
) -> None:
    verdict = reconcile_attestation(entry, attested_hash, attesting_validators, quorum)
    if verdict == "cache_diverged":
        raise CacheConsumptionError(
            f"quorum ({attesting_validators} validators >= {2 * quorum.f + 1}) "
            f"disagrees with cache entry {entry.key!r}: "
            f"cached={entry.payload_hash} attested={attested_hash}; "
            f"roll back committed consumers of this entry"
        )
