# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-tool-call-batch-when-the-safety-gate-s-commit-warrant-is-invalidated-by-a-mid-batch-preconditio.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-tool-call-batch-when-the-safety-gate-s-commit-warrant-is-invalidated-by-a-mid-batch-preconditio.warrant.json
# Markdown SHA-256:   9d2380bbd69c6d072d004d3973f46650556aee33b2e22e8a0112f5d2dc7ff6d9
# Code AST SHA-256:   5a168504130e8138c53efa2142189948901364ba186d1cda6ee9c9976a411767
# Verified Classes:   SpeculationWindowViolation, BufferedCall, CommitWarrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class SpeculationWindowViolation(RuntimeError):
    """Raised when a buffered speculative batch's snapshot chain is broken."""


@dataclass
class BufferedCall:
    name: str
    dispatch_snapshot: str
    buffered_output: dict
    commutative: bool = False


@dataclass
class CommitWarrant:
    batch_id: int
    gate_snapshot: str
    signature_valid: bool


def _hash_state(state: dict) -> str:
    return hashlib.sha256(repr(sorted(state.items())).encode()).hexdigest()


def commit_speculative_batch(
    calls: list[BufferedCall],
    warrant: CommitWarrant,
    current_state: dict,
) -> list[str]:
    """
    Commit a speculative batch only if the three-way snapshot invariant holds
    per call, or if drift is confined to commutative/idempotent effects.
    """
    if not warrant.signature_valid:
        raise SpeculationWindowViolation(
            f"batch {warrant.batch_id}: warrant signature invalid"
        )

    commit_snapshot = _hash_state(current_state)
    committed: list[str] = []
    drifted_noncommutative: list[str] = []

    for call in calls:
        dispatch_matches_gate = call.dispatch_snapshot == warrant.gate_snapshot
        gate_matches_commit = warrant.gate_snapshot == commit_snapshot

        if dispatch_matches_gate and gate_matches_commit:
            committed.append(call.name)
            continue

        # Drift detected somewhere in the dispatch->gate->commit chain.
        if call.commutative:
            # Idempotent, commutative effect: safe to commit under fresh state.
            committed.append(call.name)
            continue

        drifted_noncommutative.append(call.name)

    if drifted_noncommutative:
        # Atomic abort: cross-call invariants (e.g. debit/credit) require
        # all-or-nothing when any non-commutative leg drifted.
        raise SpeculationWindowViolation(
            f"batch {warrant.batch_id}: non-commutative drift on "
            f"{drifted_noncommutative}; dispatch={calls[0].dispatch_snapshot[:8]} "
            f"gate={warrant.gate_snapshot[:8]} commit={commit_snapshot[:8]}"
        )

    return committed


def reconcile_audit_log(entries: list[dict]) -> None:
    """Offline reconciler: flag any committed batch with a broken snapshot chain."""
    for e in entries:
        if not e.get("committed"):
            continue
        if not (
            e["dispatch_snapshot"] == e["gate_snapshot"] == e["commit_snapshot"]
        ):
            raise SpeculationWindowViolation(
                f"batch {e['batch_id']}: committed across speculation window; "
                "quarantine for review"
            )
