# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-executor-commit-work-that-its-verifier-has-already-invalidated-the-verifier-gated-commit-race-in-multi-agent-spe.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-executor-commit-work-that-its-verifier-has-already-invalidated-the-verifier-gated-commit-race-in-multi-agent-spe.warrant.json
# Markdown SHA-256:   846db746c9178a14f9fc7f04e43091929372622db149119f745f8f08231109ee
# Code AST SHA-256:   b0c902a9e697737df6e9b60566a55f8fa00d80ead32b2d71fd999b0beff68d2d
# Verified Classes:   GhostCommitError, Decision, Handle, HandleState, VerifierGatedCommitStore
# Defensive Guards:   10 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class GhostCommitError(RuntimeError):
    """Raised when a speculator attempts to commit a handle whose verifier
    decision is INVALIDATE, or when a handle's identity is re-derived from a
    shared counter instead of its build-time version."""


class Decision(Enum):
    PENDING = "pending"
    PROMOTE = "promote"
    INVALIDATE = "invalidate"
    COMMITTING = "committing"
    COMMITTED = "committed"


@dataclass(frozen=True)
class Handle:
    branch_id: str
    spec_version_at_build: int  # immutable; assigned at artifact build time


@dataclass
class HandleState:
    decision: Decision = Decision.PENDING
    committed: bool = False


class VerifierGatedCommitStore:
    """Minimal model of a verifier-gated commit protocol.

    The invariant enforced here: a speculator may only flush side-effects for
    a handle it has CAS-acquired from PENDING, and the decision read inside
    that CAS is authoritative. A decision classified by any counter other than
    the handle's build-time version is rejected as a ghost-commit vector.
    """

    def __init__(self) -> None:
        self._handles: dict[Handle, HandleState] = {}

    def register(self, handle: Handle) -> None:
        if handle in self._handles:
            raise GhostCommitError(f"handle already registered: {handle}")
        self._handles[handle] = HandleState()

    def verifier_decide(self, handle: Handle, decision: Decision) -> None:
        if decision not in (Decision.PROMOTE, Decision.INVALIDATE):
            raise GhostCommitError(f"illegal verifier decision: {decision}")
        state = self._handles.get(handle)
        if state is None:
            raise GhostCommitError(f"decision for unknown handle: {handle}")
        # Decision monotonicity per handle: PENDING -> terminal, never back.
        if state.decision is not Decision.PENDING:
            raise GhostCommitError(
                f"handle {handle} already decided as {state.decision}; "
                f"refusing to overwrite with {decision}"
            )
        state.decision = decision

    def speculator_commit(
        self,
        handle: Handle,
        observed_global_version: int,
        side_effect: str,
    ) -> None:
        """Commit path. `observed_global_version` exists ONLY to demonstrate
        the bug: a correct implementation must not use it to classify
        decisions. It is accepted here so the guard below can reject callers
        that try to use version ordering as a staleness key.
        """
        state = self._handles.get(handle)
        if state is None:
            raise GhostCommitError(f"commit for unknown handle: {handle}")

        # The bug: classifying a decision as stale by comparing a *global*
        # counter against the handle's build-time version. Any peer increment
        # makes a fresh invalidation look stale. Reject this shape outright.
        if observed_global_version != handle.spec_version_at_build:
            raise GhostCommitError(
                f"commit for {handle} classified by global version "
                f"{observed_global_version} != build-time "
                f"{handle.spec_version_at_build}; "
                f"this is the ghost-commit vector"
            )

        # CAS-acquire the handle from PENDING. The decision read inside this
        # critical section is authoritative.
        if state.decision is Decision.INVALIDATE:
            raise GhostCommitError(
                f"refusing to commit {handle}: verifier already invalidated"
            )
        if state.decision is Decision.PROMOTE and not state.committed:
            state.committed = True
            self._flush(handle, side_effect)
            return
        if state.decision is Decision.COMMITTED or state.committed:
            # Idempotent: already committed, do not re-flush.
            return
        raise GhostCommitError(
            f"cannot commit {handle}: decision is {state.decision}, "
            f"not PROMOTE"
        )

    def _flush(self, handle: Handle, side_effect: str) -> None:
        # Placeholder for the real side-effect flush (write_file, API call).
        pass


def reproduce_ghost_commit() -> None:
    store = VerifierGatedCommitStore()
    handle = Handle(branch_id="S2", spec_version_at_build=7)
    store.register(handle)

    # Verifier invalidates the candidate at build-time version 7.
    store.verifier_decide(handle, Decision.INVALIDATE)

    # Speculator polls at loop top, sees global spec_version has advanced to 8
    # (a peer incremented it), and — under the buggy guard — would treat the
    # invalidation as stale and proceed. The store rejects the shape.
    try:
        store.speculator_commit(
            handle,
            observed_global_version=8,
            side_effect="write_file:/etc/task_T/state.json",
        )
    except GhostCommitError as exc:
        # Expected: the protocol refuses to let the speculator commit.
        assert "ghost-commit vector" in str(exc)
        return
    raise GhostCommitError(
        "ghost commit was not prevented: speculator committed an "
        "invalidated handle"
    )


if __name__ == "__main__":
    reproduce_ghost_commit()
