# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-divergent-speculative-branches-whose-merge-is-contaminated-by-non-idempotent-side-effects-already-committed-by-a-sibling-b.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-divergent-speculative-branches-whose-merge-is-contaminated-by-non-idempotent-side-effects-already-committed-by-a-sibling-b.warrant.json
# Markdown SHA-256:   407368beaf75833cb9bd40a8e9035413b09e5610c85731d35c6404bacf531987
# Code AST SHA-256:   b269b00bc91630bb6aeff43d0c5ef54d63ab20b22d1c00b936fbf316f7d51b76
# Verified Classes:   EffectClass, EffectDivergenceError, EffectRecord, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    PURE = "pure"
    COMPENSABLE = "compensable"
    NON_COMPENSABLE = "non_compensable"


class EffectDivergenceError(RuntimeError):
    """Raised when a merge would proceed on a world state contaminated by
    effects committed by a discarded sibling branch."""
    pass


@dataclass
class EffectRecord:
    branch_id: str
    effect_seq: int
    idempotency_key: str
    effect_class: EffectClass
    inverse_ref: str | None = None
    compensated: bool = False


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


def reconcile_effects(branches: Dict[str, Branch], winner_id: str) -> Set[str]:
    """Return the set of idempotency keys the winner must cover."""
    winner_keys = {e.idempotency_key for e in branches[winner_id].effects}
    orphan_keys: Set[str] = set()
    for bid, branch in branches.items():
        if bid == winner_id:
            continue
        for eff in branch.effects:
            if eff.compensated:
                continue
            if eff.idempotency_key not in winner_keys:
                orphan_keys.add(eff.idempotency_key)
    return orphan_keys


def merge_branches(branches: Dict[str, Branch], winner_id: str) -> None:
    if winner_id not in branches:
        raise EffectDivergenceError(f"winner {winner_id!r} not among branches")

    orphans = reconcile_effects(branches, winner_id)
    if orphans:
        # Attempt compensation is the caller's job; here we refuse to merge.
        raise EffectDivergenceError(
            f"merge of {winner_id!r} rejected: {len(orphans)} orphan effect(s) "
            f"committed by discarded siblings: {sorted(orphans)}"
        )

    # Safe: winner's effect set subsumes all sibling effects (or they were
    # compensated). Only now may the winner's context be merged.
    _commit_merge(branches[winner_id])


def _commit_merge(winner: Branch) -> None:
    # Placeholder for context merge; effects already reconciled.
    return None
