# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-sub-plan-branches-from-corrupting-the-committed-agent-state-during-rollback-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-sub-plan-branches-from-corrupting-the-committed-agent-state-during-rollback-reconciliation.warrant.json
# Markdown SHA-256:   d60d1afec1fe7b6826e32ea7fda2e13f1eab5591a7473a7d13e3c66e46cd5673
# Code AST SHA-256:   236f3790fc9d2c1732cb9125e4641b419efb26a05faf3fc9adc0d996a7f5b605
# Verified Classes:   SpeculativeForkIllegal, RollbackInvariantViolation, Branch, SharedResource
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SpeculativeForkIllegal(RuntimeError):
    """Raised when a branch's toolset includes a writer to a shared,
    non-branch-namespaced resource, making rollback unsound."""
    pass


class RollbackInvariantViolation(RuntimeError):
    """Raised when post-rollback state is not observationally equivalent
    to 'branch never ran' (cache residue, phantom side effect, or
    narrative leakage detected)."""
    pass


@dataclass
class Branch:
    branch_id: str
    fork_epoch: int
    effect_log: list[tuple[str, str]] = field(default_factory=list)  # (resource, op)
    writes_shared: bool = False


@dataclass
class SharedResource:
    name: str
    namespaced: bool


def fork_branch(branch_id: str, epoch: int, toolsets: list[SharedResource]) -> Branch:
    # Invariant: a speculative fork is legal only if every shared resource
    # this branch can write is namespaced by (branch_id, epoch).
    illegal = [r.name for r in toolsets if not r.namespaced]
    if illegal:
        raise SpeculativeForkIllegal(
            f"branch {branch_id} at epoch {epoch} can write non-namespaced "
            f"shared resources {illegal}; speculative rollback would be unsound. "
            f"Serialize this branch instead."
        )
    return Branch(branch_id=branch_id, fork_epoch=epoch, writes_shared=False)


def rollback_and_reconcile(
    branch: Branch,
    cache: dict[tuple[str, int], Any],
    committed: dict[str, Any],
    pre_fork_snapshot: dict[str, Any],
) -> dict[str, Any]:
    # Restore local snapshot.
    committed.clear()
    committed.update(pre_fork_snapshot)

    # Invariant check 1: no cache residue attributable to this branch.
    for (bid, epoch) in list(cache.keys()):
        if bid == branch.branch_id and epoch == branch.fork_epoch:
            del cache[(bid, epoch)]

    # Invariant check 2: effect log must be empty for a purely speculative
    # branch; any entry means a side effect escaped the namespace.
    if branch.effect_log:
        raise RollbackInvariantViolation(
            f"branch {branch.branch_id} logged external effects "
            f"{branch.effect_log} despite speculative fork; rollback is not "
            f"observationally equivalent to 'branch never ran'."
        )

    # Invariant check 3: committed state must equal pre-fork state exactly.
    if committed != pre_fork_snapshot:
        raise RollbackInvariantViolation(
            f"post-rollback state diverged from pre-fork snapshot for "
            f"branch {branch.branch_id}"
        )
    return committed


def run_speculative(branch: Branch, work: Callable[[], None],
                    cache: dict, committed: dict, snapshot: dict) -> dict:
    try:
        work()
    finally:
        return rollback_and_reconcile(branch, cache, committed, snapshot)
