# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-provenance-at-write-time-but-never-re-validates-it-at-read-time.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-provenance-at-write-time-but-never-re-validates-it-at-read-time.warrant.json
# Markdown SHA-256:   307e75e63fda3794354994bc839c9cdadd525a4995fba7bb758f68d0e0422f71
# Code AST SHA-256:   15929fbbc00341df1cbe769c7a8840e69421e37a7a505e1e63ddc2e310434267
# Verified Classes:   TrustViolationError, Memory
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TrustViolationError(RuntimeError):
    """Raised when a memory would be served into the reasoning loop
    despite unresolved contradiction, supersession, or signer demotion."""
    pass


@dataclass
class Memory:
    mid: str
    content: str
    signer: str
    signer_current_trust: float          # live, may be demoted later
    admission_trust: float               # snapshot at write time
    conflicts_with: set = field(default_factory=set)
    superseded_by: Optional[str] = None
    quarantined: bool = False


def effective_trust(m: Memory, store: dict) -> float:
    # Contradiction clearance is zero if this memory participates in any
    # unresolved conflict or has been superseded by a live memory.
    clearance = 1.0
    if m.quarantined:
        clearance = 0.0
    if m.conflicts_with:
        clearance = 0.0
    if m.superseded_by is not None and m.superseded_by in store:
        clearance = 0.0
    return min(m.admission_trust, m.signer_current_trust, clearance)


def retrieve(mid: str, store: dict, required_trust: float) -> Memory:
    m = store.get(mid)
    if m is None:
        raise TrustViolationError(f"memory {mid} not found")
    et = effective_trust(m, store)
    if et < required_trust:
        # Fail closed: surface the conflict, never fall back to similarity
        # or recency. The reasoning loop must resolve or halt.
        raise TrustViolationError(
            f"refusing to serve {mid}: effective_trust={et} "
            f"< required={required_trust}; "
            f"conflicts={sorted(m.conflicts_with)} "
            f"superseded_by={m.superseded_by} quarantined={m.quarantined}"
        )
    return m


def write_with_contradiction_check(new: Memory, store: dict) -> None:
    # Detect contradictions and, critically, wire the resolution into the
    # servable set in the SAME operation -- not a side table.
    for existing in store.values():
        if existing.content.split()[-1] != new.content.split()[-1]:
            continue
        # direct conflict detected: quarantine the older memory atomically
        existing.conflicts_with.add(new.mid)
        new.conflicts_with.add(existing.mid)
        existing.quarantined = True
        new.quarantined = True
        # If signer of new outranks existing, resolve rather than leave both dead:
        if new.signer_current_trust > existing.signer_current_trust:
            existing.superseded_by = new.mid
            new.quarantined = False
            new.conflicts_with.discard(existing.mid)
    store[new.mid] = new


if __name__ == "__main__":
    store: dict = {}
    m1 = Memory("m1", "endpoint is api.internal/v2", "warrant-A", 0.4, 1.0)
    write_with_contradiction_check(m1, store)          # admitted, no conflict yet
    assert retrieve("m1", store, 0.5).mid == "m1"       # servable at 0.4? no -> raises
