# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-revocation-of-a-derived-memory-write-when-the-provenance-graph-is-acyclic-but-the-retention-clock-diverges-from-the-rev.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-revocation-of-a-derived-memory-write-when-the-provenance-graph-is-acyclic-but-the-retention-clock-diverges-from-the-rev.warrant.json
# Markdown SHA-256:   f9e91373bbc23dcaa2c1785ffa09d5a55e15e13120be80f185a5d0104813c930
# Code AST SHA-256:   15584cb82580cce7887a7e986f3d9ff2726510979cbc08eac6b683f958065eaa
# Verified Classes:   ProvenanceRevocationError, MemoryRecord
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceRevocationError(RuntimeError):
    """Raised when a memory operation would violate the revocation-dominates-read invariant."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    created_at: float
    ttl: float
    revoked: bool = False
    revoked_at: Optional[float] = None
    propagated: bool = False
    provenance: list[str] = field(default_factory=list)


def write_derived(store: dict[str, MemoryRecord], record: MemoryRecord) -> None:
    """Write a derived record only if its retention is bounded by every live source."""
    for src_id in record.provenance:
        src = store.get(src_id)
        if src is None:
            raise ProvenanceRevocationError(
                f"derived {record.record_id} cites unknown source {src_id}"
            )
        if src.revoked and not record.propagated:
            raise ProvenanceRevocationError(
                f"derived {record.record_id} cites revoked source {src_id} "
                f"without a propagated tombstone marker"
            )
        src_expiry = src.created_at + src.ttl
        derived_expiry = record.created_at + record.ttl
        if derived_expiry > src_expiry:
            raise ProvenanceRevocationError(
                f"derived {record.record_id} expires at {derived_expiry} but source "
                f"{src_id} expires at {src_expiry}; derived may not outlive any source"
            )
    store[record.record_id] = record


def read_for_grounding(store: dict[str, MemoryRecord], record_id: str) -> MemoryRecord:
    """Read a record only if every provenance edge resolves to live-or-propagated."""
    record = store.get(record_id)
    if record is None:
        raise ProvenanceRevocationError(f"record {record_id} missing")
    if record.revoked:
        raise ProvenanceRevocationError(f"record {record_id} is revoked")
    for src_id in record.provenance:
        src = store.get(src_id)
        if src is None:
            raise ProvenanceRevocationError(
                f"record {record_id} has dangling provenance edge to {src_id}"
            )
        if src.revoked and not record.propagated:
            raise ProvenanceRevocationError(
                f"record {record_id} derives from revoked {src_id} with no propagation marker"
            )
    return record


def forget(store: dict[str, MemoryRecord], source_id: str, now: float) -> int:
    """Transactional revocation over the full descendant set, or fail atomically."""
    src = store.get(source_id)
    if src is None:
        raise ProvenanceRevocationError(f"cannot forget unknown record {source_id}")

    descendants: list[str] = []
    frontier = [source_id]
    while frontier:
        current = frontier.pop()
        for rid, rec in store.items():
            if current in rec.provenance:
                descendants.append(rid)
                frontier.append(rid)

    for rid in descendants:
        if store[rid].revoked:
            continue
    src.revoked = True
    src.revoked_at = now
    for rid in descendants:
        store[rid].revoked = True
        store[rid].revoked_at = now
        store[rid].propagated = True
    return len(descendants)
