# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-memory-poisoning-when-provenance-attestation-is-only-checked-at-write-time-and-not-re-validated-at-read-time.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-memory-poisoning-when-provenance-attestation-is-only-checked-at-write-time-and-not-re-validated-at-read-time.warrant.json
# Markdown SHA-256:   6f76b42eaae9a5eb40f8b99baafe64317bbb583079470a53992baf6af7ea6cd9
# Code AST SHA-256:   bf45e7a7203b06a390e970c2a5a07068bdb359369296b54f1c89b1fc4b411c9a
# Verified Classes:   StaleProvenanceError, TrustService, ProvenanceStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class StaleProvenanceError(RuntimeError):
    """Raised when a memory record's provenance is no longer valid at read time."""
    pass


class TrustService:
    def __init__(self, tiers: dict[str, str], revoked: set[str]):
        self._tiers = tiers
        self._revoked = revoked

    def current_tier(self, origin_id: str) -> str:
        if origin_id in self._revoked:
            return "revoked"
        return self._tiers.get(origin_id, "unknown")


class ProvenanceStore:
    def __init__(self, trust: TrustService, max_depth: int = 4):
        self._records: dict[str, dict] = {}
        self._trust = trust
        self._max_depth = max_depth

    def write(self, record_id: str, origin_id: str, trust_tier: str,
              derived_from: list[str] | None = None) -> None:
        self._records[record_id] = {
            "origin_id": origin_id,
            "trust_tier": trust_tier,
            "derived_from": derived_from or [],
        }

    def read(self, record_id: str, required_tier: str = "verified") -> dict:
        rec = self._records.get(record_id)
        if rec is None:
            raise StaleProvenanceError(f"record {record_id} not found")

        current = self._trust.current_tier(rec["origin_id"])
        if current != rec["trust_tier"]:
            raise StaleProvenanceError(
                f"record {record_id}: stored tier {rec['trust_tier']!r} "
                f"!= current tier {current!r} for origin {rec['origin_id']}"
            )
        if current != required_tier:
            raise StaleProvenanceError(
                f"record {record_id}: current tier {current!r} "
                f"below required {required_tier!r}"
            )

        # Transitive check: any quarantined ancestor invalidates the record.
        stack = [(anc, 1) for anc in rec["derived_from"]]
        while stack:
            anc_id, depth = stack.pop()
            if depth > self._max_depth:
                raise StaleProvenanceError(
                    f"record {record_id}: derivation depth exceeds {self._max_depth}"
                )
            anc = self._records.get(anc_id)
            if anc is None:
                continue
            anc_tier = self._trust.current_tier(anc["origin_id"])
            if anc_tier in ("quarantined", "revoked"):
                raise StaleProvenanceError(
                    f"record {record_id}: ancestor {anc_id} is {anc_tier!r}"
                )
            stack.extend((a, depth + 1) for a in anc["derived_from"])

        return rec


# Reproduction of the incident trace.
trust = TrustService(
    tiers={"A7": "verified", "R3": "verified"},
    revoked=set(),
)
store = ProvenanceStore(trust)
store.write("M", origin_id="A7", trust_tier="verified")
store.write("M'", origin_id="R3", trust_tier="verified", derived_from=["M"])

# A7 gets compromised and downgraded after the write.
trust._tiers["A7"] = "quarantined"

for rid in ("M", "M'"):
    try:
        store.read(rid)
    except StaleProvenanceError as e:
        print(f"rejected {rid}: {e}")
