# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-sibling-branches-and-the-rollback-ledger-diverges-from-the-reconciliation-oracle.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-sibling-branches-and-the-rollback-ledger-diverges-from-the-reconciliation-oracle.warrant.json
# Markdown SHA-256:   007b2a2f2fcf72b01abb893437fba4c9641dadfe63d4b2bdf278f6341251b2a8
# Code AST SHA-256:   0a7a00da4d6544ef14918643686bab1e6d3b223676af5cf7b8774eff45ad0575
# Verified Classes:   RollbackDivergenceError, Effect, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class RollbackDivergenceError(RuntimeError):
    """Raised when post-rollback environment state diverges from the
    pre-fork snapshot plus the winning branch's effect-set."""


@dataclass
class Effect:
    requested_id: str
    actual_id: str | None      # None if tool could not report actual identity
    committed: bool            # did the effect actually land?


@dataclass
class Branch:
    name: str
    effects: list[Effect] = field(default_factory=list)
    inverse_ledger: list[Callable[[], None]] = field(default_factory=list)


def reconcile(pre_snapshot: set[str],
              winning: Branch,
              post_state: set[str]) -> None:
    """Enforce: post_state == pre_snapshot ∪ winning.actual_effects."""
    expected = set(pre_snapshot)
    for eff in winning.effects:
        if eff.committed and eff.actual_id is not None:
            expected.add(eff.actual_id)
        elif eff.committed and eff.actual_id is None:
            # Winning branch committed an effect whose actual identity is
            # unknown — cannot certify the invariant.
            raise RollbackDivergenceError(
                f"winning branch {winning.name!r} committed effect with "
                f"unreported actual identity (requested={eff.requested_id!r}); "
                f"reconciliation cannot be certified by ledger"
            )

    orphaned = post_state - expected
    missing = expected - post_state
    if orphaned or missing:
        raise RollbackDivergenceError(
            f"rollback divergence: orphaned={sorted(orphaned)} "
            f"missing={sorted(missing)} — ledger-driven rollback is "
            f"unsound for this effect-set; require snapshot-diff remediation"
        )


def rollback_and_verify(pre_snapshot: set[str],
                        branches: list[Branch],
                        winning_name: str,
                        read_state: Callable[[], set[str]]) -> None:
    winning = next(b for b in branches if b.name == winning_name)
    for b in branches:
        if b.name == winning_name:
            continue
        for inverse in reversed(b.inverse_ledger):
            inverse()  # replay ledger inverse; may be a silent no-op

    post_state = read_state()
    # Gate MUST read the environment, never the ledgers.
    reconcile(pre_snapshot, winning, post_state)
