# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-speculative-branches-when-a-multi-agent-rollback-fires-after-side-effects-have-already-been-committed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-speculative-branches-when-a-multi-agent-rollback-fires-after-side-effects-have-already-been-committed.warrant.json
# Markdown SHA-256:   ed1765c89892a4957f8ceceff2a57fb54a80544ee6c8ac462875f1eb177162af
# Code AST SHA-256:   07a29e3c98155792773e7a501b1d724adb93d4cbf1a7f5d94c4995ad393046af
# Verified Classes:   OrphanedEffectError, BranchOutcome, Effect, Branch, SpeculativeReconciler
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class OrphanedEffectError(RuntimeError):
    """Raised when a rolled-back or non-winning branch left uncompensated side effects."""
    pass


class BranchOutcome(Enum):
    COMMITTED = "committed"
    SCORE_LOSS = "score_loss"
    TIE_BREAK_LOSS = "tie_break_loss"
    TIMEOUT = "timeout"
    VERIFIER_REJECTED = "verifier_rejected"


@dataclass
class Effect:
    branch_id: str
    seq: int
    tool: str
    args: dict
    compensated: bool = False

    @property
    def token(self) -> str:
        return f"{self.branch_id}:{self.seq}"


@dataclass
class Branch:
    branch_id: str
    effects: List[Effect] = field(default_factory=list)


class SpeculativeReconciler:
    """Reconciles speculative fan-out with branch-attributable effect ledger."""

    def __init__(self):
        self.ledger: Dict[str, Effect] = {}
        self.branches: Dict[str, Branch] = {}
        self.committed: Optional[str] = None

    def record_effect(self, branch_id: str, tool: str, args: dict) -> Effect:
        branch = self.branches.setdefault(branch_id, Branch(branch_id))
        # Ledger write happens BEFORE tool execution returns; here we model
        # the pre-execution record. Real impl writes then calls tool.
        eff = Effect(branch_id=branch_id, seq=len(branch.effects), tool=tool, args=args)
        self.ledger[eff.token] = eff
        branch.effects.append(eff)
        return eff

    def finalize_branch(self, branch_id: str, outcome: BranchOutcome) -> None:
        # CRITICAL: every terminal non-winning outcome routes here.
        # The observed failure was a missing edge (TIE_BREAK_LOSS skipped this).
        if outcome is BranchOutcome.COMMITTED:
            self.committed = branch_id
            return
        branch = self.branches.get(branch_id)
        if branch is None:
            return
        for eff in branch.effects:
            self._compensate(eff)

    def _compensate(self, eff: Effect) -> None:
        # Compensation runs while branch context still exists (before discard).
        eff.compensated = True

    def assert_no_orphans(self) -> None:
        orphans = [
            e for e in self.ledger.values()
            if not e.compensated and e.branch_id != self.committed
        ]
        if orphans:
            raise OrphanedEffectError(
                f"{len(orphans)} orphaned effect(s) from non-committed branches: "
                f"{[e.token for e in orphans]}"
            )

    def reconcile(self, outcomes: Dict[str, BranchOutcome]) -> None:
        for bid, outcome in outcomes.items():
            self.finalize_branch(bid, outcome)
        # Halt commit if any orphan survives — committed state would be
        # inconsistent with the branch that produced it.
        self.assert_no_orphans()
        # Only now is it safe to discard branch contexts.
        for bid in outcomes:
            self.branches.pop(bid, None)


# Demonstrate the failure the invariant catches:
def demo_missing_edge():
    r = SpeculativeReconciler()
    r.record_effect("A", "reserve_slot", {"slot_id": 42})
    r.record_effect("B", "reserve_slot", {"slot_id": 42})
    r.record_effect("C", "reserve_slot", {"slot_id": 42})
    # Buggy path: C loses on tie-break but finalize_branch is NOT called for it.
    r.finalize_branch("A", BranchOutcome.COMMITTED)
    r.finalize_branch("B", BranchOutcome.SCORE_LOSS)
    # C never finalized -> orphan. assert_no_orphans must fire.
    r.assert_no_orphans()  # raises OrphanedEffectError for C


if __name__ == "__main__":
    demo_missing_edge()
