# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rolls-back-a-self-edit-log-whose-inverse-patch-was-computed-against-a-context-window-that-has-already-been-mutated-by-a.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rolls-back-a-self-edit-log-whose-inverse-patch-was-computed-against-a-context-window-that-has-already-been-mutated-by-a.warrant.json
# Markdown SHA-256:   b2eed5288ddbbf4e62634d2bbfa2e17ba92c66a6ce62b4198a0289bd9c9fdcc6
# Code AST SHA-256:   8f70e446ef996e9279aafce1ef8a930bec233d9071960a1b6787e39f612ace06
# Verified Classes:   RollbackUnavailable, EditEntry, ContextWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field


class RollbackUnavailable(RuntimeError):
    """Raised when a positional inverse cannot be proven to target the bytes
    it was computed against. Rollback must not proceed optimistically."""


@dataclass
class EditEntry:
    edit_id: str
    span: tuple[int, int]
    inverse_bytes: bytes
    window_digest_at_edit: str
    segment_generation_at_edit: int
    reversible: bool = True


@dataclass
class ContextWindow:
    data: bytearray
    segment_generation: int = 0
    compaction_spans: list[tuple[int, int]] = field(default_factory=list)

    def digest(self) -> str:
        return hashlib.sha256(bytes(self.data)).hexdigest()

    def compact(self, start: int, end: int, replacement: bytes) -> None:
        """Rewrite [start,end). Invalidates positional inverses overlapping it
        and shifts all downstream offsets."""
        self.data[start:end] = replacement
        self.segment_generation += 1
        self.compaction_spans.append((start, end))


def _overlaps_or_precedes(span: tuple[int, int], comp: tuple[int, int]) -> bool:
    s0, s1 = span
    c0, c1 = comp
    # Any compaction that starts before the span end and ends after the span
    # start either overlaps it or shifts offsets upstream of it.
    return not (c1 <= s0 or c0 >= s1)


def rollback(window: ContextWindow, entry: EditEntry) -> None:
    if not entry.reversible:
        raise RollbackUnavailable(
            f"edit {entry.edit_id} was invalidated by compaction; "
            "no positional inverse exists"
        )

    if window.digest() == entry.window_digest_at_edit:
        s0, s1 = entry.span
        window.data[s0:s1] = entry.inverse_bytes
        return

    # Digest differs. The inverse is only safe if no compaction touched or
    # preceded the span since the edit.
    for comp in window.compaction_spans:
        if _overlaps_or_precedes(entry.span, comp):
            raise RollbackUnavailable(
                f"rollback of {entry.edit_id} refused: compaction {comp} "
                f"overlaps/precedes span {entry.span}; inverse would splice "
                "into relocated bytes"
            )

    # Digest drift with no overlapping rewrite: offsets stable, proceed but
    # the caller should record a STALE_DIGEST audit event.
    s0, s1 = entry.span
    window.data[s0:s1] = entry.inverse_bytes
