# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-speculative-branch-merges-after-rollback-when-side-effects-cross-the-reconciliation-barrier.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-speculative-branch-merges-after-rollback-when-side-effects-cross-the-reconciliation-barrier.warrant.json
# Markdown SHA-256:   95da875183f756561cbd766e88eafe44cfee92d7b67c11d1b3beaa6870ad38f1
# Code AST SHA-256:   b609c920aa4fe409b8b7bfbac0c235f821714fcf6117b12ae3c45bc145f6e794
# Verified Classes:   EffectClass, Effect, Branch, ReconciliationBarrierError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class EffectClass(Enum):
    IDEMPOTENT_VERIFIED = "idempotent_verified"
    IDEMPOTENT_ASSUMED = "idempotent_assumed"
    IRREVERSIBLE = "irreversible"


@dataclass(frozen=True)
class Effect:
    branch_id: str
    dedup_key: str
    effect_class: EffectClass
    origin_tag_intact: bool


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


class ReconciliationBarrierError(RuntimeError):
    """Raised when a speculative merge would cross the reconciliation barrier."""


def _is_safe_to_merge(branches: Iterable[Branch], shared_state_touched: bool) -> tuple[bool, str]:
    branches = list(branches)
    selected = [b for b in branches if b.selected]
    if len(selected) != 1:
        return False, f"expected exactly one selected branch, got {len(selected)}"

    sel = selected[0]
    sel_keys = {e.dedup_key for e in sel.effects}

    for b in branches:
        if b.selected:
            continue
        for e in b.effects:
            if not e.origin_tag_intact:
                return False, (
                    f"rolled-back branch {b.branch_id} emitted effect {e.dedup_key} "
                    f"with lost origin tag; cannot prove it is excluded from merge"
                )
            if e.effect_class is EffectClass.IRREVERSIBLE:
                return False, (
                    f"rolled-back branch {b.branch_id} emitted irreversible effect "
                    f"{e.dedup_key}; merge would re-include an un-undoable side effect"
                )
            if e.effect_class is EffectClass.IDEMPOTENT_ASSUMED and e.dedup_key not in sel_keys:
                return False, (
                    f"rolled-back branch {b.branch_id} emitted effect {e.dedup_key} "
                    f"whose idempotency is only assumed, not verified; refusing merge"
                )

    if shared_state_touched:
        return False, "shared mutable state was touched during speculation; merge output may depend on rolled-back effects"

    return True, "merge permitted"


def reconcile(branches: Iterable[Branch], shared_state_touched: bool = False) -> Branch:
    ok, reason = _is_safe_to_merge(branches, shared_state_touched)
    if not ok:
        raise ReconciliationBarrierError(reason)
    return next(b for b in branches if b.selected)


if __name__ == "__main__":
    # Contaminated case: rolled-back branch emitted an irreversible transfer.
    bad = [
        Branch("A", True, [Effect("A", "txn-1", EffectClass.IDEMPOTENT_VERIFIED, True)]),
        Branch("B", False, [Effect("B", "txn-1", EffectClass.IRREVERSIBLE, True)]),
    ]
    try:
        reconcile(bad)
    except ReconciliationBarrierError as exc:
        print(f"refused: {exc}")
