# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-rollback-divergence-from-silently-forking-agent-state-across-speculative-branches.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-rollback-divergence-from-silently-forking-agent-state-across-speculative-branches.warrant.json
# Markdown SHA-256:   aa2f13a33f56a4cd20e82e67cd1088f4a83a27e3639e4e6294a7b7ee849cc1cc
# Code AST SHA-256:   94335ab24e1c935ae6f6691fb5fb349c39152577ee906447a78eb0d30afa46dc
# Verified Classes:   SilentForkError, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Any


class SilentForkError(RuntimeError):
    """Raised when a committed branch's post-commit state diverges from its replay."""


@dataclass
class Branch:
    branch_id: str
    epoch: int
    wal: list[tuple[str, dict[str, Any]]] = field(default_factory=list)
    committed: bool = False


def _state_hash(state: dict[str, Any]) -> str:
    return hashlib.sha256(repr(sorted(state.items())).encode()).hexdigest()


def commit_with_replay_audit(
    winner: Branch,
    snapshot_at_spawn: dict[str, Any],
    apply_wal,
    live_state: dict[str, Any],
) -> dict[str, Any]:
    """
    Atomically promote the winning branch's WAL, then replay its log against the
    spawn snapshot and assert the resulting state matches the live post-commit state.
    Any mismatch is a silent fork: a sibling branch's residue leaked past rollback.
    """
    if not winner.wal:
        # Nothing to commit; still audit that live state equals the snapshot.
        if _state_hash(live_state) != _state_hash(snapshot_at_spawn):
            raise SilentForkError(
                f"branch {winner.branch_id} wrote nothing but live state drifted "
                f"from spawn snapshot — sibling residue leaked"
            )
        return live_state

    # Atomic epoch-flip: apply the winner's WAL in one step.
    apply_wal(winner.wal)
    winner.committed = True

    # Replay against a clean snapshot to obtain the expected post-commit state.
    replay_state = dict(snapshot_at_spawn)
    for op, payload in winner.wal:
        replay_state = _apply_op(replay_state, op, payload)

    live_hash = _state_hash(live_state)
    replay_hash = _state_hash(replay_state)
    if live_hash != replay_hash:
        raise SilentForkError(
            f"branch {winner.branch_id} committed but state hash diverged: "
            f"live={live_hash[:12]} replay={replay_hash[:12]} — "
            f"a rolled-back sibling's side-effects were not reversed"
        )
    return live_state


def _apply_op(state: dict[str, Any], op: str, payload: dict[str, Any]) -> dict[str, Any]:
    new_state = dict(state)
    if op == "insert":
        new_state[payload["key"]] = payload["value"]
    elif op == "delete":
        new_state.pop(payload["key"], None)
    elif op == "update":
        new_state[payload["key"]] = payload["value"]
    else:
        raise ValueError(f"unknown op {op!r} in WAL replay")
    return new_state
