# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-retrieved-memory-whose-provenance-hash-verifies-but-whose-write-epoch-precedes-the-last-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-retrieved-memory-whose-provenance-hash-verifies-but-whose-write-epoch-precedes-the-last-compaction.warrant.json
# Markdown SHA-256:   a4df9a208ed8b53e9ab4556bbef6a55c7ccd71fad4da83a0f17a27689c7fe660
# Code AST SHA-256:   971db467f77fe98bf64dde59bb2cb10aead75328bdc00b28ebef730c27d732df
# Verified Classes:   StaleProvenanceError, MemoryRecord, LiveRoot
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleProvenanceError(RuntimeError):
    """Raised when a record self-verifies but its write-epoch precedes the live root's compaction epoch."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    content: bytes
    self_hash: str
    parent_hash: str
    write_epoch: int


@dataclass
class LiveRoot:
    root_id: str
    compaction_epoch: int
    live: bool


def verify_self_hash(record: MemoryRecord) -> bool:
    return hashlib.sha256(record.content).hexdigest() == record.self_hash


def resolve_root(record: MemoryRecord, roots: dict[str, LiveRoot]) -> LiveRoot | None:
    # In production this walks the parent-hash chain; here the record's
    # parent_hash is treated as the root id for brevity.
    return roots.get(record.parent_hash)


def admit_for_retrieval(
    record: MemoryRecord,
    roots: dict[str, LiveRoot],
    as_of_epoch: int,
) -> str:
    """Returns 'ADMIT' | 'DISCARD' | 'QUARANTINE'. Raises on the ambiguous boundary."""
    if not verify_self_hash(record):
        return "DISCARD"  # content corruption, unrecoverable

    root = resolve_root(record, roots)
    if root is None or not root.live:
        return "DISCARD"  # orphan: chain points at GC'd root, nothing to reconcile against

    if record.write_epoch < root.compaction_epoch:
        # Self-hash passed, chain resolves to a live root, but the record
        # predates the compaction that produced that root. This is the
        # boundary: quarantine, do not admit, do not discard.
        if as_of_epoch >= root.compaction_epoch:
            # The caller is querying the current epoch; admitting this record
            # would contaminate reasoning with a superseded entity model.
            raise StaleProvenanceError(
                f"record {record.record_id} write_epoch={record.write_epoch} "
                f"precedes live root {root.root_id} compaction_epoch={root.compaction_epoch} "
                f"while as_of_epoch={as_of_epoch}; quarantine required"
            )
        return "QUARANTINE"  # historical read; hold for reconciliation

    return "ADMIT"


def pre_write_epoch_fence(write_epoch: int, store_epoch: int) -> None:
    if write_epoch < store_epoch:
        raise StaleProvenanceError(
            f"refusing write at epoch {write_epoch}: store has advanced to {store_epoch}; "
            f"refresh epoch cache before writing"
        )
