# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-results-when-an-mcp-streamable-http-session-resumes-across-a-load-balanced-replica-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-results-when-an-mcp-streamable-http-session-resumes-across-a-load-balanced-replica-boundary.warrant.json
# Markdown SHA-256:   ae41e31a220c40030c40608e71b27c55a8d0453670ab8c1183f56f45d8ce54eb
# Code AST SHA-256:   cef78eea5e9e20fbcfc83f12cef3376c1b3dc0ff6caa435939ac6b280331e23e
# Verified Classes:   SessionResumptionError, SessionState, StreamableHTTPReplica
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class SessionResumptionError(RuntimeError):
    """Raised when a Last-Event-ID cannot be honored by the receiving replica."""
    pass


@dataclass
class SessionState:
    session_id: str
    replica_id: str
    event_log: list = field(default_factory=list)   # list of (event_id, payload)
    pending_call: Optional[str] = None              # request id of in-flight tool call
    effectful: bool = False


class StreamableHTTPReplica:
    def __init__(self, replica_id: str, shared_log_backend=None):
        self.replica_id = replica_id
        self.local_sessions: dict[str, SessionState] = {}
        # shared_log_backend: optional external store keyed by session_id
        self.shared_log_backend = shared_log_backend

    def _resolve_session(self, session_id: str) -> Optional[SessionState]:
        if session_id in self.local_sessions:
            return self.local_sessions[session_id]
        if self.shared_log_backend is not None:
            return self.shared_log_backend.get(session_id)
        return None

    def resume(self, session_id: str, last_event_id: int, client_will_reissue: bool) -> list:
        """
        Handle a reconnect carrying Last-Event-ID. The spec says: return events
        after last_event_id. The deployment invariant says: only do that if the
        log is reachable AND, for effectful sessions, the pending future is
        reachable or the call is safely re-issuable.
        """
        session = self._resolve_session(session_id)

        if session is None:
            # Unknown session on this replica. Do NOT return a bare 404 that the
            # client maps to re-initialize + re-issue; that duplicates effectful calls.
            if client_will_reissue:
                raise SessionResumptionError(
                    f"session {session_id} unknown on replica {self.replica_id}; "
                    f"refusing to signal re-issue because the original call may be "
                    f"in-flight on another replica"
                )
            raise SessionResumptionError(
                f"session {session_id} unreachable from replica {self.replica_id}; "
                f"event log not shared and no affinity"
            )

        # Log is reachable. But if the session is effectful and the pending call
        # future is not resolvable here, resuming the stream would hang the client
        # waiting for a result that this replica cannot produce.
        if session.effectful and session.pending_call is not None:
            future_reachable = (
                session.replica_id == self.replica_id
                or self.shared_log_backend is not None
            )
            if not future_reachable:
                raise SessionResumptionError(
                    f"session {session_id} log reachable but pending call "
                    f"{session.pending_call} lives on replica {session.replica_id}; "
                    f"resuming here would block the client indefinitely"
                )

        return [e for e in session.event_log if e[0] > last_event_id]

    def emit(self, session_id: str, payload: dict) -> int:
        session = self._resolve_session(session_id)
        if session is None:
            raise SessionResumptionError(f"cannot emit into unknown session {session_id}")
        event_id = (session.event_log[-1][0] + 1) if session.event_log else 1
        session.event_log.append((event_id, payload))
        return event_id


def reconnect_guard(replica: StreamableHTTPReplica, session_id: str,
                    last_event_id: int, tool_is_effectful: bool) -> list:
    """
    Client-facing entry point. Enforces the deployment invariant before the
    protocol contract is honored.
    """
    try:
        events = replica.resume(session_id, last_event_id,
                                client_will_reissue=not tool_is_effectful)
    except SessionResumptionError as e:
        # Surface a distinct code so the client polls status instead of re-issuing.
        raise SessionResumptionError(
            f"resumption refused: {e}. Client must poll by original request id, "
            f"not re-issue the tool call."
        ) from e

    if tool_is_effectful and not events:
        raise SessionResumptionError(
            f"effectful session {session_id} resumed with empty event tail; "
            f"result may have been emitted into an orphaned log — poll status"
        )
    return events
