# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-provenance-laundered-memory-write-when-a-read-modify-write-cycle-crosses-the-ttl-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-provenance-laundered-memory-write-when-a-read-modify-write-cycle-crosses-the-ttl-horizon.warrant.json
# Markdown SHA-256:   fd4de70fdb54e19d843329a38af744a1cad0efa4cfa7d5f6e8560b93e68311d4
# Code AST SHA-256:   cc3c7986a545139c240289add10d4c154362c34cd2580555491190a35f79a75b
# Verified Classes:   ProvenanceLaunderingError, Record, MemoryStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional
import time


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write extends a lease or promotes a dangling parent."""


@dataclass
class Record:
    id: str
    payload: dict
    origin: str
    depth: int
    parent: Optional[str]
    expires_at: float
    confidence: float = 1.0


class MemoryStore:
    def __init__(self) -> None:
        self._records: dict[str, Record] = {}

    def read(self, rid: str) -> Record:
        rec = self._records.get(rid)
        if rec is None:
            raise ProvenanceLaunderingError(f"record {rid} not found")
        if rec.parent is not None and rec.parent not in self._records:
            # C2: dangling parent is fatal, never promoted to root.
            raise ProvenanceLaunderingError(
                f"record {rid} has unresolved parent {rec.parent}; "
                f"refusing to serve as depth-0"
            )
        return rec

    def write(self, rec: Record, now: Optional[float] = None) -> None:
        now = time.time() if now is None else now
        if rec.parent is not None:
            parent = self._records.get(rec.parent)
            if parent is None:
                raise ProvenanceLaunderingError(
                    f"write of {rec.id} references missing parent {rec.parent}"
                )
            # C1: monotone lease. A derivation may not extend the parent's TTL.
            if rec.expires_at > parent.expires_at:
                raise ProvenanceLaunderingError(
                    f"write of {rec.id} extends lease "
                    f"({rec.expires_at} > parent {parent.expires_at}); "
                    f"laundering via read-modify-write"
                )
            # A derivation must not claim first-hand status.
            if rec.depth <= parent.depth:
                raise ProvenanceLaunderingError(
                    f"write of {rec.id} claims depth {rec.depth} "
                    f"<= parent depth {parent.depth}"
                )
        self._records[rec.id] = rec

    def forget(self, rid: str, now: Optional[float] = None) -> None:
        now = time.time() if now is None else now
        rec = self._records[rid]
        # C3: refuse to GC a parent that still has live children.
        for other in self._records.values():
            if other.parent == rid and other.expires_at > now:
                raise ProvenanceLaunderingError(
                    f"cannot forget {rid}: live child {other.id} depends on it"
                )
        del self._records[rid]


def merge_into(store: MemoryStore, parent_id: str, extra: dict) -> Record:
    """Derive a child record from a parent, clamping the lease to the parent's."""
    parent = store.read(parent_id)
    child = Record(
        id=f"{parent_id}.m{parent.depth + 1}",
        payload={**parent.payload, **extra},
        origin=parent.origin,
        depth=parent.depth + 1,
        parent=parent_id,
        expires_at=parent.expires_at,  # clamped; never now + ttl
        confidence=parent.confidence * 0.95,
    )
    store.write(child)
    return child
