# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-speculate-past-a-non-idempotent-tool-call-without-a-proven-compensator.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-speculate-past-a-non-idempotent-tool-call-without-a-proven-compensator.warrant.json
# Markdown SHA-256:   f475f9e136f88b84ee93fbc4cd884601c1ca2605987421cce4dacd42e88e7b90
# Code AST SHA-256:   b128803ec1eed8971b063f288ebba1049e1ead189c08ed275e56870396fe0a9b
# Verified Classes:   SpeculationBoundaryError, ToolCall, Compensator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class SpeculationBoundaryError(RuntimeError):
    """Raised when a speculative batch violates the compensation-graph invariant."""


@dataclass
class ToolCall:
    name: str
    mutates: bool
    postconditions: set[str] = field(default_factory=set)
    compensator: "Compensator | None" = None


@dataclass
class Compensator:
    name: str
    preconditions: set[str]
    max_attempts: int = 2


def validate_speculative_batch(batch: list[ToolCall]) -> None:
    """Reject a batch if any compensator's precondition is weakened by a sibling call."""
    for call in batch:
        if not call.mutates:
            continue
        if call.compensator is None:
            raise SpeculationBoundaryError(
                f"mutating call {call.name!r} has no compensator; cannot speculate"
            )
        for sibling in batch:
            if sibling is call or not sibling.mutates:
                continue
            overlap = call.compensator.preconditions & sibling.postconditions
            if overlap:
                raise SpeculationBoundaryError(
                    f"compensator {call.compensator.name!r} for {call.name!r} "
                    f"requires {sorted(overlap)} which sibling {sibling.name!r} "
                    f"can invalidate; serialize this batch"
                )


def run_compensation(
    call: ToolCall,
    execute: Callable[[str], bool],
    attempt: int = 0,
) -> None:
    comp = call.compensator
    if comp is None:
        raise SpeculationBoundaryError(f"no compensator for {call.name!r}")
    if attempt >= comp.max_attempts:
        raise SpeculationBoundaryError(
            f"compensator {comp.name!r} exhausted {comp.max_attempts} attempts; "
            f"stranded resource from {call.name!r} requires supervisor arbitration"
        )
    if not execute(comp.name):
        run_compensation(call, execute, attempt + 1)


# Observed batch: create_bucket's compensator (delete_bucket, needs bucket_empty)
# is invalidated by a sibling replication write postcondition.
if __name__ == "__main__":
    batch = [
        ToolCall(
            name="create_bucket",
            mutates=True,
            postconditions={"bucket_exists"},
            compensator=Compensator(name="delete_bucket", preconditions={"bucket_empty"}),
        ),
        ToolCall(
            name="start_replication",
            mutates=True,
            postconditions={"bucket_empty"},  # replication writes a placeholder
        ),
    ]
    validate_speculative_batch(batch)  # raises SpeculationBoundaryError
