From f4d7b6aca36c8b54386088bd7be06805ad3f1a27 Mon Sep 17 00:00:00 2001 From: Seth Troisi Date: Wed, 2 Dec 2026 10:23:47 -0800 Subject: [PATCH] fix(run,session): keep local record on failed unassign and allow stopping by endpoint In `colab run` teardown, do not remove the local session record (or log session_terminated) when `unassign` fails; instead log a warning and print a `colab stop -s ` retry hint to stderr so the session stays addressable. In `colab stop -s `, fall back to `list_assignments()` and match by server endpoint when no local session matches by name, allowing orphaned (`[?]`) assignments shown in `colab sessions` to be stopped directly. Refs: https://github.com/googlecolab/google-colab-cli/discussions/309 --- docs/01_session_management.md | 5 ++- docs/05_run_command.md | 5 +-- src/colab_cli/commands/run.py | 21 ++++++++---- src/colab_cli/commands/session.py | 24 +++++++++++-- tests/test_cli.py | 52 ++++++++++++++++++++++++++++ tests/test_run.py | 57 +++++++++++++++++++++++++++++++ 6 files changed, 151 insertions(+), 13 deletions(-) diff --git a/docs/01_session_management.md b/docs/01_session_management.md index aa5e8943..eceddeaa 100644 --- a/docs/01_session_management.md +++ b/docs/01_session_management.md @@ -1,5 +1,6 @@ --- log: +2026-12-02: `colab stop -s ` now falls back to `list_assignments()` and matches by server endpoint when `` is not found in local state, allowing orphaned (`[?]`) assignments to be stopped directly (discussion #309). 2026-12-01: Extracted `assign_runtime` in `session.py` (shared by `colab new` and `colab run`) to translate exhausted `HTTP 502/503/504` and `ReadTimeout` allocation failures into actionable CLI messages (including the browser Colab Terms of Service acceptance hint for first-time/newly entitled accounts, `colab sessions`, and `COLAB_CLI_REQUEST_TIMEOUT`) with exit code 1 instead of raw tracebacks (#273). 2026-11-23: `colab stop -s ` now exits 1 when the named session does not exist (or has already vanished from the backend), delegating missing-session handling to `State.get_session` (#251). 2026-11-13: Documented `--auth {oauth2,adc}` (default `oauth2`) and required ADC `gcloud` scopes under Global Flags. @@ -125,7 +126,8 @@ end to end; mocked timeouts alone do not establish backend compatibility. - `authuser`: 0. - ``: The unique session identifier returned during assignment (e.g., `tpu-v5e1-s-kkb-...`). - **Cleanup**: Remove the session from the local state file upon successful 204 response. -- **Missing sessions**: Stopping a specific session (`colab stop` or `colab stop -s `) exits with code 1 if no matching active session exists. `colab stop --all` exits 0 when no sessions are active. +- **Endpoint fallback**: If `-s ` does not match a local session name, `colab stop` queries `list_assignments()` and matches by server endpoint ID (as shown in `colab sessions`), unassigning the matching runtime and removing any local entry referencing that endpoint. +- **Missing sessions**: Stopping a specific session (`colab stop` or `colab stop -s `) exits with code 1 if no matching local session or server endpoint exists. `colab stop --all` exits 0 when no sessions are active. ### 4. Session Listing (`colab sessions`) - **API**: `GET https://colab.research.google.com/tun/m/assignments` (based on `colab-agent` implementation). @@ -163,6 +165,7 @@ TDD is mandatory for all session management features. ### 1. Mock Assignment API - **Test Case**: Verify `colab new` correctly parses a `PostAssignmentResponse` and stores it in the local `StateStore`. - **Test Case**: Verify `colab stop` sends a `POST` request with the correct XSRF token to the unassign endpoint. +- **Test Case**: Verify `colab stop -s ` unassigns an orphaned server-side assignment matched via `list_assignments()` (and removes any local record pointing to that endpoint). - **Test Case**: Verify `colab stop -s ` prints a not-found error and exits with status 1 without calling unassign. - **Test Case**: Verify that the path provided via `-c` is correctly passed to the authentication flow. - **Mocking**: Use `unittest.mock` to intercept `requests.Session.request` and return simulated XSSI-prefixed JSON payloads matching the HAR traces. diff --git a/docs/05_run_command.md b/docs/05_run_command.md index 0c77ce82..7b1d3aed 100644 --- a/docs/05_run_command.md +++ b/docs/05_run_command.md @@ -1,5 +1,6 @@ --- log: +2026-12-02: `_teardown` now keeps the local session record and logs/prints a retry hint (`colab stop -s `) when `unassign` fails, instead of silently deleting local state and orphaning the VM (discussion #309). 2026-11-23: Moved CPython `SystemExit` helpers (`_exit_code_from_outputs`, `_make_script_output_hook`) to `commands/execution.py` so `colab exec` and `colab run` share identical exit-code and `stderr` message semantics (including printing non-integer `sys.exit("msg")` messages to `stderr`). 2026-09-25: Removed keep-alive daemon spawning from session allocation and teardown. `--keep` remains supported and skips unassignment on completion. 2026-08-09: Added `--high-mem` flag (passthrough to session creation; sends `shape=hm` on assign when supported). @@ -64,8 +65,7 @@ print(torch.cuda.get_device_name(0)) 4. **Tear down**: In a `finally` block, unless `--keep` was passed, the CLI: - Sends `runtime.stop(shutdown_kernel=True)` (best-effort). - Calls `state.client.unassign(endpoint)` to free the billable VM. - - Removes the session from `StateStore`. - - Logs `session_terminated` with `reason="run_completed"` (or `"run_failed"`). + - Only after `unassign` succeeds: removes the session from `StateStore` and logs `session_terminated` with `reason="run_completed"` (or `"run_failed"`). If `unassign` fails, the failure is logged and printed to `stderr` with a `colab stop -s ` retry hint, and the local record is kept so the session remains addressable. If `--keep` is set, the session remains visible in `colab sessions` and `colab status` and can be reused with `colab exec -s `, `colab repl -s `, etc., until the user runs `colab stop` (or the backend reclaims it due to inactivity). @@ -85,6 +85,7 @@ If `--keep` is set, the session remains visible in `colab sessions` and `colab s 7. **`test_run_missing_script_errors`** — `colab run` with no script path errors out (Typer-level). 8. **`test_run_nonexistent_script_errors_before_assign`** — `colab run does-not-exist.py` MUST exit non-zero **without** calling `client.assign` so users don't burn a VM on a typo. 9. **`test_run_unassign_called_on_exception_during_execute`** — If `runtime.execute_code` raises, unassign is still called (try/finally guarantee). +10. **`test_run_teardown_keeps_local_session_when_unassign_fails`** / **`test_run_teardown_keeps_local_session_when_execute_and_unassign_fail`** — If `unassign` raises during teardown, the local session record is kept, `session_terminated` is not logged, and a warning with `colab stop -s ` is printed to `stderr` without masking the script's exit status. ### Integration test (`integration/repro_run_command/test.sh`) - Write a tiny script that prints its argv and exits 0. diff --git a/src/colab_cli/commands/run.py b/src/colab_cli/commands/run.py index 085e1d45..a8d66eb4 100644 --- a/src/colab_cli/commands/run.py +++ b/src/colab_cli/commands/run.py @@ -31,6 +31,7 @@ """ import datetime +import logging import os import uuid from typing import List, Optional @@ -41,8 +42,6 @@ from colab_cli.client import ( HIGH_MEM_ONLY_ACCELERATORS, PostAssignmentResponse, - Shape, - TooManyAssignmentsError, ) from colab_cli.commands.execution import ( _build_env_prelude, @@ -60,6 +59,8 @@ from colab_cli.state import SessionState from colab_cli.utils import is_terminal_error +logger = logging.getLogger(__name__) + def _build_script_payload( script_path: str, script_args: List[str], env_vars: Optional[dict[str, str]] = None @@ -387,9 +388,9 @@ def _teardown(name: str, s: SessionState, *, reason: str) -> None: """Best-effort full session teardown: ask the remote kernel to shut down, unassign the VM, and remove local state. - Mirrors `commands.session.stop` but with a richer history event reason and - swallowing all errors (we don't want a teardown failure to mask the user's - exit code). + Errors are logged rather than raised so a teardown failure never masks the + script's exit code. Local state is only removed after `unassign` succeeds + so the session remains addressable via `colab stop`. """ from colab_cli.common import state @@ -405,8 +406,14 @@ def _teardown(name: str, s: SessionState, *, reason: str) -> None: try: state.client.unassign(s.endpoint) - except Exception: - pass + except Exception as e: + logger.warning("Failed to unassign session '%s' (%s): %s", name, s.endpoint, e) + typer.echo( + f"[colab] Failed to stop session '{name}' ({e}). " + f"Run `colab stop -s {name}` to retry.", + err=True, + ) + return try: state.store.remove(name) diff --git a/src/colab_cli/commands/session.py b/src/colab_cli/commands/session.py index 140b56e2..27177cad 100644 --- a/src/colab_cli/commands/session.py +++ b/src/colab_cli/commands/session.py @@ -393,7 +393,8 @@ def _stopOne(name: str, s: SessionState) -> None: def stop( session: Annotated[ - Optional[str], typer.Option("-s", "--session", help="Session name") + Optional[str], + typer.Option("-s", "--session", help="Session name or endpoint"), ] = None, allSessions: Annotated[ bool, typer.Option("--all", help="Stop all active sessions") @@ -413,8 +414,25 @@ def stop( return name = state.resolve_session(session) - s = state.get_session(name) - _stopOne(name, s) + s = state.get_session(name, ignore_missing_session=True) + if s is not None: + _stopOne(name, s) + typer.echo("[colab] Session terminated.") + return + + match = next( + (a for a in state.client.list_assignments() if a.endpoint == name), None + ) + if match is None: + typer.echo(f"[colab] Session '{name}' not found.") + raise typer.Exit(1) + + typer.echo(f"[colab] Stopping session '{name}'...") + state.client.unassign(match.endpoint) + for local_name, local_s in state.store.list().items(): + if local_s.endpoint == match.endpoint: + state.store.remove(local_name) + state.history.log_event(name, "session_terminated", {"reason": "user_requested"}) typer.echo("[colab] Session terminated.") diff --git a/tests/test_cli.py b/tests/test_cli.py index 00a0157b..2aa8c33e 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -385,6 +385,58 @@ def test_cli_stop_pruned_session_exits_nonzero(tmp_path, mocker): real_state.client.unassign.assert_not_called() +def test_cli_stop_orphaned_session_by_endpoint( + mock_client, mock_store, mock_common_state +): + mock_store.get.return_value = None + mock_common_state.resolve_session.return_value = "m-s-orphan123" + mock_client.list_assignments.return_value = [MagicMock(endpoint="m-s-orphan123")] + + result = runner.invoke(app, ["stop", "-s", "m-s-orphan123"]) + + assert result.exit_code == 0, result.output + assert "Session terminated." in result.output + mock_client.unassign.assert_called_once_with("m-s-orphan123") + mock_store.remove.assert_not_called() + + +def test_cli_stop_by_endpoint_removes_matching_local_record(tmp_path, mocker): + from colab_cli.common import State + from colab_cli.state import SessionState, StateStore + + config_file = str(tmp_path / "sessions.json") + real_state = State() + real_state._client = MagicMock() + real_state._client.list_assignments.return_value = [MagicMock(endpoint="ep-123")] + real_state._history = MagicMock() + StateStore(config_file).add( + SessionState(name="demo", token="tok", url="https://url", endpoint="ep-123") + ) + mocker.patch("colab_cli.common.state", real_state) + mocker.patch("colab_cli.cli.state", real_state) + mocker.patch("colab_cli.auto_update.run_background_check") + + result = runner.invoke(app, ["--config", config_file, "stop", "-s", "ep-123"]) + + assert result.exit_code == 0, result.output + real_state.client.unassign.assert_called_once_with("ep-123") + assert StateStore(config_file).get("demo") is None + + +def test_cli_stop_unknown_endpoint_exits_nonzero( + mock_client, mock_store, mock_common_state +): + mock_store.get.return_value = None + mock_common_state.resolve_session.return_value = "m-s-other" + mock_client.list_assignments.return_value = [MagicMock(endpoint="m-s-orphan123")] + + result = runner.invoke(app, ["stop", "-s", "m-s-other"]) + + assert result.exit_code == 1 + assert "[colab] Session 'm-s-other' not found." in result.output + mock_client.unassign.assert_not_called() + + def test_cli_stop_all(mock_client, mock_store, mock_common_state): sessions = {"s1": MagicMock(endpoint="e1"), "s2": MagicMock(endpoint="e2")} mock_common_state.sync_sessions.return_value = (sessions, []) diff --git a/tests/test_run.py b/tests/test_run.py index 4cb48c05..ab65fabd 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -482,6 +482,63 @@ def test_run_unassign_called_on_exception_during_execute( mock_client.unassign.assert_called_once_with("ep-123") +def test_run_teardown_keeps_local_session_when_unassign_fails( + mock_common_state, + mock_client, + mock_store, + mock_runtime_class, + assign_response, + script_path, +): + mock_client.assign.return_value = assign_response + mock_runtime_class.return_value.execute_code.return_value = [] + mock_client.unassign.side_effect = RuntimeError("network down") + + persisted = {} + mock_store.add.side_effect = lambda s: persisted.setdefault("s", s) + mock_store.get.side_effect = lambda name: persisted.get("s") + + result = runner.invoke(app, ["run", "-s", "demo", str(script_path)]) + + assert result.exit_code == 0, result.output + mock_client.unassign.assert_called_once_with("ep-123") + mock_store.remove.assert_not_called() + terminated_events = [ + c + for c in mock_common_state.history.log_event.call_args_list + if len(c.args) >= 2 and c.args[1] == "session_terminated" + ] + assert not terminated_events + assert "Failed to stop session 'demo'" in result.stderr + assert "colab stop -s demo" in result.stderr + assert "Session terminated." not in result.stderr + + +def test_run_teardown_keeps_local_session_when_execute_and_unassign_fail( + mock_client, + mock_store, + mock_runtime_class, + assign_response, + script_path, +): + mock_client.assign.return_value = assign_response + mock_runtime_class.return_value.execute_code.side_effect = RuntimeError( + "websocket closed" + ) + mock_client.unassign.side_effect = RuntimeError("network down") + + persisted = {} + mock_store.add.side_effect = lambda s: persisted.setdefault("s", s) + mock_store.get.side_effect = lambda name: persisted.get("s") + + result = runner.invoke(app, ["run", "-s", "demo", str(script_path)]) + + assert result.exit_code != 0 + mock_client.unassign.assert_called_once_with("ep-123") + mock_store.remove.assert_not_called() + assert "colab stop -s demo" in result.stderr + + # --------------------------------------------------------------------------- # Accelerator passthrough # ---------------------------------------------------------------------------