# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-checkpoint-is-unsafe-to-commit-during-multi-agent-rollback-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-checkpoint-is-unsafe-to-commit-during-multi-agent-rollback-replay.warrant.json
# Markdown SHA-256:   db29a984afc9a686b2982623668bcd9c9428bafdb4c421211c57bd4d921ae158
# Code AST SHA-256:   239bef4f55855ea18a5e0bdfdfbc214d697a1dac7e2478f7270f76acb47c5007
# Verified Classes:   Provenance, UnsafeSpeculativeCommit, EnvelopeInput, SpeculativeCheckpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class Provenance(Enum):
    OBSERVED = "observed"
    COMMITTED = "committed"


class UnsafeSpeculativeCommit(RuntimeError):
    """Raised when a speculative checkpoint is committed while carrying
    uncommitted (observed-only) provenance for a non-idempotent dependency."""
    pass


@dataclass
class EnvelopeInput:
    name: str
    value: object
    provenance: Provenance
    producer_step: str
    producer_committed_at: Optional[int]
    producer_idempotent: bool


@dataclass
class SpeculativeCheckpoint:
    step_id: str
    frozen_at: int
    ancestors: set
    envelope: list = field(default_factory=list)
    replay_clean: bool = False


def committable(cp: SpeculativeCheckpoint, frontier_moved: bool) -> bool:
    if not cp.replay_clean:
        return False
    for inp in cp.envelope:
        if inp.provenance is Provenance.OBSERVED:
            # Speculative dependency: only admissible if producer is idempotent
            # AND the frontier has not shifted since freeze.
            if not inp.producer_idempotent or frontier_moved:
                return False
        if inp.provenance is Provenance.COMMITTED:
            if inp.producer_committed_at is None:
                return False
            if inp.producer_committed_at > cp.frozen_at:
                # Committed after we froze: our freeze predates the commit.
                return False
        if inp.producer_step not in cp.ancestors:
            return False
    return True


def commit_speculative(cp: SpeculativeCheckpoint, frontier_moved: bool) -> None:
    if not cp.replay_clean:
        raise UnsafeSpeculativeCommit(
            f"checkpoint {cp.step_id} is not replay-clean; commit refused"
        )
    if not committable(cp, frontier_moved):
        offending = [
            i.name for i in cp.envelope
            if i.provenance is Provenance.OBSERVED and not i.producer_idempotent
        ]
        raise UnsafeSpeculativeCommit(
            f"checkpoint {cp.step_id} carries uncommitted provenance for "
            f"non-idempotent inputs {offending}; frontier_moved={frontier_moved}. "
            f"Wait, re-derive, or demote to advisory."
        )
    # Safe to commit: every pinned input is either committed-before-freeze
    # or an idempotent observation on a stationary frontier.
    cp.frozen_at = cp.frozen_at  # commit is a no-op on the record itself
