# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-pre-execution-from-committing-effects-that-were-valid-at-pre-execution-time-but-invalid-at-commit-time.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-pre-execution-from-committing-effects-that-were-valid-at-pre-execution-time-but-invalid-at-commit-time.warrant.json
# Markdown SHA-256:   d741eb4f24018b4bbf4c733cf47fbc635dacdb22af43d295bc7c2552dce6e1bd
# Code AST SHA-256:   60ebdaa1d9713483eb93647f60ec529dfe060a6c0bc04bbb01de4819accd2028
# Verified Classes:   SpeculativeCommitViolation, SpeculativeEffect
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Callable


class SpeculativeCommitViolation(RuntimeError):
    """Raised when a speculative effect is committed without revalidating its
    guard predicate against current state, or when a conflicting effect has
    already committed and the two are non-commutative."""


@dataclass
class SpeculativeEffect:
    name: str
    read_set: frozenset[str]
    write_set: frozenset[str]
    guard: Callable[[dict[str, Any]], bool]
    # The exact values the guard was evaluated against at pre-execution time.
    guard_inputs: dict[str, Any]
    apply: Callable[[dict[str, Any]], None]
    committed: bool = field(default=False)


def commit_speculative(
    effect: SpeculativeEffect,
    live_state: dict[str, Any],
    committed_since_pre_exec: list[SpeculativeEffect],
) -> None:
    # 1. Conflict detection over read/write sets, not call identity.
    for prior in committed_since_pre_exec:
        overlap = (
            effect.write_set & (prior.read_set | prior.write_set)
        ) or (prior.write_set & effect.read_set)
        if overlap and not _commutes(effect, prior):
            raise SpeculativeCommitViolation(
                f"effect {effect.name!r} conflicts with already-committed "
                f"{prior.name!r} on {sorted(overlap)}; serialize and re-check"
            )

    # 2. Stale-read guard: predicate must be re-evaluated against current
    #    values, and those values must match what the guard was evaluated on.
    current_inputs = {k: live_state.get(k) for k in effect.guard_inputs}
    if current_inputs != effect.guard_inputs:
        if not effect.guard(live_state):
            raise SpeculativeCommitViolation(
                f"effect {effect.name!r} guard failed at commit: "
                f"pre-exec inputs {effect.guard_inputs} != live {current_inputs}"
            )
        raise SpeculativeCommitViolation(
            f"effect {effect.name!r} stale-read hazard: guard passes but "
            f"inputs shifted {effect.guard_inputs} -> {current_inputs}; re-plan"
        )

    # 3. Commit is an irreversible transition and requires its own warrant.
    if not effect.guard(live_state):
        raise SpeculativeCommitViolation(
            f"effect {effect.name!r} committed without a valid guard"
        )

    effect.apply(live_state)
    effect.committed = True
    committed_since_pre_exec.append(effect)


def _commutes(a: SpeculativeEffect, b: SpeculativeEffect) -> bool:
    # Conservative: only disjoint write-sets are assumed commutative.
    return not (a.write_set & b.write_set)
