# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-speculative-branch-and-validate-execution-has-silently-collapsed-into-serial-validation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-speculative-branch-and-validate-execution-has-silently-collapsed-into-serial-validation.warrant.json
# Markdown SHA-256:   f5c03a92493abd6af7d5eb59b7c4b9e153e6329ab7a7306b58ec7653571a4a80
# Code AST SHA-256:   4c810862ee66449a2ab8f6e686c976510fd2f7fe0f4a181b883d0eaad1185466
# Verified Classes:   SpeculationCollapseError, Branch, Validator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class SpeculationCollapseError(RuntimeError):
    """Raised when a validator's read set leaks outside a branch's speculative write set."""


@dataclass(frozen=True)
class Branch:
    name: str
    writes: FrozenSet[str]
    private_view: dict


@dataclass
class Validator:
    name: str
    reads: FrozenSet[str]
    fork_snapshot: FrozenSet[str] = field(default_factory=frozenset)


def assert_independent_validation(
    validator: Validator, branches: list[Branch]
) -> None:
    """Enforce the validity condition before committing any branch.

    A branch is independently validatable only if the validator reads
    nothing outside that branch's writes plus the frozen fork snapshot,
    and no two branches write the same field.
    """
    # Condition 2: no write-write conflicts across siblings.
    seen: dict[str, str] = {}
    for b in branches:
        for w in b.writes:
            if w in seen:
                raise SpeculationCollapseError(
                    f"write-write conflict on {w!r}: branches "
                    f"{seen[w]!r} and {b.name!r} both claim it; "
                    f"validation is no longer branch-local"
                )
            seen[w] = b.name

    # Condition 1 & 3: validator reads must be covered per-branch.
    for b in branches:
        uncovered = validator.reads - (b.writes | validator.fork_snapshot)
        if uncovered:
            raise SpeculationCollapseError(
                f"validator {validator.name!r} reads {sorted(uncovered)} "
                f"which branch {b.name!r} does not write and is not in the "
                f"fork snapshot; branch is being validated against "
                f"predecessor or sibling state (silent serialization)"
            )


def commit_winner(
    validator: Validator, branches: list[Branch], scores: dict[str, float]
) -> Branch:
    assert_independent_validation(validator, branches)
    if len(scores) != len(branches):
        raise SpeculationCollapseError(
            "every branch must be scored against its own private_view"
        )
    winner = max(branches, key=lambda b: scores[b.name])
    losers = [b for b in branches if b is not winner]
    if not losers:
        raise SpeculationCollapseError(
            "zero rollback: no losing branch, speculation did not occur"
        )
    return winner
