# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-scoped-forget-from-silently-resurrecting-memory-via-the-write-ahead-log-during-ttl-expiry.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-scoped-forget-from-silently-resurrecting-memory-via-the-write-ahead-log-during-ttl-expiry.warrant.json
# Markdown SHA-256:   34b98f5da0e892d2f204e418ca77320bdd34490fc02b30be74407170a45248c0
# Code AST SHA-256:   3c6edbfc315579d1424df8d9b4a04982e4db029a8adf50944bf9fc5acbbd7ada
# Verified Classes:   ResurrectionRiskError, Record, ScopedMemory
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ResurrectionRiskError(RuntimeError):
    """Raised when a forget would no-op against an expired-but-durable record."""


@dataclass
class Record:
    scope: str
    subject_id: str
    content: bytes
    write_clock: float
    expires_at: float
    segment: str


class ScopedMemory:
    def __init__(self, now: float):
        self.now = now
        self.durable: dict[str, list[Record]] = {}   # segment -> records (WAL)
        self.tombstones: set[tuple[str, str, str]] = set()

    def write(self, scope, subject_id, content, ttl, segment):
        rec = Record(scope, subject_id, content, self.now, self.now + ttl, segment)
        self.durable.setdefault(segment, []).append(rec)
        return rec

    def read(self, scope, subject_id) -> Optional[Record]:
        # Serving-layer filter: TTL-expired records are invisible here.
        for seg in self.durable.values():
            for r in seg:
                if r.scope == scope and r.subject_id == subject_id and r.expires_at > self.now:
                    return r
        return None

    def exists_durable(self, scope, subject_id) -> bool:
        # Bypasses TTL filter; consults tombstones.
        for seg in self.durable.values():
            for r in seg:
                key = (r.scope, r.subject_id, hashlib.sha256(r.content).hexdigest())
                if key in self.tombstones:
                    continue
                if r.scope == scope and r.subject_id == subject_id:
                    return True
        return False

    def forget(self, scope, subject_id) -> dict:
        # Guardrail: never trust read()==None as absence for RTBF.
        if self.read(scope, subject_id) is None and not self.exists_durable(scope, subject_id):
            # Affirmatively absent at durable layer: legitimate no-op, explicit proof.
            return {"coverage": [], "affirmative_absence": True}

        scrubbed = []
        for seg_name, seg in self.durable.items():
            for r in list(seg):
                if r.scope == scope and r.subject_id == subject_id:
                    h = hashlib.sha256(r.content).hexdigest()
                    self.tombstones.add((scope, subject_id, h))
                    seg.remove(r)
                    scrubbed.append(seg_name)

        if not scrubbed:
            # Expired-but-durable with no scrub coverage: resurrection would be possible.
            raise ResurrectionRiskError(
                f"forget({scope},{subject_id}) matched no durable segment; "
                f"read()==None masked a durable record. Refusing to emit empty proof."
            )
        return {"coverage": scrubbed, "affirmative_absence": False}

    def compact(self, segment: str, replayed: list[Record]):
        # Replay must honor tombstones and must not extend original TTL.
        for r in replayed:
            h = hashlib.sha256(r.content).hexdigest()
            if (r.scope, r.subject_id, h) in self.tombstones:
                continue  # shadowed: do not resurrect
            r.expires_at = min(r.expires_at, r.write_clock + (r.expires_at - r.write_clock))
            self.durable.setdefault(segment, []).append(r)


def rtbf_forget(mem: ScopedMemory, scope: str, subject_id: str) -> dict:
    proof = mem.forget(scope, subject_id)
    if not proof["coverage"] and not proof.get("affirmative_absence"):
        raise ResurrectionRiskError(
            f"Invalid RTBF proof for {subject_id}: empty coverage without durable absence."
        )
    return proof
