# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-speculative-plan-branches-before-their-side-effects-become-unrollbackable.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-speculative-plan-branches-before-their-side-effects-become-unrollbackable.warrant.json
# Markdown SHA-256:   50d867baa934cd9464c035bf4157c6daa751102203df14e3bed1d04bbefa9712
# Code AST SHA-256:   6bb4ca71e588c8e99b96b1f1a1e71eb8e79b0a352dd17a38ea11ab0fed6e001d
# Verified Classes:   BranchState, SpeculationRollbackError, Effect, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class BranchState(Enum):
    PROVISIONAL = "provisional"
    COMMITTED = "committed"
    ROLLED_BACK = "rolled_back"
    PENDING_COMPENSATION = "pending_compensation"
    ORPHANED = "orphaned"


class SpeculationRollbackError(RuntimeError):
    """Raised when an orchestrator attempts to terminate a speculative branch
    whose effects are not provably rolled back."""


@dataclass
class Effect:
    entity_id: str
    tool: str
    terminal: bool          # compensation confirmed terminal by system of record
    escaped_containment: bool


@dataclass
class Branch:
    branch_id: str
    state: BranchState = BranchState.PROVISIONAL
    effects: list = field(default_factory=list)
    write_set: set = field(default_factory=set)


def mark_rolled_back(branch: Branch) -> None:
    """Transition a branch to ROLLED_BACK only if every escaped effect has a
    confirmed-terminal compensation. Otherwise the branch is PENDING_COMPENSATION
    and must not be treated as clean."""
    escaped = [e for e in branch.effects if e.escaped_containment]
    unconfirmed = [e for e in escaped if not e.terminal]
    if unconfirmed:
        branch.state = BranchState.PENDING_COMPENSATION
        raise SpeculationRollbackError(
            f"branch {branch.branch_id} has {len(unconfirmed)} escaped effect(s) "
            f"without confirmed compensation: "
            f"{[(e.tool, e.entity_id) for e in unconfirmed]}. "
            f"Branch is PENDING_COMPENSATION, not ROLLED_BACK; do not release lock."
        )
    branch.state = BranchState.ROLLED_BACK


def fork_speculative(branches: list) -> None:
    """Refuse to fork branches whose write-sets intersect on any entity id."""
    seen: dict = {}
    for b in branches:
        for entity in b.write_set:
            if entity in seen:
                raise SpeculationRollbackError(
                    f"cannot fork speculatively: branches {seen[entity]} and "
                    f"{b.branch_id} both write entity {entity!r}; serialize or stage."
                )
            seen[entity] = b.branch_id


def arbitrate_and_rollback(branches: list, winner_id: str) -> None:
    """Select a winner and roll back losers. Losers that committed to the real
    world cannot be discarded; they must be compensated or the fork aborted."""
    for b in branches:
        if b.branch_id == winner_id:
            b.state = BranchState.COMMITTED
            continue
        if any(e.escaped_containment for e in b.effects):
            # Losing branch already acted on the shared world.
            mark_rolled_back(b)  # raises if compensation unconfirmed
        else:
            b.state = BranchState.ROLLED_BACK  # discard is safe


# --- Reproduce the incident ---
a = Branch("A", effects=[Effect("sub_77", "refund", terminal=False,
                                escaped_containment=True)],
           write_set={"sub_77"})
b = Branch("B", effects=[Effect("sub_77", "cancel", terminal=True,
                                escaped_containment=True)],
           write_set={"sub_77"})

fork_speculative([a, b])  # raises: intersecting write-set, must serialize
arbitrate_and_rollback([a, b], winner_id="B")  # would raise on A: PENDING_COMPENSATION
