# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-execution-from-committing-divergent-state-in-parallel-agent-orchestration.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-execution-from-committing-divergent-state-in-parallel-agent-orchestration.warrant.json
# Markdown SHA-256:   ebededb956c7ee0307bbf9989e761034f5db2cf02da2a41c3622052b358cf23f
# Code AST SHA-256:   0f4524d52f90eaeebf7c9d032eca7c8345f4f92161de47f0e6cb9f135365bbec
# Verified Classes:   SpeculationCommitViolation, Frontier
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SpeculationCommitViolation(RuntimeError):
    """Raised when a speculative branch attempts to externalize an effect
    before promotion, or when promotion would violate frontier monotonicity."""
    pass


class Frontier:
    def __init__(self):
        self._promoted = None  # linearization token of the winning branch

    def promote(self, branch_token, staged_effects, read_provenance):
        # Invariant 3: branch may only have read state from its own fork lineage.
        if any(p != branch_token for p in read_provenance):
            raise SpeculationCommitViolation(
                f"branch {branch_token} read state from foreign provenance "
                f"{set(read_provenance) - {branch_token}}"
            )
        # Invariant 2: frontier is monotone; re-validate against prior promotion.
        if self._promoted is not None and self._promoted != branch_token:
            raise SpeculationCommitViolation(
                f"frontier already promoted to {self._promoted}; "
                f"cannot promote {branch_token} against a stale frontier"
            )
        # Invariant 1: every staged effect must carry this branch's token.
        for effect in staged_effects:
            if effect.token != branch_token:
                raise SpeculationCommitViolation(
                    f"effect {effect.id} carries token {effect.token}, "
                    f"not branch token {branch_token}"
                )
        self._promoted = branch_token
        return [e.externalize() for e in staged_effects]


def commit_winner(frontier, branch_token, staged_effects, read_provenance):
    if not staged_effects and frontier._promoted is not None:
        # A no-op branch promoting after a real commit is a divergence signal.
        raise SpeculationCommitViolation(
            f"empty branch {branch_token} attempted promotion after "
            f"{frontier._promoted} already committed"
        )
    return frontier.promote(branch_token, staged_effects, read_provenance)
