# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reuses-an-mcp-session-identifier-across-independent-http-requests-after-the-server-has-already-retired-that-session.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reuses-an-mcp-session-identifier-across-independent-http-requests-after-the-server-has-already-retired-that-session.warrant.json
# Markdown SHA-256:   36ccd842a2139f438a0592f51cb5a78f210807a5ede0b08a63d0aa0211b05ff7
# Code AST SHA-256:   65cf4616da2b36e9d738566d88566e50ce026b7ad22bcb69305c2430ae416c43
# Verified Classes:   SessionEpochInvalidated, SessionEpoch, McpHttpSession
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class SessionEpochInvalidated(RuntimeError):
    """Raised when an MCP session-bearing request returns 404, meaning the
    server has retired the session the client still believed was live.
    This is plan-invalidating, not retryable."""


@dataclass(frozen=True)
class SessionEpoch:
    session_id: str
    protocol_version: str
    capabilities_hash: str


def _hash_caps(capabilities: dict) -> str:
    canonical = repr(sorted(capabilities.items())).encode()
    return hashlib.sha256(canonical).hexdigest()


class McpHttpSession:
    def __init__(self, transport):
        self._transport = transport
        self._epoch: Optional[SessionEpoch] = None

    def initialize(self) -> SessionEpoch:
        resp = self._transport.post("initialize", {})
        caps = resp.get("capabilities", {})
        self._epoch = SessionEpoch(
            session_id=resp["Mcp-Session-Id"],
            protocol_version=resp["protocolVersion"],
            capabilities_hash=_hash_caps(caps),
        )
        return self._epoch

    def call(self, method: str, params: dict) -> dict:
        if self._epoch is None:
            raise SessionEpochInvalidated(
                "call() invoked before initialize(); no epoch to bind to"
            )
        resp = self._transport.post(
            method, params, headers={"Mcp-Session-Id": self._epoch.session_id}
        )
        if resp.status == 404:
            # Server has retired (or never knew) this session. Do NOT retry
            # with the same header. Re-initialize and diff capabilities.
            prior = self._epoch
            new = self.initialize()
            if new.capabilities_hash != prior.capabilities_hash:
                raise SessionEpochInvalidated(
                    f"session {prior.session_id} retired; re-initialized as "
                    f"{new.session_id} but capabilities changed "
                    f"({prior.capabilities_hash[:8]} -> "
                    f"{new.capabilities_hash[:8]}). Plan constructed under "
                    f"prior epoch is invalid; re-plan from checkpoint."
                )
            raise SessionEpochInvalidated(
                f"session {prior.session_id} retired; re-initialized as "
                f"{new.session_id} with identical capabilities. Re-issue "
                f"non-idempotent in-flight requests before resuming."
            )
        return resp.body
