# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-the-mcp-session-id-after-a-202-accepted-resumption-against-a-replayed-json-rpc-id-on-an-http-native-mcp-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-the-mcp-session-id-after-a-202-accepted-resumption-against-a-replayed-json-rpc-id-on-an-http-native-mcp-binding.warrant.json
# Markdown SHA-256:   dcf046562cfd9c4777fbb81ee7239e75c1f46e00323c1773770dfac4b2f87341
# Code AST SHA-256:   c7ef886edbe8886460b7e74a1e752f1ba833dea642805fd67114f61feef2b3e6
# Verified Classes:   SessionIdAliasingError, CallTriple, StatelessMcpClient
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class SessionIdAliasingError(RuntimeError):
    """Raised when a 202 resumption cannot be reconciled with a replayed JSON-RPC id."""


@dataclass(frozen=True)
class CallTriple:
    session_id: str
    last_event_id: str
    jsonrpc_id: int

    def fingerprint(self) -> str:
        raw = f"{self.session_id}|{self.last_event_id}|{self.jsonrpc_id}"
        return hashlib.sha256(raw.encode()).hexdigest()


class StatelessMcpClient:
    def __init__(self, durable_store: dict[str, str]):
        # durable_store maps fingerprint -> "in_flight" | "completed"
        self._store = durable_store

    def prepare_call(
        self,
        session_id: str,
        last_event_id: str,
        proposed_id: int,
        is_retry: bool,
    ) -> CallTriple:
        triple = CallTriple(session_id, last_event_id, proposed_id)
        fp = triple.fingerprint()

        if is_retry and fp not in self._store:
            # We are retrying but have no durable record of the original call.
            # Reusing the id would alias against an in-flight original on the server.
            raise SessionIdAliasingError(
                f"retry of jsonrpc_id={proposed_id} on session={session_id} "
                f"has no durable triple; mint a fresh id before sending"
            )

        if not is_retry and fp in self._store:
            # A fresh call whose triple collides with a prior in-flight call.
            raise SessionIdAliasingError(
                f"jsonrpc_id={proposed_id} already in flight on session={session_id} "
                f"under fingerprint {fp[:12]}; id reuse across turns is unsafe"
            )

        self._store[fp] = "in_flight"
        return triple

    def on_202(self, triple: CallTriple, resume_token: Optional[str]) -> None:
        fp = triple.fingerprint()
        if self._store.get(fp) != "in_flight":
            raise SessionIdAliasingError(
                f"202 received for triple {fp[:12]} not marked in_flight; "
                f"server may have attached us to a foreign stream"
            )
        if resume_token is None:
            # Server did not disambiguate; we cannot safely resume.
            raise SessionIdAliasingError(
                f"202 on session={triple.session_id} without resume_token; "
                f"refusing to attach a second event consumer"
            )

    def on_result(self, triple: CallTriple) -> None:
        fp = triple.fingerprint()
        if self._store.get(fp) == "completed":
            raise SessionIdAliasingError(
                f"duplicate result for triple {fp[:12]}; "
                f"event stream was consumed twice under one session"
            )
        self._store[fp] = "completed"


def demo() -> None:
    store: dict[str, str] = {}
    client = StatelessMcpClient(store)

    first = client.prepare_call("s-7", "e5", 42, is_retry=False)
    client.on_202(first, resume_token="r-1")
    client.on_result(first)

    # Stateless turn 2: same id, no memory of the triple.
    try:
        client.prepare_call("s-7", "e5", 42, is_retry=True)
    except SessionIdAliasingError as exc:
        print(f"blocked aliasing: {exc}")
        # Correct path: mint a fresh id.
        retry = client.prepare_call("s-7", "e5", 43, is_retry=True)
        assert retry.jsonrpc_id == 43


if __name__ == "__main__":
    demo()
