# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-streamable-session-resumption-has-silently-re-based-onto-a-fresh-event-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-streamable-session-resumption-has-silently-re-based-onto-a-fresh-event-stream.warrant.json
# Markdown SHA-256:   222aabec5d047fe71dd6f7c4f5a42214c22f491d37113df3676e87ffaef589c3
# Code AST SHA-256:   9c3c01cf0b50108f657e5690107d1b3fd9e794f16fbb4cc1ecc884b9c8ed0d57
# Verified Classes:   SessionRebaseError, LedgerInconsistencyError, Event, ToolLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field


class SessionRebaseError(RuntimeError):
    """Raised when a resumed SSE stream re-bases onto a fresh event-ID namespace."""


class LedgerInconsistencyError(RuntimeError):
    """Raised when a tool invocation lacks a terminal event after a stream boundary."""


@dataclass
class Event:
    id: int
    kind: str
    payload: dict = field(default_factory=dict)


@dataclass
class ToolLedger:
    open_calls: dict = field(default_factory=dict)   # call_id -> invocation
    closed_calls: dict = field(default_factory=dict)

    def on_tool_call(self, call_id: str, tool: str) -> None:
        self.open_calls[call_id] = {"tool": tool}

    def on_tool_result(self, call_id: str) -> None:
        if call_id in self.open_calls:
            self.closed_calls[call_id] = self.open_calls.pop(call_id)

    def unresolved(self) -> list:
        return list(self.open_calls.keys())


def validate_resumption(
    last_event_id: int,
    first_event: Event,
    ledger: ToolLedger,
) -> None:
    """
    Enforce the resumption invariant at connect time, before any event
    reaches the reasoning loop. Called exactly once per reconnect.
    """
    if first_event.id <= last_event_id:
        # Regression (or duplicate) relative to the client cursor.
        # A conforming resumption MUST emit id > last_event_id.
        raise SessionRebaseError(
            f"resumed stream re-based: first event id={first_event.id} "
            f"<= Last-Event-ID={last_event_id}; event-log continuity broken"
        )

    if ledger.unresolved():
        # Even with a valid ID sequence, a resumed stream that leaves
        # tool invocations without terminal events is unsafe to reason over.
        raise LedgerInconsistencyError(
            f"tool calls without terminal event across stream boundary: "
            f"{ledger.unresolved()}"
        )


def handle_reconnect(
    last_event_id: int,
    stream: list,
    ledger: ToolLedger,
) -> None:
    if not stream:
        raise SessionRebaseError(
            "resumed stream emitted no events; cannot establish ID continuity"
        )
    validate_resumption(last_event_id, stream[0], ledger)
    # Safe to hand events to the reasoning loop.
    for ev in stream:
        if ev.kind == "tool_call":
            ledger.on_tool_call(ev.payload["call_id"], ev.payload["tool"])
        elif ev.kind == "tool_result":
            ledger.on_tool_result(ev.payload["call_id"])
