# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-divergence-from-surviving-rollback-in-multi-agent-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-divergence-from-surviving-rollback-in-multi-agent-pipelines.warrant.json
# Markdown SHA-256:   ff2ad6e270ae4beb8dcbbd259c0ec2fd0cb39fb8363e20f874bac4c3c94d91c8
# Code AST SHA-256:   f85d825b15f2a0f6976a072c5ba36e264fdc690f00dfce240881e39a7988f49a
# Verified Classes:   SurfaceClass, SpeculationInvariantViolation, Branch, SideEffectSurface, ScratchStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class SurfaceClass(Enum):
    EPOCH_TAGGABLE = "epoch_taggable"
    OPAQUE = "opaque"


class SpeculationInvariantViolation(RuntimeError):
    """Raised when a speculative fork would cross an untaggable surface."""


@dataclass
class Branch:
    branch_id: str
    epoch: int
    reachable_surfaces: Set[str]


@dataclass
class SideEffectSurface:
    name: str
    surface_class: SurfaceClass
    read_only: bool = False


@dataclass
class ScratchStore:
    # key -> (value, epoch, branch_id)
    data: Dict[str, tuple] = field(default_factory=dict)

    def write(self, key: str, value, epoch: int, branch_id: str) -> None:
        self.data[key] = (value, epoch, branch_id)

    def read(self, key: str, reader_epoch: int, adopted_epochs: Set[int]) -> object:
        value, epoch, _ = self.data[key]
        if epoch == reader_epoch or epoch in adopted_epochs:
            return value
        raise KeyError(f"epoch {epoch} not visible to reader at epoch {reader_epoch}")


def authorize_fork(
    branches: list[Branch],
    surfaces: Dict[str, SideEffectSurface],
) -> None:
    for br in branches:
        for sname in br.reachable_surfaces:
            surf = surfaces.get(sname)
            if surf is None:
                raise SpeculationInvariantViolation(
                    f"branch {br.branch_id} reaches unknown surface {sname!r}; "
                    "cannot prove epoch-taggability"
                )
            if surf.surface_class is SurfaceClass.OPAQUE and not surf.read_only:
                raise SpeculationInvariantViolation(
                    f"branch {br.branch_id} would write opaque surface {sname!r}; "
                    "speculative fork must degrade to serial execution"
                )


def reconcile(branches: list[Branch], store: ScratchStore, adopted: Set[int]) -> float:
    # agreement weighted by lineage independence: branches sharing a read of the
    # same speculative write are not independent votes.
    reads: Dict[str, Set[str]] = {}
    for br in branches:
        seen = set()
        for key, (_, epoch, _) in store.data.items():
            if epoch == br.epoch or epoch in adopted:
                seen.add(key)
        reads[br.branch_id] = seen
    independent_pairs = 0
    total_pairs = 0
    ids = [b.branch_id for b in branches]
    for i in range(len(ids)):
        for j in range(i + 1, len(ids)):
            total_pairs += 1
            if reads[ids[i]].isdisjoint(reads[ids[j]]):
                independent_pairs += 1
    if total_pairs == 0:
        return 0.0
    return independent_pairs / total_pairs


# --- demonstration of the failure and the guardrail ---
surfaces = {
    "retrieval_index": SideEffectSurface("retrieval_index", SurfaceClass.OPAQUE, read_only=True),
    "scratch_store": SideEffectSurface("scratch_store", SurfaceClass.EPOCH_TAGGABLE),
    "external_crm": SideEffectSurface("external_crm", SurfaceClass.OPAQUE, read_only=False),
}

store = ScratchStore()
# abandoned branch B1 wrote under epoch 0 before rollback
store.write("task::summary", "plan-assumes-S0", epoch=0, branch_id="B1")

b1_prime = Branch("B1'", epoch=1, reachable_surfaces={"retrieval_index", "scratch_store"})
b2_prime = Branch("B2'", epoch=1, reachable_surfaces={"retrieval_index", "scratch_store"})

authorize_fork([b1_prime, b2_prime], surfaces)  # ok: no opaque writes

# naive reconciliation would see both branches "agree" on task::summary
naive_conf = 1.0
# lineage-aware reconciliation reveals shared contamination -> not independent
real_conf = reconcile([b1_prime, b2_prime], store, adopted={0})
assert real_conf < naive_conf, "contamination must reduce independence"

# a branch that reaches the opaque CRM must be rejected before forking
bad = Branch("B3", epoch=1, reachable_surfaces={"external_crm"})
try:
    authorize_fork([bad], surfaces)
except SpeculationInvariantViolation as e:
    print(f"fork rejected: {e}")
