From 5d16dabbc8919566cd2eef363d80513cfee25f76 Mon Sep 17 00:00:00 2001 From: aarsaputra Date: Fri, 4 Dec 2026 13:09:52 +0800 Subject: [PATCH] fix(runtime,exec): wait for cold kernel WebSocket handshake and stop runtime on prelude failure --- src/colab_cli/commands/execution.py | 2 + src/colab_cli/runtime.py | 45 ++++++++++++ tests/test_runtime.py | 105 ++++++++++++++++++++++++++++ 3 files changed, 152 insertions(+) diff --git a/src/colab_cli/commands/execution.py b/src/colab_cli/commands/execution.py index 30255096..12cbb3d5 100644 --- a/src/colab_cli/commands/execution.py +++ b/src/colab_cli/commands/execution.py @@ -296,6 +296,7 @@ def on_sess_started(sid): "os.makedirs('/content', exist_ok=True); os.chdir('/content')" ) except Exception as e: + runtime.stop() if is_terminal_error(e): typer.echo( f"[colab] Session '{name}' appears to be lost (404/401). Cleaning up." @@ -399,6 +400,7 @@ def on_sess_started(sid): "import os; os.makedirs('/content', exist_ok=True); os.chdir('/content')" ) except Exception as e: + runtime.stop() if is_terminal_error(e): typer.echo( f"[colab] Session '{name}' appears to be lost (404/401). Cleaning up." diff --git a/src/colab_cli/runtime.py b/src/colab_cli/runtime.py index 96cd442b..0310c2fc 100644 --- a/src/colab_cli/runtime.py +++ b/src/colab_cli/runtime.py @@ -13,6 +13,7 @@ # limitations under the License. import logging +import os import queue import time from typing import Any, Callable, Dict, List, Optional @@ -23,10 +24,24 @@ # The longest single wait for a kernel message, so a lost connection is noticed. _WAIT_SLICE_SEC = 1.0 +# Default time to wait for a cold runtime's kernel WebSocket handshake to finish. +_DEFAULT_WS_CONNECT_TIMEOUT_SEC = 60.0 # Kernel states that end any execution in progress. _KERNEL_GONE = frozenset({"dead", "restarting"}) +def _ws_connect_timeout() -> float: + raw = os.getenv("COLAB_CLI_KERNEL_CONNECT_TIMEOUT", "") + if raw.strip(): + try: + val = float(raw) + if val > 0: + return val + except ValueError: + pass + return _DEFAULT_WS_CONNECT_TIMEOUT_SEC + + class ColabRuntime: def __init__( self, @@ -141,6 +156,7 @@ def kernel_client(self): self._kernel_client._own_kernel = False self._kernel_client.start() + self._wait_for_ws_ready() self._apply_ws_hook() # Capture IDs if we started fresh @@ -178,6 +194,33 @@ def kernel_client(self): return self._kernel_client + def _wait_for_ws_ready(self) -> None: + """Ensure the kernel WebSocket handshake completed before returning. + + ``jupyter_kernel_client``'s ``start_channels()`` waits only + ``REQUEST_TIMEOUT`` (10 s) on ``connection_ready`` and ignores a + ``False`` return value. Cold runtimes can take 20-40 s to finish the + ``101 Switching Protocols`` upgrade, which otherwise causes the next + ``execute()`` call to fail immediately with a misleading + ``RuntimeError("Connection was lost.")``. + """ + wsclient = self._kernel_client._manager.client + ready_event = getattr(wsclient, "connection_ready", None) + if ready_event is None or ready_event.is_set(): + return + + connect_timeout = _ws_connect_timeout() + logging.debug( + "Kernel WebSocket handshake still in progress; waiting up to %gs...", + connect_timeout, + ) + if not ready_event.wait(timeout=connect_timeout): + self.stop() + raise requests.exceptions.ConnectTimeout( + f"Timed out after {connect_timeout:g}s waiting for kernel " + "WebSocket handshake (cold runtime may still be starting)." + ) + def restart( self, timeout: Optional[float] = None, @@ -349,3 +392,5 @@ def stop(self, shutdown_kernel: bool = False): self._kernel_client._manager.shutdown_kernel(now=True) except Exception: logging.exception("Error stopping kernel client") + finally: + self._kernel_client = None diff --git a/tests/test_runtime.py b/tests/test_runtime.py index 00f00dde..32088ab0 100644 --- a/tests/test_runtime.py +++ b/tests/test_runtime.py @@ -243,3 +243,108 @@ def test_colab_runtime_stdin_logging(): mock_history.log_event.assert_any_call( "test-s", "input_reply", {"value": "user input"} ) + + +def test_colab_runtime_waits_for_slow_cold_ws_handshake(monkeypatch): + """If start() returns before the cold WebSocket upgrade completes, + kernel_client waits for connection_ready instead of failing immediately.""" + import threading + + target_attr = ( + "ColabKernelClient" + if hasattr(jupyter_kernel_client, "ColabKernelClient") + else ( + "KernelClient" + if hasattr(jupyter_kernel_client, "KernelClient") + else "JupyterKernelClient" + ) + ) + ready_event = threading.Event() + + def delayed_wait(timeout=None): + ready_event.set() + return True + + with patch.object(jupyter_kernel_client, target_attr) as mock_kc_cls: + mock_kc = mock_kc_cls.return_value + mock_kc._manager.client.connection_ready = MagicMock() + mock_kc._manager.client.connection_ready.is_set.side_effect = ready_event.is_set + mock_kc._manager.client.connection_ready.wait.side_effect = delayed_wait + + monkeypatch.setenv("COLAB_CLI_KERNEL_CONNECT_TIMEOUT", "45") + runtime = ColabRuntime("http://url", "token123") + kc = runtime.kernel_client + + assert kc == mock_kc + mock_kc._manager.client.connection_ready.wait.assert_called_once_with( + timeout=45.0 + ) + + +def test_colab_runtime_ws_handshake_timeout_retries_and_cleans_up(monkeypatch): + """When the kernel WebSocket never becomes ready, runtime stops the client, + retries, and raises a retryable ConnectTimeout instead of 'Connection was lost.'""" + import requests + + target_attr = ( + "ColabKernelClient" + if hasattr(jupyter_kernel_client, "ColabKernelClient") + else ( + "KernelClient" + if hasattr(jupyter_kernel_client, "KernelClient") + else "JupyterKernelClient" + ) + ) + + with ( + patch.object(jupyter_kernel_client, target_attr) as mock_kc_cls, + patch("colab_cli.runtime.time.sleep") as mock_sleep, + ): + mock_kc = mock_kc_cls.return_value + mock_kc._manager.client.connection_ready = MagicMock() + mock_kc._manager.client.connection_ready.is_set.return_value = False + mock_kc._manager.client.connection_ready.wait.return_value = False + + monkeypatch.setenv("COLAB_CLI_KERNEL_CONNECT_TIMEOUT", "12") + runtime = ColabRuntime("http://url", "token123") + + with pytest.raises( + requests.exceptions.ConnectTimeout, + match=r"Timed out after 12s waiting for kernel WebSocket handshake", + ): + _ = runtime.kernel_client + + assert mock_kc_cls.call_count == 3 + assert mock_kc._manager.client.stop_channels.call_count == 3 + assert runtime._kernel_client is None + assert mock_sleep.call_count == 2 + + +def test_exec_stops_runtime_when_prelude_fails(): + """If the /content prelude fails in exec_command, runtime.stop() must still + be called so background WebSocket threads do not hang the process on exit.""" + import requests + from typer.testing import CliRunner + + from colab_cli.cli import app + + runner = CliRunner() + mock_session = MagicMock() + mock_session.url = "http://url" + mock_session.token = "tok" + mock_session.kernel_id = None + mock_session.session_id = None + + with ( + patch("colab_cli.common.state.resolve_session", return_value="llm"), + patch("colab_cli.common.state.get_session", return_value=mock_session), + patch("colab_cli.commands.execution.ColabRuntime") as mock_rt_cls, + ): + mock_rt = mock_rt_cls.return_value + mock_rt.execute_code.side_effect = requests.exceptions.ConnectTimeout( + "Timed out waiting for kernel WebSocket handshake" + ) + + result = runner.invoke(app, ["exec", "-s", "llm"], input="print(1)\n") + assert result.exit_code != 0 + mock_rt.stop.assert_called_once()