# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-horizon-before-hierarchical-summarization-silently-voids-lossless-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-horizon-before-hierarchical-summarization-silently-voids-lossless-rollback.warrant.json
# Markdown SHA-256:   06e9db13d5728f6f66485c33b377da55e0b8530bf6f04d73b0313bb89746e3cd
# Code AST SHA-256:   87ed8c777a8fead7465c39642af9d6d7c7bcc6b204233d2944408787bbb57966
# Verified Classes:   CompactionHorizonViolation, Checkpoint, ContextStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionHorizonViolation(RuntimeError):
    """Raised when a rollback target is not covered by a retained raw span."""


@dataclass
class Checkpoint:
    index: int
    raw_span_hash: str
    klass: str  # "raw" or "summary"
    horizon_version: int


@dataclass
class ContextStore:
    horizon: int = 0            # highest raw index NOT yet folded into a summary
    horizon_version: int = 0
    checkpoints: dict = field(default_factory=dict)

    def record_checkpoint(self, index: int, raw_span_hash: str) -> Checkpoint:
        cp = Checkpoint(index=index, raw_span_hash=raw_span_hash,
                        klass="raw", horizon_version=self.horizon_version)
        self.checkpoints[index] = cp
        return cp

    def min_live_checkpoint(self) -> Optional[int]:
        live = [i for i, c in self.checkpoints.items() if c.klass == "raw"]
        return min(live) if live else None

    def advance_horizon(self, new_horizon: int) -> None:
        """Advance the compaction frontier, atomically demoting any checkpoint it crosses."""
        oldest = self.min_live_checkpoint()
        if oldest is not None and new_horizon >= oldest:
            # Regime B: demote every checkpoint at or below the new horizon.
            for idx, cp in self.checkpoints.items():
                if cp.klass == "raw" and idx <= new_horizon:
                    cp.klass = "summary"
        self.horizon = new_horizon
        self.horizon_version += 1

    def rollback(self, index: int, expected_hash: str) -> Checkpoint:
        cp = self.checkpoints.get(index)
        if cp is None:
            raise CompactionHorizonViolation(
                f"no checkpoint at index {index}; cannot rollback")
        # Re-validate horizon version inside the critical section (TOCTOU guard).
        if cp.horizon_version != self.horizon_version:
            raise CompactionHorizonViolation(
                f"checkpoint {index} stale: horizon advanced from "
                f"v{cp.horizon_version} to v{self.horizon_version} mid-rollback")
        if cp.klass != "raw":
            raise CompactionHorizonViolation(
                f"checkpoint {index} is summary-class (horizon={self.horizon}); "
                f"lossless rollback unavailable")
        if cp.raw_span_hash != expected_hash:
            raise CompactionHorizonViolation(
                f"checkpoint {index} hash mismatch: expected {expected_hash}, "
                f"got {cp.raw_span_hash}")
        return cp


def rollback_to(store: ContextStore, index: int, expected_hash: str) -> Checkpoint:
    return store.rollback(index, expected_hash)
