# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-speculative-agent-plan-whose-byzantine-quorum-check-passes-on-the-plan-hash-but-fails-on-the-pre-state-bin.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-speculative-agent-plan-whose-byzantine-quorum-check-passes-on-the-plan-hash-but-fails-on-the-pre-state-bin.warrant.json
# Markdown SHA-256:   38668f9732b5badd6f73e207f94c25ccda605d0822c8cf86b1a5242c0c2ecada
# Code AST SHA-256:   efa839f0059edc9fdd2bb025fd12d6bf9afed20a98b1c581862a6380f493ec93
# Verified Classes:   StalePreconditionError, Plan, WorldState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StalePreconditionError(RuntimeError):
    """Raised when a quorate plan's pre-state binding no longer holds at commit."""


@dataclass(frozen=True)
class Plan:
    plan_hash: bytes
    asserted_epoch: int
    asserted_resource_version: int
    read_snapshot_ts: float
    staleness_budget_s: float


@dataclass(frozen=True)
class WorldState:
    lease_epoch: int
    resource_version: int


def verify_and_commit(
    plan: Plan,
    quorum_signatures: int,
    quorum_threshold: int,
    world: WorldState,
    cas_guard_fields: frozenset[str],
    now: float | None = None,
) -> None:
    now = time.monotonic() if now is None else now

    # 1. Structural quorum: necessary, not sufficient.
    if quorum_signatures < quorum_threshold:
        raise StalePreconditionError(
            f"quorum not reached: {quorum_signatures}/{quorum_threshold}"
        )

    # 2. Static verifiability: asserted fields must be a subset of CAS guards.
    asserted = {"lease_epoch", "resource_version"}
    if not asserted.issubset(cas_guard_fields):
        raise StalePreconditionError(
            f"plan asserts fields {asserted - cas_guard_fields} "
            f"that the commit path does not guard on"
        )

    # 3. Staleness budget: a quorate plan can still be about the past.
    if now - plan.read_snapshot_ts > plan.staleness_budget_s:
        raise StalePreconditionError(
            f"plan snapshot age {now - plan.read_snapshot_ts:.3f}s "
            f"exceeds budget {plan.staleness_budget_s:.3f}s"
        )

    # 4. The binding: CAS on the exact asserted preconditions.
    if (world.lease_epoch != plan.asserted_epoch
            or world.resource_version != plan.asserted_resource_version):
        raise StalePreconditionError(
            f"pre-state drifted: asserted epoch={plan.asserted_epoch} "
            f"rv={plan.asserted_resource_version}, "
            f"observed epoch={world.lease_epoch} rv={world.resource_version}"
        )

    # Only here is a side effect permitted.
    return None
