# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-poisoned-memory-because-provenance-was-inherited-rather-than-re-attested-at-write-time.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-poisoned-memory-because-provenance-was-inherited-rather-than-re-attested-at-write-time.warrant.json
# Markdown SHA-256:   c27cd647787eff13de5dc49bf5934e2417e0ed3936be96897d2269a66c1a8a80
# Code AST SHA-256:   4179b9da39f5083eb3f97afda914494b1580a48a3f626767814796acbed1c6e6
# Verified Classes:   ProvenanceInheritanceError, TrustGraph, MemoryRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceInheritanceError(RuntimeError):
    """Raised when a memory write would admit a frozen trust scalar
    instead of re-attesting its provenance chain against the live graph."""
    pass


@dataclass
class TrustGraph:
    # issuer_id -> current effective trust weight in [0.0, 1.0]
    weights: dict[str, float] = field(default_factory=dict)
    revoked: set[str] = field(default_factory=set)

    def resolve(self, issuer_id: str) -> float:
        if issuer_id in self.revoked:
            return 0.0
        return self.weights.get(issuer_id, 0.0)


@dataclass
class MemoryRecord:
    content: str
    # provenance chain: source -> distiller -> writer, each hop an issuer id
    chain: list[str]
    # the frozen scalar that caused the incident; must NOT be authoritative
    minted_trust: float


FLOOR = 0.0


def reattest(record: MemoryRecord, graph: TrustGraph) -> float:
    """Recompute effective trust from the live graph. The weakest hop
    bounds the whole chain; a revoked hop collapses it to the floor."""
    if not record.chain:
        raise ProvenanceInheritanceError(
            "record has empty provenance chain; cannot re-attest"
        )
    effective = record.minted_trust
    for issuer in record.chain:
        hop = graph.resolve(issuer)
        if hop <= FLOOR:
            return FLOOR
        effective = min(effective, hop)
    return effective


def admit_write(record: MemoryRecord, graph: TrustGraph,
                min_trust: float) -> MemoryRecord:
    """Admission gate. Rejects any write whose live re-attested trust
    falls below threshold, and refuses to persist a bare trust scalar."""
    live = reattest(record, graph)
    if live < min_trust:
        raise ProvenanceInheritanceError(
            f"write rejected: live trust {live:.2f} < threshold {min_trust:.2f} "
            f"for chain {record.chain}; minted_trust={record.minted_trust:.2f} "
            f"is not authoritative"
        )
    # Persist the chain; the trust is recomputed at read time, never stored.
    return MemoryRecord(content=record.content, chain=list(record.chain),
                        minted_trust=live)


# Trace: S writes under R's warrant at T0, R revoked at T1.
graph = TrustGraph(weights={"R": 0.9, "S": 0.8})
poisoned = MemoryRecord(
    content="deployment token is prod-...",
    chain=["page:evil", "S", "R"],
    minted_trust=0.8,
)

# At T0 admission succeeds (all hops live).
admit_write(poisoned, graph, min_trust=0.5)

# At T1 R is revoked; the chain now fails re-attestation.
graph.revoked.add("R")
try:
    admit_write(poisoned, graph, min_trust=0.5)
except ProvenanceInheritanceError as e:
    print(f"contained: {e}")
