# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-merge-a-speculative-branch-whose-tool-side-effects-were-already-committed-upstream.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-merge-a-speculative-branch-whose-tool-side-effects-were-already-committed-upstream.warrant.json
# Markdown SHA-256:   4573db48fb7b2d43bd4a4f958197ad2830b62ff17bfeb1fde65d5df70b001781
# Code AST SHA-256:   307f73ce332ccbec1fe88a8aec66ad6c28e61230aaf65dd0eaa49a75ce547036
# Verified Classes:   PhantomCommitError, EffectLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class PhantomCommitError(RuntimeError):
    """Raised when a merge would orphan an un-reverted external effect
    from a discarded speculative branch."""
    pass


@dataclass
class EffectLedger:
    # branch_id -> set of committed external effect ids not yet compensated
    committed: Dict[str, Set[str]] = field(default_factory=dict)
    # branch_id -> set of effect ids whose compensation is confirmed
    compensated: Dict[str, Set[str]] = field(default_factory=dict)

    def record_commit(self, branch_id: str, effect_id: str) -> None:
        self.committed.setdefault(branch_id, set()).add(effect_id)

    def record_compensation(self, branch_id: str, effect_id: str) -> None:
        # Only a CONFIRMED compensation clears the effect.
        if effect_id not in self.committed.get(branch_id, set()):
            raise PhantomCommitError(
                f"compensation for unknown effect {effect_id} on {branch_id}"
            )
        self.committed[branch_id].discard(effect_id)
        self.compensated.setdefault(branch_id, set()).add(effect_id)

    def residue(self, branch_id: str) -> Set[str]:
        return set(self.committed.get(branch_id, set()))


def commit_merge(
    winner: str,
    losers: list[str],
    ledger: EffectLedger,
    compensate,  # callable(branch_id, effect_id) -> bool (True if confirmed)
) -> None:
    # Gate: no loser may carry un-reverted committed effects.
    for loser in losers:
        pending = ledger.residue(loser)
        if pending:
            # Attempt compensation; only clear on confirmation.
            for effect_id in list(pending):
                confirmed = compensate(loser, effect_id)
                if not confirmed:
                    raise PhantomCommitError(
                        f"cannot merge: branch {loser} holds un-reverted "
                        f"effect {effect_id}; compensation unconfirmed"
                    )
                ledger.record_compensation(loser, effect_id)

    # Re-check after compensation: residue must be empty for every loser.
    for loser in losers:
        if ledger.residue(loser):
            raise PhantomCommitError(
                f"merge blocked: branch {loser} still holds effects "
                f"{sorted(ledger.residue(loser))}"
            )

    # Winner's committed effects are adopted into the canonical graph,
    # NOT compensated. Losers' effects are now all cleared.
    return None
