# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-edit-rollback-is-unsafe-diff-based-context-rewriting-and-the-tombstone-collapse-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-edit-rollback-is-unsafe-diff-based-context-rewriting-and-the-tombstone-collapse-failure.warrant.json
# Markdown SHA-256:   5a16c827ae53c00182e09c46d7759c2bdf6d3b031ffe023927355b96c109a465
# Code AST SHA-256:   78f06836070377d6cc1a40a8e7b30dd0019f45a013d1b70f38fbaed3d261b027
# Verified Classes:   UnsafeRollbackError, JournalEntry, AnchorAwareJournal
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Set, Tuple


class UnsafeRollbackError(RuntimeError):
    """Raised when a diff-based rollback cannot be applied without silent partial restore."""
    pass


@dataclass
class JournalEntry:
    edit_id: int
    deleted_lines: Set[int]          # lines this edit removes from the buffer
    inverse_context: Set[int]        # lines the inverse patch needs to anchor on
    inverse_body: str                # the resurrected content
    promoted_snapshot: str | None = None  # set if promoted to snapshot


@dataclass
class AnchorAwareJournal:
    entries: List[JournalEntry] = field(default_factory=list)
    # line -> set of edit_ids whose inverse context references that line
    anchor_owners: Dict[int, Set[int]] = field(default_factory=dict)
    snapshot_budget_frac: float = 0.20
    buffer_lines: int = 0

    def _live_context_lines(self) -> Set[int]:
        live: Set[int] = set()
        for e in self.entries:
            if e.promoted_snapshot is None:
                live |= e.inverse_context
        return live

    def record_edit(self, edit_id: int, deleted: Set[int],
                    inverse_context: Set[int], inverse_body: str) -> JournalEntry:
        live_ctx = self._live_context_lines()
        conflict = deleted & live_ctx

        if not conflict:
            entry = JournalEntry(edit_id, deleted, inverse_context, inverse_body)
        else:
            # Promotion required: capture snapshot of affected region before deletion.
            affected_span = max(conflict) - min(conflict) + 1
            if affected_span > self.snapshot_budget_frac * max(self.buffer_lines, 1):
                raise UnsafeRollbackError(
                    f"edit {edit_id}: anchor conflict on {len(conflict)} lines spans "
                    f"{affected_span} lines, exceeding snapshot budget "
                    f"({self.snapshot_budget_frac:.0%}). Refuse and re-plan."
                )
            entry = JournalEntry(
                edit_id, deleted, inverse_context, inverse_body,
                promoted_snapshot=f"<snapshot of lines {min(conflict)}..{max(conflict)}>",
            )

        self.entries.append(entry)
        for line in inverse_context:
            self.anchor_owners.setdefault(line, set()).add(edit_id)
        return entry

    def rollback_to(self, target_edit_id: int, applier_fuzz: int = 0) -> None:
        if applier_fuzz != 0:
            raise UnsafeRollbackError(
                "rollback requires exact apply (fuzz=0); fuzz>0 converts "
                "anchor misses into silent partial restores"
            )
        for entry in reversed(self.entries):
            if entry.edit_id <= target_edit_id:
                break
            if entry.promoted_snapshot is not None:
                continue  # snapshot restore is total; safe
            missing = entry.inverse_context - self._live_context_lines()
            if missing:
                raise UnsafeRollbackError(
                    f"rollback of edit {entry.edit_id}: inverse anchors "
                    f"{sorted(missing)} were deleted by later edits; "
                    f"tombstone-collapse risk. Refusing partial restore."
                )
        self.entries = [e for e in self.entries if e.edit_id <= target_edit_id]


def demonstrate_tombstone_collapse() -> None:
    journal = AnchorAwareJournal(buffer_lines=400)
    # Edit 7: deletes 210-228, anchors on 205-209 and 229-233.
    journal.record_edit(
        edit_id=7,
        deleted=set(range(210, 229)),
        inverse_context=set(range(205, 210)) | set(range(229, 234)),
        inverse_body="<19 constraint lines>",
    )
    # Edit 11: deletes 229-233 (the trailing anchor of edit 7's inverse).
    try:
        journal.record_edit(
            edit_id=11,
            deleted=set(range(229, 234)),
            inverse_context=set(range(234, 239)),
            inverse_body="<compacted summary>",
        )
    except UnsafeRollbackError as exc:
        print(f"caught at record time: {exc}")
        return
    # If we reached here without promotion, rollback would be unsafe:
    journal.rollback_to(target_edit_id=0)


if __name__ == "__main__":
    demonstrate_tombstone_collapse()
