# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-merges-when-rollback-of-a-losing-plan-leaves-orphaned-side-effects-in-shared-tool-state.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-merges-when-rollback-of-a-losing-plan-leaves-orphaned-side-effects-in-shared-tool-state.warrant.json
# Markdown SHA-256:   02ac1678bbc012899ee2b30784ae28468f7803a866fed5d1548acd02fd10ea56
# Code AST SHA-256:   8242b854374c517c3067e24e1ff7d5d6c0ca2281b30ebab284658a077459e21b
# Verified Classes:   UncompensableSpeculativeEffect, BranchState, EffectRecord, Branch, SpeculativeMergeGuard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class UncompensableSpeculativeEffect(RuntimeError):
    """Raised when a branch emits a side effect that cannot be rolled back
    before the merge election has resolved."""


class BranchState(Enum):
    SPECULATIVE = "speculative"
    WINNER = "winner"
    ROLLED_BACK = "rolled_back"


@dataclass
class EffectRecord:
    branch_id: str
    step_id: str
    tool: str
    idempotency_key: str
    compensator: Callable[[], None] | None
    irreversible: bool


@dataclass
class Branch:
    branch_id: str
    state: BranchState = BranchState.SPECULATIVE
    effects: list[EffectRecord] = field(default_factory=list)


class SpeculativeMergeGuard:
    def __init__(self) -> None:
        self.branches: dict[str, Branch] = {}
        self._outbox: dict[str, list[EffectRecord]] = {}

    def register_branch(self, branch_id: str) -> Branch:
        b = Branch(branch_id)
        self.branches[branch_id] = b
        self._outbox[branch_id] = []
        return b

    def emit(
        self,
        branch_id: str,
        step_id: str,
        tool: str,
        compensator: Callable[[], None] | None,
        irreversible: bool,
        apply: Callable[[], None],
    ) -> None:
        branch = self.branches[branch_id]
        if branch.state is not BranchState.SPECULATIVE:
            raise UncompensableSpeculativeEffect(
                f"branch {branch_id} is {branch.state.value}; cannot emit {tool}"
            )
        key = f"{branch_id}:{step_id}:{tool}"
        rec = EffectRecord(branch_id, step_id, tool, key, compensator, irreversible)

        # INVARIANT: irreversible effects must not execute pre-merge.
        if irreversible:
            self._outbox[branch_id].append(rec)
            branch.effects.append(rec)
            return

        if compensator is None:
            raise UncompensableSpeculativeEffect(
                f"effect {tool} on {branch_id} has no compensator and is not "
                f"marked irreversible; refusing speculative emission"
            )
        apply()
        branch.effects.append(rec)

    def elect(self, winner_id: str) -> list[EffectRecord]:
        """Mark winner, roll back losers, flush winner outbox only."""
        for bid, branch in self.branches.items():
            if bid == winner_id:
                branch.state = BranchState.WINNER
            elif branch.state is BranchState.SPECULATIVE:
                branch.state = BranchState.ROLLED_BACK
                for rec in branch.effects:
                    if rec.compensator is not None:
                        rec.compensator()
                # Loser outbox is discarded, never flushed.
                self._outbox[bid].clear()

        flushed: list[EffectRecord] = []
        for rec in self._outbox[winner_id]:
            # Winner's guarded irreversible effects execute now, post-merge.
            flushed.append(rec)
        self._outbox[winner_id].clear()
        return flushed

    def reconciler_view(self) -> dict[str, list[EffectRecord]]:
        """Feed this to the reconciler instead of raw tool state, so it can
        distinguish loser-rollback residue from winner anomalies."""
        return {
            bid: [r for r in b.effects if b.state is not BranchState.ROLLED_BACK]
            for bid, b in self.branches.items()
        }
