# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-parallel-agent-plans-from-committing-side-effects-that-a-later-rollback-cannot-undo.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-parallel-agent-plans-from-committing-side-effects-that-a-later-rollback-cannot-undo.warrant.json
# Markdown SHA-256:   f89b1efe66e2b97fdc1123399a9c8943f185d938062d5b2b60998d28def8cf4c
# Code AST SHA-256:   ff5a244cddc449e16321474772d8d9852b228ab2dec9392ff730b3876d195000
# Verified Classes:   UnsafeSpeculativeCommit
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnsafeSpeculativeCommit(RuntimeError):
    """Raised when a speculative branch attempts an effect that rollback cannot bound."""
    pass


NON_COMPENSABLE = {"send_email", "charge_card", "page_oncall", "create_ticket"}


def apply_winner(effect_set, tool_registry, committed):
    """Apply only the committed branch's effects, after the reconciliation barrier.

    Invariant: no effect reaches an external observer until `committed` is True,
    and every effect in the set must be fully applicable atomically.
    """
    if not committed:
        raise UnsafeSpeculativeCommit(
            "apply_winner called before reconciliation barrier committed"
        )
    for effect in effect_set:
        tool = effect["tool"]
        if tool in NON_COMPENSABLE and not effect.get("staged_intent"):
            # A non-compensable tool reached the barrier without being staged;
            # rollback cannot undo it, so we must refuse rather than guess.
            raise UnsafeSpeculativeCommit(
                f"non-compensable tool {tool!r} not expressed as staged intent; "
                "refusing to commit because rollback cannot bound this effect"
            )
        tool_registry.invoke(tool, effect["args"])
    return True


def reconcile(branches, winner_id):
    """Select a winner and discard losers' staged effects before any external call."""
    winner = next((b for b in branches if b.id == winner_id), None)
    if winner is None:
        raise UnsafeSpeculativeCommit(f"winner {winner_id!r} not among branches")
    for b in branches:
        if b.id != winner_id and b.has_applied_non_compensable_effect():
            # Loser already leaked an effect; rollback is no longer sufficient.
            raise UnsafeSpeculativeCommit(
                f"branch {b.id!r} applied a non-compensable effect before the "
                "barrier; reconciliation cannot restore consistency"
            )
    return winner.staged_effects
