# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-fan-out-from-corrupting-cross-org-agent-coalitions-when-the-fastest-replica-wins-the-baton.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-fan-out-from-corrupting-cross-org-agent-coalitions-when-the-fastest-replica-wins-the-baton.warrant.json
# Markdown SHA-256:   d0aa0cef9c024daf3f4c97ecb9f960a41c8f6f963790d5a1c9c77bd11476b239
# Code AST SHA-256:   4451485c8579a3dcbe44a980151249807a0f068d71e8a3a41a13e03c8bcef42c
# Verified Classes:   SpeculationScopeError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculationScopeError(RuntimeError):
    """Raised when a coalition step is scheduled for speculative fan-out
    despite having a union-scoped correctness predicate or immediate effects."""
    pass


def classify_and_dispatch(step, replicas, latency_budget_ms):
    # Hard gate: union-scoped predicates must not race.
    if step.context_scope == "union" and step.effect_mode == "immediate":
        raise SpeculationScopeError(
            f"step {step.id}: union-context predicate with per-replica effects "
            f"is not speculatable; serialize or redesign (latency_budget={latency_budget_ms}ms)"
        )

    if step.context_scope == "union":
        # Barrier-join: collect all replicas, then merge under union context.
        results = [r.execute() for r in replicas]
        winner = merge_union(results)
        winner.attest(consulted=union_of(r.context for r in replicas))
        return winner

    # Single-context, deferred effects: safe to race with fencing.
    generation = new_generation()
    for r in replicas:
        r.stage_effects(generation)
    winner = first_valid(replicas)
    if winner is None:
        raise SpeculationScopeError(
            f"step {step.id}: no replica produced a valid response within budget"
        )
    commit_generation(winner, generation)  # discards all other generations
    verify_against_union(winner, replicas)  # verifier sees union, not winner's slice
    return winner
