# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-invalidate-a-speculative-tool-call-cache-shared-across-agents-and-how-does-a-stale-but-well-formed-memoization-entry-silently-co.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-invalidate-a-speculative-tool-call-cache-shared-across-agents-and-how-does-a-stale-but-well-formed-memoization-entry-silently-co.warrant.json
# Markdown SHA-256:   1a482fb970933beccdc774ae04bcaf7a5c4420cb444372fbc3a4e12c77fca964
# Code AST SHA-256:   d8fd6a8f064cc6df9fb1c04d9edd481e169057d8144f2164dccb892eafa45fe5
# Verified Classes:   Provenance, StaleSpeculativeEntryError, CacheEntry, Cache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Dict, Set


class Provenance(IntEnum):
    SPECULATIVE = 0
    VERIFIED = 1
    INDEPENDENTLY_VERIFIED = 2


class StaleSpeculativeEntryError(RuntimeError):
    """Raised when a consumer requires verified provenance but the cache
    can only offer a speculative entry, or when a generation counter in the
    entry's read_set advanced. Fails closed: the workflow must not proceed
    on a verification path that was never independent."""


@dataclass
class CacheEntry:
    key: str
    payload: dict
    provenance: Provenance
    read_set: Set[str]          # generation-counter names this result depends on
    gens_at_write: Dict[str, int]
    caller_scope: frozenset


@dataclass
class Cache:
    entries: Dict[str, CacheEntry] = field(default_factory=dict)
    generations: Dict[str, int] = field(default_factory=dict)

    def bump(self, counter: str) -> None:
        self.generations[counter] = self.generations.get(counter, 0) + 1

    def lookup(
        self,
        key: str,
        required_provenance: Provenance,
        consumer_scope: frozenset,
    ) -> dict:
        entry = self.entries.get(key)
        if entry is None:
            raise StaleSpeculativeEntryError(f"cache miss for {key}")

        # Invariant 1: world-generation monotonicity over declared read_set.
        for counter in entry.read_set:
            if self.generations.get(counter, 0) != entry.gens_at_write.get(counter, 0):
                raise StaleSpeculativeEntryError(
                    f"entry {key} invalidated: counter {counter!r} advanced "
                    f"{entry.gens_at_write.get(counter, 0)} -> "
                    f"{self.generations.get(counter, 0)}"
                )

        # Invariant 2: provenance sufficiency. Fail closed, do not downgrade.
        if entry.provenance < required_provenance:
            raise StaleSpeculativeEntryError(
                f"entry {key} has provenance {entry.provenance.name} but "
                f"consumer requires {required_provenance.name}; "
                f"refusing to serve a speculative echo as verification"
            )

        # Invariant 3: caller-scope compatibility.
        if not consumer_scope.issubset(entry.caller_scope):
            raise StaleSpeculativeEntryError(
                f"entry {key} computed under narrower scope than consumer"
            )

        return entry.payload


def auditor_replay(cache: Cache, key: str, consumer_scope: frozenset) -> dict:
    # The auditor MUST require independently_verified provenance; sharing a
    # speculative entry with the executor collapses verification.
    return cache.lookup(
        key,
        required_provenance=Provenance.INDEPENDENTLY_VERIFIED,
        consumer_scope=consumer_scope,
    )
