# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-the-wal-segment-boundary-when-auditable-forget-tombstones-collide-with-in-flight-checkpoints.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-the-wal-segment-boundary-when-auditable-forget-tombstones-collide-with-in-flight-checkpoints.warrant.json
# Markdown SHA-256:   9335267f35c651371087bff99284ca189a2d777e1bb9bf973dceabd806ebbe5e
# Code AST SHA-256:   ef9d7b6b3fae8709892de8a506e79216238c67a043a78efd37e1305a0ada0adf
# Verified Classes:   ForgetOrderingError, Tombstone, Checkpoint, AuditableWAL
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ForgetOrderingError(RuntimeError):
    """Raised when a forget tombstone cannot be proven authoritative
    against the checkpoints that will be replayed against it."""
    pass


@dataclass
class Tombstone:
    key: str
    logical_ts: int
    fsynced: bool = False
    audit_acked: bool = False


@dataclass
class Checkpoint:
    high_water_ts: int
    live_keys: Dict[str, bytes] = field(default_factory=dict)


class AuditableWAL:
    def __init__(self) -> None:
        self.tombstones: List[Tombstone] = []
        self.checkpoints: List[Checkpoint] = []
        self._clock = 0

    def _tick(self) -> int:
        self._clock += 1
        return self._clock

    def append_tombstone(self, key: str) -> Tombstone:
        ts = self._tick()
        t = Tombstone(key=key, logical_ts=ts)
        self.tombstones.append(t)
        return t

    def fsync_tombstone(self, t: Tombstone) -> None:
        # Durability point. Only after this may the audit sink be written.
        t.fsynced = True

    def ack_audit(self, t: Tombstone) -> None:
        if not t.fsynced:
            raise ForgetOrderingError(
                f"tombstone for key={t.key!r} ts={t.logical_ts} was acked to "
                f"audit sink before its segment fsync; forget event is unprovable"
            )
        t.audit_acked = True

    def write_checkpoint(self, live_keys: Dict[str, bytes]) -> Checkpoint:
        # Checkpoint high-water is the clock at materialization time.
        cp = Checkpoint(high_water_ts=self._tick(), live_keys=dict(live_keys))
        self.checkpoints.append(cp)
        return cp

    def replay(self) -> Dict[str, bytes]:
        # Replay checkpoints in order, then apply fsynced tombstones by ts.
        state: Dict[str, bytes] = {}
        for cp in sorted(self.checkpoints, key=lambda c: c.high_water_ts):
            state = dict(cp.live_keys)
        for t in sorted(self.tombstones, key=lambda x: x.logical_ts):
            if not t.fsynced:
                continue
            state.pop(t.key, None)
        return state

    def verify_forget_authoritative(self, t: Tombstone) -> None:
        """A tombstone is authoritative only if every checkpoint that will be
        replayed against it either postdates it or will be superseded."""
        if not t.fsynced:
            raise ForgetOrderingError(
                f"tombstone key={t.key!r} ts={t.logical_ts} not fsynced; "
                f"forget is not committed"
            )
        for cp in self.checkpoints:
            if cp.high_water_ts < t.logical_ts and t.key in cp.live_keys:
                raise ForgetOrderingError(
                    f"tombstone key={t.key!r} ts={t.logical_ts} predates "
                    f"checkpoint high_water_ts={cp.high_water_ts} which still "
                    f"contains the key; replay would resurrect it"
                )


def exercise_boundary() -> None:
    wal = AuditableWAL()
    # Checkpoint materializes state containing the key at ts=1.
    wal.write_checkpoint({"session.ctx.42": b"secret"})
    # Forget arrives at ts=2.
    t = wal.append_tombstone("session.ctx.42")
    # Crash before fsync: forget is not committed.
    try:
        wal.verify_forget_authoritative(t)
    except ForgetOrderingError:
        pass  # expected: not fsynced
    wal.fsync_tombstone(t)
    wal.verify_forget_authoritative(t)
    wal.ack_audit(t)
    # A later checkpoint at ts=3 still carries the key (stale view).
    wal.write_checkpoint({"session.ctx.42": b"secret"})
    # Now the tombstone predates a checkpoint that resurrects the key.
    try:
        wal.verify_forget_authoritative(t)
    except ForgetOrderingError as e:
        print(f"boundary violation detected: {e}")
    else:
        raise ForgetOrderingError("expected resurrection boundary to be caught")


if __name__ == "__main__":
    exercise_boundary()
