# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-idempotent-replay-from-duplicate-delivery-in-http-native-mcp-multiplexing.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-idempotent-replay-from-duplicate-delivery-in-http-native-mcp-multiplexing.warrant.json
# Markdown SHA-256:   2795c5b5699a2e12519580814c2125c23238234a917a9dd9bc6d1f9781b566c8
# Code AST SHA-256:   ab8ee8a6c10b83448a6099d9ec2804797520d9e1dc8df196854eb64b59dc9cff
# Verified Classes:   ReplayIndistinguishableError, ReplayRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ReplayIndistinguishableError(RuntimeError):
    """Raised when a replayed request cannot be safely classified as replay vs fresh.

    This is a fail-closed signal: the server refuses to execute a non-idempotent
    tool because it cannot prove the side effect has not already occurred.
    """


class ReplayRecord:
    INTENT = "intent"
    COMPLETED = "completed"


def dispatch_tool_call(
    session_id: str,
    request_id: str,
    tool_name: str,
    payload: dict,
    dedup_store,
    idempotent_tools: frozenset,
) -> dict:
    key = (session_id, request_id)
    record = dedup_store.get(key)

    if record is not None:
        if record.state == ReplayRecord.COMPLETED:
            return record.result
        if record.state == ReplayRecord.INTENT:
            # In flight elsewhere; do not re-execute.
            raise ReplayIndistinguishableError(
                f"request {key} already in flight; replay rejected"
            )

    if tool_name in idempotent_tools:
        # Reads are always safe to re-execute; never cache them.
        return _execute(tool_name, payload)

    # Non-idempotent: must commit intent BEFORE the side effect.
    committed = dedup_store.put_if_absent(key, state=ReplayRecord.INTENT)
    if not committed:
        # Lost the race to another worker; that worker owns execution.
        raise ReplayIndistinguishableError(
            f"intent for {key} committed by another worker; replay rejected"
        )

    result = _execute(tool_name, payload)
    dedup_store.update(key, state=ReplayRecord.COMPLETED, result=result)
    return result


def _execute(tool_name: str, payload: dict) -> dict:
    # Placeholder for the actual upstream tool executor.
    raise NotImplementedError(tool_name)
