# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-become-un-rollbackable-during-parallel-drafting.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-become-un-rollbackable-during-parallel-drafting.warrant.json
# Markdown SHA-256:   37d3f4ad519f90f82d60e87962a4679d50c3dfe6334ae9c2d1caaa31c5f37141
# Code AST SHA-256:   b2c5eb2c33b380d41d2de7848056ca338548fa52c3772cd2551cec8fe4c3cda5
# Verified Classes:   RollbackIntegrityError, SpeculationClass, Effect, Branch, SharedStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class RollbackIntegrityError(RuntimeError):
    """Raised when a discarded branch left an un-compensated effect in shared state."""


class SpeculationClass(Enum):
    PURE = "pure"            # safe to discard on rollback
    COMMITTED = "committed"  # must be compensated, not discarded


@dataclass
class Effect:
    tool: str
    side_effect: bool
    compensation_handle: str | None = None


@dataclass
class Branch:
    branch_id: str
    speculation_class: SpeculationClass
    effects: list[Effect] = field(default_factory=list)
    discarded: bool = False


@dataclass
class SharedStore:
    # key -> (value, writer_branch_id)
    entries: dict[str, tuple[str, str]] = field(default_factory=dict)


def dispatch_effect(branch: Branch, effect: Effect, store: SharedStore,
                    key: str, value: str) -> None:
    """Enforce the speculation contract at call time."""
    if effect.side_effect and branch.speculation_class is SpeculationClass.PURE:
        # Signal 1: effect-class / speculation-class divergence.
        raise RollbackIntegrityError(
            f"branch {branch.branch_id} tagged PURE attempted side-effect "
            f"tool {effect.tool!r}; promote-and-serialize or abort"
        )
    if effect.side_effect and effect.compensation_handle is None:
        # Signal 2: commitment without a compensation handle.
        raise RollbackIntegrityError(
            f"branch {branch.branch_id} committed {effect.tool!r} with no "
            f"compensation_handle; rollback cannot be modeled as discard"
        )
    branch.effects.append(effect)
    if effect.side_effect:
        store.entries[key] = (value, branch.branch_id)


def rollback(branch: Branch, store: SharedStore) -> None:
    """Discard a loser; refuse if it left un-compensable residue."""
    if branch.speculation_class is not SpeculationClass.PURE:
        raise RollbackIntegrityError(
            f"branch {branch.branch_id} is COMMITTED; must compensate, not discard"
        )
    branch.discarded = True


def assert_merge_integrity(branches: list[Branch], store: SharedStore) -> None:
    """Signal 3: every writer_ref must resolve to a live (non-discarded) branch."""
    live = {b.branch_id for b in branches if not b.discarded}
    for key, (_value, writer) in store.entries.items():
        if writer not in live:
            # Signal 4 precursor: dangling writer_ref from a rolled-back branch.
            raise RollbackIntegrityError(
                f"shared key {key!r} written by discarded branch {writer!r}; "
                f"merge would commit a zombie effect"
            )
