# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-commit-a-speculative-branch-that-its-own-rollback-log-proves-was-never-valid.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-commit-a-speculative-branch-that-its-own-rollback-log-proves-was-never-valid.warrant.json
# Markdown SHA-256:   79e0de02d6ae36b94fbafff75102029160f4ec4e27f2b5fd97dd3684ff7d2851
# Code AST SHA-256:   8ca37b67a2ffeb1343102f5f819abcc05cdfb5439bd7dc858123ed3ec578ce60
# Verified Classes:   SpeculativeCommitViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeCommitViolation(RuntimeError):
    """Raised when a branch is about to commit despite a rollback-log invariant violation."""
    pass


def commit_speculative_branch(branch, log_entries):
    # Invariant scan MUST precede forward replay. The rollback log is the
    # deterministic witness; the reasoning trace is not admissible here.
    violations = [
        e for e in log_entries
        if e.get("precondition_violated") is True
    ]
    if violations:
        raise SpeculativeCommitViolation(
            f"branch {branch.id} commit blocked: rollback log contains "
            f"{len(violations)} precondition_violated entr(ies); "
            f"first={violations[0]!r}. Trace confidence is not admissible."
        )

    # Only now is forward replay safe: every optimistic write was validly applied.
    for entry in log_entries:
        replay_forward(entry)

    return branch.id


def select_and_commit(branches):
    # Scan-then-score: violated branches are removed before ranking so they
    # cannot become silent winners.
    eligible = []
    for b in branches:
        if any(e.get("precondition_violated") is True for e in b.rollback_log):
            continue
        eligible.append(b)
    if not eligible:
        raise SpeculativeCommitViolation("no branch survived rollback-log invariant scan")
    winner = max(eligible, key=lambda b: b.score)
    return commit_speculative_branch(winner, winner.rollback_log)
