# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-forget-acknowledgement-with-in-flight-derived-writes-the-retention-scope-tombstone-race.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-forget-acknowledgement-with-in-flight-derived-writes-the-retention-scope-tombstone-race.warrant.json
# Markdown SHA-256:   2fa25cd3de9032697fe1c3f6c7f64ca2a5e6b169dbfdfc01512fb317e4815e34
# Code AST SHA-256:   fc255b3d2a8b8b71ac727cb68e8cc8feafc116bde169f2ab361aa906fb3280ec
# Verified Classes:   DerivationAfterErasure, TombstoneLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class DerivationAfterErasure(RuntimeError):
    """Raised when a derived write commits against a tombstoned source or a stale scope epoch."""
    pass


@dataclass
class TombstoneLedger:
    # record_id -> forgotten_at (monotonic)
    erased: dict[str, float] = field(default_factory=dict)
    # scope -> current epoch (incremented on every forget)
    scope_epoch: dict[str, int] = field(default_factory=dict)

    def erase_scope(self, scope: str, record_ids: list[str]) -> int:
        now = time.monotonic()
        for rid in record_ids:
            self.erased[rid] = now
        self.scope_epoch[scope] = self.scope_epoch.get(scope, 0) + 1
        return self.scope_epoch[scope]


def commit_derived_write(
    ledger: TombstoneLedger,
    scope: str,
    source_record_ids: Optional[list[str]],
    derivation_epoch: int,
    payload: dict,
) -> dict:
    """Commit-time barrier. Rejects writes whose lineage touches erased records
    or whose derivation epoch predates the scope's current epoch."""
    if source_record_ids is not None:
        hit = [rid for rid in source_record_ids if rid in ledger.erased]
        if hit:
            raise DerivationAfterErasure(
                f"derived write for scope={scope!r} references erased sources {hit}; "
                f"re-derive from surviving records or abandon"
            )

    current = ledger.scope_epoch.get(scope, 0)
    if derivation_epoch < current:
        raise DerivationAfterErasure(
            f"derived write for scope={scope!r} carries epoch {derivation_epoch} "
            f"but scope is at epoch {current}; lineage unavailable, epoch fence tripped"
        )

    return {"committed": True, "scope": scope, "epoch": current, "payload": payload}


# --- trace of the observed failure ---
ledger = TombstoneLedger()
ledger.erase_scope("user:U", record_ids=[f"ep_{i}" for i in range(12)])

try:
    commit_derived_write(
        ledger,
        scope="user:U",
        source_record_ids=["ep_3", "ep_7"],   # distillation read these pre-erasure
        derivation_epoch=0,                    # context captured before forget
        payload={"kind": "semantic_summary"},
    )
except DerivationAfterErasure as e:
    print("BLOCKED:", e)
