# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-speculative-tool-call-batch-that-has-already-been-committed-by-a-peer-idempotency-key-collisions-across-speculative-fan.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-speculative-tool-call-batch-that-has-already-been-committed-by-a-peer-idempotency-key-collisions-across-speculative-fan.warrant.json
# Markdown SHA-256:   580b9bd40cfcbe278903f58e1a5e45c31d83d1f32bf77bc0178b56e9e1ad5960
# Code AST SHA-256:   bc50fbaf8ab1f5a3633c5504ba989f8a86503e518310c5d85cce5dce7bc06ad6
# Verified Classes:   SpeculativeKeyMismatchError, CommittedEffect
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from hashlib import sha256
from typing import Optional


class SpeculativeKeyMismatchError(RuntimeError):
    """Raised when a speculative retry reuses an intent key with a drifted payload
    against an already-committed effect. Must halt the batch, not merge."""


@dataclass(frozen=True)
class CommittedEffect:
    intent_key: str
    payload_digest: str
    effect_id: str


def payload_digest(payload: dict) -> str:
    canonical = repr(sorted(payload.items())).encode()
    return sha256(canonical).hexdigest()


def resolve_speculative_retry(
    intent_key: str,
    retry_payload: dict,
    committed: Optional[CommittedEffect],
) -> str:
    """Return 'merge' or 'execute', or raise on the unsafe boundary.

    Invariant: key-effect congruence. A retry may only merge if the committed
    payload digest matches the retry payload digest. A committed effect with a
    drifted digest under the same intent key is a conflict, not a replay.
    """
    retry_digest = payload_digest(retry_payload)

    if committed is None:
        # First emission never landed; retry is the first real execution.
        return "execute"

    if committed.payload_digest == retry_digest:
        # True idempotent replay: safe to merge.
        return "merge"

    # Committed effect exists under the intent key, but payload drifted.
    # This is the exact condition that produced the double-apply in the trace.
    raise SpeculativeKeyMismatchError(
        f"intent_key={intent_key!r} committed as {committed.effect_id!r} "
        f"with digest {committed.payload_digest[:12]} but retry carries "
        f"digest {retry_digest[:12]}; payload drifted under a stable intent "
        f"key. Halting batch and escalating to conflict resolution."
    )


def merge_speculative_batch(batch: list[dict], store: dict[str, CommittedEffect]) -> list[str]:
    outcomes: list[str] = []
    for call in batch:
        key = call["intent_key"]
        committed = store.get(key)
        try:
            decision = resolve_speculative_retry(key, call["payload"], committed)
        except SpeculativeKeyMismatchError:
            # Do not swallow: the coordinator must surface this to the auditor.
            raise
        outcomes.append(decision)
    return outcomes
