# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-committed-side-effects-when-a-speculative-branch-is-rolled-back-after-a-checkpoint-divergence.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-committed-side-effects-when-a-speculative-branch-is-rolled-back-after-a-checkpoint-divergence.warrant.json
# Markdown SHA-256:   81d522520578ee39f298189e7ee3c0daa0816783ee789e9435c5daa67b8f8494
# Code AST SHA-256:   feafb8ee8073e43cf0a340c8d9a0d15de1b3163f8c89a8bc72ad4e001b48d0ad
# Verified Classes:   SurfaceClass, SpeculationAdmissionError, Branch, SpeculationGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SurfaceClass(Enum):
    ISOLATED = "isolated"          # per-branch copy; rollback is free
    FENCED = "fenced"              # shared, but reads filtered by branch epoch
    SHARED_MUTABLE = "shared_mutable"  # shared, no read filter; rollback leaks


class SpeculationAdmissionError(RuntimeError):
    """Raised when a branch is admitted for speculative execution but its
    effect surface cannot be rolled back without leaking into siblings."""


@dataclass
class Branch:
    branch_id: str
    checkpoint_epoch: int
    write_surfaces: Set[str] = field(default_factory=set)
    read_surfaces: Set[str] = field(default_factory=set)
    rolled_back: bool = False


class SpeculationGate:
    def __init__(self, surface_classes: Dict[str, SurfaceClass]):
        self.surface_classes = surface_classes
        self.live_branches: Dict[str, Branch] = {}
        self.effect_ledger: Dict[str, Set[str]] = {}  # surface -> branch_ids that wrote

    def admit(self, branch: Branch) -> None:
        for surface in branch.write_surfaces:
            cls = self.surface_classes.get(surface, SurfaceClass.SHARED_MUTABLE)
            if cls is SurfaceClass.SHARED_MUTABLE:
                raise SpeculationAdmissionError(
                    f"branch {branch.branch_id} writes shared-mutable surface "
                    f"{surface!r}; it cannot be speculatively rolled back. "
                    f"Serialize this branch or isolate the surface."
                )
        self.live_branches[branch.branch_id] = branch
        for surface in branch.write_surfaces:
            self.effect_ledger.setdefault(surface, set()).add(branch.branch_id)

    def reconcile(self, keep: str, drop: Set[str]) -> None:
        for bid in drop:
            branch = self.live_branches.get(bid)
            if branch is None:
                continue
            branch.rolled_back = True
            for surface in branch.write_surfaces:
                cls = self.surface_classes[surface]
                if cls is SurfaceClass.ISOLATED:
                    continue  # namespace dropped with the branch
                if cls is SurfaceClass.FENCED:
                    continue  # reads filtered by epoch; effect invisible
                # SHARED_MUTABLE should never reach here (blocked at admit),
                # but if surface classification changed mid-run, fail closed.
                raise SpeculationAdmissionError(
                    f"rollback of {bid} would leak effects on {surface!r} "
                    f"into surviving branch {keep!r}"
                )
        # Verify no surviving branch reads a surface a dropped branch wrote
        # through a non-isolated path.
        survivor = self.live_branches[keep]
        for surface in survivor.read_surfaces:
            writers = self.effect_ledger.get(surface, set())
            leaked = {w for w in writers if w in drop}
            if leaked and self.surface_classes[surface] is not SurfaceClass.FENCED:
                raise SpeculationAdmissionError(
                    f"survivor {keep!r} reads {surface!r} written by rolled-back "
                    f"branches {leaked}; reconciliation is unsound"
                )


def run_speculative_round(
    gate: SpeculationGate,
    branches: list,
    keep: str,
) -> None:
    for b in branches:
        gate.admit(b)  # raises SpeculationAdmissionError on unsafe surface
    gate.reconcile(keep=keep, drop={b.branch_id for b in branches} - {keep})
