# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-speculative-branch-merges-as-side-effect-reconciliation-not-state-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-speculative-branch-merges-as-side-effect-reconciliation-not-state-reconciliation.warrant.json
# Markdown SHA-256:   16d826f978992401a29c4a522b29cf02169cb51a8932b817e073a1701148173a
# Code AST SHA-256:   7c940a1fe5580be1bada4d46918092ce1cf6364cc076bec522a363f15640b274
# Verified Classes:   SpeculativeMergeEffectDivergence
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SpeculativeMergeEffectDivergence(RuntimeError):
    """Raised when a speculative branch merge would discard committed external effects."""
    pass


def merge_speculative_branches(branches, winner_id):
    """
    branches: list of dicts, each with:
        id, score, ledger (list of {tool, resource_id, committed: bool, status: str})
    winner_id: id of the selected branch

    Invariant: the merged state's belief about external effects must be a
    superset of effects actually committed across ALL branches. Never a subset.
    """
    winner = next((b for b in branches if b["id"] == winner_id), None)
    if winner is None:
        raise SpeculativeMergeEffectDivergence(f"winner {winner_id} not among branches")

    committed_effects = set()
    unknown_effects = set()
    for b in branches:
        for entry in b.get("ledger", []):
            key = (entry["tool"], entry["resource_id"])
            if entry.get("status") == "effect_unknown":
                unknown_effects.add(key)
            elif entry.get("committed"):
                committed_effects.add(key)

    # A crashed/timed-out branch is effect-unknown, not effect-free.
    if unknown_effects:
        raise SpeculativeMergeEffectDivergence(
            f"cannot merge: {len(unknown_effects)} effect-unknown entries require "
            f"external read-back before reconciliation: {sorted(unknown_effects)}"
        )

    winner_effects = {
        (e["tool"], e["resource_id"])
        for e in winner.get("ledger", [])
        if e.get("committed")
    }

    # Effects committed by losers that the winner's plan does not account for
    # would be silently erased by a state-only merge.
    orphaned = committed_effects - winner_effects
    if orphaned:
        raise SpeculativeMergeEffectDivergence(
            f"merge would discard {len(orphaned)} committed effects from losing "
            f"branches: {sorted(orphaned)}; compensate or surface as conflict "
            f"before proceeding"
        )

    # Safe: every committed effect is represented in the winner's reconciled view.
    return {
        "winner": winner_id,
        "reconciled_effects": sorted(committed_effects),
        "merge_kind": "effect_reconciled",
    }
