# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-compensate-a-speculatively-executed-tool-call-the-idempotency-lease-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-compensate-a-speculatively-executed-tool-call-the-idempotency-lease-boundary.warrant.json
# Markdown SHA-256:   ea73e8c3fd9c50e078e8f3bc84fe7b643b8333a96c8745e0d682bc3f55917717
# Code AST SHA-256:   9e96e510127eca23210d052478b7e3306809195404a0c68e29f6a08e1e25cbe6
# Verified Classes:   CompensationRefused, Speculation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class CompensationRefused(RuntimeError):
    """Raised when a speculative tool call's effect has escaped the compensation boundary."""
    pass


@dataclass
class Speculation:
    speculation_id: str
    lease_held: bool
    lease_expires_at: float
    external_ack: bool


def compensate(spec: Speculation, now: float | None = None) -> None:
    now = time.monotonic() if now is None else now

    # Ground truth is the lease and the external acknowledgment, never the local record.
    lease_valid = spec.lease_held and now < spec.lease_expires_at

    if spec.external_ack:
        # Effect escaped before the lease released; the ack is authority now.
        # Compensation would be a new destructive act, not an undo.
        raise CompensationRefused(
            f"speculation {spec.speculation_id}: external acknowledgment present; "
            f"effect escaped compensation boundary (lease_valid={lease_valid}). "
            f"Route to forward resolution, not compensation."
        )

    if not lease_valid:
        # Lease lapsed with no ack: attempt re-acquisition; refuse if unavailable.
        raise CompensationRefused(
            f"speculation {spec.speculation_id}: idempotency lease not held at "
            f"compensation time (expired at {spec.lease_expires_at}, now {now}). "
            f"Re-acquire lease or quarantine for reconciliation; do not compensate."
        )

    # Safe: lease held, no external consumption. Compensation is a true undo.
    _issue_compensation(spec.speculation_id)


def _issue_compensation(speculation_id: str) -> None:
    # Placeholder for the actual compensating tool call.
    pass
