# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-http-native-mcp-session-resumption-as-a-non-idempotent-replay-hazard-rather-than-a-transparent-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-http-native-mcp-session-resumption-as-a-non-idempotent-replay-hazard-rather-than-a-transparent-reconnect.warrant.json
# Markdown SHA-256:   fcb1d0a8fd2cce2e1804c062e63ec1b849c46a0b341d528d85461d5cb3957c66
# Code AST SHA-256:   aef7132b7da3aa953e5ad2297908ffad6430ea7d0f9d9cfdf402943ec7ab6f75
# Verified Classes:   IndeterminateOperationError, InFlightRequest, Session
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class IndeterminateOperationError(RuntimeError):
    """Raised when a non-idempotent request was in flight at partition time
    and cannot be safely replayed or proven committed on a resumed session."""


@dataclass
class InFlightRequest:
    jsonrpc_id: int
    tool_name: str
    args: dict
    side_effecting: bool


@dataclass
class Session:
    session_id: str
    # Durable, session-scoped ledger of committed operations keyed by idempotency key.
    committed: dict = field(default_factory=dict)

    def idempotency_key(self, req: InFlightRequest) -> str:
        payload = f"{req.tool_name}:{sorted(req.args.items())}"
        return hashlib.sha256(payload.encode()).hexdigest()


def resume_and_retry(
    session: Session,
    in_flight: InFlightRequest,
    server_supports_dedup: bool,
) -> dict:
    """Attempt to resume a session and replay an in-flight request after partition.

    Enforces the invariant: session continuity is NOT operation continuity.
    """
    # Idempotent work: replay is always safe.
    if not in_flight.side_effecting:
        return {"status": "replayed", "id": in_flight.jsonrpc_id}

    key = session.idempotency_key(in_flight)

    # Non-idempotent + durable dedup ledger: safe, return committed result.
    if server_supports_dedup and key in session.committed:
        return {"status": "deduplicated", "result": session.committed[key]}

    # Non-idempotent + dedup supported but no record: the prior attempt did NOT
    # commit (or ledger was lost). A single replay is safe only if we can prove
    # non-commitment; absent that proof, we must not assume it.
    if server_supports_dedup and key not in session.committed:
        # We cannot distinguish "never executed" from "executed but ledger lost".
        raise IndeterminateOperationError(
            f"Non-idempotent tool {in_flight.tool_name!r} (key={key[:12]}) "
            f"was in flight at partition; dedup ledger has no committed record. "
            f"Commit state is indeterminate; refusing to replay on resumed "
            f"session {session.session_id!r}."
        )

    # Non-idempotent + no dedup support at all: never replay on resume.
    raise IndeterminateOperationError(
        f"Server for session {session.session_id!r} exposes no idempotency "
        f"ledger; cannot resume-replay side-effecting tool "
        f"{in_flight.tool_name!r}. Force re-initialize and reconcile downstream."
    )
