# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-forget-request-with-an-in-flight-read-that-already-resolved-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-forget-request-with-an-in-flight-read-that-already-resolved-provenance.warrant.json
# Markdown SHA-256:   738bfb77ab3885947d4dae605d9480a051655e315e126fa39c0ffbd12f5db243
# Code AST SHA-256:   334822c464589cf5a58ee48c81574c9dddfb78ccf250760c8a76783d11bf9bdf
# Verified Classes:   ProvenanceEpochViolation, ReadResult, TombstoneRecord, ProvenanceGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceEpochViolation(RuntimeError):
    """Raised when a write would cite a read that predates the source's tombstone."""


@dataclass
class ReadResult:
    key: str
    value: object
    read_epoch: Optional[int]  # None means the API did not stamp the read
    resolved_at_turn: int


@dataclass
class TombstoneRecord:
    key: str
    tombstone_epoch: int
    reason: str


class ProvenanceGate:
    def __init__(self) -> None:
        self._tombstones: dict[str, TombstoneRecord] = {}
        self._max_seen_epoch: int = 0

    def observe_tombstone(self, rec: TombstoneRecord) -> None:
        self._tombstones[rec.key] = rec
        self._max_seen_epoch = max(self._max_seen_epoch, rec.tombstone_epoch)

    def validate_citation(self, read: ReadResult) -> None:
        """Call before adding `read` to any write's provenance block."""
        tomb = self._tombstones.get(read.key)
        if tomb is None:
            return  # no forget has been observed for this key
        if read.read_epoch is None:
            # Fail closed: an unstamped read cannot be proven fresh against a tombstone.
            raise ProvenanceEpochViolation(
                f"read of {read.key!r} at turn {read.resolved_at_turn} carries no "
                f"read_epoch; cannot prove it postdates tombstone_epoch="
                f"{tomb.tombstone_epoch} (reason={tomb.reason!r}). "
                f"Re-read after forget or drop the citation."
            )
        if read.read_epoch < tomb.tombstone_epoch:
            raise ProvenanceEpochViolation(
                f"stale read: {read.key!r} read_epoch={read.read_epoch} predates "
                f"tombstone_epoch={tomb.tombstone_epoch} (reason={tomb.reason!r}); "
                f"citing it would launder a retracted source into provenance."
            )

    def build_provenance(self, reads: list[ReadResult], source: str) -> dict:
        for r in reads:
            self.validate_citation(r)
        return {
            "source": source,
            "derived_from": [
                {"key": r.key, "read_epoch": r.read_epoch} for r in reads
            ],
        }


# Example triggering the guard: read resolves after the forget tombstoned the key.
gate = ProvenanceGate()
gate.observe_tombstone(
    TombstoneRecord(key="vendor_contract_terms", tombstone_epoch=88,
                    reason="superseded_by_amendment_7")
)
stale = ReadResult(key="vendor_contract_terms", value={"clause": "auto-renew"},
                   read_epoch=71, resolved_at_turn=43)
gate.build_provenance([stale], source="synthesis_memo_step44")
# -> raises ProvenanceEpochViolation: read_epoch=71 < tombstone_epoch=88
