# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branches-when-a-rollback-crosses-a-side-effecting-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branches-when-a-rollback-crosses-a-side-effecting-tool-call.warrant.json
# Markdown SHA-256:   8668dda5afdedf2265e2457ee49e6614b1602fa0b9b584792ebb1cc465ff91a0
# Code AST SHA-256:   2fb45724d15b120b3ca4dff03c12633ba47973cf99fd523622a128d9bf2cef2f
# Verified Classes:   EffectFenceViolation, Plane, EffectRecord, Branch, SpeculativeOrchestrator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EffectFenceViolation(RuntimeError):
    """Raised when a speculative branch crosses a side-effecting call
    without holding the commit token, or when reconciliation finds an
    orphaned effect with no surviving journal record."""
    pass


class Plane(Enum):
    COGNITIVE = "cognitive"   # rewinds cleanly
    EFFECT = "effect"         # does not rewind; needs compensation


@dataclass
class EffectRecord:
    branch_id: str
    effect_id: str
    compensator: Optional[str]   # None => irreversible, must not speculate
    committed: bool = False


@dataclass
class Branch:
    branch_id: str
    holds_commit_token: bool = False
    context: dict = field(default_factory=dict)
    effects: list = field(default_factory=list)


class SpeculativeOrchestrator:
    def __init__(self):
        # Effect journal lives on the EFFECT plane: outlives branch context.
        self.effect_journal: list[EffectRecord] = []
        self.compensation_log: list[str] = []

    def call_tool(self, branch: Branch, effect_id: str,
                  compensator: Optional[str], effect_bearing: bool) -> None:
        if not effect_bearing:
            # Pure call: safe to execute under speculation.
            branch.context[f"pure:{effect_id}"] = True
            return

        if not branch.holds_commit_token:
            # Guardrail: block at the fence, stage intent, do not mutate world.
            raise EffectFenceViolation(
                f"branch {branch.branch_id} attempted effect '{effect_id}' "
                f"without commit token; must stage and wait"
            )
        if compensator is None:
            raise EffectFenceViolation(
                f"effect '{effect_id}' has no compensator; not speculatable"
            )

        # Record BEFORE the world mutation so a crash cannot orphan it.
        rec = EffectRecord(branch.branch_id, effect_id, compensator, committed=True)
        self.effect_journal.append(rec)
        branch.effects.append(effect_id)
        # ... world mutation happens here ...

    def reconcile(self, winner_id: str) -> None:
        # 1. Enumerate effects from ALL branches, including losers whose
        #    context is about to be discarded.
        losers = {r.branch_id for r in self.effect_journal} - {winner_id}

        # 2. Compensate orphans in reverse causal order BEFORE ledger flip.
        for rec in reversed(self.effect_journal):
            if rec.branch_id in losers and rec.committed:
                if rec.compensator is None:
                    raise EffectFenceViolation(
                        f"orphaned irreversible effect {rec.effect_id} "
                        f"from branch {rec.branch_id}; manual reconciliation required"
                    )
                self.compensation_log.append(rec.compensator)

        # 3. Only now is it safe to mark losers rolled back.
        for rec in self.effect_journal:
            if rec.branch_id in losers:
                rec.committed = False


def run_speculation(orch: SpeculativeOrchestrator, loser: Branch,
                    winner: Branch) -> None:
    # Loser tries to provision before winning: must be blocked.
    try:
        orch.call_tool(loser, "provision_resource:42", "delete_resource:42",
                       effect_bearing=True)
    except EffectFenceViolation:
        pass  # correctly fenced; no orphan created

    winner.holds_commit_token = True
    orch.call_tool(winner, "provision_resource:42", "delete_resource:42",
                   effect_bearing=True)
    orch.reconcile(winner_id=winner.branch_id)

    # Invariant check: no effect record may reference a discarded branch
    # with committed=True and no compensation entry.
    for rec in orch.effect_journal:
        if rec.committed and rec.branch_id != winner.branch_id:
            raise EffectFenceViolation(
                f"invariant broken: orphaned committed effect {rec.effect_id}"
            )
