# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-erasure-tombstone-as-authoritative-over-an-in-flight-write-and-what-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-erasure-tombstone-as-authoritative-over-an-in-flight-write-and-what-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   9ce09a8e1af5a698b81c65759aabc4d193c579348b0d3f01222da370733bbb69
# Code AST SHA-256:   90315f1db73d53f5fed2264a01e7ff9659a47f678d1f496da70fe4d77293888f
# Verified Classes:   ResurrectionWriteError, Record, MemoryClient
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class ResurrectionWriteError(RuntimeError):
    """Raised when a write's provenance ancestry intersects a live tombstone.

    Carries the tombstone id and the ancestry path so the operator can trace
    which reader leaked the forgotten value forward into a derived record.
    """

    def __init__(self, record_key: str, tombstone_id: str, ancestry: list[str]):
        self.record_key = record_key
        self.tombstone_id = tombstone_id
        self.ancestry = ancestry
        super().__init__(
            f"write to {record_key!r} resurrects forgotten value "
            f"(tombstone={tombstone_id!r}, ancestry={' -> '.join(ancestry)})"
        )


@dataclass
class Record:
    key: str
    value: str
    provenance: str
    ancestry: list[str] = field(default_factory=list)  # transitive source record ids
    ttl_s: int = 3600


class MemoryClient:
    """Thin wrapper enforcing tombstone-as-authoritative over in-flight writes."""

    def __init__(self, tombstone_retention_s: int = 900):
        self._tombstones: dict[str, int] = {}  # record_id -> commit time
        self._records: dict[str, Record] = {}
        self._retention_s = tombstone_retention_s

    def forget(self, record_id: str, now: int) -> None:
        self._tombstones[record_id] = now
        self._records.pop(record_id, None)

    def _live_tombstones(self, now: int) -> Iterable[str]:
        for rid, committed in self._tombstones.items():
            if now - committed <= self._retention_s:
                yield rid

    def write(self, record: Record, now: int) -> str:
        live = set(self._live_tombstones(now))
        # Transitive check: any ancestor (including the record's own key lineage)
        # that is tombstoned blocks the commit.
        hit = [a for a in record.ancestry if a in live]
        if hit:
            raise ResurrectionWriteError(
                record_key=record.key,
                tombstone_id=hit[0],
                ancestry=record.ancestry,
            )
        self._records[record.key] = record
        return record.key

    def read(self, key: str, now: int) -> Record | None:
        rec = self._records.get(key)
        if rec is None:
            return None
        if any(a in set(self._live_tombstones(now)) for a in rec.ancestry):
            # A derived record whose ancestor was forgotten after it was written:
            # treat as unreachable rather than returning laundered data.
            return None
        return rec


def commit_summary(
    client: MemoryClient,
    key: str,
    summary: str,
    sources: list[str],
    now: int,
) -> str:
    """Commit a derived summary, refusing if any source was forgotten mid-task."""
    record = Record(
        key=key,
        value=summary,
        provenance="subagent_B",
        ancestry=list(sources),
        ttl_s=86400,
    )
    try:
        return client.write(record, now=now)
    except ResurrectionWriteError as exc:
        # Escalate: the erasure attestation must be withheld for this task.
        raise ResurrectionWriteError(
            record_key=exc.record_key,
            tombstone_id=exc.tombstone_id,
            ancestry=exc.ancestry,
        ) from exc


# Trace from the observed incident:
#   client.forget("r_4412", now=0)
#   commit_summary(..., sources=["r_4412"], now=1)  -> ResurrectionWriteError
