# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-laundered-memory-writes-from-surviving-retention-compaction-in-agent-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-laundered-memory-writes-from-surviving-retention-compaction-in-agent-memory-tool-apis.warrant.json
# Markdown SHA-256:   4935bc17268e6afda7f211bfd6092205f690325ceae855a827a467d2262e4880
# Code AST SHA-256:   9c9d1dc6d53bdb3b555ac0896635cad3e4a4df53f450c53e83044ad9678fa117
# Verified Classes:   ProvenanceInvariantError, Provenance, MemoryRecord, ProvenanceAwareStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceInvariantError(RuntimeError):
    """Raised when a memory write or retention decision would violate
    provenance/retention monotonicity (liveness, expiry, or trust)."""


@dataclass
class Provenance:
    derived_from: list = field(default_factory=list)
    trust_rank: int = 0  # higher = more trusted


@dataclass
class MemoryRecord:
    record_id: str
    body_hash: str
    provenance: Provenance
    retention_expiry: float  # absolute time; computed, not stored on write
    live: bool = True


class ProvenanceAwareStore:
    TRUST_RANK = {"external_untrusted": 0, "derived": 1, "trusted": 2}

    def __init__(self):
        self._records: dict = {}

    def _live_parents(self, rec: MemoryRecord) -> list:
        return [
            self._records[pid]
            for pid in rec.provenance.derived_from
            if pid in self._records and self._records[pid].live
        ]

    def write(self, rec: MemoryRecord, now: float) -> None:
        # Sub-condition: trust monotonicity, checked at write, not compaction.
        parents = self._live_parents(rec)
        if rec.provenance.derived_from and not parents:
            raise ProvenanceInvariantError(
                f"write of {rec.record_id} references no live parent; "
                f"must be an explicit adopt with a new provenance envelope"
            )
        for p in parents:
            if rec.provenance.trust_rank > p.provenance.trust_rank:
                raise ProvenanceInvariantError(
                    f"trust escalation: {rec.record_id} rank "
                    f"{rec.provenance.trust_rank} exceeds parent "
                    f"{p.record_id} rank {p.provenance.trust_rank}"
                )
        # Sub-condition: expiry monotonicity, inherited from earliest parent.
        if parents:
            rec.retention_expiry = min(
                rec.retention_expiry,
                min(p.retention_expiry for p in parents),
            )
        self._records[rec.record_id] = rec

    def forget(self, record_id: str) -> None:
        rec = self._records.get(record_id)
        if rec is None:
            return
        rec.live = False
        # Cascade: any child whose only parent was this record is now orphaned.
        for child in self._records.values():
            if child.live and record_id in child.provenance.derived_from:
                if not self._live_parents(child):
                    child.live = False

    def compact(self, now: float) -> list:
        evicted = []
        for rec in self._records.values():
            if not rec.live:
                continue
            if rec.retention_expiry <= now:
                rec.live = False
                evicted.append(rec.record_id)
                continue
            # Re-verify liveness invariant at compaction time.
            if rec.provenance.derived_from and not self._live_parents(rec):
                raise ProvenanceInvariantError(
                    f"compaction found retained record {rec.record_id} "
                    f"with no live ancestor: provenance laundering"
                )
        return evicted
