# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-tombstoned-memory-against-in-flight-retrieval-before-honoring-a-forget-call.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-tombstoned-memory-against-in-flight-retrieval-before-honoring-a-forget-call.warrant.json
# Markdown SHA-256:   8e1debcc6b1a52bbd2b65c367780102f5994282a78ebaed477ac3c59abfffd21
# Code AST SHA-256:   ad8109fd4cc2b6324339d8a9ea8eec58c032576ac9321aa8a672e8473c3e8e33
# Verified Classes:   ForgetBoundaryViolation, Provenance, ContextSpan, DerivedRecord, MemorySubsystem
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

class ForgetBoundaryViolation(RuntimeError):
    """Raised when a forget cannot be honored because content survives in
    live context or in derivative scopes not covered by the cascade."""
    pass

@dataclass(frozen=True)
class Provenance:
    scope: str
    key: str

@dataclass
class ContextSpan:
    provenance: Provenance
    redacted: bool = False

@dataclass
class DerivedRecord:
    record_id: str
    scope: str
    lineage: frozenset  # set of (scope, key)

@dataclass
class MemorySubsystem:
    live_context: list = field(default_factory=list)
    derived: list = field(default_factory=list)
    tombstones: set = field(default_factory=set)

    def forget(self, scope: str, key: str, cascade_scopes: Iterable[str]) -> str:
        target = Provenance(scope, key)
        cascade = set(cascade_scopes)

        # Phase 1: tombstone the authoritative store.
        self.tombstones.add(target)

        # Evaluate the boundary predicate BEFORE claiming completion.
        in_context = any(
            s.provenance == target and not s.redacted
            for s in self.live_context
        )
        uncovered_derivatives = [
            d for d in self.derived
            if (scope, key) in d.lineage and d.scope not in cascade
        ]

        if uncovered_derivatives:
            raise ForgetBoundaryViolation(
                f"forget({scope},{key}) leaves derivatives in scopes "
                f"{[d.scope for d in uncovered_derivatives]} not in cascade {cascade}"
            )

        if in_context:
            # Phase 2a: redact in-context spans carrying the tombstoned provenance.
            for s in self.live_context:
                if s.provenance == target:
                    s.redacted = True
            # Phase 2b: cascade to covered derivatives.
            for d in self.derived:
                if (scope, key) in d.lineage:
                    d.scope = "_tombstoned"
            return "committed"

        # No live context, no uncovered derivatives: store tombstone suffices.
        for d in self.derived:
            if (scope, key) in d.lineage:
                d.scope = "_tombstoned"
        return "committed"

    def read(self, scope: str, key: str) -> None:
        if (scope, key) in self.tombstones:
            raise ForgetBoundaryViolation(
                f"read({scope},{key}) targets a tombstoned record"
            )
        self.live_context.append(ContextSpan(Provenance(scope, key)))

# Demonstration of the split: read materializes content, then forget fires.
mem = MemorySubsystem()
mem.read("session", "pii_block_7")          # content now live in context
mem.derived.append(DerivedRecord(
    record_id="note_1",
    scope="task",
    lineage=frozenset({("session", "pii_block_7")}),
))

try:
    # Cascade names only 'session'; derivative survives in 'task'.
    mem.forget("session", "pii_block_7", cascade_scopes=["session"])
except ForgetBoundaryViolation as e:
    print(f"blocked: {e}")

# Correct call: cascade covers the derivative scope and redacts live context.
status = mem.forget("session", "pii_block_7", cascade_scopes=["session", "task"])
assert status == "committed"
assert all(s.redacted for s in mem.live_context)
