# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-continuity-when-an-mcp-streamable-http-session-is-re-bound-to-a-fresh-sse-channel-mid-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-continuity-when-an-mcp-streamable-http-session-is-re-bound-to-a-fresh-sse-channel-mid-tool-call.warrant.json
# Markdown SHA-256:   d8adeb3bce8eb2f65a543967a083fc686e78546408616e9eb8003453635d3790
# Code AST SHA-256:   7c79cdb022945f9d3275d3e01417f621df646ab70d161ab72429256e3821e0e3
# Verified Classes:   OrphanedToolCallError, PendingRequest, SessionState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class OrphanedToolCallError(RuntimeError):
    """Raised when an in-flight MCP tool call's response stream was lost
    and the server did not advertise resumability, so the result cannot
    be recovered on the new stream generation."""


@dataclass
class PendingRequest:
    request_id: int
    stream_generation: int
    dispatched_at: float
    resumable: bool


@dataclass
class SessionState:
    session_id: str
    stream_generation: int = 0
    resumability_advertised: bool = False
    pending: dict = field(default_factory=dict)

    def on_sse_reconnect(self, now: Optional[float] = None) -> list:
        """Called when the GET SSE channel is re-established.
        Returns request_ids that were resolved (failed) by this reconnect."""
        now = now if now is not None else time.time()
        self.stream_generation += 1
        orphaned = []
        for rid, req in list(self.pending.items()):
            if req.stream_generation >= self.stream_generation:
                continue  # dispatched on the new stream already
            if self.resumability_advertised and req.resumable:
                continue  # will be replayed via Last-Event-ID; keep alive
            # No replay path: the result, if produced, is unrecoverable.
            orphaned.append(rid)
            del self.pending[rid]
        if orphaned:
            raise OrphanedToolCallError(
                f"session {self.session_id}: {len(orphaned)} tool call(s) "
                f"{orphaned} orphaned by stream generation "
                f"{self.stream_generation - 1}->{self.stream_generation}; "
                f"server resumability={self.resumability_advertised}. "
                f"Re-issue under fresh ids; tools are at-least-once."
            )
        return orphaned
