# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-server-push-elicitation-answers-when-an-mcp-streamable-session-resumes-across-a-dropped-sse-leg.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-server-push-elicitation-answers-when-an-mcp-streamable-session-resumes-across-a-dropped-sse-leg.warrant.json
# Markdown SHA-256:   b5bd55cc8ad8faf46768d371263d6d19b837b4d9dda4fbe9b9d681d3b06e3f5f
# Code AST SHA-256:   1c288f68fcad27c7ab5732baaeeb3a06f0c198e726da64c467c6f91e0d14a40e
# Verified Classes:   OrphanedElicitationError, StreamState, StreamableSession
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict, Optional, Set


class OrphanedElicitationError(RuntimeError):
    """Raised when a streamable-session reattach completes but the client's
    outstanding server-push request set diverges from the server's."""
    pass


@dataclass
class StreamState:
    last_event_id: int = 0
    # request_id -> sent_at; populated when the client *receives* a server-push request
    pending_server_requests: Dict[str, float] = field(default_factory=dict)


class StreamableSession:
    def __init__(self, session_id: str):
        self.session_id = session_id
        self.state = StreamState()

    def on_server_push_request(self, request_id: str) -> None:
        self.state.pending_server_requests[request_id] = time.monotonic()

    def on_elicitation_response(self, request_id: str) -> None:
        self.state.pending_server_requests.pop(request_id, None)

    def on_event(self, event_id: int) -> None:
        if event_id <= self.state.last_event_id:
            return
        self.state.last_event_id = event_id

    def reattach(self, server_outstanding: Set[str], resync_ok: bool) -> None:
        # Transport reconnect is NOT protocol resumption. Reconcile explicitly.
        client_outstanding = set(self.state.pending_server_requests)
        orphaned_on_client = server_outstanding - client_outstanding  # server awaits, client never saw
        orphaned_on_server = client_outstanding - server_outstanding  # client awaits, server forgot

        if orphaned_on_client and not resync_ok:
            raise OrphanedElicitationError(
                f"session {self.session_id}: reattach would orphan "
                f"{sorted(orphaned_on_client)} (server awaiting, client never received); "
                f"refusing to proceed without explicit resync round-trip"
            )
        if orphaned_on_server:
            raise OrphanedElicitationError(
                f"session {self.session_id}: client holds pending requests "
                f"{sorted(orphaned_on_server)} the server no longer tracks; "
                f"session state diverged — cancel and re-establish"
            )
        # Only after a clean reconciliation may new tool calls proceed on this session.
        self.state.pending_server_requests = {rid: time.monotonic() for rid in server_outstanding}
