# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-before-its-validator-has-returned-commit-order-inversion-in-parallel-rollouts.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-before-its-validator-has-returned-commit-order-inversion-in-parallel-rollouts.warrant.json
# Markdown SHA-256:   eb94f30292dac34b288917fbbd7cdedd095ce84ce910a12633eb8f081b3955d1
# Code AST SHA-256:   212b84fa8931a06955c026fce917bcb65ceb7c77d327cf1dba2942e9d69b0ed0
# Verified Classes:   StaleVerdictError, Branch, Orchestrator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Optional


class StaleVerdictError(RuntimeError):
    """Raised when a branch's PASS was derived against a resource version
    that has since advanced, or when a sibling is not quiescent at commit."""


@dataclass
class Branch:
    name: str
    validator_returned: bool = False
    verdict: Optional[str] = None          # "PASS" | "FAIL"
    snapshot_version: int = 0              # resource version validator observed
    mutates_shared: bool = False           # non-idempotent write to shared resource
    rolled_back: bool = False


@dataclass
class Orchestrator:
    resource_version: int = 0
    branches: Dict[str, Branch] = field(default_factory=dict)

    def commit(self, winner: str) -> None:
        w = self.branches[winner]
        if not w.validator_returned or w.verdict != "PASS":
            raise StaleVerdictError(f"{winner}: no fresh PASS to commit")

        # Invariant 1: verdict freshness — snapshot must match live version.
        if w.snapshot_version != self.resource_version:
            raise StaleVerdictError(
                f"{winner}: PASS bound to v{w.snapshot_version}, "
                f"resource at v{self.resource_version}"
            )

        # Invariant 2: sibling quiescence — no in-flight shared mutation.
        for name, b in self.branches.items():
            if name == winner:
                continue
            if b.mutates_shared and not (b.validator_returned and b.rolled_back):
                raise StaleVerdictError(
                    f"{winner}: sibling {name} not quiescent "
                    f"(validator_returned={b.validator_returned}, "
                    f"rolled_back={b.rolled_back})"
                )

        self.resource_version += 1


# Reproduces the observed failure: B's rename executed at t=3.2, A commits at t=4.1.
orch = Orchestrator(resource_version=1)
orch.branches["A"] = Branch("A", validator_returned=True, verdict="PASS",
                            snapshot_version=1, mutates_shared=True)
orch.branches["B"] = Branch("B", validator_returned=False, verdict=None,
                            snapshot_version=1, mutates_shared=True)
try:
    orch.commit("A")   # raises: B is mid-flight against a shared resource
except StaleVerdictError as e:
    print("blocked:", e)
