# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-fan-out-from-committing-orphaned-side-effects-when-a-verifier-branch-wins-after-a-sibling-branch-already-mutated.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-fan-out-from-committing-orphaned-side-effects-when-a-verifier-branch-wins-after-a-sibling-branch-already-mutated.warrant.json
# Markdown SHA-256:   f1f1c2b1971673b7a2947d7486db4394066fbf7dec0d47716f14c4a08642b28e
# Code AST SHA-256:   4b78b414788c0ff2889b5ad04702fb516a9ffc20555cb8e3f32f85341273fb91
# Verified Classes:   UncompensatedBranchEffect, BranchEffect
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UncompensatedBranchEffect(RuntimeError):
    """Raised when a losing speculative branch committed a world effect
    whose inverse was never registered or never applied before barrier release."""
    pass


class BranchEffect:
    def __init__(self, branch_id: str, tool: str, inverse_call):
        self.branch_id = branch_id
        self.tool = tool
        self.inverse_call = inverse_call


def release_fanout_barrier(winner_id: str, branches: dict, compensation_log: dict) -> list:
    """Reconcile winner commit set and loser compensations into one durable record.

    `branches[branch_id]` = {"effects": [BranchEffect, ...], "state": dict}
    `compensation_log[branch_id]` = list of registered inverse callables
    Returns the list of compensation results actually applied.
    """
    applied = []
    for branch_id, branch in branches.items():
        if branch_id == winner_id:
            continue  # winner's effects stand; its own inverses are not fired
        effects = branch.get("effects", [])
        registered = compensation_log.get(branch_id, [])
        if len(effects) != len(registered):
            # A loser mutated the world without a registered inverse.
            raise UncompensatedBranchEffect(
                f"branch {branch_id} produced {len(effects)} effect(s) but only "
                f"{len(registered)} compensation(s) were registered before barrier release"
            )
        for effect, inverse in zip(effects, registered):
            try:
                inverse()
                applied.append((branch_id, effect.tool, "compensated"))
            except Exception as exc:
                # Compensation itself failed: halt, do not silently continue.
                raise UncompensatedBranchEffect(
                    f"compensation for branch {branch_id} tool {effect.tool} failed: {exc}"
                ) from exc
    return applied
