# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-unsafe-speculative-tool-call-prefetch-when-the-compensation-path-itself-executes-a-side-effecting-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-unsafe-speculative-tool-call-prefetch-when-the-compensation-path-itself-executes-a-side-effecting-tool.warrant.json
# Markdown SHA-256:   481caa78154febfbde895163cae7272817ce8197bb158b37428a1dd3526f9ba4
# Code AST SHA-256:   4b095d5ec0804d5bc0136e3cda5cc04bde7aa9dd47a40164037004a19ea702de
# Verified Classes:   SpeculativeCompensationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeCompensationError(RuntimeError):
    """Raised when a compensation call was itself prefetched, making its
    error result untrustworthy for escalation decisions."""
    pass


COMPENSATION_REGISTRY = {"release_hold", "refund_reservation", "cancel_order"}


def dispatch_compensation(call, dispatcher):
    # Guard: a compensation handler must never carry a speculative id.
    if call.name in COMPENSATION_REGISTRY and call.spec_id is not None:
        raise SpeculativeCompensationError(
            f"compensation {call.name} was prefetched under spec_id={call.spec_id}; "
            f"its result cannot be trusted for escalation"
        )

    result = dispatcher.invoke(call, committed=True)

    if result.ok:
        return result

    if result.error_class == "not_found":
        # Idempotent success: the effect is already gone.
        return result.as_resolved()

    # Any other error on a committed compensation is a real escalation,
    # emitted synchronously and never re-entered by the prefetch scheduler.
    raise SpeculativeCompensationError(
        f"committed compensation {call.name} failed with {result.error_class}; "
        f"escalation must be issued as a synchronous non-speculative emission"
    )
