# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-reversible-context-edit-journal-silently-become-irreversible-when-a-salience-rescore-rewrites-the-tombstone-of-an-already-compa.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-reversible-context-edit-journal-silently-become-irreversible-when-a-salience-rescore-rewrites-the-tombstone-of-an-already-compa.warrant.json
# Markdown SHA-256:   286d240ad12606126ea64ca001126b4ef9766765be398cb2430f89b90f9a49f3
# Code AST SHA-256:   1db4234c82d5ea71fbd152842cecd13948f6118696a5ad9665f919125f8fc458
# Verified Classes:   IrreversibleRollbackError, JournalEntry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class IrreversibleRollbackError(RuntimeError):
    """Raised when a journal inverse op resolves to a compaction tombstone
    instead of the bytes recorded at edit time."""
    pass


@dataclass
class JournalEntry:
    span_id: str
    expected_hash: str          # hash of original bytes at edit time
    inverse_op: str             # e.g. "restore"
    tombstoned: bool = False    # set if scorer compacted this span post-edit


def restore(entry: JournalEntry, current_bytes: bytes) -> bytes:
    # Content-verifying restore: refuse to write back a tombstone.
    actual = hashlib.sha256(current_bytes).hexdigest()
    if actual != entry.expected_hash:
        raise IrreversibleRollbackError(
            f"span {entry.span_id}: journal expected {entry.expected_hash[:12]}, "
            f"found {actual[:12]} (likely compacted by salience scorer); "
            f"span is unrecoverable from journal — re-derive from source"
        )
    return current_bytes


def rollback(entry: JournalEntry, resolve) -> bytes:
    if entry.tombstoned:
        raise IrreversibleRollbackError(
            f"span {entry.span_id}: scorer tombstoned a span with a live journal "
            f"entry; inverse op would restore an elision marker"
        )
    return restore(entry, resolve(entry.span_id))
