# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-diverge-from-its-own-replay-log-when-a-multi-agent-rollback-re-executes-a-checkpointed-tool-call-whose-idempotency-key-was-minted.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-diverge-from-its-own-replay-log-when-a-multi-agent-rollback-re-executes-a-checkpointed-tool-call-whose-idempotency-key-was-minted.warrant.json
# Markdown SHA-256:   8c3a324ffcbc5adf7ebc1da51dd72a4f0af08772d4e947265b6843c83943a680
# Code AST SHA-256:   f3994f0ed1254b0aea6675a440424fe0fced43787e5ffb821fc85fb88ebc1dca
# Verified Classes:   ReplayIdentityDivergence, DedupHorizonExpired, CheckpointedCall, ReplayContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from typing import Any


class ReplayIdentityDivergence(RuntimeError):
    """Raised when a replayed tool call's recomputed idempotency key differs
    from the key recorded in the checkpoint, or when the key is absent and
    the runtime cannot prove effect-idempotence."""
    pass


class DedupHorizonExpired(RuntimeError):
    """Raised when the external dedup window is shorter than the rollback
    horizon, so a stable key cannot prevent a duplicate effect."""
    pass


@dataclass
class CheckpointedCall:
    turn_index: int
    tool_name: str
    args: dict[str, Any]
    # Must be populated at checkpoint-write time. None means the checkpoint
    # was written by a runtime that deferred identity resolution.
    recorded_idempotency_key: str | None = None
    recorded_at_ns: int = 0


@dataclass
class ReplayContext:
    checkpoint_id: str
    dedup_ttl_ns: int
    current_time_ns: int = field(default_factory=time.time_ns)


def recompute_key(call: CheckpointedCall) -> str:
    # Simulates the naive dispatch-time key: wall clock at replay.
    return hashlib.sha256(
        f"{call.tool_name}:{call.args.get('resource_id')}:{time.time_ns()}".encode()
    ).hexdigest()


def replay_tool_call(call: CheckpointedCall, ctx: ReplayContext) -> str:
    if call.recorded_idempotency_key is None:
        raise ReplayIdentityDivergence(
            f"checkpoint {ctx.checkpoint_id} turn {call.turn_index}: "
            f"no recorded idempotency key for tool {call.tool_name!r}; "
            f"refusing to replay under recomputed identity"
        )

    recomputed = recompute_key(call)
    if recomputed != call.recorded_idempotency_key:
        raise ReplayIdentityDivergence(
            f"checkpoint {ctx.checkpoint_id} turn {call.turn_index}: "
            f"recorded key {call.recorded_idempotency_key[:12]}... != "
            f"recomputed key {recomputed[:12]}...; effect identity diverged"
        )

    rollback_latency_ns = ctx.current_time_ns - call.recorded_at_ns
    if rollback_latency_ns > ctx.dedup_ttl_ns:
        raise DedupHorizonExpired(
            f"checkpoint {ctx.checkpoint_id} turn {call.turn_index}: "
            f"rollback latency {rollback_latency_ns}ns exceeds dedup TTL "
            f"{ctx.dedup_ttl_ns}ns; stable key cannot prevent duplicate effect"
        )

    return call.recorded_idempotency_key
