# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a-speculative-multi-agent-plan-commit-a-verifier-passed-branch-whose-verification-was-performed-against-a-stale-sibling-s-stat.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-speculative-multi-agent-plan-commit-a-verifier-passed-branch-whose-verification-was-performed-against-a-stale-sibling-s-stat.warrant.json
# Markdown SHA-256:   b75a5f42b3761871429a413d0fe08a32d8ea0b4f4709707fc966e4034b516b5d
# Code AST SHA-256:   9c35babd3d4c9ab512fbf075fa264ba686247e76ea1d49391628d85e0a6b91f3
# Verified Classes:   StaleVerdictCommitError, Verdict, Diff, CommitGate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import FrozenSet


class StaleVerdictCommitError(RuntimeError):
    """Raised when a commit gate is asked to honor a verdict minted against a
    snapshot that is no longer the head, without a re-verification pass."""


@dataclass(frozen=True)
class Verdict:
    branch_id: str
    predicate_hash: str
    snapshot_hash: str
    passed: bool
    read_set: FrozenSet[str] = field(default_factory=frozenset)
    monotone_stable: bool = False


@dataclass(frozen=True)
class Diff:
    branch_id: str
    write_set: FrozenSet[str]


class CommitGate:
    def __init__(self) -> None:
        self.head = "S0"
        self.committed_writes: FrozenSet[str] = frozenset()

    def _interferes(self, v: Verdict) -> bool:
        # A stale verdict is only safe if the predicate is monotone-stable AND
        # no committed sibling has written into the predicate's read-set.
        if v.monotone_stable:
            return False
        return bool(v.read_set & self.committed_writes)

    def commit(self, v: Verdict, diff: Diff, reverified: Verdict | None) -> str:
        if not v.passed:
            raise StaleVerdictCommitError(
                f"branch {v.branch_id}: refusing to commit a failed verdict"
            )
        if v.snapshot_hash != self.head:
            # Token is stale relative to head. Either re-verify or refuse.
            if reverified is None:
                raise StaleVerdictCommitError(
                    f"branch {v.branch_id}: verdict minted against {v.snapshot_hash} "
                    f"but head is {self.head}; no re-verification supplied"
                )
            if reverified.snapshot_hash != self.head or not reverified.passed:
                raise StaleVerdictCommitError(
                    f"branch {v.branch_id}: re-verification did not pass at head "
                    f"{self.head}"
                )
            if self._interferes(v):
                raise StaleVerdictCommitError(
                    f"branch {v.branch_id}: committed sibling write-set intersects "
                    f"read-set {sorted(v.read_set)}; stale verdict is not consumable"
                )
            v = reverified
        # Admit: verdict is fresh for the current head.
        self.committed_writes = self.committed_writes | diff.write_set
        self.head = f"{self.head}+{diff.branch_id}"
        return self.head


def _demo() -> None:
    gate = CommitGate()
    b1 = Verdict("B1", "pred_config_key", "S0", True, frozenset({"config.timeout_ms"}))
    b1_diff = Diff("B1", frozenset({"config.timeout_ms"}))
    gate.commit(b1, b1_diff, reverified=None)  # fresh at S0 -> head advances

    # B2 minted against S0; head is now S0+B1. Its predicate reads callers,
    # which B1's write touched. No re-verification supplied -> must raise.
    b2 = Verdict(
        "B2", "pred_all_callers_resolve", "S0", True,
        frozenset({"callers", "config.timeout_ms"}), monotone_stable=False,
    )
    b2_diff = Diff("B2", frozenset({"symbols.rename"}))
    gate.commit(b2, b2_diff, reverified=None)


if __name__ == "__main__":
    _demo()
