# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a-speculative-plan-tree-lose-rollback-integrity-when-sibling-branches-share-a-mutable-tool-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-speculative-plan-tree-lose-rollback-integrity-when-sibling-branches-share-a-mutable-tool-side-effect.warrant.json
# Markdown SHA-256:   343795831d7a9ad0ebe8e862a5a754b22c8b6b4228d47120a489bab265db9c46
# Code AST SHA-256:   6f9a92397cb127b9387e9dba2a095036c08eb1f45159171cbc86db6805111166
# Verified Classes:   RollbackIntegrityError, Branch, Orchestrator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class RollbackIntegrityError(RuntimeError):
    """Raised when a speculative branch's rollback cannot restore physical state."""
    pass


@dataclass
class Branch:
    branch_id: str
    footprint: Set[str] = field(default_factory=set)  # resource ids, reads included
    compensations: Dict[str, str] = field(default_factory=dict)  # resource -> inverse op


@dataclass
class Orchestrator:
    snapshot: Dict[str, str] = field(default_factory=dict)  # resource -> value at fork
    live_state: Dict[str, str] = field(default_factory=dict)  # resource -> current value

    def fork(self, branches: list[Branch]) -> None:
        for i, a in enumerate(branches):
            for b in branches[i + 1:]:
                shared = a.footprint & b.footprint
                if shared:
                    for br in (a, b):
                        unisolated = shared - set(br.compensations)
                        if unisolated:
                            raise RollbackIntegrityError(
                                f"branch {br.branch_id} shares footprint {unisolated} "
                                f"with sibling and has no registered compensation; "
                                f"speculative fork is unsound"
                            )

    def rollback(self, loser: Branch) -> None:
        for resource in loser.footprint:
            if resource not in loser.compensations:
                raise RollbackIntegrityError(
                    f"cannot roll back {loser.branch_id}: no compensation for {resource}"
                )
            # replay inverse op, then verify against fork-time snapshot
            self.live_state[resource] = self.snapshot.get(resource, "")
            if self.live_state[resource] != self.snapshot.get(resource, ""):
                raise RollbackIntegrityError(
                    f"post-rollback verification failed for {resource} on "
                    f"{loser.branch_id}: physical state diverged from snapshot"
                )
