# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-it-is-about-to-commit-was-verified-against-a-stale-sibling-state.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-it-is-about-to-commit-was-verified-against-a-stale-sibling-state.warrant.json
# Markdown SHA-256:   13f4185acadff2f737b06dcf651f14d851e624481234ab7f115abc57eb367f3d
# Code AST SHA-256:   14b35c750082e945d5e4d402b44f1d02eb651064c83a9868d6925228f1879393
# Verified Classes:   StaleCertificateError, Certificate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleCertificateError(RuntimeError):
    """Raised when a verifier certificate is bound to a base snapshot that no longer matches the live world-state."""


@dataclass(frozen=True)
class Certificate:
    branch_id: str
    certified_base_digest: str
    verdict: str  # "accept" | "reject"
    verifier_run: int


def commit_speculative_branch(
    cert: Certificate,
    live_world_state: bytes,
    apply_fn,
) -> None:
    live_digest = hashlib.sha256(live_world_state).hexdigest()

    if cert.verdict != "accept":
        raise StaleCertificateError(
            f"branch {cert.branch_id}: certificate verdict={cert.verdict!r}, "
            f"refusing commit (re-plan required, not re-verify)"
        )

    # Base-identity binding: the certificate is only valid for the exact
    # snapshot the verifier observed. TTL is irrelevant if a sibling moved
    # the shared substrate in the interim.
    if cert.certified_base_digest != live_digest:
        raise StaleCertificateError(
            f"branch {cert.branch_id}: certificate bound to base "
            f"{cert.certified_base_digest[:12]} but live base is "
            f"{live_digest[:12]}; certificate voided — re-verify against "
            f"current digest, do NOT re-plan (plan itself is sound)"
        )

    # CAS succeeded: cert and world agree. Apply.
    apply_fn()
