# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewinds-its-context-journal-past-a-compaction-boundary-it-no-longer-holds.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewinds-its-context-journal-past-a-compaction-boundary-it-no-longer-holds.warrant.json
# Markdown SHA-256:   cfcde00c17caa8593e1f63ab235d6bdb36d80e1b703345dae601dff9e1b27a5c
# Code AST SHA-256:   2c93343726b666395c1f5307add11e07373ae401c2b9fed3ad260e2c1ea83a91
# Verified Classes:   EpochBoundaryViolation, ContextJournal
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class EpochBoundaryViolation(RuntimeError):
    """Raised when a rewind targets a turn whose journal records predate the current compaction epoch."""


class ContextJournal:
    def __init__(self):
        self.epoch = 0
        self.records = []          # each: {"turn": int, "epoch": int, "inverse": callable}
        self.rewindable_from = 0   # lowest turn still safely invertible

    def record(self, turn: int, inverse: callable) -> None:
        self.records.append({"turn": turn, "epoch": self.epoch, "inverse": inverse})

    def compact(self, boundary_turn: int, retain_cold: bool) -> None:
        # Lossy compaction: bytes before boundary_turn are replaced by a summary.
        self.epoch += 1
        if not retain_cold:
            # No cold storage => journal before boundary is orphaned. Truncate.
            self.records = [r for r in self.records if r["turn"] > boundary_turn]
            self.rewindable_from = boundary_turn + 1
        # If retain_cold: records survive, but their epoch is now stale and the
        # rewind path must hydrate from cold storage before inverting them.

    def rewind_to(self, target_turn: int) -> None:
        if target_turn < self.rewindable_from:
            raise EpochBoundaryViolation(
                f"rewind to turn {target_turn} crosses compaction boundary at "
                f"{self.rewindable_from - 1}; pre-boundary bytes were discarded"
            )
        for r in reversed([r for r in self.records if r["turn"] > target_turn]):
            if r["epoch"] != self.epoch:
                raise EpochBoundaryViolation(
                    f"journal record at turn {r['turn']} was written in epoch "
                    f"{r['epoch']}, current epoch is {self.epoch}; inverse would "
                    f"restore bytes that no longer match the substrate"
                )
            r["inverse"]()
        self.records = [r for r in self.records if r["turn"] <= target_turn]
