# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-desynchronize-its-tool-call-ledger-when-an-http-native-mcp-server-upgrades-a-stateless-stream-to-a-stateful-session-mid.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-desynchronize-its-tool-call-ledger-when-an-http-native-mcp-server-upgrades-a-stateless-stream-to-a-stateful-session-mid.warrant.json
# Markdown SHA-256:   ff0a862f8afb4236b5d7eeb061980c293733084b1c336522ba03c0b82265376e
# Code AST SHA-256:   0e770e4eaea608be052a41cfef8a246bd7f7818825efa32f48c9029c7ab4b520
# Verified Classes:   LedgerDesyncError, PendingFuture, SessionLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import itertools
from dataclasses import dataclass, field
from typing import Any


class LedgerDesyncError(RuntimeError):
    """Raised when a response id collides with an already-resolved pending future."""


@dataclass
class PendingFuture:
    call_name: str
    resolved: bool = False
    payload: Any = None


@dataclass
class SessionLedger:
    session_id: str
    # Session-scoped monotonic allocator. Never reset within a session.
    _id_counter: itertools.count = field(default_factory=lambda: itertools.count(1))
    pending: dict[int, PendingFuture] = field(default_factory=dict)
    resolved: dict[int, Any] = field(default_factory=dict)
    upgraded_to_stream: bool = False

    def allocate_id(self, call_name: str) -> int:
        rid = next(self._id_counter)
        self.pending[rid] = PendingFuture(call_name=call_name)
        return rid

    def on_response(self, rid: int, payload: Any) -> None:
        # The invariant: a response id must resolve exactly once per session.
        if rid in self.resolved:
            raise LedgerDesyncError(
                f"duplicate response for id={rid} on session={self.session_id!r}; "
                f"previously resolved by {self.resolved[rid]!r}, now {payload!r}. "
                "Client likely recycled a JSON-RPC id across a stateless->stateful "
                "upgrade boundary. Treat as protocol violation and re-handshake."
            )
        if rid not in self.pending:
            raise LedgerDesyncError(
                f"response for unknown id={rid} on session={self.session_id!r}; "
                "no matching in-flight call. Response stream is out of sync."
            )
        fut = self.pending.pop(rid)
        fut.resolved = True
        fut.payload = payload
        self.resolved[rid] = payload

    def on_timeout(self, rid: int) -> int:
        """Recovery path. Returns the id to use for a retry, or raises."""
        if not self.upgraded_to_stream:
            # Stateless: exchange failed, safe to re-issue with a fresh id.
            self.pending.pop(rid, None)
            return self.allocate_id("retry")
        # Stateful: the original response may still arrive on the stream.
        # Reusing the id here is the exact bug this record documents.
        raise LedgerDesyncError(
            f"timeout on id={rid} while session={self.session_id!r} is in "
            "stream-upgraded mode. Do not recycle id. Send notifications/cancelled "
            "for this id, await or discard the late response, then re-issue with a "
            "fresh allocation."
        )
