# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-replay-a-speculative-tool-call-cache-entry-whose-idempotency-key-was-minted-by-a-peer-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-replay-a-speculative-tool-call-cache-entry-whose-idempotency-key-was-minted-by-a-peer-agent.warrant.json
# Markdown SHA-256:   6e96de5d2b00ff37429c8b6486232b3f068a5e50eeaa9372cd6da55aa4898147
# Code AST SHA-256:   6d7bf0c2c8bb0b6389b6f28dde6540b9d1cea5df59842cf6e2f09e29b2caeda7
# Verified Classes:   SpeculativeCacheReplayError, CacheEntry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class SpeculativeCacheReplayError(RuntimeError):
    """Raised when a peer attempts to consume a speculative cache entry it cannot verify."""


@dataclass(frozen=True)
class CacheEntry:
    key: str
    resolved_args_hash: str
    decision_id: str
    speculative: bool
    result: dict


def mint_key(resolved_args: dict) -> str:
    # Key MUST bind fully-resolved committed arguments, not plan skeleton.
    material = "|".join(f"{k}={resolved_args[k]}" for k in sorted(resolved_args))
    return hashlib.sha256(material.encode()).hexdigest()


def consume_for_retry(
    entry: Optional[CacheEntry],
    consumer_decision_id: str,
    consumer_resolved_args: dict,
) -> dict:
    if entry is None:
        raise SpeculativeCacheReplayError("cache miss; caller must re-execute")

    expected_hash = hashlib.sha256(
        "|".join(f"{k}={consumer_resolved_args[k]}" for k in sorted(consumer_resolved_args)).encode()
    ).hexdigest()

    if entry.resolved_args_hash != expected_hash:
        raise SpeculativeCacheReplayError(
            f"key material mismatch: entry={entry.resolved_args_hash[:8]} "
            f"consumer={expected_hash[:8]}"
        )

    if entry.speculative and entry.decision_id != consumer_decision_id:
        # Peer consuming originator's unconfirmed speculation: refuse.
        raise SpeculativeCacheReplayError(
            f"refusing peer replay of speculative entry owned by {entry.decision_id}"
        )

    return entry.result
