# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-speculative-branch-commits-when-a-verifier-s-approval-is-itself-produced-by-a-stale-snapshot-of-shared-state.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-speculative-branch-commits-when-a-verifier-s-approval-is-itself-produced-by-a-stale-snapshot-of-shared-state.warrant.json
# Markdown SHA-256:   d6ef3298e37bee53b9e9da97a7960326bf9c06611dfb2cb32ba896fcc620488f
# Code AST SHA-256:   68dc9750d813f886f30d333ae424bdc3428b91134a38f3a650c71ceb3aac579e
# Verified Classes:   StaleVerifierTokenError, ReadSetUnobservableError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StaleVerifierTokenError(RuntimeError):
    """Raised when a speculative branch's approval token is applied against
    shared state that has drifted from the snapshot the verifier evaluated."""


class ReadSetUnobservableError(RuntimeError):
    """Raised when a branch touched a resource whose read-set cannot be
    enumerated, making optimistic speculation unsafe for that resource."""


def commit_speculative_branch(
    branch_id: str,
    token: dict,
    current_state: dict,
    branch_readset: set[str] | None,
) -> dict:
    """
    token: {"v_eval": int, "readset": set[str], "branch": str, "approved": bool}
    current_state: {key: {"value": ..., "version": int}}
    """
    if not token.get("approved"):
        raise StaleVerifierTokenError(f"branch {branch_id}: token not approved")

    if branch_readset is None:
        raise ReadSetUnobservableError(
            f"branch {branch_id}: read-set unobservable; serialize instead of speculate"
        )

    if token["branch"] != branch_id:
        raise StaleVerifierTokenError(
            f"branch {branch_id}: token issued for {token['branch']}, not transferable"
        )

    v_eval = token["v_eval"]
    drifted = [
        k for k in token["readset"]
        if k in current_state and current_state[k]["version"] != v_eval
    ]
    if drifted:
        raise StaleVerifierTokenError(
            f"branch {branch_id}: read-set drifted since v={v_eval}: {sorted(drifted)}; "
            f"re-verify or discard"
        )

    # All read-set keys still at v_eval: verdict is bound to current world.
    return {"committed": branch_id, "at_version": v_eval}
