# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-poisoned-branch-state-during-speculative-parallel-execution-with-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-poisoned-branch-state-during-speculative-parallel-execution-with-rollback.warrant.json
# Markdown SHA-256:   a7825271da218f1bbaf214fb45faa482b292529d5ba11b44e6dbaa7987dbe959
# Code AST SHA-256:   c415910208425f4a927484e57bc59a5cde82d5f2f02c04432a88c0effabe3446
# Verified Classes:   RollbackLeakError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class RollbackLeakError(RuntimeError):
    """Raised when a losing speculative branch's side effects survive rollback
    and contaminate the world state consumed by the committed branch."""
    pass


def commit_speculative_winner(
    pre_fork_checkpoint: dict,      # resource_id -> monotonic version token
    branch_journals: dict,          # branch_id -> list[Effect]
    winner_id: str,
    quiescence_confirmed: dict,     # branch_id -> bool
) -> None:
    # 1. Every losing branch must have positively confirmed quiescence.
    for bid, confirmed in quiescence_confirmed.items():
        if bid == winner_id:
            continue
        if not confirmed:
            raise RollbackLeakError(
                f"branch {bid} did not confirm quiescence before commit; "
                f"in-flight effects may still land after rollback"
            )

    # 2. No losing branch may have advanced any resource past the pre-fork token.
    for bid, journal in branch_journals.items():
        if bid == winner_id:
            continue
        for effect in journal:
            base = pre_fork_checkpoint.get(effect.resource_id)
            if base is None:
                raise RollbackLeakError(
                    f"branch {bid} wrote to untracked resource "
                    f"{effect.resource_id}; speculation was not authorized"
                )
            if effect.version_token > base:
                raise RollbackLeakError(
                    f"rollback leak: branch {bid} advanced "
                    f"{effect.resource_id} from {base} to {effect.version_token} "
                    f"before rollback; committed state would be contaminated"
                )

    # 3. Winner's journal must be the sole source of post-fork state.
    winner_effects = branch_journals.get(winner_id, [])
    for effect in winner_effects:
        base = pre_fork_checkpoint.get(effect.resource_id)
        if base is None:
            raise RollbackLeakError(
                f"winner {winner_id} wrote to untracked resource "
                f"{effect.resource_id}; cannot certify reachability"
            )

    # 4. Apply winner effects to canonical world (outside this function's scope).
    apply_effects(winner_effects)
