# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-winner-s-commit-invalidates-a-sibling-branch-s-already-applied-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-winner-s-commit-invalidates-a-sibling-branch-s-already-applied-side-effects.warrant.json
# Markdown SHA-256:   626049a11e42570001c9358e680b9ab92eaf24c74e07938b9195f5a7d85f4ce8
# Code AST SHA-256:   9fda1e807be95681bc0b5f4eba6a4b3da0712dccd64a98c7bd5c49de0372ae56
# Verified Classes:   SpeculativeCommitContamination, Effect, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class SpeculativeCommitContamination(RuntimeError):
    """Raised when losers' side effects leaked past a winner-take-all commit."""
    pass


@dataclass
class Effect:
    branch_id: str
    intent: str          # semantic intent, branch-stable
    idempotency_key: str # must be derived from intent, NOT branch trace


@dataclass
class Branch:
    branch_id: str
    effects: list[Effect] = field(default_factory=list)
    score: float = 0.0


def intent_key(task_id: str, intent: str) -> str:
    # Branch-stable: identical intent across siblings collapses to one key.
    return hashlib.sha256(f"{task_id}::{intent}".encode()).hexdigest()


def commit_winner(task_id: str, branches: list[Branch],
                  external_effect_count: int) -> Branch:
    if not branches:
        raise SpeculativeCommitContamination("no branches to commit")

    winner = max(branches, key=lambda b: b.score)

    # Guardrail: every effect must carry an intent-stable key. A branch-local
    # key (e.g. trace hash) is the silent-failure trap.
    winner_keys = {e.idempotency_key for e in winner.effects}
    for b in branches:
        for e in b.effects:
            if e.idempotency_key != intent_key(task_id, e.intent):
                raise SpeculativeCommitContamination(
                    f"branch {b.branch_id} effect '{e.intent}' uses a "
                    f"branch-local key; cross-branch collapse is impossible"
                )

    # Post-commit reconciliation: the external system is the authority.
    if external_effect_count > len(winner_keys):
        leaked = external_effect_count - len(winner_keys)
        raise SpeculativeCommitContamination(
            f"commit contaminated: {leaked} leaked loser effect(s); "
            f"winner={winner.branch_id}, expected={len(winner_keys)}, "
            f"observed={external_effect_count}; compensate before reporting done"
        )
    return winner
