# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-speculatively-pre-execute-a-tool-call-under-an-idempotency-key-and-still-double-apply-the-effect-when-the-optimistic-concurrency.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-speculatively-pre-execute-a-tool-call-under-an-idempotency-key-and-still-double-apply-the-effect-when-the-optimistic-concurrency.warrant.json
# Markdown SHA-256:   f798ec23aaa517a722d0c9d060cb75fe56f2886e4261a58612904df6749e0baf
# Code AST SHA-256:   0cd5594fc7e1985bd06571adc8edc1e39446eb9afa99e8a15f24e39adff0967b
# Verified Classes:   SpeculativeCommitDivergence, SpeculativeRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SpeculativeCommitDivergence(RuntimeError):
    """Raised when a speculative tool call's commit-time precondition no longer
    matches the speculation-time precondition recorded with its idempotency key."""


@dataclass(frozen=True)
class SpeculativeRecord:
    idem_key: str
    tool: str
    args_digest: str
    precondition_token: int  # version/ETag observed BEFORE any speculative effect


def commit_speculative(record: SpeculativeRecord, observed_token: int) -> str:
    """Commit a speculatively executed effect, refusing to re-derive the
    optimistic-concurrency precondition across a preemption boundary."""
    if observed_token != record.precondition_token:
        # The world moved between speculation and commit. Retrying with a
        # fresh token would authorize a second, semantically distinct write
        # that the idempotency key does not cover.
        raise SpeculativeCommitDivergence(
            f"precondition drifted for key={record.idem_key} "
            f"tool={record.tool} args={record.args_digest}: "
            f"speculated v={record.precondition_token}, observed v={observed_token}; "
            f"route to keyed read-back reconciliation, do not retry"
        )
    return f"committed:{record.idem_key}"


def resume_step(record: SpeculativeRecord, store_token: int) -> str:
    """Resume path: replay the recorded tuple verbatim; never re-mint the key."""
    if store_token > record.precondition_token:
        # Prior speculative effect likely landed; reconcile by key, not by re-issue.
        raise SpeculativeCommitDivergence(
            f"ambiguous outcome on resume for key={record.idem_key}: "
            f"store at v={store_token} > speculated v={record.precondition_token}; "
            f"perform keyed read-back before any re-issue"
        )
    return commit_speculative(record, store_token)


def args_digest(tool: str, **kwargs) -> str:
    canon = tool + "|" + "|".join(f"{k}={kwargs[k]}" for k in sorted(kwargs))
    return hashlib.sha256(canon.encode()).hexdigest()[:16]
