# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-self-edit-whose-diff-validates-but-whose-rollback-base-is-stale.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-self-edit-whose-diff-validates-but-whose-rollback-base-is-stale.warrant.json
# Markdown SHA-256:   a05fa2b8637f8b76acbf177494c63849e59d46074cdd7ab1c2d702a3c2424d6a
# Code AST SHA-256:   3726fda1a1080d11db1cf2cc6ecc37d9c3cf658c287d989615b61e34df721141
# Verified Classes:   StaleRollbackBaseError, Snapshot
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class StaleRollbackBaseError(RuntimeError):
    """Raised when a diff is computed against a buffer whose rollback
    snapshot cannot reproduce the pre-edit state."""
    pass


@dataclass
class Snapshot:
    content: dict
    lineage_hash: str
    replayable_delta: set = field(default_factory=set)


def _hash(buf: dict) -> str:
    return hashlib.sha256(repr(sorted(buf.items())).encode()).hexdigest()


def apply_self_edit(buffer: dict, snapshot: Snapshot, diff: dict,
                    non_replayable_keys: set) -> dict:
    # Precondition: the snapshot must be a faithful rollback base for the
    # buffer the diff was computed against.
    delta = set(buffer) - set(snapshot.content)
    unsafe = delta & non_replayable_keys

    if unsafe:
        raise StaleRollbackBaseError(
            f"Snapshot {snapshot.lineage_hash[:8]} is stale as a rollback "
            f"base; non-replayable keys {sorted(unsafe)} landed after the "
            f"snapshot was taken. Refusing to apply diff computed against "
            f"the live buffer, because rollback would silently drop them."
        )

    if snapshot.lineage_hash != _hash(snapshot.content):
        raise StaleRollbackBaseError(
            "Snapshot content hash does not match recorded lineage; "
            "snapshot was mutated out of band."
        )

    # Safe: either buffer == snapshot, or every delta element is replayable.
    new_buffer = dict(buffer)
    for key, op in diff.items():
        if op["action"] == "delete":
            new_buffer.pop(key, None)
        elif op["action"] == "set":
            new_buffer[key] = op["value"]
    return new_buffer


def rollback(buffer: dict, snapshot: Snapshot) -> dict:
    # Replay only the replayable delta on top of the snapshot base.
    base = dict(snapshot.content)
    for key in snapshot.replayable_delta:
        if key in buffer:
            base[key] = buffer[key]
    return base
