# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-via-provenance-divergence-across-read-write-forget-operations.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-via-provenance-divergence-across-read-write-forget-operations.warrant.json
# Markdown SHA-256:   1f711daa8700e3dbccb7283d12ec2ab2b1b71ae69bc12b3dbe9f3d46824e9127
# Code AST SHA-256:   aa0f5c9fac5b14e97280f91773f44963cd60c3e236e98d39a42c30eedef7ecac
# Verified Classes:   ProvenanceClosureError, MemoryRecord, OpLog
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class ProvenanceClosureError(RuntimeError):
    """Raised when a memory read cannot be closed against the append-only operation log."""
    pass

@dataclass
class MemoryRecord:
    id: str
    content: str
    source_principal: str
    warrant_id: Optional[str]
    write_epoch: int
    derived_from: Optional[str] = None

@dataclass
class OpLog:
    # append-only: warrant_id -> epoch issued; record_id -> tombstone epoch
    warrants: dict = field(default_factory=dict)
    tombstones: dict = field(default_factory=dict)
    records: dict = field(default_factory=dict)

DERIVATION_PRINCIPALS = {"distiller", "summarizer", "peer_agent"}

def assert_provenance_closed(rec: MemoryRecord, log: OpLog) -> None:
    # 1. orphan warrant: write path bypassed the ledger
    if rec.warrant_id is None or rec.warrant_id not in log.warrants:
        raise ProvenanceClosureError(
            f"orphan warrant on {rec.id}: {rec.warrant_id!r} absent from log"
        )
    # 2. laundering: a derivation principal with no ancestry
    if rec.source_principal in DERIVATION_PRINCIPALS and rec.derived_from is None:
        raise ProvenanceClosureError(
            f"laundered provenance on {rec.id}: derivation principal "
            f"{rec.source_principal!r} carries no derived_from edge"
        )
    # 3. dominated-but-live: ancestor tombstoned after this write, forget failed to cascade
    if rec.derived_from is not None:
        parent_tomb = log.tombstones.get(rec.derived_from)
        if parent_tomb is not None and parent_tomb >= rec.write_epoch:
            raise ProvenanceClosureError(
                f"dominated-but-live {rec.id}: ancestor {rec.derived_from!r} "
                f"tombstoned at {parent_tomb} >= write_epoch {rec.write_epoch}"
            )
    # 4. self-tombstone must not be readable
    own_tomb = log.tombstones.get(rec.id)
    if own_tomb is not None and own_tomb >= rec.write_epoch:
        raise ProvenanceClosureError(
            f"tombstoned record {rec.id} served as live (tomb={own_tomb})"
        )

def read_trusted(rec: MemoryRecord, log: OpLog) -> str:
    assert_provenance_closed(rec, log)
    return rec.content
