# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-speculatively-prefetch-side-effecting-tool-calls-and-then-commit-them-out-of-order.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-speculatively-prefetch-side-effecting-tool-calls-and-then-commit-them-out-of-order.warrant.json
# Markdown SHA-256:   58b4178fa95baf89788ba63af96dd5ed73d66ad448554bb132ac5dd859c29642
# Code AST SHA-256:   a30c16f13a8cf621a7fd3cc5a1b018a33717e0dbc217b090e6f3a23a20d3fc02
# Verified Classes:   SpeculativeEffectFault
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SpeculativeEffectFault(RuntimeError):
    """Raised when a speculative call's effect layer diverges from its commit ledger."""
    pass


EFFECT_PURE = "pure"
EFFECT_COMPENSABLE = "compensable"
EFFECT_OPAQUE = "opaque"


def dispatch_speculative(call, effect_class, inverse=None):
    """Issue a speculative call only if its effect is reversible at the callee.

    effect_class must be resolved BEFORE dispatch. Unknown must be treated as
    opaque, never as pure.
    """
    if effect_class == EFFECT_OPAQUE or effect_class is None:
        raise SpeculativeEffectFault(
            f"refusing to speculate opaque effect tool={call.name!r}; "
            "serialize behind commit gate"
        )
    if effect_class == EFFECT_COMPENSABLE and inverse is None:
        raise SpeculativeEffectFault(
            f"compensable tool={call.name!r} has no registered inverse; "
            "cannot guarantee discard is reversible"
        )
    token = call.prepare() if effect_class == EFFECT_COMPENSABLE else None
    return {"call": call, "token": token, "effect_class": effect_class}


def discard_speculative(handle):
    """Abort a prepared effect. A failed abort is a hard fault, not a warning."""
    if handle["effect_class"] == EFFECT_COMPENSABLE:
        aborted = handle["call"].abort(handle["token"])
        if not aborted:
            raise SpeculativeEffectFault(
                f"abort failed for token={handle['token']!r}; "
                "live token is a pending side effect, halting agent"
            )
    # pure handles have nothing to abort
    return True


def reconcile(commit_ledger, external_events):
    """If external state contradicts the ledger, halt; do not compensate."""
    for event in external_events:
        if event.effect_id not in commit_ledger.committed:
            raise SpeculativeEffectFault(
                f"external effect {event.effect_id!r} has no committed cause; "
                "halt and surface, never issue compensating writes"
            )
    return True
