# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-memory-write-whose-provenance-chain-is-internally-consistent-but-whose-semantic-content-contradicts-a-pr.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-memory-write-whose-provenance-chain-is-internally-consistent-but-whose-semantic-content-contradicts-a-pr.warrant.json
# Markdown SHA-256:   0562198fea681d6f3fb968cec29905f010a2009f5968b3ec5d4740f1181363a5
# Code AST SHA-256:   f0bfe620560c6425da9d1c7e83583f23d71e2995b56dd70412c2fa7098d0cbb6
# Verified Classes:   MemoryPoisoningError, FactLedgerEntry, MemoryWrite, MemoryAdmissionController
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class MemoryPoisoningError(RuntimeError):
    """Raised when a provenance-valid write contradicts a committed fact
    without an explicit supersession claim from a trusted source."""
    pass


@dataclass
class FactLedgerEntry:
    key: str
    value: str
    ledger_id: str
    source_trust: str  # "trusted" | "untrusted"
    supersedes: Optional[str] = None


@dataclass
class MemoryWrite:
    key: str
    value: str
    author_session: str
    author_tool: str
    content_source_trust: str  # "trusted" | "untrusted"
    supersedes: Optional[str] = None
    provenance_hash: str = ""

    def provenance_valid(self) -> bool:
        expected = hashlib.sha256(
            f"{self.key}:{self.value}:{self.author_session}:{self.author_tool}".encode()
        ).hexdigest()
        return self.provenance_hash == expected


class MemoryAdmissionController:
    def __init__(self) -> None:
        self._ledger: dict[str, FactLedgerEntry] = {}
        self._quarantine: list[tuple[MemoryWrite, FactLedgerEntry]] = []

    def _current_committed(self, key: str) -> Optional[FactLedgerEntry]:
        return self._ledger.get(key)

    def admit(self, write: MemoryWrite) -> None:
        if not write.provenance_valid():
            raise MemoryPoisoningError(
                f"provenance hash mismatch for write to {write.key!r}"
            )

        committed = self._current_committed(write.key)

        # Provenance is valid. Now check semantic consistency.
        if committed is not None and committed.value != write.value:
            explicit_supersession = (
                write.supersedes is not None
                and write.supersedes == committed.ledger_id
                and write.content_source_trust == "trusted"
            )
            if not explicit_supersession:
                # Provenance-valid but contradicts committed fact without
                # trusted explicit supersession -> quarantine, do not admit.
                self._quarantine.append((write, committed))
                raise MemoryPoisoningError(
                    f"write to {write.key!r} contradicts committed fact "
                    f"{committed.ledger_id!r} (value={committed.value!r} -> "
                    f"{write.value!r}) with content_source_trust="
                    f"{write.content_source_trust!r} and no valid supersession "
                    f"claim; quarantined"
                )

        ledger_id = hashlib.sha256(
            f"{write.key}:{write.value}:{write.author_session}".encode()
        ).hexdigest()[:12]
        self._ledger[write.key] = FactLedgerEntry(
            key=write.key,
            value=write.value,
            ledger_id=ledger_id,
            source_trust=write.content_source_trust,
            supersedes=write.supersedes,
        )

    def quarantined(self) -> list[tuple[MemoryWrite, FactLedgerEntry]]:
        return list(self._quarantine)


def _demo() -> None:
    ctrl = MemoryAdmissionController()

    # S1: legitimate commit from trusted config reader.
    w1 = MemoryWrite(
        key="service.timeout_ms",
        value="3000",
        author_session="S1",
        author_tool="config_reader",
        content_source_trust="trusted",
    )
    w1.provenance_hash = hashlib.sha256(
        f"{w1.key}:{w1.value}:{w1.author_session}:{w1.author_tool}".encode()
    ).hexdigest()
    ctrl.admit(w1)

    # S2: provenance-valid write derived from an untrusted fetched document.
    w2 = MemoryWrite(
        key="service.timeout_ms",
        value="30000",
        author_session="S2",
        author_tool="memory_writer",
        content_source_trust="untrusted",
        supersedes=None,
    )
    w2.provenance_hash = hashlib.sha256(
        f"{w2.key}:{w2.value}:{w2.author_session}:{w2.author_tool}".encode()
    ).hexdigest()

    try:
        ctrl.admit(w2)
    except MemoryPoisoningError as exc:
        print(f"BLOCKED: {exc}")
        print(f"quarantine depth: {len(ctrl.quarantined())}")


if __name__ == "__main__":
    _demo()
