# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-verifier-gated-speculative-branches-from-committing-on-stale-world-state-after-a-parallel-tool-call-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-verifier-gated-speculative-branches-from-committing-on-stale-world-state-after-a-parallel-tool-call-fan-out.warrant.json
# Markdown SHA-256:   cf5df2f17bae9673fecf04c647d79839df6b8de2b820502ceb97db0dfe34f36c
# Code AST SHA-256:   c82eaf5254efaedc85829d9644da842d83c75ab9173b4148aeb3324c6de5cf07
# Verified Classes:   StaleVerdictCommitError, Verdict, World
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class StaleVerdictCommitError(RuntimeError):
    """Raised when a verifier verdict is committed against a world it was not computed against."""


@dataclass
class Verdict:
    branch_id: str
    passed: bool
    world_version: int
    read_set: frozenset
    write_set: frozenset


@dataclass
class World:
    version: int = 0
    # resource -> owning branch, for contended resources
    owners: dict = field(default_factory=dict)


def commit_speculative_branch(
    verdict: Verdict,
    world: World,
    sibling_commits_since_verdict: list,
) -> None:
    if not verdict.passed:
        raise StaleVerdictCommitError(
            f"branch {verdict.branch_id} has no PASS verdict; refusing commit"
        )

    # Invariant 1: snapshot identity — verdict must be against current world
    if verdict.world_version != world.version:
        # Invariant 2: disjointness — admissible only if no sibling wrote our read-set
        intersecting = [
            s for s in sibling_commits_since_verdict
            if s.write_set & verdict.read_set
        ]
        if intersecting:
            raise StaleVerdictCommitError(
                f"branch {verdict.branch_id} verdict computed against world v"
                f"{verdict.world_version}, current v{world.version}; "
                f"sibling writes intersect read-set: "
                f"{[s.branch_id for s in intersecting]}. Re-verify required."
            )
        # Disjoint: safe to commit against mutated world
        # (fall through)

    # Invariant 3: single-commit latch — no other branch may own our write-set
    for res in verdict.write_set:
        existing = world.owners.get(res)
        if existing is not None and existing != verdict.branch_id:
            raise StaleVerdictCommitError(
                f"branch {verdict.branch_id} would clobber resource {res!r} "
                f"owned by branch {existing}; verdict is stale on contended resource"
            )

    for res in verdict.write_set:
        world.owners[res] = verdict.branch_id
    world.version += 1
