# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-reconcile-sibling-branches-after-a-speculative-fork-has-already-emitted-irreversible-external-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-reconcile-sibling-branches-after-a-speculative-fork-has-already-emitted-irreversible-external-side-effect.warrant.json
# Markdown SHA-256:   55c34bdb65f23e54f6cc5819e5e2c21dbc0fa52b898fb944ef38b5485ef21160
# Code AST SHA-256:   9c55d5f65facd841a58c4fce91d4c96daa90d58ea62925db4cfb871639fda550
# Verified Classes:   ReconciliationError, EffectClass, EmittedCall, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ReconciliationError(RuntimeError):
    """Raised when a merge would discard a branch that already crossed the side-effect boundary."""


class EffectClass(Enum):
    READ_ONLY = "read_only"
    IDEMPOTENT = "idempotent"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


@dataclass
class EmittedCall:
    tool: str
    effect: EffectClass
    compensation_key: Optional[str] = None


@dataclass
class Branch:
    branch_id: str
    score: float = 0.0
    ledger: list[EmittedCall] = field(default_factory=list)

    def emit(self, call: EmittedCall) -> None:
        # Recorded at emission time, not plan time. This is the whole point.
        self.ledger.append(call)

    def crossed_boundary(self) -> bool:
        return any(
            c.effect in (EffectClass.IRREVERSIBLE,)
            or (c.effect == EffectClass.COMPENSABLE and c.compensation_key is None)
            for c in self.ledger
        )


def reconcile(branches: list[Branch], keep_id: str) -> list[Branch]:
    """
    Discard all non-winning branches. Refuses if any discard candidate
    has crossed the side-effect boundary.
    """
    winner = next((b for b in branches if b.branch_id == keep_id), None)
    if winner is None:
        raise ReconciliationError(f"keep_id {keep_id!r} not among branches")

    discard_candidates = [b for b in branches if b.branch_id != keep_id]

    for b in discard_candidates:
        if b.crossed_boundary():
            irreversible = [c.tool for c in b.ledger if c.effect == EffectClass.IRREVERSIBLE]
            raise ReconciliationError(
                f"refusing to discard branch {b.branch_id!r}: it emitted "
                f"irreversible effects {irreversible}. Promote to committed and "
                f"compensate before merge; do not roll back local state only."
            )

    # Safe: every discarded branch stayed inside the compensation set.
    return [winner]


# --- reproduction of the observed failure, now bounded ---
if __name__ == "__main__":
    a = Branch("branch_A")
    b = Branch("branch_B")
    c = Branch("branch_C", score=0.91)

    a.emit(EmittedCall("send_invoice", EffectClass.IRREVERSIBLE))
    b.emit(EmittedCall("send_invoice", EffectClass.IRREVERSIBLE))
    c.emit(EmittedCall("query_billing", EffectClass.READ_ONLY))

    try:
        merged = reconcile([a, b, c], keep_id="branch_C")
    except ReconciliationError as e:
        # Correct behavior: halt loudly instead of silently diverging from the world.
        print(f"merge halted: {e}")
        # Follow-up: merged agent must be told these invoices exist and compensate them.
