# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-parallel-agent-branches-from-committing-divergent-side-effects-after-a-winner-take-all-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-parallel-agent-branches-from-committing-divergent-side-effects-after-a-winner-take-all-rollback.warrant.json
# Markdown SHA-256:   0d39433d418dc7f278c142dae7ef55d2f167657738b9ae8949ff26db84b05193
# Code AST SHA-256:   2299816126a362f796831a5780a9c14282ecef60feb0497ef0a97e14b8950e6d
# Verified Classes:   EffectHorizonViolation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class EffectHorizonViolation(RuntimeError):
    """Raised when a losing speculative branch has crossed the effect horizon
    (emitted a non-invertible or non-idempotent effect) before the winner-take-all
    commit decision. Compensation cannot restore the pre-commit world; the commit
    must be refused, not repaired."""
    pass


def commit_winner(branches, winner_id, effect_ledger):
    """
    branches: dict[branch_id -> BranchState]
    effect_ledger: dict[branch_id -> list[Effect]]  (effects actually emitted,
                   not the intent log)
    Returns the committed effect set iff the effect-horizon invariant holds.
    """
    winner = branches[winner_id]
    committed = list(effect_ledger.get(winner_id, []))

    for bid, state in branches.items():
        if bid == winner_id:
            continue
        for effect in effect_ledger.get(bid, []):
            if not (effect.invertible and effect.idempotent_under_replay):
                raise EffectHorizonViolation(
                    f"loser branch {bid} crossed effect horizon before commit: "
                    f"effect={effect.kind!r} invertible={effect.invertible} "
                    f"idempotent={effect.idempotent_under_replay}. "
                    f"Winner {winner_id} cannot be committed without residue. "
                    f"Refuse commit; escalate to staging or serialization."
                )
        # Loser effects are all safe; they may be compensated, but note that
        # compensation is itself an effect and must be recorded in the ledger.
        committed.extend(_compensate(bid, effect_ledger.get(bid, [])))

    return committed


def _compensate(branch_id, effects):
    # Only reached when every effect in the branch is invertible+idempotent.
    # Returns the compensation effects (recorded, not silently dropped).
    return [e.inverse() for e in reversed(effects)]
