# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-merge-a-speculative-branch-after-an-optimistic-tool-side-effect-has-already-escaped-the-sandbox.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-merge-a-speculative-branch-after-an-optimistic-tool-side-effect-has-already-escaped-the-sandbox.warrant.json
# Markdown SHA-256:   819ca3939aedd9171de55cf00963a0bf62442f8a1ac1239fd437decac24d4657
# Code AST SHA-256:   dc317648ba6182d0ef779352b5f941b3eccfd3937f46197ba89f854c55c7e145
# Verified Classes:   MergeRefusedError, EffectState, EffectEntry, Branch, Orchestrator
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class MergeRefusedError(RuntimeError):
    """Raised when a speculative merge would orphan an escaped, uncompensated effect."""
    pass


class EffectState(Enum):
    BUFFERED = "buffered"        # never left the sandbox; safe to drop
    ESCAPED = "escaped"          # reached an external surface
    COMPENSATED = "compensated"  # reversal confirmed by external read-back


@dataclass
class EffectEntry:
    branch_id: str
    tool: str
    idempotency_key: str
    external_id: str | None
    state: EffectState


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


@dataclass
class Orchestrator:
    branches: Dict[str, Branch] = field(default_factory=dict)

    def record_effect(self, entry: EffectEntry) -> None:
        # Journal write MUST happen before the result is consumed by reasoning.
        self.branches[entry.branch_id].effects.append(entry)

    def refuse_if_orphaned(self, winner_id: str) -> None:
        orphans: List[EffectEntry] = []
        for bid, branch in self.branches.items():
            if bid == winner_id:
                continue
            for e in branch.effects:
                if e.state is EffectState.ESCAPED:
                    orphans.append(e)
        if orphans:
            detail = ", ".join(
                f"{e.branch_id}:{e.tool}:{e.external_id}" for e in orphans
            )
            raise MergeRefusedError(
                f"refusing merge of {winner_id}: {len(orphans)} escaped, "
                f"uncompensated effect(s) from discarded branches -> {detail}; "
                f"enter reconciliation_required"
            )

    def merge(self, winner_id: str) -> str:
        self.refuse_if_orphaned(winner_id)
        return f"committed:{winner_id}"


# --- trace of the observed failure ---
orch = Orchestrator()
orch.branches["A"] = Branch("A")
orch.branches["B"] = Branch("B")

# Branch A optimistically issues a refund before the merge decision.
orch.record_effect(EffectEntry(
    branch_id="A", tool="payments.refund",
    idempotency_key="A-7f3c", external_id="re_8821",
    state=EffectState.ESCAPED,
))
# Branch B, the eventual winner, issues its own refund with a different key.
orch.record_effect(EffectEntry(
    branch_id="B", tool="payments.refund",
    idempotency_key="B-11a0", external_id="re_8822",
    state=EffectState.ESCAPED,
))

# Without the guard this would return "committed:B" and orphan re_8821.
try:
    orch.merge("B")
except MergeRefusedError as exc:
    print(f"HALT: {exc}")
    # -> HALT: refusing merge of B: 1 escaped, uncompensated effect(s)
    #    from discarded branches -> A:payments.refund:re_8821;
    #    enter reconciliation_required
