# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-poisoned-memory-slot-because-provenance-was-verified-at-write-time-but-never-re-verified-at-read-time.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-poisoned-memory-slot-because-provenance-was-verified-at-write-time-but-never-re-verified-at-read-time.warrant.json
# Markdown SHA-256:   30d85f82f1e171a7e3b8c5c9fb931f49329a935bf4eb04f1fd163e0fe1d32039
# Code AST SHA-256:   1c5f6e914a1f67d2f2b7beeaa5849fd27d3b04c1de02de9654acde731ab2a92c
# Verified Classes:   StaleProvenanceError, ProvenanceStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

def fetch(slot):
    if not verify_hmac(slot):          # verifies against slot.source_epoch
        raise ProvenanceError(...)
    return slot.content

class StaleProvenanceError(RuntimeError):
    """Raised when a memory slot's attestation epoch is behind the store's
    current trust epoch, meaning its source may have been demoted since write."""
    pass


class ProvenanceStore:
    def __init__(self, current_epoch: int):
        self.current_epoch = current_epoch
        self._slots = {}  # slot_id -> dict(content, source_id, source_epoch, hmac)

    def put(self, slot_id: str, content: str, source_id: str, hmac: str):
        # Write path: attest under the epoch active at write time.
        self._slots[slot_id] = {
            "content": content,
            "source_id": source_id,
            "source_epoch": self.current_epoch,
            "hmac": hmac,
        }

    def demote_source(self, source_id: str):
        # Demotion bumps the global epoch. Prior attestations become stale,
        # NOT invalid — their HMACs still verify. Only the epoch check catches them.
        self.current_epoch += 1
        self._demoted = getattr(self, "_demoted", set())
        self._demoted.add(source_id)

    def fetch(self, slot_id: str, verify_hmac) -> str:
        slot = self._slots[slot_id]
        # Integrity check alone is insufficient: it verifies against the slot's
        # own (possibly stale) epoch, so it passes for demoted sources.
        if not verify_hmac(slot["content"], slot["source_id"],
                           slot["source_epoch"], slot["hmac"]):
            raise StaleProvenanceError(f"HMAC failed for {slot_id}")
        # The guardrail: re-check attestation freshness against current epoch.
        if slot["source_epoch"] < self.current_epoch:
            raise StaleProvenanceError(
                f"slot {slot_id} attested under epoch {slot['source_epoch']} "
                f"but store is at epoch {self.current_epoch}; "
                f"source {slot['source_id']} may have been demoted — "
                f"re-attest before trust"
            )
        return slot["content"]
