# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-and-unwind-a-speculative-tool-call-whose-compensation-was-silently-deduplicated-by-a-downstream-idempotency-key-collision.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-and-unwind-a-speculative-tool-call-whose-compensation-was-silently-deduplicated-by-a-downstream-idempotency-key-collision.warrant.json
# Markdown SHA-256:   55d45db3d9a115036837fa88dfca7eb9f51c20b908e44b90e896a29d130173dd
# Code AST SHA-256:   47b4fb43e130e83e0d2cc804912d18ba96613f904872e9273a5fd476a66c23bf
# Verified Classes:   CompensationDeduplicatedError, SpeculativeCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CompensationDeduplicatedError(RuntimeError):
    """Raised when a compensation's 200 response was a dedup hit, not an execution."""


@dataclass
class SpeculativeCall:
    resource_id: str
    attempt_nonce: int
    planner_epoch: int


def derive_compensation_key(call: SpeculativeCall) -> str:
    # Key must bind the compensation *event*, not just the resource.
    payload = f"{call.resource_id}:{call.attempt_nonce}:{call.planner_epoch}"
    return hashlib.sha256(payload.encode()).hexdigest()


def compensate_and_verify(
    call: SpeculativeCall,
    issue_compensation,   # returns (status_code, executed: bool)
    read_state,           # returns current resource state
    expected_post_state,
) -> None:
    key = derive_compensation_key(call)
    status, executed = issue_compensation(key)
    if status != 200:
        raise CompensationDeduplicatedError(
            f"compensation for {call.resource_id} returned {status}"
        )
    if not executed:
        # 200 but the downstream deduplicated: the key collided with a prior
        # compensation event. This is the silent-rollback-loss condition.
        raise CompensationDeduplicatedError(
            f"compensation key {key[:12]}… was deduplicated; "
            f"resource {call.resource_id} not actually released"
        )
    observed = read_state(call.resource_id)
    if observed != expected_post_state:
        # Defense in depth: even an executed compensation must be verified.
        raise CompensationDeduplicatedError(
            f"post-compensation state mismatch for {call.resource_id}: "
            f"expected {expected_post_state!r}, observed {observed!r}"
        )
