# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-resumed-mcp-streamable-http-session-as-a-fresh-correlation-namespace-rather-than-a-continuation-of-the-pre.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-resumed-mcp-streamable-http-session-as-a-fresh-correlation-namespace-rather-than-a-continuation-of-the-pre.warrant.json
# Markdown SHA-256:   d5bb6de7e8cf347c8eed3724afd6b28c7555f65638d077fccf73d7f326c30004
# Code AST SHA-256:   956db4b2e11f6bf4e80c8075da420289858ce0ef5b4646088a3b7aab41ff10ae
# Verified Classes:   StaleCorrelationError, PendingRequest, McpSessionState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass, field
from typing import Dict, Tuple


class StaleCorrelationError(RuntimeError):
    """Raised when a response is matched against a server-initiated request
    that belongs to a prior connection generation of the same MCP session."""


@dataclass
class PendingRequest:
    session_id: str
    connection_generation: int
    rpc_id: int
    method: str
    issued_at: float


@dataclass
class McpSessionState:
    session_id: str
    connection_generation: int = 0
    pending: Dict[Tuple[str, int, int], PendingRequest] = field(default_factory=dict)

    def on_reconnect(self) -> None:
        # Fresh-namespace invariant: prior-generation server-initiated
        # requests are historical. Do not carry them into the new stream.
        self.connection_generation += 1
        self.pending.clear()

    def register_server_request(self, rpc_id: int, method: str) -> PendingRequest:
        key = (self.session_id, self.connection_generation, rpc_id)
        if key in self.pending:
            raise StaleCorrelationError(
                f"duplicate server-initiated id {rpc_id} within generation "
                f"{self.connection_generation} of session {self.session_id}"
            )
        req = PendingRequest(
            session_id=self.session_id,
            connection_generation=self.connection_generation,
            rpc_id=rpc_id,
            method=method,
            issued_at=time.monotonic(),
        )
        self.pending[key] = req
        return req

    def resolve_client_response(self, rpc_id: int, generation: int) -> PendingRequest:
        key = (self.session_id, generation, rpc_id)
        req = self.pending.pop(key, None)
        if req is None:
            raise StaleCorrelationError(
                f"response for id {rpc_id} arrived under generation {generation}, "
                f"but live generation is {self.connection_generation}; "
                f"request is stale or was never issued on this connection"
            )
        return req


def handle_inbound_response(
    state: McpSessionState, rpc_id: int, response_generation: int
) -> PendingRequest:
    # A response replayed from before a reconnect carries the old generation.
    # Reject it rather than silently matching against a reused id.
    if response_generation != state.connection_generation:
        raise StaleCorrelationError(
            f"id {rpc_id} responded under generation {response_generation}, "
            f"current generation {state.connection_generation}; "
            f"discarding to avoid mis-correlation on resumed stream"
        )
    return state.resolve_client_response(rpc_id, response_generation)
