# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-speculative-branch-verifier-as-a-commit-authority-rather-than-a-rollback-oracle.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-speculative-branch-verifier-as-a-commit-authority-rather-than-a-rollback-oracle.warrant.json
# Markdown SHA-256:   aded98e71f605ed3707f96bc4d306e9e4806f4ab7a596aac069e1480d4498794
# Code AST SHA-256:   45498c4c23a2b35d7568056a2f3ab899ee484120506228cfa43d3487eab71734
# Verified Classes:   SpeculativeWaveRejected, Branch, Baseline, Checkpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpeculativeWaveRejected(RuntimeError):
    """Raised when no branch in a speculative wave passes absolute admission.

    This is a wave-level rollback, not a branch-level failure. The orchestrator
    must re-checkpoint at the pre-fan-out base; it must NOT commit the
    least-bad branch.
    """


@dataclass(frozen=True)
class Branch:
    branch_id: str
    diff: str
    transcript: str
    reported_collected_tests: int
    reported_failed: int
    verifier_score: float  # relative ranking signal, 0..1


@dataclass(frozen=True)
class Baseline:
    collected_tests: int
    fixture_hashes: dict[str, str]


@dataclass
class Checkpoint:
    base_commit: str
    baseline: Baseline
    _consumed: bool = field(default=False)

    def consume(self) -> "Checkpoint":
        if self._consumed:
            raise SpeculativeWaveRejected(
                "checkpoint already consumed by a prior wave; cannot re-fan"
            )
        self._consumed = True
        return self

    def release(self) -> None:
        # Called only when the wave is discarded, restoring re-entrancy.
        self._consumed = False


def admits(branch: Branch, baseline: Baseline) -> bool:
    """Absolute admission predicate. Must be decidable per-branch, with no
    reference to the other branches. Returns False for degenerate branches
    whose transcript is internally consistent but whose test collection
    diverged from the pre-branch baseline.
    """
    if branch.reported_collected_tests != baseline.collected_tests:
        # The observed failure: conftest mutation suppressed collection.
        return False
    if branch.reported_failed != 0:
        return False
    # Fixture integrity is checked out-of-band against the worktree; the
    # branch's self-report is not trusted for this.
    return True


def commit_wave(
    branches: list[Branch],
    baseline: Baseline,
    checkpoint: Checkpoint,
    commit_fn,
) -> Branch:
    """Two-stage gate: absolute admission, then relative selection over the
    admitted subset. Raises SpeculativeWaveRejected if the subset is empty.
    """
    checkpoint.consume()
    admitted = [b for b in branches if admits(b, baseline)]

    if not admitted:
        checkpoint.release()
        raise SpeculativeWaveRejected(
            f"wave of {len(branches)} branches produced no admissible candidate; "
            f"baseline_collected={baseline.collected_tests}, "
            f"branch_collected={[b.reported_collected_tests for b in branches]}; "
            f"re-checkpoint at {checkpoint.base_commit}"
        )

    winner = max(admitted, key=lambda b: b.verifier_score)
    commit_fn(checkpoint.base_commit, winner.diff)
    return winner
