# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconstitute-a-resumable-mcp-sse-session-when-the-server-s-event-id-namespace-resets-mid-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconstitute-a-resumable-mcp-sse-session-when-the-server-s-event-id-namespace-resets-mid-stream.warrant.json
# Markdown SHA-256:   e67194aa1cea5b42b5074c2cc14adc287588e0611f1d5d4dd7a4961b8f0fb3bc
# Code AST SHA-256:   fa3989fd022ee900e6c9d72368bc72c19a15a0ff5c8e52818471e809698497d2
# Verified Classes:   SessionNamespaceReset, ResumableSSEClient
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SessionNamespaceReset(RuntimeError):
    """Raised when a resumed MCP SSE stream's event-ID namespace does not match the session's recorded namespace."""
    pass


class ResumableSSEClient:
    def __init__(self, session_id: str, namespace_token: str, last_event_id: int):
        self.session_id = session_id
        self.namespace_token = namespace_token  # recorded at initialize
        self.last_event_id = last_event_id
        self.pending_tool_calls: dict[str, object] = {}

    def resume(self, response_namespace_token: str, first_event_id: int) -> None:
        # Guard 1: server must attest the namespace it is emitting into.
        if response_namespace_token != self.namespace_token:
            raise SessionNamespaceReset(
                f"namespace token mismatch on resume: session={self.session_id} "
                f"expected={self.namespace_token!r} got={response_namespace_token!r}; "
                f"pending tool calls {list(self.pending_tool_calls)} cannot be resolved "
                f"in the new namespace and must be re-driven."
            )
        # Guard 2: monotonicity. A first event id <= last seen is positive
        # evidence of namespace reset, not benign duplication.
        if first_event_id <= self.last_event_id:
            raise SessionNamespaceReset(
                f"non-monotonic resume: last_event_id={self.last_event_id} "
                f"first_event_id={first_event_id}; treating as namespace reset."
            )
        self.last_event_id = first_event_id

    def invalidate_and_reinitialize(self) -> None:
        # Caller must re-run MCP initialize to obtain a fresh session + namespace,
        # then re-drive every call in pending_tool_calls with idempotency keys.
        self.pending_tool_calls.clear()
        self.namespace_token = ""
        self.last_event_id = 0
