# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-anchor-its-tool-call-ledger-when-an-mcp-stream-session-resumes-across-the-sse-to-streamable-http-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-anchor-its-tool-call-ledger-when-an-mcp-stream-session-resumes-across-the-sse-to-streamable-http-boundary.warrant.json
# Markdown SHA-256:   1c0915d157613ae234e5bd35a50dc8e761e0e65af3c1838caaa4a0fa8e2a7b70
# Code AST SHA-256:   2ed4035a504f1add05c4520109b3cfe8084e69ce6e7d9210e99fa6ff1867872d
# Verified Classes:   LedgerDesyncError, CallState, LedgerEntry, ToolCallLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class LedgerDesyncError(RuntimeError):
    """Raised when a resumption would cross a transport generation boundary
    without reconciliation, or when an indeterminate call cannot be resolved."""


class CallState(Enum):
    PENDING = "pending"
    APPLIED = "applied"
    INDETERMINATE = "indeterminate"


@dataclass
class LedgerEntry:
    session_id: str
    transport_generation: str
    event_id: int
    jsonrpc_id: str
    tool_name: str
    idempotency_key: Optional[str]
    state: CallState = CallState.PENDING


@dataclass
class ToolCallLedger:
    entries: dict[str, LedgerEntry] = field(default_factory=dict)

    def record_pending(self, entry: LedgerEntry) -> None:
        self.entries[entry.jsonrpc_id] = entry

    def mark_applied(self, jsonrpc_id: str, generation: str, event_id: int) -> None:
        e = self.entries[jsonrpc_id]
        if e.transport_generation != generation:
            # A result arriving on a different generation than the call was issued
            # on cannot be trusted as the result of *this* call.
            e.state = CallState.INDETERMINATE
            raise LedgerDesyncError(
                f"result for {jsonrpc_id} arrived on generation {generation}, "
                f"call issued on {e.transport_generation}"
            )
        e.state = CallState.APPLIED
        e.event_id = event_id

    def reconcile_on_reconnect(
        self,
        new_generation: str,
        server_query,  # callable(jsonrpc_id) -> "applied" | "not-executed" | "unknown"
    ) -> list[str]:
        """Returns the list of jsonrpc_ids safe to re-issue. Raises if any
        indeterminate call cannot be resolved and is non-idempotent."""
        reissue: list[str] = []
        for jid, e in self.entries.items():
            if e.state == CallState.APPLIED:
                continue
            if e.transport_generation != new_generation:
                e.state = CallState.INDETERMINATE
            if e.state == CallState.INDETERMINATE:
                verdict = server_query(jid)
                if verdict == "applied":
                    e.state = CallState.APPLIED
                elif verdict == "not-executed":
                    if e.idempotency_key is None and not _is_idempotent(e.tool_name):
                        raise LedgerDesyncError(
                            f"cannot re-issue non-idempotent {e.tool_name} "
                            f"({jid}) across generation boundary without "
                            f"idempotency key; manual reconciliation required"
                        )
                    reissue.append(jid)
                else:
                    raise LedgerDesyncError(
                        f"server could not resolve {jid} across generation "
                        f"{e.transport_generation} -> {new_generation}"
                    )
        return reissue


_IDEMPOTENT_TOOLS = {"read_file", "list_dir", "web_fetch", "search"}


def _is_idempotent(tool_name: str) -> bool:
    return tool_name in _IDEMPOTENT_TOOLS


def resume_stream(
    ledger: ToolCallLedger,
    new_generation: str,
    last_event_id: Optional[int],
    server_query,
    open_stream,  # callable(generation, cursor) -> iterator of events
):
    pending = [e for e in ledger.entries.values() if e.state != CallState.APPLIED]
    cross_generation = any(
        e.transport_generation != new_generation for e in pending
    )
    if cross_generation and last_event_id is not None:
        # Never replay a cursor across a generation boundary.
        last_event_id = None
    reissue = ledger.reconcile_on_reconnect(new_generation, server_query)
    for jid in reissue:
        ledger.entries[jid].state = CallState.PENDING
    return open_stream(new_generation, last_event_id), reissue
