From ed8f98889400c450a19392bc0f1141e375fd1424 Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Thu, 19 Nov 2026 03:51:30 +0000 Subject: [PATCH 01/17] feat(state): track attached sessions in sessions.json Add `SessionState.attached` (default `False`) and `StateStore.is_attached_endpoint` so attached runtimes are stored in `sessions.json` instead of a second file. Derive the default `sessions.json` and `colab.log` directory from `SettingsStore.path`, and ensure the store directory exists before opening its `ReadWriteLock`. --- AGENTS.md | 2 +- CHANGELOG.md | 2 + docs/01_session_management.md | 4 +- src/colab_cli/common.py | 12 +++-- src/colab_cli/state.py | 18 +++++-- tests/test_common.py | 63 +++++++++++++++++++++++- tests/test_state.py | 93 +++++++++++++++++++++++++++++++++++ 7 files changed, 184 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e8236b4c..85b47c80 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,7 @@ - `colab.research.google.com` (session backend / `tun/m/...`): requires the `colaboratory` and `userinfo.email` scopes. Handles assign, unassign, CCU info, and the contents API. - **Runtime**: `ColabRuntime` wraps `jupyter-kernel-client` for execution. - **State**: - - `StateStore` persists session metadata in `~/.config/colab-cli/sessions.json`. + - `StateStore` persists session metadata in `~/.config/colab-cli/sessions.json`, with `SessionState.attached` marking sessions attached to a runtime the CLI did not create. - Persistent settings are in `~/.config/colab-cli/settings.json`. - **History**: `HistoryLogger` records structured events in `~/.config/colab-cli/history/*.jsonl`. diff --git a/CHANGELOG.md b/CHANGELOG.md index 8633acd9..85fdd338 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,8 @@ below corresponds to a tag of the same name. ### Added - **ssh:** `colab ssh [-s NAME] -- CMD` runs one command on an existing runtime and exits with its status. Output is byte-exact when piped (a PTY only when stdin and stdout are terminals), and it never creates a runtime. Its handshake is tagged `ssh-mode-cmd`. +- **sessions:** Track sessions attached to a runtime the CLI did not create in + `sessions.json` via `SessionState.attached`. ### Removed diff --git a/docs/01_session_management.md b/docs/01_session_management.md index eceddeaa..1d6b6dec 100644 --- a/docs/01_session_management.md +++ b/docs/01_session_management.md @@ -3,6 +3,7 @@ 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-18: `SessionState.attached` marks sessions attached to a runtime the CLI did not create in `sessions.json`; `State.store` and `setup_logging` derive the default config directory from `SettingsStore.path`. 2026-11-13: Documented `--auth {oauth2,adc}` (default `oauth2`) and required ADC `gcloud` scopes under Global Flags. 2026-11-04: `--gpu` and `--tpu` now reject unknown values instead of silently selecting `A100` (GPU) or `v6e1` (TPU). `resolve_runtime_options()` uses the new `GPU_ACCELERATORS` / `TPU_ACCELERATORS` maps and raises a `typer.BadParameter` that names the flag and the supported list; `--help` is generated from the same maps so it cannot drift. Validation runs before any assignment request, in both `colab new` and `colab run`. 2026-11-02: Added `_check_linux_keyring_locked` in `auth.py` to check if the active Linux `SecretService` keyring collection is locked via `secretstorage` before reading or writing OAuth tokens, logging and printing an immediate warning with the collection label, timeout, and `--auth=adc` hint while still attempting the keyring operation. @@ -154,7 +155,8 @@ The runtime proxy token (`runtimeProxyInfo.token`) authenticates every request t - Handle authentication headers (likely `Authorization: Bearer ` or cookies). ### State Persistence & File Locking -- **Stores**: `StateStore` (`sessions.json`) and `SettingsStore` (`settings.json`) both derive from `_LockedFileStore`, which guards concurrent access across independent `colab` invocations. +- **Stores**: `StateStore` (`sessions.json`) and `SettingsStore` (`settings.json`) both derive from `_LockedFileStore`, which guards concurrent access across independent `colab` invocations. `State.store` and `setup_logging` derive the default config directory from `SettingsStore.path`. +- **Attached sessions**: `SessionState.attached` (default `False`) marks sessions in `sessions.json` attached to a runtime the CLI did not create; token refresh and session sync preserve the flag. - **Cross-platform locking**: Locking uses the [`filelock`](https://pypi.org/project/filelock/) library rather than `fcntl.flock`. `fcntl` is POSIX-only and is unavailable on Windows, so the original implementation crashed on import there. `filelock` provides the same advisory cross-process locking on Linux, macOS, and Windows. - **Shared vs. exclusive**: Each store owns a `filelock.ReadWriteLock` bound to a sidecar file (`.lock`). Reads acquire `read_lock()` (shared — multiple concurrent readers allowed) and writes acquire `write_lock()` (exclusive). This preserves the `LOCK_SH`/`LOCK_EX` distinction of the previous `fcntl` implementation. - **`is_singleton=False`**: The `ReadWriteLock` is created with `is_singleton=False`. With `filelock`'s default (`True`), two `ReadWriteLock` objects for the same path *within a single process* are deduplicated into one reentrant lock; its reentrancy guard then raises `RuntimeError` when two threads each construct their own `StateStore` and contend for the write lock. Disabling the singleton registry makes each store's lock independent so they serialize via the underlying file lock instead. diff --git a/src/colab_cli/common.py b/src/colab_cli/common.py index 2cf4c744..67737f5b 100644 --- a/src/colab_cli/common.py +++ b/src/colab_cli/common.py @@ -46,7 +46,7 @@ def _apply_proxy_info(s: SessionState, info: RuntimeProxyInfo): class State: def __init__(self): self.client_oauth_config = os.path.expanduser("~/.colab-cli-oauth-config.json") - self.config_path = None + self.config_path: Optional[str] = None self.logtostderr = False self.auth_provider = AuthProvider.OAUTH2 self.use_public_api: Optional[bool] = None @@ -59,7 +59,10 @@ def __init__(self): @property def store(self): if self._store is None: - self._store = StateStore(self.config_path) + path = self.config_path or os.path.join( + os.path.dirname(self.settings_store.path), "sessions.json" + ) + self._store = StateStore(path) return self._store @property @@ -248,7 +251,10 @@ def setup_logging(log_to_stderr: bool): # Its DEBUG output includes stdin replies to the kernel, such as passwords. logging.getLogger("jupyter_kernel_client").setLevel(logging.INFO) - log_dir = os.path.expanduser("~/.config/colab-cli") + settings_path = state.settings_store.path + if not isinstance(settings_path, str): + settings_path = SettingsStore().path + log_dir = os.path.dirname(settings_path) os.makedirs(log_dir, exist_ok=True) log_path = os.path.join(log_dir, "colab.log") # FileHandler can't set permissions, so create the file owner-only first. diff --git a/src/colab_cli/state.py b/src/colab_cli/state.py index 6d08b7b3..2cf86b20 100644 --- a/src/colab_cli/state.py +++ b/src/colab_cli/state.py @@ -35,6 +35,7 @@ class SessionState(BaseModel): session_id: Optional[str] = None last_execution: Optional[Tuple[str, Optional[str], str]] = None running: Optional[str] = None + attached: bool = False class Settings(BaseModel): @@ -48,6 +49,7 @@ class Settings(BaseModel): tunnel_api_supported: Optional[bool] = None +_DEFAULT_CONFIG_DIR = "~/.config/colab-cli" _OWNER_ONLY_MODE = 0o600 @@ -69,6 +71,7 @@ class _LockedFileStore: def __init__(self, path: str): self.path = path self.lock_path = "%s.lock" % self.path + self._ensure_dir() # ReadWriteLock gives us shared (concurrent) readers and exclusive # writers -- the cross-platform equivalent of fcntl LOCK_SH/LOCK_EX. # is_singleton=False keeps each store's lock independent: with the @@ -77,7 +80,6 @@ def __init__(self, path: str): # guard then raises RuntimeError when two threads contend for the write # lock. We want them to actually serialize via the underlying file lock. self._rwlock = filelock.ReadWriteLock(self.lock_path, is_singleton=False) - self._ensure_dir() make_private(self.path) def _ensure_dir(self): @@ -109,7 +111,9 @@ def _lock_exclusive(self) -> Iterator[IO]: class SettingsStore(_LockedFileStore): def __init__(self, path: Optional[str] = None): if not path: - path = os.path.expanduser("~/.config/colab-cli/settings.json") + path = os.path.expanduser( + os.path.join(_DEFAULT_CONFIG_DIR, "settings.json") + ) super().__init__(path) def load(self) -> Settings: @@ -133,7 +137,9 @@ def save(self, settings: Settings): class StateStore(_LockedFileStore): def __init__(self, path: Optional[str] = None): if not path: - path = os.path.expanduser("~/.config/colab-cli/sessions.json") + path = os.path.expanduser( + os.path.join(_DEFAULT_CONFIG_DIR, "sessions.json") + ) super().__init__(path) def _load_raw(self, f) -> Dict[str, SessionState]: @@ -178,3 +184,9 @@ def list(self) -> Dict[str, SessionState]: if f is None: return {} return self._load_raw(f) + + def is_attached_endpoint(self, endpoint: str) -> bool: + return any( + session.attached is True and session.endpoint == endpoint + for session in self.list().values() + ) diff --git a/tests/test_common.py b/tests/test_common.py index 3ec4d473..3146cae9 100644 --- a/tests/test_common.py +++ b/tests/test_common.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import logging from datetime import datetime, timedelta, timezone from unittest.mock import MagicMock @@ -19,8 +20,8 @@ import typer from colab_cli.client import ListedAssignment -from colab_cli.common import State -from colab_cli.state import SessionState, StateStore +from colab_cli.common import State, setup_logging +from colab_cli.state import SessionState, SettingsStore, StateStore def _assignment(endpoint, token, expires_in=3600): @@ -146,3 +147,61 @@ def test_state_client_use_public_api_precedence( mocker.patch("colab_cli.common.get_credentials", return_value=MagicMock()) assert st.client.use_public_api is expected + + +def test_get_session_refresh_preserves_attached_flag(real_state): + attached_session = _session(None) + attached_session.attached = True + real_state.store.add(attached_session) + real_state.client.list_assignments.return_value = [_assignment("ep1", "new-token")] + + refreshed = real_state.get_session("s1") + + assert refreshed is not None and refreshed.attached is True + assert refreshed.token == "new-token" + assert real_state.store.get("s1").attached is True + + +def test_sync_sessions_preserves_attached_flag(real_state): + attached_session = _session(None) + attached_session.attached = True + real_state.store.add(attached_session) + real_state.client.list_assignments.return_value = [_assignment("ep1", "new-token")] + + sessions, _ = real_state.sync_sessions() + + assert sessions["s1"].attached is True + assert real_state.store.get("s1").attached is True + + +def test_state_store_derives_default_path_from_settings_store(tmp_path): + settings_dir = tmp_path / "cfg" + local_state = State() + local_state._settings_store = SettingsStore(str(settings_dir / "settings.json")) + + assert local_state.store.path == str(settings_dir / "sessions.json") + + +def test_state_store_uses_explicit_config_path(tmp_path): + override = tmp_path / "override.json" + local_state = State() + local_state._settings_store = SettingsStore(str(tmp_path / "cfg" / "settings.json")) + local_state.config_path = str(override) + + assert local_state.store.path == str(override) + + +def test_setup_logging_uses_settings_store_directory(tmp_path, monkeypatch): + settings_dir = tmp_path / "custom-log-dir" + local_state = State() + local_state._settings_store = SettingsStore(str(settings_dir / "settings.json")) + monkeypatch.setattr("colab_cli.common.state", local_state) + root_logger = logging.getLogger() + monkeypatch.setattr(root_logger, "handlers", []) + try: + setup_logging(False) + logging.getLogger("colab_cli.test").info("hello-from-settings-dir") + finally: + root_logger.handlers[0].close() + + assert "hello-from-settings-dir" in (settings_dir / "colab.log").read_text() diff --git a/tests/test_state.py b/tests/test_state.py index 94285a3e..6aea9fbf 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -12,9 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. +import json import multiprocessing import os import pytest +import stat import tempfile import threading from datetime import datetime, timezone @@ -356,3 +358,94 @@ def test_state_store_multiprocess_concurrency(temp_config): assert p1.exitcode == 0 assert p2.exitcode == 0 assert len(StateStore(temp_config).list()) == 80 + + +OWNER_ONLY = 0o600 +WORLD_READABLE = 0o644 +DEFAULT_UMASK = 0o022 + + +def test_session_state_attached_defaults_to_false(): + session = SessionState(name="s", token="t", url="u", endpoint="e") + + assert session.attached is False + + +@pytest.mark.parametrize("attached", [False, True], ids=["cli", "attached"]) +def test_state_store_persists_attached_flag(tmp_path, attached): + path = tmp_path / "sessions.json" + store = StateStore(str(path)) + + store.add( + SessionState(name="s", token="t", url="u", endpoint="e", attached=attached) + ) + + raw = json.loads(path.read_text()) + assert raw["s"]["attached"] is attached + loaded = StateStore(str(path)).get("s") + assert loaded is not None + assert loaded.attached is attached + assert not (tmp_path / "sessions.attached.json").exists() + + +def test_state_store_loads_legacy_record_without_attached_as_false(tmp_path): + path = tmp_path / "sessions.json" + path.write_text( + json.dumps({"s": {"name": "s", "token": "t", "url": "u", "endpoint": "e"}}) + ) + + loaded = StateStore(str(path)).get("s") + + assert loaded is not None + assert loaded.attached is False + + +def test_is_attached_endpoint(tmp_path): + store = StateStore(str(tmp_path / "sessions.json")) + store.add(SessionState(name="cli", token="t", url="u", endpoint="cli-ep")) + store.add( + SessionState(name="att", token="t", url="u", endpoint="att-ep", attached=True) + ) + + assert store.is_attached_endpoint("att-ep") is True + assert store.is_attached_endpoint("cli-ep") is False + assert store.is_attached_endpoint("missing") is False + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX file modes") +def test_attached_session_creates_private_sessions_file(tmp_path): + path = tmp_path / "sessions.json" + old_umask = os.umask(DEFAULT_UMASK) + try: + store = StateStore(str(path)) + store.add( + SessionState(name="att", token="t", url="u", endpoint="e", attached=True) + ) + finally: + os.umask(old_umask) + + assert stat.S_IMODE(path.stat().st_mode) == OWNER_ONLY + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX file modes") +def test_attached_session_tightens_existing_sessions_file_to_private(tmp_path): + path = tmp_path / "sessions.json" + path.touch() + os.chmod(path, WORLD_READABLE) + + store = StateStore(str(path)) + store.add(SessionState(name="att", token="t", url="u", endpoint="e", attached=True)) + + assert stat.S_IMODE(path.stat().st_mode) == OWNER_ONLY + + +def test_default_store_paths_share_config_dir(tmp_path, monkeypatch): + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setenv("USERPROFILE", str(tmp_path)) + + settings_store = SettingsStore() + state_store = StateStore() + + expected_dir = str(tmp_path / ".config" / "colab-cli") + assert settings_store.path == os.path.join(expected_dir, "settings.json") + assert state_store.path == os.path.join(expected_dir, "sessions.json") From 8d8f3351b6f09022397edddfbd8843173a6c5f08 Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Thu, 19 Nov 2026 03:58:56 +0000 Subject: [PATCH 02/17] feat(stop): skip stopping attached sessions in colab stop Remove attached sessions (and records sharing an attached endpoint) from `sessions.json` without stopping their kernel or unassigning their runtime, printing that the session was not created by the CLI and was only removed from the sessions list. Check the local record before `State.get_session` so removing an attached session makes no HTTP calls. --- CHANGELOG.md | 4 +- docs/01_session_management.md | 3 +- src/colab_cli/commands/session.py | 50 ++++++++++-- tests/test_cli.py | 121 +++++++++++++++++++++++++++++- 4 files changed, 168 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 85fdd338..2791f43a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,7 +22,9 @@ below corresponds to a tag of the same name. - **ssh:** `colab ssh [-s NAME] -- CMD` runs one command on an existing runtime and exits with its status. Output is byte-exact when piped (a PTY only when stdin and stdout are terminals), and it never creates a runtime. Its handshake is tagged `ssh-mode-cmd`. - **sessions:** Track sessions attached to a runtime the CLI did not create in - `sessions.json` via `SessionState.attached`. + `sessions.json` via `SessionState.attached`; `colab stop` and `colab stop --all` + remove attached sessions from `sessions.json` without stopping or unassigning + their runtimes. ### Removed diff --git a/docs/01_session_management.md b/docs/01_session_management.md index 1d6b6dec..5b9f2ae1 100644 --- a/docs/01_session_management.md +++ b/docs/01_session_management.md @@ -3,7 +3,7 @@ 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-18: `SessionState.attached` marks sessions attached to a runtime the CLI did not create in `sessions.json`; `State.store` and `setup_logging` derive the default config directory from `SettingsStore.path`. +2026-11-18: `SessionState.attached` marks sessions attached to a runtime the CLI did not create in `sessions.json`; `colab stop` (including `--all`) removes attached sessions without stopping or unassigning their runtimes; `State.store` and `setup_logging` derive the default config directory from `SettingsStore.path`. 2026-11-13: Documented `--auth {oauth2,adc}` (default `oauth2`) and required ADC `gcloud` scopes under Global Flags. 2026-11-04: `--gpu` and `--tpu` now reject unknown values instead of silently selecting `A100` (GPU) or `v6e1` (TPU). `resolve_runtime_options()` uses the new `GPU_ACCELERATORS` / `TPU_ACCELERATORS` maps and raises a `typer.BadParameter` that names the flag and the supported list; `--help` is generated from the same maps so it cannot drift. Validation runs before any assignment request, in both `colab new` and `colab run`. 2026-11-02: Added `_check_linux_keyring_locked` in `auth.py` to check if the active Linux `SecretService` keyring collection is locked via `secretstorage` before reading or writing OAuth tokens, logging and printing an immediate warning with the collection label, timeout, and `--auth=adc` hint while still attempting the keyring operation. @@ -119,6 +119,7 @@ end to end; mocked timeouts alone do not establish backend compatibility. - **Future**: Real-time VM resource usage (CPU/RAM/GPU) via a kernel diagnostic snippet is still TODO. For account-level compute-unit balance and usage rate, use `colab usage`. ### 3. Stop Session (`colab stop`) +- **Attached sessions**: `colab stop` (and `colab stop --all`) on an attached session, or a record sharing an attached session's endpoint, only removes the record from `sessions.json` without shutting down its kernel or unassigning its runtime, and prints `[colab] '' wasn't created by the cli and isn't stopped, only removed from sessions list`. - **API**: `POST https://colab.sandbox.google.com/tun/m/unassign/` (based on `tpu-v5e1-unassign.har`). - **Flow**: 1. Perform a `GET` request to the unassign URL to obtain a fresh XSRF token. diff --git a/src/colab_cli/commands/session.py b/src/colab_cli/commands/session.py index 27177cad..d8f121a9 100644 --- a/src/colab_cli/commands/session.py +++ b/src/colab_cli/commands/session.py @@ -377,10 +377,22 @@ def status( _print_status_for(s) -def _stopOne(name: str, s: SessionState) -> None: - """Terminate a single session (kernel, backend, local store).""" +def attached_not_stopped_message(name: str) -> str: + return ( + f"[colab] {name!r} wasn't created by the cli and isn't stopped," + " only removed from sessions list" + ) + + +def _stopOne(name: str, s: SessionState) -> bool: + """Terminate a single session, or only remove it if its runtime is attached.""" from colab_cli.common import state + if s.attached is True or state.store.is_attached_endpoint(s.endpoint) is True: + state.store.remove(name) + typer.echo(attached_not_stopped_message(name)) + return False + typer.echo(f"[colab] Stopping session '{name}'...") try: ColabRuntime(s.url, s.token, kernel_id=s.kernel_id).stop(shutdown_kernel=True) @@ -389,6 +401,7 @@ def _stopOne(name: str, s: SessionState) -> None: state.client.unassign(s.endpoint) state.store.remove(name) state.history.log_event(name, "session_terminated", {"reason": "user_requested"}) + return True def stop( @@ -408,16 +421,30 @@ def stop( if not sessions: typer.echo("[colab] No active sessions.") return - for name, s in sessions.items(): - _stopOne(name, s) - typer.echo(f"[colab] Stopped {len(sessions)} session(s).") + stopped = sum(1 for name, s in sessions.items() if _stopOne(name, s)) + if stopped: + typer.echo(f"[colab] Stopped {stopped} session(s).") return name = state.resolve_session(session) + record = state.store.get(name) + if record is not None and ( + record.attached is True + or state.store.is_attached_endpoint(record.endpoint) is True + ): + _stopOne(name, record) + return s = state.get_session(name, ignore_missing_session=True) if s is not None: - _stopOne(name, s) - typer.echo("[colab] Session terminated.") + if _stopOne(name, s): + typer.echo("[colab] Session terminated.") + return + + if state.store.is_attached_endpoint(name) is True: + for local_name, local_s in state.store.list().items(): + if local_s.endpoint == name: + state.store.remove(local_name) + typer.echo(attached_not_stopped_message(local_name)) return match = next( @@ -427,10 +454,19 @@ def stop( typer.echo(f"[colab] Session '{name}' not found.") raise typer.Exit(1) + if state.store.is_attached_endpoint(match.endpoint) is True: + for local_name, local_s in state.store.list().items(): + if local_s.endpoint == match.endpoint: + state.store.remove(local_name) + typer.echo(attached_not_stopped_message(local_name)) + return + 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: + if local_s.attached is True: + typer.echo(attached_not_stopped_message(local_name)) 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 2aa8c33e..02f9ceb1 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -25,7 +25,6 @@ from colab_cli.auth import AuthProvider from colab_cli.cli import app -from colab_cli.state import SessionState, Settings from colab_cli.client import ( Assignment, ColabRequestError, @@ -33,7 +32,10 @@ RuntimeProxyInfo, TooManyAssignmentsError, ) +from colab_cli.commands import session as session_cmd +from colab_cli.common import State from colab_cli.consumption import ConsumptionUserInfo +from colab_cli.state import SessionState, Settings, StateStore runner = CliRunner() @@ -987,3 +989,120 @@ def test_cli_logout_adc_prints_gcloud_hint(mock_common_state, mocker): assert mock_common_state.auth_provider == AuthProvider.ADC m_clear.assert_not_called() assert "gcloud auth application-default revoke" in res.output + + +def _real_stop_state(tmp_path, mocker): + mocker.patch("colab_cli.cli.auto_update.run_background_check") + local_state = State() + local_state._store = StateStore(str(tmp_path / "sessions.json")) + local_state._client = MagicMock() + local_state._history = MagicMock() + mocker.patch("colab_cli.common.state", local_state) + mocker.patch("colab_cli.cli.state", local_state) + return local_state + + +def test_attached_not_stopped_message(): + assert session_cmd.attached_not_stopped_message("nb1") == ( + "[colab] 'nb1' wasn't created by the cli and isn't stopped," + " only removed from sessions list" + ) + + +def test_stop_removes_attached_session_without_stopping_runtime(tmp_path, mocker): + local_state = _real_stop_state(tmp_path, mocker) + expired = datetime.now(timezone.utc) - timedelta(minutes=10) + local_state.store.add( + SessionState( + name="nb1", + token="t", + url="https://u", + endpoint="ep-nb1", + token_expires_at=expired, + attached=True, + ) + ) + + result = runner.invoke(app, ["stop", "-s", "nb1"]) + + assert result.exit_code == 0, result.output + assert result.output == ( + "[colab] 'nb1' wasn't created by the cli and isn't stopped," + " only removed from sessions list\n" + ) + local_state.client.list_assignments.assert_not_called() + local_state.client.unassign.assert_not_called() + session_cmd.ColabRuntime.assert_not_called() + local_state.history.log_event.assert_not_called() + assert local_state.store.get("nb1") is None + + +def test_stop_removes_cli_record_sharing_attached_endpoint(tmp_path, mocker): + local_state = _real_stop_state(tmp_path, mocker) + local_state.store.add( + SessionState( + name="nb1", token="t", url="u", endpoint="ep-shared", attached=True + ) + ) + local_state.store.add( + SessionState(name="cli2", token="t", url="u", endpoint="ep-shared") + ) + + result = runner.invoke(app, ["stop", "-s", "cli2"]) + + assert result.exit_code == 0, result.output + assert result.output == ( + "[colab] 'cli2' wasn't created by the cli and isn't stopped," + " only removed from sessions list\n" + ) + local_state.client.unassign.assert_not_called() + session_cmd.ColabRuntime.assert_not_called() + assert local_state.store.get("cli2") is None + assert local_state.store.get("nb1") is not None + + +def test_stop_all_skips_unassign_for_attached_sessions(tmp_path, mocker): + local_state = _real_stop_state(tmp_path, mocker) + cli_sess = SessionState(name="cli1", token="t", url="u", endpoint="ep-cli") + att_sess = SessionState( + name="nb1", token="t", url="u", endpoint="ep-nb1", attached=True + ) + local_state.store.add(cli_sess) + local_state.store.add(att_sess) + mocker.patch.object( + local_state, + "sync_sessions", + return_value=({"cli1": cli_sess, "nb1": att_sess}, []), + ) + + result = runner.invoke(app, ["stop", "--all"]) + + assert result.exit_code == 0, result.output + assert ( + "[colab] 'nb1' wasn't created by the cli and isn't stopped," + " only removed from sessions list" in result.output + ) + assert "[colab] Stopped 1 session(s)." in result.output + local_state.client.unassign.assert_called_once_with("ep-cli") + assert local_state.store.list() == {} + + +def test_stop_all_attached_only_omits_stopped_count(tmp_path, mocker): + local_state = _real_stop_state(tmp_path, mocker) + att_sess = SessionState( + name="nb1", token="t", url="u", endpoint="ep-nb1", attached=True + ) + local_state.store.add(att_sess) + mocker.patch.object( + local_state, "sync_sessions", return_value=({"nb1": att_sess}, []) + ) + + result = runner.invoke(app, ["stop", "--all"]) + + assert result.exit_code == 0, result.output + assert result.output == ( + "[colab] 'nb1' wasn't created by the cli and isn't stopped," + " only removed from sessions list\n" + ) + local_state.client.unassign.assert_not_called() + assert local_state.store.list() == {} From ae70edc21e2823d0c6e337c364983bcacdafe74f Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Thu, 19 Nov 2026 04:02:17 +0000 Subject: [PATCH 03/17] feat(client): guard unassign and teardown against attached runtimes Raise `AttachedRuntimeError` in `Client.unassign` when `is_attached` reports an attached endpoint, wired from `StateStore.is_attached_endpoint` in `State.client`. Guard `colab ssh --rm` and `colab run` teardown against stopping or removing attached runtimes, and keep the session record with a `colab stop -s` retry hint when `unassign` fails. --- CHANGELOG.md | 7 +++-- docs/01_session_management.md | 4 +-- src/colab_cli/client.py | 12 +++++++- src/colab_cli/commands/run.py | 10 +++++-- src/colab_cli/commands/ssh.py | 9 ++++++ src/colab_cli/common.py | 1 + tests/test_client.py | 29 +++++++++++++++++++ tests/test_run.py | 42 +++++++++++++++++++++++++++- tests/test_ssh_autocreate.py | 52 +++++++++++++++++++++++++++++++++++ 9 files changed, 157 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2791f43a..0446b556 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,9 +22,10 @@ below corresponds to a tag of the same name. - **ssh:** `colab ssh [-s NAME] -- CMD` runs one command on an existing runtime and exits with its status. Output is byte-exact when piped (a PTY only when stdin and stdout are terminals), and it never creates a runtime. Its handshake is tagged `ssh-mode-cmd`. - **sessions:** Track sessions attached to a runtime the CLI did not create in - `sessions.json` via `SessionState.attached`; `colab stop` and `colab stop --all` - remove attached sessions from `sessions.json` without stopping or unassigning - their runtimes. + `sessions.json` via `SessionState.attached`; `Client.unassign` refuses + attached endpoints, `colab stop`, `colab stop --all` and `colab ssh --rm` + remove attached sessions without stopping or unassigning their runtimes, and + `colab run` cleanup removes its record only once its runtime is released. ### Removed diff --git a/docs/01_session_management.md b/docs/01_session_management.md index 5b9f2ae1..59e06e71 100644 --- a/docs/01_session_management.md +++ b/docs/01_session_management.md @@ -3,7 +3,7 @@ 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-18: `SessionState.attached` marks sessions attached to a runtime the CLI did not create in `sessions.json`; `colab stop` (including `--all`) removes attached sessions without stopping or unassigning their runtimes; `State.store` and `setup_logging` derive the default config directory from `SettingsStore.path`. +2026-11-18: `SessionState.attached` marks sessions attached to a runtime the CLI did not create in `sessions.json`; `Client.unassign` refuses attached endpoints, `colab stop` (including `--all`) and `colab ssh --rm` remove attached sessions without stopping or unassigning their runtimes, `colab run` cleanup removes its non-attached record only once its runtime is released, and `State.store` and `setup_logging` derive the default config directory from `SettingsStore.path`. 2026-11-13: Documented `--auth {oauth2,adc}` (default `oauth2`) and required ADC `gcloud` scopes under Global Flags. 2026-11-04: `--gpu` and `--tpu` now reject unknown values instead of silently selecting `A100` (GPU) or `v6e1` (TPU). `resolve_runtime_options()` uses the new `GPU_ACCELERATORS` / `TPU_ACCELERATORS` maps and raises a `typer.BadParameter` that names the flag and the supported list; `--help` is generated from the same maps so it cannot drift. Validation runs before any assignment request, in both `colab new` and `colab run`. 2026-11-02: Added `_check_linux_keyring_locked` in `auth.py` to check if the active Linux `SecretService` keyring collection is locked via `secretstorage` before reading or writing OAuth tokens, logging and printing an immediate warning with the collection label, timeout, and `--auth=adc` hint while still attempting the keyring operation. @@ -119,7 +119,7 @@ end to end; mocked timeouts alone do not establish backend compatibility. - **Future**: Real-time VM resource usage (CPU/RAM/GPU) via a kernel diagnostic snippet is still TODO. For account-level compute-unit balance and usage rate, use `colab usage`. ### 3. Stop Session (`colab stop`) -- **Attached sessions**: `colab stop` (and `colab stop --all`) on an attached session, or a record sharing an attached session's endpoint, only removes the record from `sessions.json` without shutting down its kernel or unassigning its runtime, and prints `[colab] '' wasn't created by the cli and isn't stopped, only removed from sessions list`. +- **Attached sessions**: `colab stop` (and `colab stop --all`) and `colab ssh --rm` on an attached session, or a record sharing an attached session's endpoint, only remove the record from `sessions.json` without shutting down its kernel or unassigning its runtime, and print `[colab] '' wasn't created by the cli and isn't stopped, only removed from sessions list`. `Client.unassign` refuses any endpoint the store holds as attached, and `colab run` cleanup removes its non-attached record only once its runtime is released (otherwise it keeps the record and prints a `colab stop -s ` retry hint). - **API**: `POST https://colab.sandbox.google.com/tun/m/unassign/` (based on `tpu-v5e1-unassign.har`). - **Flow**: 1. Perform a `GET` request to the unassign URL to obtain a fresh XSRF token. diff --git a/src/colab_cli/client.py b/src/colab_cli/client.py index a094b1c3..b0d6dcd6 100644 --- a/src/colab_cli/client.py +++ b/src/colab_cli/client.py @@ -21,7 +21,7 @@ from dataclasses import dataclass from datetime import datetime, timedelta, timezone from enum import Enum -from typing import Dict, List, Optional, Union +from typing import Callable, Dict, List, Optional, Union from urllib.parse import urljoin, urlparse import requests @@ -235,6 +235,10 @@ class TooManyAssignmentsError(Exception): pass +class AttachedRuntimeError(Exception): + """Unassign was refused for an attached runtime.""" + + class Client: def __init__( self, @@ -243,6 +247,7 @@ def __init__( logger=None, use_public_api: bool = False, settings_store=None, + is_attached: Optional[Callable[[str], bool]] = None, ): self.colab_domain = env.domain self.colab_api_domain = env.api @@ -251,6 +256,7 @@ def __init__( self.logger = logger or logging.getLogger(__name__) self.use_public_api = use_public_api self.settings_store = settings_store + self._is_attached = is_attached or (lambda endpoint: False) def _auth_error_hint(self, endpoint: str, status_code: int) -> str: if status_code not in (401, 403) or self.settings_store is None: @@ -426,6 +432,10 @@ def _list_assignments_public(self) -> List[ListedAssignment]: return assignments def unassign(self, endpoint: str): + if self._is_attached(endpoint) is True: + raise AttachedRuntimeError( + f"Refusing to unassign '{endpoint}': it is an attached runtime." + ) url = urljoin(self.colab_domain, f"{TUN_ENDPOINT}/unassign/{endpoint}") resp = self._issue_request(url, schema=GetUnassignRequest) headers = {COLAB_XSRF_TOKEN_HEADER["key"]: resp.token} diff --git a/src/colab_cli/commands/run.py b/src/colab_cli/commands/run.py index a8d66eb4..bd8dfae0 100644 --- a/src/colab_cli/commands/run.py +++ b/src/colab_cli/commands/run.py @@ -398,7 +398,11 @@ def _teardown(name: str, s: SessionState, *, reason: str) -> None: try: # The script may have outlived the proxy token. fresh = state.get_session(name, ignore_missing_session=True) - if fresh: + if ( + fresh + and fresh.attached is not True + and state.store.is_attached_endpoint(fresh.endpoint) is not True + ): rt = ColabRuntime(fresh.url, fresh.token, kernel_id=fresh.kernel_id) rt.stop(shutdown_kernel=True) except Exception: @@ -416,7 +420,9 @@ def _teardown(name: str, s: SessionState, *, reason: str) -> None: return try: - state.store.remove(name) + stored = state.store.get(name) + if stored is None or stored.attached is not True: + state.store.remove(name) except Exception: pass diff --git a/src/colab_cli/commands/ssh.py b/src/colab_cli/commands/ssh.py index cbf6a42b..88c23287 100644 --- a/src/colab_cli/commands/ssh.py +++ b/src/colab_cli/commands/ssh.py @@ -229,8 +229,17 @@ def _auto_create_session( def _stop_session(name: str) -> None: """Best-effort ``colab stop`` for a session (used by ``--rm``).""" from colab_cli.commands import session as session_cmd + from colab_cli.common import state try: + record = state.store.get(name) + if record is not None and ( + record.attached is True + or state.store.is_attached_endpoint(record.endpoint) is True + ): + state.store.remove(name) + typer.echo(session_cmd.attached_not_stopped_message(name)) + return session_cmd.stop(session=name) except typer.Exit: raise diff --git a/src/colab_cli/common.py b/src/colab_cli/common.py index 67737f5b..9f5eee25 100644 --- a/src/colab_cli/common.py +++ b/src/colab_cli/common.py @@ -95,6 +95,7 @@ def client(self): creds, use_public_api=use_public, settings_store=self.settings_store, + is_attached=self.store.is_attached_endpoint, ) return self._client diff --git a/tests/test_client.py b/tests/test_client.py index 46fa8f66..a90caf35 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -22,6 +22,7 @@ from colab_cli.client import ( Accelerator, Assignment, + AttachedRuntimeError, Client, ColabRequestError, ConnectionInfo, @@ -551,3 +552,31 @@ def test_issue_request_auth_error_uses_cached_support_for_hint(tmp_path, mock_se assert "--public-api" in str(exc2.value) assert store.load().tunnel_api_supported is False + + +def test_client_unassign_refuses_attached_endpoint(mock_session): + guarded = Client(Prod(), mock_session, is_attached=lambda ep: ep == "att-ep") + + with pytest.raises(AttachedRuntimeError, match="att-ep"): + guarded.unassign("att-ep") + + mock_session.request.assert_not_called() + + +def test_state_client_wires_attached_endpoint_guard(tmp_path, mocker): + from colab_cli.common import State + from colab_cli.state import SessionState, SettingsStore, StateStore + + local_state = State() + local_state._settings_store = SettingsStore(str(tmp_path / "settings.json")) + local_state._store = StateStore(str(tmp_path / "sessions.json")) + local_state.store.add( + SessionState(name="nb1", token="t", url="u", endpoint="att-ep", attached=True) + ) + mock_http = MagicMock() + mocker.patch("colab_cli.common.get_credentials", return_value=mock_http) + + with pytest.raises(AttachedRuntimeError, match="att-ep"): + local_state.client.unassign("att-ep") + + mock_http.request.assert_not_called() diff --git a/tests/test_run.py b/tests/test_run.py index ab65fabd..b8bfd34f 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -26,13 +26,15 @@ from colab_cli.cli import app from colab_cli.client import ( Accelerator, + AttachedRuntimeError, ColabRequestError, PostAssignmentResponse, RuntimeProxyInfo, TooManyAssignmentsError, Variant, ) -from colab_cli.state import SessionState +from colab_cli.commands import run as run_cmd +from colab_cli.state import SessionState, StateStore runner = CliRunner() @@ -819,3 +821,41 @@ def test_run_with_timeout_flag( code_calls = mock_runtime.execute_code.call_args_list body_call = next(c for c in code_calls if "hello from script" in c.args[0]) assert body_call.kwargs.get("timeout") == 3600.0 + + +def test_teardown_skips_kernel_and_keeps_attached_record( + mock_common_state, mock_runtime_class, tmp_path, capsys +): + store = StateStore(str(tmp_path / "sessions.json")) + attached = SessionState( + name="nb1", token="t", url="http://u", endpoint="ep-nb1", attached=True + ) + store.add(attached) + mock_common_state.store = store + mock_common_state.get_session.side_effect = lambda name, **_: store.get(name) + mock_common_state.client.unassign.side_effect = AttachedRuntimeError("attached") + + run_cmd._teardown("nb1", attached, reason="run_completed") + + mock_runtime_class.assert_not_called() + assert store.get("nb1") is not None + assert "colab stop -s nb1" in capsys.readouterr().err + + +def test_teardown_keeps_record_and_prints_retry_hint_when_unassign_fails( + mock_common_state, mock_runtime_class, tmp_path, capsys +): + store = StateStore(str(tmp_path / "sessions.json")) + cli_sess = SessionState(name="job1", token="t", url="http://u", endpoint="ep-job") + store.add(cli_sess) + mock_common_state.store = store + mock_common_state.get_session.side_effect = lambda name, **_: store.get(name) + mock_common_state.client.unassign.side_effect = RuntimeError("network error") + + run_cmd._teardown("job1", cli_sess, reason="run_completed") + + mock_runtime_class.return_value.stop.assert_called_once_with(shutdown_kernel=True) + assert store.get("job1") is not None + err = capsys.readouterr().err + assert "[colab] Failed to stop session 'job1' (network error)." in err + assert "Run `colab stop -s job1` to retry." in err diff --git a/tests/test_ssh_autocreate.py b/tests/test_ssh_autocreate.py index b23132f0..aa484a6f 100644 --- a/tests/test_ssh_autocreate.py +++ b/tests/test_ssh_autocreate.py @@ -28,6 +28,7 @@ from click import unstyle from colab_cli.cli import app from colab_cli.commands import ssh as ssh_module +from colab_cli.state import SessionState, StateStore import pytest from typer.testing import CliRunner import typer @@ -331,3 +332,54 @@ def test_ssh_help_advertises_autocreate_flags(mocker, force_color): assert result.exit_code == 0 for flag in ("--rm", "--gpu", "--tpu"): assert flag in unstyle(result.output) + + +def test_ssh_rm_removes_attached_session_without_stopping_runtime( + mock_common_state, tmp_path, mocker, capsys +): + store = StateStore(str(tmp_path / "sessions.json")) + attached = SessionState( + name="nb1", token="t", url="https://u", endpoint="ep-nb1", attached=True + ) + store.add(attached) + mock_common_state.store = store + stop = mocker.patch("colab_cli.commands.session.stop") + _patch_interactive(mocker) + + ssh_module._run_interactive_shell(attached, None, True, True) + + stop.assert_not_called() + mock_common_state.client.unassign.assert_not_called() + assert store.get("nb1") is None + assert ( + "[colab] 'nb1' wasn't created by the cli and isn't stopped," + " only removed from sessions list" in capsys.readouterr().out + ) + + +def test_ssh_rm_proxy_removes_shared_attached_endpoint( + mock_common_state, tmp_path, mocker, capsys +): + store = StateStore(str(tmp_path / "sessions.json")) + store.add( + SessionState( + name="nb1", token="t", url="https://u", endpoint="ep1", attached=True + ) + ) + shared = SessionState(name="cli2", token="t", url="https://u", endpoint="ep1") + store.add(shared) + mock_common_state.store = store + stop = mocker.patch("colab_cli.commands.session.stop") + mocker.patch("signal.signal") + _patch_proxy(mocker) + + ssh_module._run_proxy_bridge(shared, None, True) + + stop.assert_not_called() + mock_common_state.client.unassign.assert_not_called() + assert store.get("cli2") is None + assert store.get("nb1") is not None + assert ( + "[colab] 'cli2' wasn't created by the cli and isn't stopped," + " only removed from sessions list" in capsys.readouterr().err + ) From f26d0d62e63e1424778b5db30405a6f3f2d0e114 Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Thu, 19 Nov 2026 20:00:22 +0000 Subject: [PATCH 04/17] fix(stop): guard shared attached endpoints in stop --all Collect attached endpoints before removing records in colab stop --all so a shared CLI record cannot unassign an attached runtime after the attached record is removed. Also use store keys in sessions and status output, read the active store dynamically in State.client, and add missing docstrings. --- src/colab_cli/commands/session.py | 37 +++++++++++++++++------ src/colab_cli/common.py | 2 +- src/colab_cli/state.py | 9 ++++++ tests/test_cli.py | 50 +++++++++++++++++++++++++++++++ 4 files changed, 88 insertions(+), 10 deletions(-) diff --git a/src/colab_cli/commands/session.py b/src/colab_cli/commands/session.py index d8f121a9..41c77465 100644 --- a/src/colab_cli/commands/session.py +++ b/src/colab_cli/commands/session.py @@ -316,7 +316,7 @@ def sessions_command(): return # Build endpoint -> local-name lookup so we can lead with the friendly name. - name_by_endpoint = {s.endpoint: s.name for s in sessions.values()} + name_by_endpoint = {s.endpoint: k for k, s in sessions.items()} for a in assignments: name = name_by_endpoint.get(a.endpoint, "?") # `a.variant` is an int-valued AssignmentVariant (DEFAULT=0/GPU=1/TPU=2); @@ -333,12 +333,12 @@ def sessions_command(): ) -def _print_status_for(s: SessionState) -> None: +def _print_status_for(s: SessionState, name: Optional[str] = None) -> None: """Print one session's status line plus optional last-execution detail.""" status = f"BUSY ({s.running})" if s.running else "IDLE" typer.echo( _format_session_line( - name=s.name, + name=name if name is not None else s.name, endpoint=s.endpoint, accelerator=s.accelerator, variant=s.variant, @@ -364,7 +364,7 @@ def status( if session: s = state.store.get(session) if s: - _print_status_for(s) + _print_status_for(s, name=session) else: typer.echo(f"[colab] Session '{session}' not found.", err=True) raise typer.Exit(1) @@ -373,22 +373,34 @@ def status( if not local_sessions: typer.echo("[colab] No active sessions.") return - for s in local_sessions.values(): - _print_status_for(s) + for k, s in local_sessions.items(): + _print_status_for(s, name=k) def attached_not_stopped_message(name: str) -> str: + """Returns the notice printed when removing an attached session. + + Args: + name: Session name removed from the local store. + + Returns: + Message stating the runtime was not stopped and only removed locally. + """ return ( f"[colab] {name!r} wasn't created by the cli and isn't stopped," " only removed from sessions list" ) -def _stopOne(name: str, s: SessionState) -> bool: +def _stopOne(name: str, s: SessionState, *, skip_unassign: bool = False) -> bool: """Terminate a single session, or only remove it if its runtime is attached.""" from colab_cli.common import state - if s.attached is True or state.store.is_attached_endpoint(s.endpoint) is True: + if ( + s.attached is True + or skip_unassign + or state.store.is_attached_endpoint(s.endpoint) is True + ): state.store.remove(name) typer.echo(attached_not_stopped_message(name)) return False @@ -421,7 +433,14 @@ def stop( if not sessions: typer.echo("[colab] No active sessions.") return - stopped = sum(1 for name, s in sessions.items() if _stopOne(name, s)) + attached_endpoints = { + s.endpoint for s in sessions.values() if s.attached is True + } + stopped = sum( + 1 + for name, s in sessions.items() + if _stopOne(name, s, skip_unassign=s.endpoint in attached_endpoints) + ) if stopped: typer.echo(f"[colab] Stopped {stopped} session(s).") return diff --git a/src/colab_cli/common.py b/src/colab_cli/common.py index 9f5eee25..e72caf4c 100644 --- a/src/colab_cli/common.py +++ b/src/colab_cli/common.py @@ -95,7 +95,7 @@ def client(self): creds, use_public_api=use_public, settings_store=self.settings_store, - is_attached=self.store.is_attached_endpoint, + is_attached=lambda ep: self.store.is_attached_endpoint(ep), ) return self._client diff --git a/src/colab_cli/state.py b/src/colab_cli/state.py index 2cf86b20..5695c357 100644 --- a/src/colab_cli/state.py +++ b/src/colab_cli/state.py @@ -186,6 +186,15 @@ def list(self) -> Dict[str, SessionState]: return self._load_raw(f) def is_attached_endpoint(self, endpoint: str) -> bool: + """Returns whether any attached session in the store uses ``endpoint``. + + Args: + endpoint: Colab runtime endpoint identifier. + + Returns: + True if at least one stored session has ``attached=True`` and + matches ``endpoint``, False otherwise. + """ return any( session.attached is True and session.endpoint == endpoint for session in self.list().values() diff --git a/tests/test_cli.py b/tests/test_cli.py index 02f9ceb1..7ef15c4f 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1106,3 +1106,53 @@ def test_stop_all_attached_only_omits_stopped_count(tmp_path, mocker): ) local_state.client.unassign.assert_not_called() assert local_state.store.list() == {} + + +def test_stop_all_skips_unassign_when_attached_precedes_shared_cli(tmp_path, mocker): + local_state = _real_stop_state(tmp_path, mocker) + att_sess = SessionState( + name="nb1", token="t", url="u", endpoint="ep-shared", attached=True + ) + shared_cli = SessionState(name="cli2", token="t", url="u", endpoint="ep-shared") + local_state.store.add(att_sess) + local_state.store.add(shared_cli) + mocker.patch.object( + local_state, + "sync_sessions", + return_value=({"nb1": att_sess, "cli2": shared_cli}, []), + ) + + result = runner.invoke(app, ["stop", "--all"]) + + assert result.exit_code == 0, result.output + assert session_cmd.attached_not_stopped_message("nb1") in result.output + assert session_cmd.attached_not_stopped_message("cli2") in result.output + assert "Stopped" not in result.output + local_state.client.unassign.assert_not_called() + session_cmd.ColabRuntime.assert_not_called() + assert local_state.store.list() == {} + + +def test_sessions_and_status_use_store_key_when_name_differs(mock_common_state): + mock_assignment = MagicMock() + mock_assignment.endpoint = "ep1" + mock_assignment.variant.name = "DEFAULT" + mock_assignment.accelerator.value = "NONE" + mock_assignment.machine_shape.name = "STANDARD" + sess = SessionState(name="inner", token="t", url="u", endpoint="ep1") + mock_common_state.sync_sessions.return_value = ( + {"alias": sess}, + [mock_assignment], + ) + mock_common_state.store.get.return_value = sess + + sessions_res = runner.invoke(app, ["sessions"]) + status_res = runner.invoke(app, ["status"]) + single_res = runner.invoke(app, ["status", "-s", "alias"]) + + assert sessions_res.exit_code == 0 + assert sessions_res.output.startswith("[alias] ep1 |") + assert status_res.exit_code == 0 + assert status_res.output.startswith("[alias] ep1 |") + assert single_res.exit_code == 0 + assert single_res.output.startswith("[alias] ep1 |") From a176a724268a8b529a45e1f3b2138a7a94c90262 Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Thu, 19 Nov 2026 20:02:06 +0000 Subject: [PATCH 05/17] test(ssh,run): invoke CLI entrypoints for teardown and ssh --rm tests Exercise public CLI invocations via CliRunner in ssh --rm and run teardown tests instead of calling private helpers directly, wrap new changelog and session management doc lines to 80 columns, and update run command teardown docs. --- CHANGELOG.md | 11 ++++--- docs/01_session_management.md | 27 +++++++++++++--- docs/05_run_command.md | 14 ++++++-- tests/test_run.py | 61 ++++++++++++++++++++++++----------- tests/test_ssh_autocreate.py | 47 +++++++++++++++++++-------- 5 files changed, 116 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0446b556..a644bd6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,11 +21,12 @@ below corresponds to a tag of the same name. ### Added - **ssh:** `colab ssh [-s NAME] -- CMD` runs one command on an existing runtime and exits with its status. Output is byte-exact when piped (a PTY only when stdin and stdout are terminals), and it never creates a runtime. Its handshake is tagged `ssh-mode-cmd`. -- **sessions:** Track sessions attached to a runtime the CLI did not create in - `sessions.json` via `SessionState.attached`; `Client.unassign` refuses - attached endpoints, `colab stop`, `colab stop --all` and `colab ssh --rm` - remove attached sessions without stopping or unassigning their runtimes, and - `colab run` cleanup removes its record only once its runtime is released. +- **sessions:** Track sessions attached to a runtime the CLI did not + create in `sessions.json` via `SessionState.attached`; `Client.unassign` + refuses attached endpoints, `colab stop`, `colab stop --all` and + `colab ssh --rm` remove attached sessions without stopping or unassigning + their runtimes, and `colab run` cleanup removes its record only once its + runtime is released. ### Removed diff --git a/docs/01_session_management.md b/docs/01_session_management.md index 59e06e71..a682f795 100644 --- a/docs/01_session_management.md +++ b/docs/01_session_management.md @@ -3,7 +3,13 @@ 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-18: `SessionState.attached` marks sessions attached to a runtime the CLI did not create in `sessions.json`; `Client.unassign` refuses attached endpoints, `colab stop` (including `--all`) and `colab ssh --rm` remove attached sessions without stopping or unassigning their runtimes, `colab run` cleanup removes its non-attached record only once its runtime is released, and `State.store` and `setup_logging` derive the default config directory from `SettingsStore.path`. +2026-11-18: `SessionState.attached` marks sessions attached to a runtime the + CLI did not create in `sessions.json`; `Client.unassign` refuses attached + endpoints, `colab stop` (including `--all`) and `colab ssh --rm` remove + attached sessions without stopping or unassigning their runtimes, `colab run` + cleanup removes its non-attached record only once its runtime is released, + and `State.store` and `setup_logging` derive the default config directory + from `SettingsStore.path`. 2026-11-13: Documented `--auth {oauth2,adc}` (default `oauth2`) and required ADC `gcloud` scopes under Global Flags. 2026-11-04: `--gpu` and `--tpu` now reject unknown values instead of silently selecting `A100` (GPU) or `v6e1` (TPU). `resolve_runtime_options()` uses the new `GPU_ACCELERATORS` / `TPU_ACCELERATORS` maps and raises a `typer.BadParameter` that names the flag and the supported list; `--help` is generated from the same maps so it cannot drift. Validation runs before any assignment request, in both `colab new` and `colab run`. 2026-11-02: Added `_check_linux_keyring_locked` in `auth.py` to check if the active Linux `SecretService` keyring collection is locked via `secretstorage` before reading or writing OAuth tokens, logging and printing an immediate warning with the collection label, timeout, and `--auth=adc` hint while still attempting the keyring operation. @@ -119,7 +125,15 @@ end to end; mocked timeouts alone do not establish backend compatibility. - **Future**: Real-time VM resource usage (CPU/RAM/GPU) via a kernel diagnostic snippet is still TODO. For account-level compute-unit balance and usage rate, use `colab usage`. ### 3. Stop Session (`colab stop`) -- **Attached sessions**: `colab stop` (and `colab stop --all`) and `colab ssh --rm` on an attached session, or a record sharing an attached session's endpoint, only remove the record from `sessions.json` without shutting down its kernel or unassigning its runtime, and print `[colab] '' wasn't created by the cli and isn't stopped, only removed from sessions list`. `Client.unassign` refuses any endpoint the store holds as attached, and `colab run` cleanup removes its non-attached record only once its runtime is released (otherwise it keeps the record and prints a `colab stop -s ` retry hint). +- **Attached sessions**: `colab stop` (and `colab stop --all`) and + `colab ssh --rm` on an attached session, or a record sharing an attached + session's endpoint, only remove the record from `sessions.json` without + shutting down its kernel or unassigning its runtime, and print + `[colab] '' wasn't created by the cli and isn't stopped, only removed` + `from sessions list`. `Client.unassign` refuses any endpoint the store holds + as attached, and `colab run` cleanup removes its non-attached record only + once its runtime is released (otherwise it keeps the record and prints a + `colab stop -s ` retry hint). - **API**: `POST https://colab.sandbox.google.com/tun/m/unassign/` (based on `tpu-v5e1-unassign.har`). - **Flow**: 1. Perform a `GET` request to the unassign URL to obtain a fresh XSRF token. @@ -156,8 +170,13 @@ The runtime proxy token (`runtimeProxyInfo.token`) authenticates every request t - Handle authentication headers (likely `Authorization: Bearer ` or cookies). ### State Persistence & File Locking -- **Stores**: `StateStore` (`sessions.json`) and `SettingsStore` (`settings.json`) both derive from `_LockedFileStore`, which guards concurrent access across independent `colab` invocations. `State.store` and `setup_logging` derive the default config directory from `SettingsStore.path`. -- **Attached sessions**: `SessionState.attached` (default `False`) marks sessions in `sessions.json` attached to a runtime the CLI did not create; token refresh and session sync preserve the flag. +- **Stores**: `StateStore` (`sessions.json`) and `SettingsStore` + (`settings.json`) both derive from `_LockedFileStore`, which guards + concurrent access across independent `colab` invocations. `State.store` and + `setup_logging` derive the default config directory from `SettingsStore.path`. +- **Attached sessions**: `SessionState.attached` (default `False`) marks + sessions in `sessions.json` attached to a runtime the CLI did not create; + token refresh and session sync preserve the flag. - **Cross-platform locking**: Locking uses the [`filelock`](https://pypi.org/project/filelock/) library rather than `fcntl.flock`. `fcntl` is POSIX-only and is unavailable on Windows, so the original implementation crashed on import there. `filelock` provides the same advisory cross-process locking on Linux, macOS, and Windows. - **Shared vs. exclusive**: Each store owns a `filelock.ReadWriteLock` bound to a sidecar file (`.lock`). Reads acquire `read_lock()` (shared — multiple concurrent readers allowed) and writes acquire `write_lock()` (exclusive). This preserves the `LOCK_SH`/`LOCK_EX` distinction of the previous `fcntl` implementation. - **`is_singleton=False`**: The `ReadWriteLock` is created with `is_singleton=False`. With `filelock`'s default (`True`), two `ReadWriteLock` objects for the same path *within a single process* are deduplicated into one reentrant lock; its reentrancy guard then raises `RuntimeError` when two threads each construct their own `StateStore` and contend for the write lock. Disabling the singleton registry makes each store's lock independent so they serialize via the underlying file lock instead. diff --git a/docs/05_run_command.md b/docs/05_run_command.md index 7b1d3aed..cb206a63 100644 --- a/docs/05_run_command.md +++ b/docs/05_run_command.md @@ -2,6 +2,10 @@ 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-11-18: `colab run` teardown skips kernel shutdown when the session or + endpoint is attached, keeps the session record with a `colab stop -s ` + retry hint when `unassign` fails (including `AttachedRuntimeError`), and + preserves any concurrently written attached record under the same name. 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). 2026-05-12: Initial design and implementation of `colab run [args...]`. Combines `colab new` + `colab exec` + `colab stop` into a single fire-and-forget invocation so a Python file can use `#!/usr/bin/env -S colab run` as a shebang line and execute on a freshly-allocated Colab VM. Adds `--keep` (skip auto-stop), `--gpu` / `--tpu` (passthrough to session creation), `-s/--session` (name the ephemeral session), and propagates the script's exit status (non-zero on any uncaught exception in the kernel). The script's `sys.argv` is re-set inside the kernel to mirror native `python script.py arg1 arg2` semantics, and `__name__` is set to `"__main__"`. @@ -63,9 +67,15 @@ print(torch.cuda.get_device_name(0)) Then executes the script body in the same kernel cell so any `if __name__ == "__main__":` guard fires. 3. **Detect failure**: If the kernel returns any output of `output_type == "error"` (uncaught exception, syntax error, etc.) the CLI exits non-zero. 4. **Tear down**: In a `finally` block, unless `--keep` was passed, the CLI: - - Sends `runtime.stop(shutdown_kernel=True)` (best-effort). + - Sends `runtime.stop(shutdown_kernel=True)` (best-effort) unless the + session or its endpoint is marked `attached` in `StateStore`. - Calls `state.client.unassign(endpoint)` to free the billable VM. - - 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. + - Only after `unassign` succeeds: removes the session from `StateStore` (unless + a concurrent attached record replaced it under the same name) and logs + `session_terminated` with `reason="run_completed"` (or `"run_failed"`). If + `unassign` fails (including `AttachedRuntimeError`), 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). diff --git a/tests/test_run.py b/tests/test_run.py index b8bfd34f..2a16222f 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -33,7 +33,6 @@ TooManyAssignmentsError, Variant, ) -from colab_cli.commands import run as run_cmd from colab_cli.state import SessionState, StateStore runner = CliRunner() @@ -824,38 +823,62 @@ def test_run_with_timeout_flag( def test_teardown_skips_kernel_and_keeps_attached_record( - mock_common_state, mock_runtime_class, tmp_path, capsys + mock_common_state, + mock_client, + mock_runtime_class, + assign_response, + script_path, + tmp_path, ): store = StateStore(str(tmp_path / "sessions.json")) - attached = SessionState( - name="nb1", token="t", url="http://u", endpoint="ep-nb1", attached=True - ) - store.add(attached) mock_common_state.store = store mock_common_state.get_session.side_effect = lambda name, **_: store.get(name) - mock_common_state.client.unassign.side_effect = AttachedRuntimeError("attached") + mock_client.assign.return_value = assign_response + mock_client.unassign.side_effect = AttachedRuntimeError("attached") + + def add_attached_mid_run(code, **kwargs): + if "hello from script" in code: + store.add( + SessionState( + name="nb1", + token="t", + url="http://u", + endpoint="ep-123", + attached=True, + ) + ) + return [] - run_cmd._teardown("nb1", attached, reason="run_completed") + mock_runtime_class.return_value.execute_code.side_effect = add_attached_mid_run - mock_runtime_class.assert_not_called() + result = runner.invoke(app, ["run", "-s", "job1", str(script_path)]) + + assert result.exit_code == 0, result.output + mock_runtime_class.return_value.stop.assert_called_once_with() + assert store.get("job1") is not None assert store.get("nb1") is not None - assert "colab stop -s nb1" in capsys.readouterr().err + assert "colab stop -s job1" in result.stderr def test_teardown_keeps_record_and_prints_retry_hint_when_unassign_fails( - mock_common_state, mock_runtime_class, tmp_path, capsys + mock_common_state, + mock_client, + mock_runtime_class, + assign_response, + script_path, + tmp_path, ): store = StateStore(str(tmp_path / "sessions.json")) - cli_sess = SessionState(name="job1", token="t", url="http://u", endpoint="ep-job") - store.add(cli_sess) mock_common_state.store = store mock_common_state.get_session.side_effect = lambda name, **_: store.get(name) - mock_common_state.client.unassign.side_effect = RuntimeError("network error") + mock_client.assign.return_value = assign_response + mock_runtime_class.return_value.execute_code.return_value = [] + mock_client.unassign.side_effect = RuntimeError("network error") - run_cmd._teardown("job1", cli_sess, reason="run_completed") + result = runner.invoke(app, ["run", "-s", "job1", str(script_path)]) - mock_runtime_class.return_value.stop.assert_called_once_with(shutdown_kernel=True) + assert result.exit_code == 0, result.output + mock_runtime_class.return_value.stop.assert_any_call(shutdown_kernel=True) assert store.get("job1") is not None - err = capsys.readouterr().err - assert "[colab] Failed to stop session 'job1' (network error)." in err - assert "Run `colab stop -s job1` to retry." in err + assert "[colab] Failed to stop session 'job1' (network error)." in result.stderr + assert "Run `colab stop -s job1` to retry." in result.stderr diff --git a/tests/test_ssh_autocreate.py b/tests/test_ssh_autocreate.py index aa484a6f..7fb272b2 100644 --- a/tests/test_ssh_autocreate.py +++ b/tests/test_ssh_autocreate.py @@ -335,30 +335,47 @@ def test_ssh_help_advertises_autocreate_flags(mocker, force_color): def test_ssh_rm_removes_attached_session_without_stopping_runtime( - mock_common_state, tmp_path, mocker, capsys + mock_common_state, tmp_path, mocker ): store = StateStore(str(tmp_path / "sessions.json")) - attached = SessionState( - name="nb1", token="t", url="https://u", endpoint="ep-nb1", attached=True - ) - store.add(attached) mock_common_state.store = store + mock_common_state.resolve_session.side_effect = lambda name, **_: name + mock_common_state.get_session.side_effect = lambda name, **_: store.get(name) + created_names = [] + + def attach_on_create(session=None, **_): + assert session is not None + created_names.append(session) + store.add( + SessionState( + name=session, + token="t", + url="https://u", + endpoint="ep-nb1", + attached=True, + ) + ) + + mocker.patch("colab_cli.commands.session.new", side_effect=attach_on_create) stop = mocker.patch("colab_cli.commands.session.stop") _patch_interactive(mocker) - ssh_module._run_interactive_shell(attached, None, True, True) + result = runner.invoke(app, ["ssh", "--rm"]) + assert result.exit_code == 0, result.output + assert len(created_names) == 1 + name = created_names[0] stop.assert_not_called() mock_common_state.client.unassign.assert_not_called() - assert store.get("nb1") is None + assert store.get(name) is None assert ( - "[colab] 'nb1' wasn't created by the cli and isn't stopped," - " only removed from sessions list" in capsys.readouterr().out + f"[colab] {name!r} wasn't created by the cli and isn't stopped," + " only removed from sessions list" in result.output ) def test_ssh_rm_proxy_removes_shared_attached_endpoint( - mock_common_state, tmp_path, mocker, capsys + mock_common_state, tmp_path, mocker ): store = StateStore(str(tmp_path / "sessions.json")) store.add( @@ -366,20 +383,22 @@ def test_ssh_rm_proxy_removes_shared_attached_endpoint( name="nb1", token="t", url="https://u", endpoint="ep1", attached=True ) ) - shared = SessionState(name="cli2", token="t", url="https://u", endpoint="ep1") - store.add(shared) + store.add(SessionState(name="cli2", token="t", url="https://u", endpoint="ep1")) mock_common_state.store = store + mock_common_state.resolve_session.side_effect = lambda name, **_: name + mock_common_state.get_session.side_effect = lambda name, **_: store.get(name) stop = mocker.patch("colab_cli.commands.session.stop") mocker.patch("signal.signal") _patch_proxy(mocker) - ssh_module._run_proxy_bridge(shared, None, True) + result = runner.invoke(app, ["ssh", "--proxy-mode", "-s", "cli2", "--rm"]) + assert result.exit_code == 0, result.output stop.assert_not_called() mock_common_state.client.unassign.assert_not_called() assert store.get("cli2") is None assert store.get("nb1") is not None assert ( "[colab] 'cli2' wasn't created by the cli and isn't stopped," - " only removed from sessions list" in capsys.readouterr().err + " only removed from sessions list" in result.stderr ) From 8e2c4b4497853179b5e0fd01f52e4a0c69a04879 Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Thu, 19 Nov 2026 21:58:23 +0000 Subject: [PATCH 06/17] refactor(session,ssh): share stop_session helper and polish changelog Extract stop_session in commands/session.py and call it from ssh._stop_session so attached and shared-endpoint teardown logic is not duplicated. Shorten _stopOne's docstring summary line and remove internal symbol names from the sessions CHANGELOG entry. --- CHANGELOG.md | 11 ++++---- src/colab_cli/commands/session.py | 42 ++++++++++++++++++++++--------- src/colab_cli/commands/ssh.py | 11 +------- tests/test_ssh.py | 2 +- tests/test_ssh_autocreate.py | 18 ++++++------- tests/test_ssh_lifecycle.py | 20 +++++++-------- 6 files changed, 56 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a644bd6c..64dcaf0b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,12 +21,11 @@ below corresponds to a tag of the same name. ### Added - **ssh:** `colab ssh [-s NAME] -- CMD` runs one command on an existing runtime and exits with its status. Output is byte-exact when piped (a PTY only when stdin and stdout are terminals), and it never creates a runtime. Its handshake is tagged `ssh-mode-cmd`. -- **sessions:** Track sessions attached to a runtime the CLI did not - create in `sessions.json` via `SessionState.attached`; `Client.unassign` - refuses attached endpoints, `colab stop`, `colab stop --all` and - `colab ssh --rm` remove attached sessions without stopping or unassigning - their runtimes, and `colab run` cleanup removes its record only once its - runtime is released. +- **sessions:** Track sessions attached to runtimes the CLI did not create + in `sessions.json`, refuse unassignment for attached endpoints, make + `colab stop`, `colab stop --all`, and `colab ssh --rm` remove attached + sessions without stopping or unassigning their runtimes, and make + `colab run` cleanup keep its record until the runtime is released. ### Removed diff --git a/src/colab_cli/commands/session.py b/src/colab_cli/commands/session.py index 41c77465..e6defda6 100644 --- a/src/colab_cli/commands/session.py +++ b/src/colab_cli/commands/session.py @@ -393,7 +393,7 @@ def attached_not_stopped_message(name: str) -> str: def _stopOne(name: str, s: SessionState, *, skip_unassign: bool = False) -> bool: - """Terminate a single session, or only remove it if its runtime is attached.""" + """Terminate a session, or remove it locally if attached.""" from colab_cli.common import state if ( @@ -416,6 +416,34 @@ def _stopOne(name: str, s: SessionState, *, skip_unassign: bool = False) -> bool return True +def _stop_by_name(name: str, *, ignore_missing: bool) -> bool: + """Stop a local session by name, returning True if it was handled.""" + from colab_cli.common import state + + record = state.store.get(name) + if record is not None and ( + record.attached is True + or state.store.is_attached_endpoint(record.endpoint) is True + ): + _stopOne(name, record) + return True + s = state.get_session(name, ignore_missing_session=ignore_missing) + if s is None: + return False + if _stopOne(name, s): + typer.echo("[colab] Session terminated.") + return True + + +def stop_session(name: str) -> None: + """Stops a named session, or removes it locally if attached. + + Args: + name: Session name in the local store. + """ + _stop_by_name(name, ignore_missing=False) + + def stop( session: Annotated[ Optional[str], @@ -446,17 +474,7 @@ def stop( return name = state.resolve_session(session) - record = state.store.get(name) - if record is not None and ( - record.attached is True - or state.store.is_attached_endpoint(record.endpoint) is True - ): - _stopOne(name, record) - return - s = state.get_session(name, ignore_missing_session=True) - if s is not None: - if _stopOne(name, s): - typer.echo("[colab] Session terminated.") + if _stop_by_name(name, ignore_missing=True): return if state.store.is_attached_endpoint(name) is True: diff --git a/src/colab_cli/commands/ssh.py b/src/colab_cli/commands/ssh.py index 88c23287..d2e8c7de 100644 --- a/src/colab_cli/commands/ssh.py +++ b/src/colab_cli/commands/ssh.py @@ -229,18 +229,9 @@ def _auto_create_session( def _stop_session(name: str) -> None: """Best-effort ``colab stop`` for a session (used by ``--rm``).""" from colab_cli.commands import session as session_cmd - from colab_cli.common import state try: - record = state.store.get(name) - if record is not None and ( - record.attached is True - or state.store.is_attached_endpoint(record.endpoint) is True - ): - state.store.remove(name) - typer.echo(session_cmd.attached_not_stopped_message(name)) - return - session_cmd.stop(session=name) + session_cmd.stop_session(name) except typer.Exit: raise except Exception as e: # Cleanup must not mask the shell's own exit. diff --git a/tests/test_ssh.py b/tests/test_ssh.py index 1c57e5ea..9846d1bd 100644 --- a/tests/test_ssh.py +++ b/tests/test_ssh.py @@ -510,7 +510,7 @@ def test_resolve_session(mock_common_state, found): def test_stop_session_error_handling(mocker, capsys, exc, expect_raises): """A failed `colab stop` during --rm must not crash the shell, except that a `typer.Exit` (a deliberate exit) is allowed to propagate.""" - mocker.patch("colab_cli.commands.session.stop", side_effect=exc) + mocker.patch("colab_cli.commands.session.stop_session", side_effect=exc) if expect_raises: with pytest.raises(typer.Exit): ssh_module._stop_session("s1") diff --git a/tests/test_ssh_autocreate.py b/tests/test_ssh_autocreate.py index 7fb272b2..45e637c5 100644 --- a/tests/test_ssh_autocreate.py +++ b/tests/test_ssh_autocreate.py @@ -239,7 +239,7 @@ def after_new(*a, **k): mock_common_state.store.get.return_value = created mocker.patch("colab_cli.commands.session.new", side_effect=after_new) - stop = mocker.patch("colab_cli.commands.session.stop") + stop = mocker.patch("colab_cli.commands.session.stop_session") mocker.patch("signal.signal") # don't install real handlers during tests _patch_proxy(mocker) @@ -249,7 +249,7 @@ def after_new(*a, **k): result = runner.invoke(app, args) assert result.exit_code == 0 if expect_stop: - stop.assert_called_once_with(session="colab-ephem") + stop.assert_called_once_with("colab-ephem") else: stop.assert_not_called() @@ -271,13 +271,13 @@ def test_interactive_rm_teardown(mock_common_state, mocker, has_existing, expect mock_common_state.store.get.return_value = sess mocker.patch("colab_cli.commands.session.new") - stop = mocker.patch("colab_cli.commands.session.stop") + stop = mocker.patch("colab_cli.commands.session.stop_session") _patch_interactive(mocker) result = runner.invoke(app, ["ssh", "--rm"]) assert result.exit_code == 0 if expect_stop: - stop.assert_called_once_with(session="auto-rm") + stop.assert_called_once_with("auto-rm") else: stop.assert_not_called() @@ -300,7 +300,7 @@ def test_proxy_mode_signal_handler_installation( mock_common_state.store.get.return_value = _make_session("colab") mock_common_state.resolve_session.return_value = "colab" sigmock = mocker.patch("signal.signal") - mocker.patch("colab_cli.commands.session.stop") + mocker.patch("colab_cli.commands.session.stop_session") _patch_proxy(mocker) args = ["ssh", "--proxy-mode", "-s", "colab"] @@ -357,7 +357,7 @@ def attach_on_create(session=None, **_): ) mocker.patch("colab_cli.commands.session.new", side_effect=attach_on_create) - stop = mocker.patch("colab_cli.commands.session.stop") + runtime = mocker.patch("colab_cli.commands.session.ColabRuntime") _patch_interactive(mocker) result = runner.invoke(app, ["ssh", "--rm"]) @@ -365,7 +365,7 @@ def attach_on_create(session=None, **_): assert result.exit_code == 0, result.output assert len(created_names) == 1 name = created_names[0] - stop.assert_not_called() + runtime.assert_not_called() mock_common_state.client.unassign.assert_not_called() assert store.get(name) is None assert ( @@ -387,14 +387,14 @@ def test_ssh_rm_proxy_removes_shared_attached_endpoint( mock_common_state.store = store mock_common_state.resolve_session.side_effect = lambda name, **_: name mock_common_state.get_session.side_effect = lambda name, **_: store.get(name) - stop = mocker.patch("colab_cli.commands.session.stop") + runtime = mocker.patch("colab_cli.commands.session.ColabRuntime") mocker.patch("signal.signal") _patch_proxy(mocker) result = runner.invoke(app, ["ssh", "--proxy-mode", "-s", "cli2", "--rm"]) assert result.exit_code == 0, result.output - stop.assert_not_called() + runtime.assert_not_called() mock_common_state.client.unassign.assert_not_called() assert store.get("cli2") is None assert store.get("nb1") is not None diff --git a/tests/test_ssh_lifecycle.py b/tests/test_ssh_lifecycle.py index 7a9575d7..d9a9809c 100644 --- a/tests/test_ssh_lifecycle.py +++ b/tests/test_ssh_lifecycle.py @@ -73,7 +73,7 @@ def test_proxy_mode_rm_stops_even_if_bridge_raises(mock_common_state, mocker): mock_common_state.store.get.return_value = sess mock_common_state.resolve_session.return_value = "colab-ephem" mocker.patch("signal.signal") - stop = mocker.patch("colab_cli.commands.session.stop") + stop = mocker.patch("colab_cli.commands.session.stop_session") mocker.patch.object(ssh_module, "_resolve_pubkey", return_value="pk") mocker.patch.object(ssh_module, "_connect_websocket", return_value=MagicMock()) mocker.patch.object( @@ -82,7 +82,7 @@ def test_proxy_mode_rm_stops_even_if_bridge_raises(mock_common_state, mocker): result = runner.invoke(app, ["ssh", "--proxy-mode", "-s", "colab-ephem", "--rm"]) assert result.exit_code != 0 - stop.assert_called_once_with(session="colab-ephem") + stop.assert_called_once_with("colab-ephem") def test_interactive_rm_stops_even_if_shell_raises(mock_common_state, mocker): @@ -92,7 +92,7 @@ def test_interactive_rm_stops_even_if_shell_raises(mock_common_state, mocker): mock_common_state.store.list.return_value = {} # empty -> auto-create mock_common_state.store.get.return_value = sess mocker.patch("colab_cli.commands.session.new") - stop = mocker.patch("colab_cli.commands.session.stop") + stop = mocker.patch("colab_cli.commands.session.stop_session") mocker.patch.object(ssh_module, "_resolve_pubkey", return_value="pk") mocker.patch.object( ssh_module, "_run_interactive_ssh", side_effect=RuntimeError("boom") @@ -100,7 +100,7 @@ def test_interactive_rm_stops_even_if_shell_raises(mock_common_state, mocker): result = runner.invoke(app, ["ssh", "--rm"]) assert result.exit_code != 0 - stop.assert_called_once_with(session="auto-rm") + stop.assert_called_once_with("auto-rm") # --- B. exit-code propagation ------------------------------------------------ @@ -159,10 +159,10 @@ def test_proxy_bridge_routes_rm_output_to_stderr(mocker, capsys): mocker.patch.object(ssh_module, "_connect_websocket", return_value=MagicMock()) mocker.patch.object(ssh_module, "_bridge_proxy_mode", return_value=0) - def stop_echo(session=None): + def stop_echo(name): typer.echo("STOP-MARKER") - mocker.patch("colab_cli.commands.session.stop", side_effect=stop_echo) + mocker.patch("colab_cli.commands.session.stop_session", side_effect=stop_echo) rc = ssh_module._run_proxy_bridge(sess, None, rm=True) assert rc == 0 @@ -237,7 +237,7 @@ def test_proxy_mode_rm_teardown_idempotent(mock_common_state, mocker): side_effect=lambda sig, h: handlers.__setitem__(sig, h), ) mocker.patch("os._exit") # keep the handler from killing the test process - stop = mocker.patch("colab_cli.commands.session.stop") + stop = mocker.patch("colab_cli.commands.session.stop_session") mocker.patch.object(ssh_module, "_resolve_pubkey", return_value="pk") mocker.patch.object(ssh_module, "_connect_websocket", return_value=MagicMock()) @@ -250,7 +250,7 @@ def bridge_then_hup(ws): result = runner.invoke(app, ["ssh", "--proxy-mode", "-s", "colab-ephem", "--rm"]) assert result.exit_code == 0 - stop.assert_called_once_with(session="colab-ephem") + stop.assert_called_once_with("colab-ephem") # --- G. --proxy-mode --rm stops a *reused* session too ----------------------- @@ -263,9 +263,9 @@ def test_proxy_mode_rm_stops_reused_session(mock_common_state, mocker): mock_common_state.store.get.return_value = sess # already exists mock_common_state.resolve_session.return_value = "colab" mocker.patch("signal.signal") - stop = mocker.patch("colab_cli.commands.session.stop") + stop = mocker.patch("colab_cli.commands.session.stop_session") _patch_proxy(mocker) result = runner.invoke(app, ["ssh", "--proxy-mode", "-s", "colab", "--rm"]) assert result.exit_code == 0 - stop.assert_called_once_with(session="colab") + stop.assert_called_once_with("colab") From c3c66674f66d9e98b8015536aaa480098fdb05cf Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Mon, 23 Nov 2026 08:49:24 +0000 Subject: [PATCH 07/17] test(state): cover store init with nonexistent nested parent dirs --- tests/test_state.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/test_state.py b/tests/test_state.py index 6aea9fbf..1e0392ec 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -449,3 +449,25 @@ def test_default_store_paths_share_config_dir(tmp_path, monkeypatch): expected_dir = str(tmp_path / ".config" / "colab-cli") assert settings_store.path == os.path.join(expected_dir, "settings.json") assert state_store.path == os.path.join(expected_dir, "sessions.json") + + +def test_state_store_creates_missing_parent_dirs(tmp_path): + path = tmp_path / "new" / "dir" / "sessions.json" + session = SessionState(name="s", token="t", url="u", endpoint="e") + + store = StateStore(str(path)) + + assert path.parent.is_dir() + store.add(session) + assert StateStore(str(path)).get("s") == session + + +def test_settings_store_creates_missing_parent_dirs(tmp_path): + path = tmp_path / "new" / "dir" / "settings.json" + settings = Settings(enable_update_check=False, use_public_api=True) + + store = SettingsStore(str(path)) + + assert path.parent.is_dir() + store.save(settings) + assert SettingsStore(str(path)).load() == settings From 9d1b4ef47c2bbdbcc2b1097346efe0ee4136ee7a Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Tue, 24 Nov 2026 16:39:09 +0000 Subject: [PATCH 08/17] test(stop): keep attached record when stop target is missing --- tests/test_cli.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/test_cli.py b/tests/test_cli.py index 7ef15c4f..bc5e8133 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1133,6 +1133,21 @@ def test_stop_all_skips_unassign_when_attached_precedes_shared_cli(tmp_path, moc assert local_state.store.list() == {} +def test_stop_missing_exits_1_keeps_attached_record(tmp_path, mocker): + local_state = _real_stop_state(tmp_path, mocker) + local_state.store.add( + SessionState( + name="nb1", token="t", url="https://u", endpoint="ep-nb1", attached=True + ) + ) + + missing_res = runner.invoke(app, ["stop", "-s", "missing"]) + + assert missing_res.exit_code == 1 + assert "[colab] Session 'missing' not found." in missing_res.output + assert local_state.store.get("nb1") is not None + + def test_sessions_and_status_use_store_key_when_name_differs(mock_common_state): mock_assignment = MagicMock() mock_assignment.endpoint = "ep1" From 731097c505c773b3c3785033f3ef1eccf70ffdf9 Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Tue, 24 Nov 2026 17:09:57 +0000 Subject: [PATCH 09/17] fix(cli,state): tighten session and state typing, docstrings, and test fakes --- src/colab_cli/client.py | 23 +++++++++++++++++++++-- src/colab_cli/commands/session.py | 2 +- src/colab_cli/common.py | 7 ++----- tests/conftest.py | 3 ++- tests/test_cli.py | 15 +++++++++++---- tests/test_client.py | 7 +++++-- tests/test_local_credentials.py | 5 ++++- tests/test_ssh_autocreate.py | 11 +++++++---- 8 files changed, 53 insertions(+), 20 deletions(-) diff --git a/src/colab_cli/client.py b/src/colab_cli/client.py index b0d6dcd6..2c2aed50 100644 --- a/src/colab_cli/client.py +++ b/src/colab_cli/client.py @@ -18,10 +18,11 @@ import os import time import uuid +from collections.abc import Callable from dataclasses import dataclass from datetime import datetime, timedelta, timezone from enum import Enum -from typing import Callable, Dict, List, Optional, Union +from typing import Dict, List, Optional, Union from urllib.parse import urljoin, urlparse import requests @@ -247,8 +248,18 @@ def __init__( logger=None, use_public_api: bool = False, settings_store=None, - is_attached: Optional[Callable[[str], bool]] = None, + is_attached: Callable[[str], bool] | None = None, ): + """Initializes a Colab API client. + + Args: + env: Target Colab environment URLs. + session: Authenticated HTTP session for API requests. + logger: Optional logger instance. + use_public_api: Whether to list runtimes via the public API. + settings_store: Optional settings store for caching API support. + is_attached: Optional predicate returning True for attached endpoints. + """ self.colab_domain = env.domain self.colab_api_domain = env.api self.colab_public_api = env.public_api @@ -432,6 +443,14 @@ def _list_assignments_public(self) -> List[ListedAssignment]: return assignments def unassign(self, endpoint: str): + """Unassigns a Colab runtime endpoint. + + Args: + endpoint: Runtime endpoint identifier to unassign. + + Raises: + AttachedRuntimeError: If the endpoint belongs to an attached runtime. + """ if self._is_attached(endpoint) is True: raise AttachedRuntimeError( f"Refusing to unassign '{endpoint}': it is an attached runtime." diff --git a/src/colab_cli/commands/session.py b/src/colab_cli/commands/session.py index e6defda6..89ca5f96 100644 --- a/src/colab_cli/commands/session.py +++ b/src/colab_cli/commands/session.py @@ -333,7 +333,7 @@ def sessions_command(): ) -def _print_status_for(s: SessionState, name: Optional[str] = None) -> None: +def _print_status_for(s: SessionState, name: str | None = None) -> None: """Print one session's status line plus optional last-execution detail.""" status = f"BUSY ({s.running})" if s.running else "IDLE" typer.echo( diff --git a/src/colab_cli/common.py b/src/colab_cli/common.py index e72caf4c..4a2fe005 100644 --- a/src/colab_cli/common.py +++ b/src/colab_cli/common.py @@ -46,7 +46,7 @@ def _apply_proxy_info(s: SessionState, info: RuntimeProxyInfo): class State: def __init__(self): self.client_oauth_config = os.path.expanduser("~/.colab-cli-oauth-config.json") - self.config_path: Optional[str] = None + self.config_path: str | None = None self.logtostderr = False self.auth_provider = AuthProvider.OAUTH2 self.use_public_api: Optional[bool] = None @@ -252,10 +252,7 @@ def setup_logging(log_to_stderr: bool): # Its DEBUG output includes stdin replies to the kernel, such as passwords. logging.getLogger("jupyter_kernel_client").setLevel(logging.INFO) - settings_path = state.settings_store.path - if not isinstance(settings_path, str): - settings_path = SettingsStore().path - log_dir = os.path.dirname(settings_path) + log_dir = os.path.dirname(state.settings_store.path) os.makedirs(log_dir, exist_ok=True) log_path = os.path.join(log_dir, "colab.log") # FileHandler can't set permissions, so create the file owner-only first. diff --git a/tests/conftest.py b/tests/conftest.py index 0f5eda5a..eb4ddeea 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -40,12 +40,13 @@ def block_real_browser(monkeypatch): @pytest.fixture(autouse=True) -def mock_common_state(mocker): +def mock_common_state(mocker, tmp_path): # Patch the state singleton in common.py mock_state = mocker.patch("colab_cli.common.state") # Setup standard mocks for properties mock_state.store = MagicMock() + mock_state.settings_store.path = str(tmp_path / "settings.json") mock_state.client = MagicMock() mock_state.history = MagicMock() mock_state.auth_provider = AuthProvider.OAUTH2 diff --git a/tests/test_cli.py b/tests/test_cli.py index bc5e8133..bfe7cf36 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -27,6 +27,7 @@ from colab_cli.cli import app from colab_cli.client import ( Assignment, + Client, ColabRequestError, PostAssignmentResponse, RuntimeProxyInfo, @@ -35,6 +36,7 @@ from colab_cli.commands import session as session_cmd from colab_cli.common import State from colab_cli.consumption import ConsumptionUserInfo +from colab_cli.history import HistoryLogger from colab_cli.state import SessionState, Settings, StateStore runner = CliRunner() @@ -992,11 +994,11 @@ def test_cli_logout_adc_prints_gcloud_hint(mock_common_state, mocker): def _real_stop_state(tmp_path, mocker): - mocker.patch("colab_cli.cli.auto_update.run_background_check") + mocker.patch("colab_cli.cli.auto_update.run_background_check", autospec=True) local_state = State() local_state._store = StateStore(str(tmp_path / "sessions.json")) - local_state._client = MagicMock() - local_state._history = MagicMock() + local_state._client = MagicMock(spec=Client) + local_state._history = MagicMock(spec=HistoryLogger) mocker.patch("colab_cli.common.state", local_state) mocker.patch("colab_cli.cli.state", local_state) return local_state @@ -1073,6 +1075,7 @@ def test_stop_all_skips_unassign_for_attached_sessions(tmp_path, mocker): local_state, "sync_sessions", return_value=({"cli1": cli_sess, "nb1": att_sess}, []), + autospec=True, ) result = runner.invoke(app, ["stop", "--all"]) @@ -1094,7 +1097,10 @@ def test_stop_all_attached_only_omits_stopped_count(tmp_path, mocker): ) local_state.store.add(att_sess) mocker.patch.object( - local_state, "sync_sessions", return_value=({"nb1": att_sess}, []) + local_state, + "sync_sessions", + return_value=({"nb1": att_sess}, []), + autospec=True, ) result = runner.invoke(app, ["stop", "--all"]) @@ -1120,6 +1126,7 @@ def test_stop_all_skips_unassign_when_attached_precedes_shared_cli(tmp_path, moc local_state, "sync_sessions", return_value=({"nb1": att_sess, "cli2": shared_cli}, []), + autospec=True, ) result = runner.invoke(app, ["stop", "--all"]) diff --git a/tests/test_client.py b/tests/test_client.py index a90caf35..1503b5f8 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -18,6 +18,7 @@ import pytest import requests +from google.auth.transport.requests import AuthorizedSession from colab_cli.client import ( Accelerator, @@ -573,8 +574,10 @@ def test_state_client_wires_attached_endpoint_guard(tmp_path, mocker): local_state.store.add( SessionState(name="nb1", token="t", url="u", endpoint="att-ep", attached=True) ) - mock_http = MagicMock() - mocker.patch("colab_cli.common.get_credentials", return_value=mock_http) + mock_http = MagicMock(spec=AuthorizedSession) + mocker.patch( + "colab_cli.common.get_credentials", return_value=mock_http, autospec=True + ) with pytest.raises(AttachedRuntimeError, match="att-ep"): local_state.client.unassign("att-ep") diff --git a/tests/test_local_credentials.py b/tests/test_local_credentials.py index 39a6b419..6af42c07 100644 --- a/tests/test_local_credentials.py +++ b/tests/test_local_credentials.py @@ -38,9 +38,12 @@ @pytest.fixture -def home(tmp_path, monkeypatch): +def home(tmp_path, monkeypatch, mock_common_state): monkeypatch.setenv("HOME", str(tmp_path)) monkeypatch.setenv("USERPROFILE", str(tmp_path)) + mock_common_state.settings_store.path = str( + tmp_path / ".config" / "colab-cli" / "settings.json" + ) monkeypatch.setattr(logging.getLogger(), "handlers", []) levels = {name: logging.getLogger(name).level for name in LOGGER_NAMES} yield tmp_path diff --git a/tests/test_ssh_autocreate.py b/tests/test_ssh_autocreate.py index 45e637c5..99a44662 100644 --- a/tests/test_ssh_autocreate.py +++ b/tests/test_ssh_autocreate.py @@ -28,6 +28,7 @@ from click import unstyle from colab_cli.cli import app from colab_cli.commands import ssh as ssh_module +from colab_cli.runtime import ColabRuntime from colab_cli.state import SessionState, StateStore import pytest from typer.testing import CliRunner @@ -356,8 +357,10 @@ def attach_on_create(session=None, **_): ) ) - mocker.patch("colab_cli.commands.session.new", side_effect=attach_on_create) - runtime = mocker.patch("colab_cli.commands.session.ColabRuntime") + mocker.patch( + "colab_cli.commands.session.new", side_effect=attach_on_create, autospec=True + ) + runtime = mocker.patch("colab_cli.commands.session.ColabRuntime", spec=ColabRuntime) _patch_interactive(mocker) result = runner.invoke(app, ["ssh", "--rm"]) @@ -387,8 +390,8 @@ def test_ssh_rm_proxy_removes_shared_attached_endpoint( mock_common_state.store = store mock_common_state.resolve_session.side_effect = lambda name, **_: name mock_common_state.get_session.side_effect = lambda name, **_: store.get(name) - runtime = mocker.patch("colab_cli.commands.session.ColabRuntime") - mocker.patch("signal.signal") + runtime = mocker.patch("colab_cli.commands.session.ColabRuntime", spec=ColabRuntime) + mocker.patch("signal.signal", autospec=True) _patch_proxy(mocker) result = runner.invoke(app, ["ssh", "--proxy-mode", "-s", "cli2", "--rm"]) From 98fc31fd0a453468a7bac23ed59d6a2983a4da4d Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Tue, 24 Nov 2026 17:41:53 +0000 Subject: [PATCH 10/17] test: isolate test_automation state, add autospecs, and test teardown race Keep test_automation logging inside tmp_path instead of MagicMock/ in cwd, build a real ListedAssignment in test_cli, autospec stop_session patches, and cover concurrent attached record preservation in run teardown. --- tests/test_automation.py | 31 +++++++++++++++--------------- tests/test_cli.py | 21 ++++++++++++++------ tests/test_run.py | 37 ++++++++++++++++++++++++++++++++++++ tests/test_ssh.py | 4 +++- tests/test_ssh_autocreate.py | 6 +++--- tests/test_ssh_lifecycle.py | 12 +++++++----- 6 files changed, 80 insertions(+), 31 deletions(-) diff --git a/tests/test_automation.py b/tests/test_automation.py index e880f61d..0bd0d6a0 100644 --- a/tests/test_automation.py +++ b/tests/test_automation.py @@ -44,9 +44,15 @@ def mock_session(): ) +@pytest.fixture +def mock_state(mocker, tmp_path): + state = mocker.patch("colab_cli.common.state") + state.settings_store.path = str(tmp_path / "settings.json") + return state + + @patch("colab_cli.commands.automation.ColabRuntime") -@patch("colab_cli.common.state") -def test_cli_auth(mock_state, mock_runtime_class, mock_session): +def test_cli_auth(mock_runtime_class, mock_state, mock_session): mock_state.get_session.return_value = mock_session mock_state.resolve_session.return_value = "test-session" @@ -70,8 +76,7 @@ def test_cli_auth(mock_state, mock_runtime_class, mock_session): @patch("colab_cli.commands.automation.ColabRuntime") -@patch("colab_cli.common.state") -def test_cli_install(mock_state, mock_runtime_class, mock_session): +def test_cli_install(mock_runtime_class, mock_state, mock_session): mock_state.get_session.return_value = mock_session mock_state.resolve_session.return_value = "test-session" @@ -94,8 +99,7 @@ def test_cli_install(mock_state, mock_runtime_class, mock_session): @patch("colab_cli.commands.automation.ColabRuntime") -@patch("colab_cli.common.state") -def test_cli_drivemount(mock_state, mock_runtime_class, mock_session): +def test_cli_drivemount(mock_runtime_class, mock_state, mock_session): mock_state.get_session.return_value = mock_session mock_state.resolve_session.return_value = "test-session" @@ -120,8 +124,7 @@ def test_cli_drivemount(mock_state, mock_runtime_class, mock_session): @patch("colab_cli.commands.automation.ColabRuntime") -@patch("colab_cli.common.state") -def test_cli_auth_uses_long_timeout(mock_state, mock_runtime_class, mock_session): +def test_cli_auth_uses_long_timeout(mock_runtime_class, mock_state, mock_session): """`colab auth` walks the user through a paste-the-code flow that routinely takes >10s, so it must pass a generous timeout to runtime.execute_code or the call will TimeoutError mid-flow.""" @@ -194,9 +197,8 @@ def _invoke_drivemount_and_get_hook(mock_state, mock_runtime_class, mock_session @patch("colab_cli.commands.automation.get_credentials") @patch("colab_cli.commands.automation.ColabRuntime") -@patch("colab_cli.common.state") def test_drivefs_hook_reports_400_without_raw_html( - mock_state, mock_runtime_class, mock_creds, mock_session, capsys + mock_runtime_class, mock_creds, mock_state, mock_session, capsys ): """The multi-account 400 must not echo HTML or re-prompt for consent.""" hook = _invoke_drivemount_and_get_hook(mock_state, mock_runtime_class, mock_session) @@ -227,9 +229,8 @@ def test_drivefs_hook_reports_400_without_raw_html( @patch("colab_cli.commands.automation.get_credentials") @patch("colab_cli.commands.automation.ColabRuntime") -@patch("colab_cli.common.state") def test_drivefs_hook_does_not_prompt_when_auth_is_not_the_cause( - mock_state, mock_runtime_class, mock_creds, mock_session, capsys + mock_runtime_class, mock_creds, mock_state, mock_session, capsys ): """A refusal without an auth URL must not claim Drive authorization is needed.""" hook = _invoke_drivemount_and_get_hook(mock_state, mock_runtime_class, mock_session) @@ -250,9 +251,8 @@ def test_drivefs_hook_does_not_prompt_when_auth_is_not_the_cause( @patch("colab_cli.commands.automation.get_credentials") @patch("colab_cli.commands.automation.ColabRuntime") -@patch("colab_cli.common.state") def test_drivefs_hook_reports_token_request_failure( - mock_state, mock_runtime_class, mock_creds, mock_session, capsys + mock_runtime_class, mock_creds, mock_state, mock_session, capsys ): hook = _invoke_drivemount_and_get_hook(mock_state, mock_runtime_class, mock_session) mock_creds.return_value.request.side_effect = [ @@ -270,9 +270,8 @@ def test_drivefs_hook_reports_token_request_failure( @patch("colab_cli.commands.automation.get_credentials") @patch("colab_cli.commands.automation.ColabRuntime") -@patch("colab_cli.common.state") def test_drivefs_hook_replies_after_successful_propagation( - mock_state, mock_runtime_class, mock_creds, mock_session, capsys + mock_runtime_class, mock_creds, mock_state, mock_session, capsys ): hook = _invoke_drivemount_and_get_hook(mock_state, mock_runtime_class, mock_session) mock_creds.return_value.request.side_effect = [ diff --git a/tests/test_cli.py b/tests/test_cli.py index bfe7cf36..f9a2502c 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -29,6 +29,7 @@ Assignment, Client, ColabRequestError, + ListedAssignment, PostAssignmentResponse, RuntimeProxyInfo, TooManyAssignmentsError, @@ -1156,15 +1157,23 @@ def test_stop_missing_exits_1_keeps_attached_record(tmp_path, mocker): def test_sessions_and_status_use_store_key_when_name_differs(mock_common_state): - mock_assignment = MagicMock() - mock_assignment.endpoint = "ep1" - mock_assignment.variant.name = "DEFAULT" - mock_assignment.accelerator.value = "NONE" - mock_assignment.machine_shape.name = "STANDARD" + assignment = ListedAssignment.model_validate( + { + "accelerator": "NONE", + "endpoint": "ep1", + "variant": 0, + "machineShape": 0, + "runtimeProxyInfo": { + "token": "t", + "tokenExpiresInSeconds": 3600, + "url": "u", + }, + } + ) sess = SessionState(name="inner", token="t", url="u", endpoint="ep1") mock_common_state.sync_sessions.return_value = ( {"alias": sess}, - [mock_assignment], + [assignment], ) mock_common_state.store.get.return_value = sess diff --git a/tests/test_run.py b/tests/test_run.py index 2a16222f..af605438 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -822,6 +822,43 @@ def test_run_with_timeout_flag( assert body_call.kwargs.get("timeout") == 3600.0 +def test_teardown_preserves_concurrent_attached_record( + mock_common_state, + mock_client, + mock_runtime_class, + assign_response, + script_path, + tmp_path, +): + store = StateStore(str(tmp_path / "sessions.json")) + mock_common_state.store = store + mock_common_state.get_session.side_effect = lambda name, **_: store.get(name) + mock_client.assign.return_value = assign_response + mock_runtime_class.return_value.execute_code.return_value = [] + + def attach_same_name_during_unassign(endpoint): + store.add( + SessionState( + name="job1", + token="t2", + url="http://u2", + endpoint="ep-attached", + attached=True, + ) + ) + + mock_client.unassign.side_effect = attach_same_name_during_unassign + + result = runner.invoke(app, ["run", "-s", "job1", str(script_path)]) + + assert result.exit_code == 0, result.output + mock_client.unassign.assert_called_once_with("ep-123") + preserved = store.get("job1") + assert preserved is not None + assert preserved.attached is True + assert preserved.endpoint == "ep-attached" + + def test_teardown_skips_kernel_and_keeps_attached_record( mock_common_state, mock_client, diff --git a/tests/test_ssh.py b/tests/test_ssh.py index 9846d1bd..76cfd171 100644 --- a/tests/test_ssh.py +++ b/tests/test_ssh.py @@ -510,7 +510,9 @@ def test_resolve_session(mock_common_state, found): def test_stop_session_error_handling(mocker, capsys, exc, expect_raises): """A failed `colab stop` during --rm must not crash the shell, except that a `typer.Exit` (a deliberate exit) is allowed to propagate.""" - mocker.patch("colab_cli.commands.session.stop_session", side_effect=exc) + mocker.patch( + "colab_cli.commands.session.stop_session", side_effect=exc, autospec=True + ) if expect_raises: with pytest.raises(typer.Exit): ssh_module._stop_session("s1") diff --git a/tests/test_ssh_autocreate.py b/tests/test_ssh_autocreate.py index 99a44662..0d268afd 100644 --- a/tests/test_ssh_autocreate.py +++ b/tests/test_ssh_autocreate.py @@ -240,7 +240,7 @@ def after_new(*a, **k): mock_common_state.store.get.return_value = created mocker.patch("colab_cli.commands.session.new", side_effect=after_new) - stop = mocker.patch("colab_cli.commands.session.stop_session") + stop = mocker.patch("colab_cli.commands.session.stop_session", autospec=True) mocker.patch("signal.signal") # don't install real handlers during tests _patch_proxy(mocker) @@ -272,7 +272,7 @@ def test_interactive_rm_teardown(mock_common_state, mocker, has_existing, expect mock_common_state.store.get.return_value = sess mocker.patch("colab_cli.commands.session.new") - stop = mocker.patch("colab_cli.commands.session.stop_session") + stop = mocker.patch("colab_cli.commands.session.stop_session", autospec=True) _patch_interactive(mocker) result = runner.invoke(app, ["ssh", "--rm"]) @@ -301,7 +301,7 @@ def test_proxy_mode_signal_handler_installation( mock_common_state.store.get.return_value = _make_session("colab") mock_common_state.resolve_session.return_value = "colab" sigmock = mocker.patch("signal.signal") - mocker.patch("colab_cli.commands.session.stop_session") + mocker.patch("colab_cli.commands.session.stop_session", autospec=True) _patch_proxy(mocker) args = ["ssh", "--proxy-mode", "-s", "colab"] diff --git a/tests/test_ssh_lifecycle.py b/tests/test_ssh_lifecycle.py index d9a9809c..bdd1c2d3 100644 --- a/tests/test_ssh_lifecycle.py +++ b/tests/test_ssh_lifecycle.py @@ -73,7 +73,7 @@ def test_proxy_mode_rm_stops_even_if_bridge_raises(mock_common_state, mocker): mock_common_state.store.get.return_value = sess mock_common_state.resolve_session.return_value = "colab-ephem" mocker.patch("signal.signal") - stop = mocker.patch("colab_cli.commands.session.stop_session") + stop = mocker.patch("colab_cli.commands.session.stop_session", autospec=True) mocker.patch.object(ssh_module, "_resolve_pubkey", return_value="pk") mocker.patch.object(ssh_module, "_connect_websocket", return_value=MagicMock()) mocker.patch.object( @@ -92,7 +92,7 @@ def test_interactive_rm_stops_even_if_shell_raises(mock_common_state, mocker): mock_common_state.store.list.return_value = {} # empty -> auto-create mock_common_state.store.get.return_value = sess mocker.patch("colab_cli.commands.session.new") - stop = mocker.patch("colab_cli.commands.session.stop_session") + stop = mocker.patch("colab_cli.commands.session.stop_session", autospec=True) mocker.patch.object(ssh_module, "_resolve_pubkey", return_value="pk") mocker.patch.object( ssh_module, "_run_interactive_ssh", side_effect=RuntimeError("boom") @@ -162,7 +162,9 @@ def test_proxy_bridge_routes_rm_output_to_stderr(mocker, capsys): def stop_echo(name): typer.echo("STOP-MARKER") - mocker.patch("colab_cli.commands.session.stop_session", side_effect=stop_echo) + mocker.patch( + "colab_cli.commands.session.stop_session", side_effect=stop_echo, autospec=True + ) rc = ssh_module._run_proxy_bridge(sess, None, rm=True) assert rc == 0 @@ -237,7 +239,7 @@ def test_proxy_mode_rm_teardown_idempotent(mock_common_state, mocker): side_effect=lambda sig, h: handlers.__setitem__(sig, h), ) mocker.patch("os._exit") # keep the handler from killing the test process - stop = mocker.patch("colab_cli.commands.session.stop_session") + stop = mocker.patch("colab_cli.commands.session.stop_session", autospec=True) mocker.patch.object(ssh_module, "_resolve_pubkey", return_value="pk") mocker.patch.object(ssh_module, "_connect_websocket", return_value=MagicMock()) @@ -263,7 +265,7 @@ def test_proxy_mode_rm_stops_reused_session(mock_common_state, mocker): mock_common_state.store.get.return_value = sess # already exists mock_common_state.resolve_session.return_value = "colab" mocker.patch("signal.signal") - stop = mocker.patch("colab_cli.commands.session.stop_session") + stop = mocker.patch("colab_cli.commands.session.stop_session", autospec=True) _patch_proxy(mocker) result = runner.invoke(app, ["ssh", "--proxy-mode", "-s", "colab", "--rm"]) From 0777634adaed772f3442c42db9a619b90b6c78a0 Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Tue, 1 Dec 2026 00:53:58 +0000 Subject: [PATCH 11/17] fix(state,session,test): simplify bool checks and tighten test fakes --- src/colab_cli/client.py | 2 +- src/colab_cli/commands/run.py | 6 +-- src/colab_cli/commands/session.py | 32 ++++++-------- src/colab_cli/common.py | 2 +- src/colab_cli/state.py | 2 +- tests/conftest.py | 6 ++- tests/test_automation.py | 6 ++- tests/test_cli.py | 72 +++++++++++++++++-------------- tests/test_client.py | 9 ++-- tests/test_ssh_autocreate.py | 21 +++++---- tests/test_state.py | 33 -------------- 11 files changed, 79 insertions(+), 112 deletions(-) diff --git a/src/colab_cli/client.py b/src/colab_cli/client.py index 2c2aed50..7614233e 100644 --- a/src/colab_cli/client.py +++ b/src/colab_cli/client.py @@ -451,7 +451,7 @@ def unassign(self, endpoint: str): Raises: AttachedRuntimeError: If the endpoint belongs to an attached runtime. """ - if self._is_attached(endpoint) is True: + if self._is_attached(endpoint): raise AttachedRuntimeError( f"Refusing to unassign '{endpoint}': it is an attached runtime." ) diff --git a/src/colab_cli/commands/run.py b/src/colab_cli/commands/run.py index bd8dfae0..1f2af10f 100644 --- a/src/colab_cli/commands/run.py +++ b/src/colab_cli/commands/run.py @@ -400,8 +400,8 @@ def _teardown(name: str, s: SessionState, *, reason: str) -> None: fresh = state.get_session(name, ignore_missing_session=True) if ( fresh - and fresh.attached is not True - and state.store.is_attached_endpoint(fresh.endpoint) is not True + and not fresh.attached + and not state.store.is_attached_endpoint(fresh.endpoint) ): rt = ColabRuntime(fresh.url, fresh.token, kernel_id=fresh.kernel_id) rt.stop(shutdown_kernel=True) @@ -421,7 +421,7 @@ def _teardown(name: str, s: SessionState, *, reason: str) -> None: try: stored = state.store.get(name) - if stored is None or stored.attached is not True: + if stored is None or not stored.attached: state.store.remove(name) except Exception: pass diff --git a/src/colab_cli/commands/session.py b/src/colab_cli/commands/session.py index 89ca5f96..2224dedc 100644 --- a/src/colab_cli/commands/session.py +++ b/src/colab_cli/commands/session.py @@ -316,7 +316,7 @@ def sessions_command(): return # Build endpoint -> local-name lookup so we can lead with the friendly name. - name_by_endpoint = {s.endpoint: k for k, s in sessions.items()} + name_by_endpoint = {s.endpoint: name for name, s in sessions.items()} for a in assignments: name = name_by_endpoint.get(a.endpoint, "?") # `a.variant` is an int-valued AssignmentVariant (DEFAULT=0/GPU=1/TPU=2); @@ -333,12 +333,12 @@ def sessions_command(): ) -def _print_status_for(s: SessionState, name: str | None = None) -> None: +def _print_status_for(s: SessionState, name: str) -> None: """Print one session's status line plus optional last-execution detail.""" status = f"BUSY ({s.running})" if s.running else "IDLE" typer.echo( _format_session_line( - name=name if name is not None else s.name, + name=name, endpoint=s.endpoint, accelerator=s.accelerator, variant=s.variant, @@ -373,8 +373,8 @@ def status( if not local_sessions: typer.echo("[colab] No active sessions.") return - for k, s in local_sessions.items(): - _print_status_for(s, name=k) + for name, s in local_sessions.items(): + _print_status_for(s, name=name) def attached_not_stopped_message(name: str) -> str: @@ -396,11 +396,7 @@ def _stopOne(name: str, s: SessionState, *, skip_unassign: bool = False) -> bool """Terminate a session, or remove it locally if attached.""" from colab_cli.common import state - if ( - s.attached is True - or skip_unassign - or state.store.is_attached_endpoint(s.endpoint) is True - ): + if s.attached or skip_unassign or state.store.is_attached_endpoint(s.endpoint): state.store.remove(name) typer.echo(attached_not_stopped_message(name)) return False @@ -422,8 +418,7 @@ def _stop_by_name(name: str, *, ignore_missing: bool) -> bool: record = state.store.get(name) if record is not None and ( - record.attached is True - or state.store.is_attached_endpoint(record.endpoint) is True + record.attached or state.store.is_attached_endpoint(record.endpoint) ): _stopOne(name, record) return True @@ -461,14 +456,11 @@ def stop( if not sessions: typer.echo("[colab] No active sessions.") return - attached_endpoints = { - s.endpoint for s in sessions.values() if s.attached is True - } - stopped = sum( - 1 - for name, s in sessions.items() - if _stopOne(name, s, skip_unassign=s.endpoint in attached_endpoints) - ) + attached_endpoints = {s.endpoint for s in sessions.values() if s.attached} + stopped = 0 + for name, s in sessions.items(): + if _stopOne(name, s, skip_unassign=s.endpoint in attached_endpoints): + stopped += 1 if stopped: typer.echo(f"[colab] Stopped {stopped} session(s).") return diff --git a/src/colab_cli/common.py b/src/colab_cli/common.py index 4a2fe005..5c8910ea 100644 --- a/src/colab_cli/common.py +++ b/src/colab_cli/common.py @@ -95,7 +95,7 @@ def client(self): creds, use_public_api=use_public, settings_store=self.settings_store, - is_attached=lambda ep: self.store.is_attached_endpoint(ep), + is_attached=lambda endpoint: self.store.is_attached_endpoint(endpoint), ) return self._client diff --git a/src/colab_cli/state.py b/src/colab_cli/state.py index 5695c357..06bf902d 100644 --- a/src/colab_cli/state.py +++ b/src/colab_cli/state.py @@ -196,6 +196,6 @@ def is_attached_endpoint(self, endpoint: str) -> bool: matches ``endpoint``, False otherwise. """ return any( - session.attached is True and session.endpoint == endpoint + session.attached and session.endpoint == endpoint for session in self.list().values() ) diff --git a/tests/conftest.py b/tests/conftest.py index eb4ddeea..f2a1da26 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -13,7 +13,7 @@ # limitations under the License. import os -from unittest.mock import MagicMock +from unittest.mock import MagicMock, create_autospec import keyring import keyring.backends.null @@ -21,6 +21,7 @@ import typer from colab_cli.auth import AuthProvider +from colab_cli.state import StateStore def pytest_configure(): @@ -45,7 +46,8 @@ def mock_common_state(mocker, tmp_path): mock_state = mocker.patch("colab_cli.common.state") # Setup standard mocks for properties - mock_state.store = MagicMock() + mock_state.store = create_autospec(StateStore, instance=True) + mock_state.store.is_attached_endpoint.return_value = False mock_state.settings_store.path = str(tmp_path / "settings.json") mock_state.client = MagicMock() mock_state.history = MagicMock() diff --git a/tests/test_automation.py b/tests/test_automation.py index 0bd0d6a0..8b1e662c 100644 --- a/tests/test_automation.py +++ b/tests/test_automation.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from unittest.mock import MagicMock, mock_open, patch +from unittest.mock import MagicMock, create_autospec, mock_open, patch import pytest from typer.testing import CliRunner from colab_cli.cli import app @@ -21,7 +21,7 @@ drive_propagation_failure_message, ) from colab_cli.commands.automation import show_drive_auth_url -from colab_cli.state import SessionState +from colab_cli.state import SessionState, StateStore runner = CliRunner() @@ -47,6 +47,8 @@ def mock_session(): @pytest.fixture def mock_state(mocker, tmp_path): state = mocker.patch("colab_cli.common.state") + state.store = create_autospec(StateStore, instance=True) + state.store.is_attached_endpoint.return_value = False state.settings_store.path = str(tmp_path / "settings.json") return state diff --git a/tests/test_cli.py b/tests/test_cli.py index f9a2502c..3354614d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -12,9 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. +import logging import time from datetime import datetime, timedelta, timezone -from unittest.mock import MagicMock, call, patch +from unittest.mock import MagicMock, call, create_autospec, patch import click from keyring.errors import KeyringError @@ -38,11 +39,30 @@ from colab_cli.common import State from colab_cli.consumption import ConsumptionUserInfo from colab_cli.history import HistoryLogger -from colab_cli.state import SessionState, Settings, StateStore +from colab_cli.state import SessionState, Settings, SettingsStore, StateStore runner = CliRunner() +@pytest.fixture(autouse=True) +def _restore_root_logger_handlers(): + root_logger = logging.getLogger() + orig_handlers = list(root_logger.handlers) + orig_levels = { + name: logging.getLogger(name).level + for name in (None, "urllib3", "jupyter_kernel_client") + } + try: + yield + finally: + for handler in list(root_logger.handlers): + if handler not in orig_handlers: + root_logger.removeHandler(handler) + handler.close() + for name, level in orig_levels.items(): + logging.getLogger(name).setLevel(level) + + @pytest.fixture def mock_client(mock_common_state): return mock_common_state.client @@ -321,12 +341,9 @@ def test_cli_new_high_mem(mock_client, mock_store): def test_cli_session_resolution(mock_store, mock_common_state): - mock_session_state = MagicMock() - mock_session_state.name = "unique-session" - mock_session_state.endpoint = "e1" - mock_session_state.url = "http://url" - mock_session_state.token = "token" - mock_session_state.kernel_id = None + mock_session_state = SessionState( + name="unique-session", token="token", url="http://url", endpoint="e1" + ) # Setup for resolve_session mock_common_state.resolve_session.return_value = "unique-session" @@ -338,12 +355,9 @@ def test_cli_session_resolution(mock_store, mock_common_state): def test_cli_stop(mock_client, mock_store, mock_common_state): - mock_session_state = MagicMock() - mock_session_state.endpoint = "e1" - mock_session_state.name = "s1" - mock_session_state.url = "http://url" - mock_session_state.token = "token" - mock_session_state.kernel_id = None + mock_session_state = SessionState( + name="s1", token="token", url="http://url", endpoint="e1" + ) mock_store.get.return_value = mock_session_state mock_common_state.resolve_session.return_value = "s1" @@ -443,7 +457,10 @@ def test_cli_stop_unknown_endpoint_exits_nonzero( def test_cli_stop_all(mock_client, mock_store, mock_common_state): - sessions = {"s1": MagicMock(endpoint="e1"), "s2": MagicMock(endpoint="e2")} + sessions = { + "s1": SessionState(name="s1", token="t", url="u", endpoint="e1"), + "s2": SessionState(name="s2", token="t", url="u", endpoint="e2"), + } mock_common_state.sync_sessions.return_value = (sessions, []) result = runner.invoke(app, ["stop", "--all"]) @@ -997,9 +1014,10 @@ def test_cli_logout_adc_prints_gcloud_hint(mock_common_state, mocker): def _real_stop_state(tmp_path, mocker): mocker.patch("colab_cli.cli.auto_update.run_background_check", autospec=True) local_state = State() + local_state._settings_store = SettingsStore(str(tmp_path / "settings.json")) local_state._store = StateStore(str(tmp_path / "sessions.json")) - local_state._client = MagicMock(spec=Client) - local_state._history = MagicMock(spec=HistoryLogger) + local_state._client = create_autospec(Client, instance=True) + local_state._history = create_autospec(HistoryLogger, instance=True) mocker.patch("colab_cli.common.state", local_state) mocker.patch("colab_cli.cli.state", local_state) return local_state @@ -1029,10 +1047,7 @@ def test_stop_removes_attached_session_without_stopping_runtime(tmp_path, mocker result = runner.invoke(app, ["stop", "-s", "nb1"]) assert result.exit_code == 0, result.output - assert result.output == ( - "[colab] 'nb1' wasn't created by the cli and isn't stopped," - " only removed from sessions list\n" - ) + assert result.output == f"{session_cmd.attached_not_stopped_message('nb1')}\n" local_state.client.list_assignments.assert_not_called() local_state.client.unassign.assert_not_called() session_cmd.ColabRuntime.assert_not_called() @@ -1054,10 +1069,7 @@ def test_stop_removes_cli_record_sharing_attached_endpoint(tmp_path, mocker): result = runner.invoke(app, ["stop", "-s", "cli2"]) assert result.exit_code == 0, result.output - assert result.output == ( - "[colab] 'cli2' wasn't created by the cli and isn't stopped," - " only removed from sessions list\n" - ) + assert result.output == f"{session_cmd.attached_not_stopped_message('cli2')}\n" local_state.client.unassign.assert_not_called() session_cmd.ColabRuntime.assert_not_called() assert local_state.store.get("cli2") is None @@ -1082,10 +1094,7 @@ def test_stop_all_skips_unassign_for_attached_sessions(tmp_path, mocker): result = runner.invoke(app, ["stop", "--all"]) assert result.exit_code == 0, result.output - assert ( - "[colab] 'nb1' wasn't created by the cli and isn't stopped," - " only removed from sessions list" in result.output - ) + assert session_cmd.attached_not_stopped_message("nb1") in result.output assert "[colab] Stopped 1 session(s)." in result.output local_state.client.unassign.assert_called_once_with("ep-cli") assert local_state.store.list() == {} @@ -1107,10 +1116,7 @@ def test_stop_all_attached_only_omits_stopped_count(tmp_path, mocker): result = runner.invoke(app, ["stop", "--all"]) assert result.exit_code == 0, result.output - assert result.output == ( - "[colab] 'nb1' wasn't created by the cli and isn't stopped," - " only removed from sessions list\n" - ) + assert result.output == f"{session_cmd.attached_not_stopped_message('nb1')}\n" local_state.client.unassign.assert_not_called() assert local_state.store.list() == {} diff --git a/tests/test_client.py b/tests/test_client.py index 1503b5f8..92ada4cb 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -14,7 +14,7 @@ import json import uuid -from unittest.mock import MagicMock +from unittest.mock import MagicMock, create_autospec import pytest import requests @@ -37,6 +37,8 @@ Variant, resolve_assign_shape, ) +from colab_cli.common import State +from colab_cli.state import SessionState, SettingsStore, StateStore @pytest.fixture @@ -565,16 +567,13 @@ def test_client_unassign_refuses_attached_endpoint(mock_session): def test_state_client_wires_attached_endpoint_guard(tmp_path, mocker): - from colab_cli.common import State - from colab_cli.state import SessionState, SettingsStore, StateStore - local_state = State() local_state._settings_store = SettingsStore(str(tmp_path / "settings.json")) local_state._store = StateStore(str(tmp_path / "sessions.json")) local_state.store.add( SessionState(name="nb1", token="t", url="u", endpoint="att-ep", attached=True) ) - mock_http = MagicMock(spec=AuthorizedSession) + mock_http = create_autospec(AuthorizedSession, instance=True) mocker.patch( "colab_cli.common.get_credentials", return_value=mock_http, autospec=True ) diff --git a/tests/test_ssh_autocreate.py b/tests/test_ssh_autocreate.py index 0d268afd..7c779691 100644 --- a/tests/test_ssh_autocreate.py +++ b/tests/test_ssh_autocreate.py @@ -23,10 +23,11 @@ way OpenSSH ends a ProxyCommand). """ -from unittest.mock import MagicMock +from unittest.mock import MagicMock, create_autospec from click import unstyle from colab_cli.cli import app +from colab_cli.commands import session as session_cmd from colab_cli.commands import ssh as ssh_module from colab_cli.runtime import ColabRuntime from colab_cli.state import SessionState, StateStore @@ -360,7 +361,9 @@ def attach_on_create(session=None, **_): mocker.patch( "colab_cli.commands.session.new", side_effect=attach_on_create, autospec=True ) - runtime = mocker.patch("colab_cli.commands.session.ColabRuntime", spec=ColabRuntime) + runtime = mocker.patch( + "colab_cli.commands.session.ColabRuntime", create_autospec(ColabRuntime) + ) _patch_interactive(mocker) result = runner.invoke(app, ["ssh", "--rm"]) @@ -371,10 +374,7 @@ def attach_on_create(session=None, **_): runtime.assert_not_called() mock_common_state.client.unassign.assert_not_called() assert store.get(name) is None - assert ( - f"[colab] {name!r} wasn't created by the cli and isn't stopped," - " only removed from sessions list" in result.output - ) + assert session_cmd.attached_not_stopped_message(name) in result.output def test_ssh_rm_proxy_removes_shared_attached_endpoint( @@ -390,7 +390,9 @@ def test_ssh_rm_proxy_removes_shared_attached_endpoint( mock_common_state.store = store mock_common_state.resolve_session.side_effect = lambda name, **_: name mock_common_state.get_session.side_effect = lambda name, **_: store.get(name) - runtime = mocker.patch("colab_cli.commands.session.ColabRuntime", spec=ColabRuntime) + runtime = mocker.patch( + "colab_cli.commands.session.ColabRuntime", create_autospec(ColabRuntime) + ) mocker.patch("signal.signal", autospec=True) _patch_proxy(mocker) @@ -401,7 +403,4 @@ def test_ssh_rm_proxy_removes_shared_attached_endpoint( mock_common_state.client.unassign.assert_not_called() assert store.get("cli2") is None assert store.get("nb1") is not None - assert ( - "[colab] 'cli2' wasn't created by the cli and isn't stopped," - " only removed from sessions list" in result.stderr - ) + assert session_cmd.attached_not_stopped_message("cli2") in result.stderr diff --git a/tests/test_state.py b/tests/test_state.py index 1e0392ec..9b132b27 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -16,7 +16,6 @@ import multiprocessing import os import pytest -import stat import tempfile import threading from datetime import datetime, timezone @@ -360,11 +359,6 @@ def test_state_store_multiprocess_concurrency(temp_config): assert len(StateStore(temp_config).list()) == 80 -OWNER_ONLY = 0o600 -WORLD_READABLE = 0o644 -DEFAULT_UMASK = 0o022 - - def test_session_state_attached_defaults_to_false(): session = SessionState(name="s", token="t", url="u", endpoint="e") @@ -412,33 +406,6 @@ def test_is_attached_endpoint(tmp_path): assert store.is_attached_endpoint("missing") is False -@pytest.mark.skipif(os.name == "nt", reason="POSIX file modes") -def test_attached_session_creates_private_sessions_file(tmp_path): - path = tmp_path / "sessions.json" - old_umask = os.umask(DEFAULT_UMASK) - try: - store = StateStore(str(path)) - store.add( - SessionState(name="att", token="t", url="u", endpoint="e", attached=True) - ) - finally: - os.umask(old_umask) - - assert stat.S_IMODE(path.stat().st_mode) == OWNER_ONLY - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX file modes") -def test_attached_session_tightens_existing_sessions_file_to_private(tmp_path): - path = tmp_path / "sessions.json" - path.touch() - os.chmod(path, WORLD_READABLE) - - store = StateStore(str(path)) - store.add(SessionState(name="att", token="t", url="u", endpoint="e", attached=True)) - - assert stat.S_IMODE(path.stat().st_mode) == OWNER_ONLY - - def test_default_store_paths_share_config_dir(tmp_path, monkeypatch): monkeypatch.setenv("HOME", str(tmp_path)) monkeypatch.setenv("USERPROFILE", str(tmp_path)) From c397666f5ae35bbba1f0a792bfc9509d0ca46668 Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Wed, 2 Dec 2026 04:24:41 +0000 Subject: [PATCH 12/17] fix(session,run): rename _stopOne param and test attached teardown branch --- src/colab_cli/commands/session.py | 6 +++--- tests/test_run.py | 26 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/colab_cli/commands/session.py b/src/colab_cli/commands/session.py index 2224dedc..183ddfb5 100644 --- a/src/colab_cli/commands/session.py +++ b/src/colab_cli/commands/session.py @@ -392,11 +392,11 @@ def attached_not_stopped_message(name: str) -> str: ) -def _stopOne(name: str, s: SessionState, *, skip_unassign: bool = False) -> bool: +def _stopOne(name: str, s: SessionState, *, attached_endpoint: bool = False) -> bool: """Terminate a session, or remove it locally if attached.""" from colab_cli.common import state - if s.attached or skip_unassign or state.store.is_attached_endpoint(s.endpoint): + if s.attached or attached_endpoint or state.store.is_attached_endpoint(s.endpoint): state.store.remove(name) typer.echo(attached_not_stopped_message(name)) return False @@ -459,7 +459,7 @@ def stop( attached_endpoints = {s.endpoint for s in sessions.values() if s.attached} stopped = 0 for name, s in sessions.items(): - if _stopOne(name, s, skip_unassign=s.endpoint in attached_endpoints): + if _stopOne(name, s, attached_endpoint=s.endpoint in attached_endpoints): stopped += 1 if stopped: typer.echo(f"[colab] Stopped {stopped} session(s).") diff --git a/tests/test_run.py b/tests/test_run.py index af605438..b3674ed2 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -919,3 +919,29 @@ def test_teardown_keeps_record_and_prints_retry_hint_when_unassign_fails( assert store.get("job1") is not None assert "[colab] Failed to stop session 'job1' (network error)." in result.stderr assert "Run `colab stop -s job1` to retry." in result.stderr + + +def test_teardown_skips_kernel_shutdown_when_fresh_record_attached( + 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_store.is_attached_endpoint.return_value = False + mock_store.get.return_value = SessionState( + name="job1", + token="t", + url="http://u", + endpoint="ep-123", + attached=True, + ) + + result = runner.invoke(app, ["run", "-s", "job1", str(script_path)]) + + assert result.exit_code == 0, result.output + mock_runtime_class.return_value.stop.assert_called_once_with() + mock_client.unassign.assert_called_once_with("ep-123") + mock_store.remove.assert_not_called() From 921590f85adae1e27359b44b2d22316560023ddb Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Wed, 2 Dec 2026 04:32:57 +0000 Subject: [PATCH 13/17] test(run): flip attached flag mid-run in fresh-record teardown test --- tests/test_run.py | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/tests/test_run.py b/tests/test_run.py index b3674ed2..db3b8564 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -929,15 +929,21 @@ def test_teardown_skips_kernel_shutdown_when_fresh_record_attached( script_path, ): mock_client.assign.return_value = assign_response - mock_runtime_class.return_value.execute_code.return_value = [] mock_store.is_attached_endpoint.return_value = False - mock_store.get.return_value = SessionState( - name="job1", - token="t", - url="http://u", - endpoint="ep-123", - attached=True, - ) + mock_store.get.return_value = None + + def mark_attached_during_run(code, **kwargs): + if "hello from script" in code: + mock_store.get.return_value = SessionState( + name="job1", + token="t", + url="http://u", + endpoint="ep-123", + attached=True, + ) + return [] + + mock_runtime_class.return_value.execute_code.side_effect = mark_attached_during_run result = runner.invoke(app, ["run", "-s", "job1", str(script_path)]) From 6c2e170d0fce227570aa24ad37097ca54ff96a70 Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Wed, 2 Dec 2026 04:33:21 +0000 Subject: [PATCH 14/17] test(run): keep fresh-record teardown assertion scoped to kernel stop --- tests/test_run.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/test_run.py b/tests/test_run.py index db3b8564..8795da30 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -950,4 +950,3 @@ def mark_attached_during_run(code, **kwargs): assert result.exit_code == 0, result.output mock_runtime_class.return_value.stop.assert_called_once_with() mock_client.unassign.assert_called_once_with("ep-123") - mock_store.remove.assert_not_called() From 8d5f6286f4ee90fc3e526dbe503b867c200d8570 Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Wed, 2 Dec 2026 04:42:40 +0000 Subject: [PATCH 15/17] fix(run,session,test): check fresh is not None, use imperative docstrings, and guard handler cleanup --- src/colab_cli/commands/run.py | 2 +- src/colab_cli/commands/session.py | 36 ++++++++++++++++--------------- tests/test_common.py | 3 ++- 3 files changed, 22 insertions(+), 19 deletions(-) diff --git a/src/colab_cli/commands/run.py b/src/colab_cli/commands/run.py index 1f2af10f..c4dd919f 100644 --- a/src/colab_cli/commands/run.py +++ b/src/colab_cli/commands/run.py @@ -399,7 +399,7 @@ def _teardown(name: str, s: SessionState, *, reason: str) -> None: # The script may have outlived the proxy token. fresh = state.get_session(name, ignore_missing_session=True) if ( - fresh + fresh is not None and not fresh.attached and not state.store.is_attached_endpoint(fresh.endpoint) ): diff --git a/src/colab_cli/commands/session.py b/src/colab_cli/commands/session.py index 183ddfb5..72e07a26 100644 --- a/src/colab_cli/commands/session.py +++ b/src/colab_cli/commands/session.py @@ -378,7 +378,7 @@ def status( def attached_not_stopped_message(name: str) -> str: - """Returns the notice printed when removing an attached session. + """Return the notice printed when removing an attached session. Args: name: Session name removed from the local store. @@ -431,7 +431,7 @@ def _stop_by_name(name: str, *, ignore_missing: bool) -> bool: def stop_session(name: str) -> None: - """Stops a named session, or removes it locally if attached. + """Stop a named session, or remove it locally if attached. Args: name: Session name in the local store. @@ -439,6 +439,18 @@ def stop_session(name: str) -> None: _stop_by_name(name, ignore_missing=False) +def _remove_local_endpoint_records( + endpoint: str, *, attached_only_notice: bool +) -> None: + from colab_cli.common import state + + for local_name, local_s in state.store.list().items(): + if local_s.endpoint == endpoint: + if attached_only_notice or local_s.attached: + typer.echo(attached_not_stopped_message(local_name)) + state.store.remove(local_name) + + def stop( session: Annotated[ Optional[str], @@ -469,11 +481,8 @@ def stop( if _stop_by_name(name, ignore_missing=True): return - if state.store.is_attached_endpoint(name) is True: - for local_name, local_s in state.store.list().items(): - if local_s.endpoint == name: - state.store.remove(local_name) - typer.echo(attached_not_stopped_message(local_name)) + if state.store.is_attached_endpoint(name): + _remove_local_endpoint_records(name, attached_only_notice=True) return match = next( @@ -483,20 +492,13 @@ def stop( typer.echo(f"[colab] Session '{name}' not found.") raise typer.Exit(1) - if state.store.is_attached_endpoint(match.endpoint) is True: - for local_name, local_s in state.store.list().items(): - if local_s.endpoint == match.endpoint: - state.store.remove(local_name) - typer.echo(attached_not_stopped_message(local_name)) + if state.store.is_attached_endpoint(match.endpoint): + _remove_local_endpoint_records(match.endpoint, attached_only_notice=True) return 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: - if local_s.attached is True: - typer.echo(attached_not_stopped_message(local_name)) - state.store.remove(local_name) + _remove_local_endpoint_records(match.endpoint, attached_only_notice=False) state.history.log_event(name, "session_terminated", {"reason": "user_requested"}) typer.echo("[colab] Session terminated.") diff --git a/tests/test_common.py b/tests/test_common.py index 3146cae9..64b609eb 100644 --- a/tests/test_common.py +++ b/tests/test_common.py @@ -202,6 +202,7 @@ def test_setup_logging_uses_settings_store_directory(tmp_path, monkeypatch): setup_logging(False) logging.getLogger("colab_cli.test").info("hello-from-settings-dir") finally: - root_logger.handlers[0].close() + for handler in root_logger.handlers: + handler.close() assert "hello-from-settings-dir" in (settings_dir / "colab.log").read_text() From 6da1c26ed1e2bcb27179618dfab59f042b5bbcb7 Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Fri, 4 Dec 2026 02:07:23 +0000 Subject: [PATCH 16/17] test(stop): cover stop -s with attached endpoint and document fallback --- docs/01_session_management.md | 2 +- tests/test_cli.py | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/docs/01_session_management.md b/docs/01_session_management.md index a682f795..663ea1ae 100644 --- a/docs/01_session_management.md +++ b/docs/01_session_management.md @@ -142,7 +142,7 @@ 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. -- **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. +- **Endpoint fallback**: If `-s ` does not match a local session name, `colab stop` removes local records locally when `` is an attached endpoint; otherwise it queries `list_assignments()` and matches by server endpoint ID (as shown in `colab sessions`), unassigning the matching runtime (unless attached) 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`) diff --git a/tests/test_cli.py b/tests/test_cli.py index 3354614d..71a0f0f2 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1193,3 +1193,21 @@ def test_sessions_and_status_use_store_key_when_name_differs(mock_common_state): assert status_res.output.startswith("[alias] ep1 |") assert single_res.exit_code == 0 assert single_res.output.startswith("[alias] ep1 |") + + +def test_stop_by_attached_endpoint_removes_local_without_http(tmp_path, mocker): + local_state = _real_stop_state(tmp_path, mocker) + local_state.store.add( + SessionState( + name="nb1", token="t", url="https://u", endpoint="ep-nb1", attached=True + ) + ) + + result = runner.invoke(app, ["stop", "-s", "ep-nb1"]) + + assert result.exit_code == 0, result.output + assert result.output == f"{session_cmd.attached_not_stopped_message('nb1')}\n" + local_state.client.list_assignments.assert_not_called() + local_state.client.unassign.assert_not_called() + session_cmd.ColabRuntime.assert_not_called() + assert local_state.store.get("nb1") is None From 5db58f8276c4a01171ce1aacd223f5720fc85882 Mon Sep 17 00:00:00 2001 From: Drake Aiman Date: Fri, 4 Dec 2026 03:06:47 +0000 Subject: [PATCH 17/17] refactor(stop,test,docs): simplify endpoint record removal, deduplicate unassign test, and document attached stop --- docs/01_session_management.md | 11 +++++----- src/colab_cli/commands/session.py | 18 +++++++--------- tests/test_run.py | 35 +++++++------------------------ 3 files changed, 21 insertions(+), 43 deletions(-) diff --git a/docs/01_session_management.md b/docs/01_session_management.md index 663ea1ae..468bb327 100644 --- a/docs/01_session_management.md +++ b/docs/01_session_management.md @@ -5,11 +5,11 @@ log: 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-18: `SessionState.attached` marks sessions attached to a runtime the CLI did not create in `sessions.json`; `Client.unassign` refuses attached - endpoints, `colab stop` (including `--all`) and `colab ssh --rm` remove - attached sessions without stopping or unassigning their runtimes, `colab run` - cleanup removes its non-attached record only once its runtime is released, - and `State.store` and `setup_logging` derive the default config directory - from `SettingsStore.path`. + endpoints, `colab stop` (including `--all` and `-s `) and + `colab ssh --rm` remove local records for attached endpoints without stopping + or unassigning their runtimes, `colab run` cleanup removes its non-attached + record only once its runtime is released, and `State.store` and + `setup_logging` derive the default config directory from `SettingsStore.path`. 2026-11-13: Documented `--auth {oauth2,adc}` (default `oauth2`) and required ADC `gcloud` scopes under Global Flags. 2026-11-04: `--gpu` and `--tpu` now reject unknown values instead of silently selecting `A100` (GPU) or `v6e1` (TPU). `resolve_runtime_options()` uses the new `GPU_ACCELERATORS` / `TPU_ACCELERATORS` maps and raises a `typer.BadParameter` that names the flag and the supported list; `--help` is generated from the same maps so it cannot drift. Validation runs before any assignment request, in both `colab new` and `colab run`. 2026-11-02: Added `_check_linux_keyring_locked` in `auth.py` to check if the active Linux `SecretService` keyring collection is locked via `secretstorage` before reading or writing OAuth tokens, logging and printing an immediate warning with the collection label, timeout, and `--auth=adc` hint while still attempting the keyring operation. @@ -188,6 +188,7 @@ TDD is mandatory for all session management features. - **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 ` removes local records for an attached endpoint without calling `list_assignments()` or `unassign()`. - **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/src/colab_cli/commands/session.py b/src/colab_cli/commands/session.py index 72e07a26..f1cbb0d4 100644 --- a/src/colab_cli/commands/session.py +++ b/src/colab_cli/commands/session.py @@ -439,16 +439,15 @@ def stop_session(name: str) -> None: _stop_by_name(name, ignore_missing=False) -def _remove_local_endpoint_records( - endpoint: str, *, attached_only_notice: bool -) -> None: +def _remove_local_endpoint_records(endpoint: str) -> list[str]: from colab_cli.common import state + removed = [] for local_name, local_s in state.store.list().items(): if local_s.endpoint == endpoint: - if attached_only_notice or local_s.attached: - typer.echo(attached_not_stopped_message(local_name)) state.store.remove(local_name) + removed.append(local_name) + return removed def stop( @@ -482,7 +481,8 @@ def stop( return if state.store.is_attached_endpoint(name): - _remove_local_endpoint_records(name, attached_only_notice=True) + for local_name in _remove_local_endpoint_records(name): + typer.echo(attached_not_stopped_message(local_name)) return match = next( @@ -492,13 +492,9 @@ def stop( typer.echo(f"[colab] Session '{name}' not found.") raise typer.Exit(1) - if state.store.is_attached_endpoint(match.endpoint): - _remove_local_endpoint_records(match.endpoint, attached_only_notice=True) - return - typer.echo(f"[colab] Stopping session '{name}'...") state.client.unassign(match.endpoint) - _remove_local_endpoint_records(match.endpoint, attached_only_notice=False) + _remove_local_endpoint_records(match.endpoint) state.history.log_event(name, "session_terminated", {"reason": "user_requested"}) typer.echo("[colab] Session terminated.") diff --git a/tests/test_run.py b/tests/test_run.py index 8795da30..0ae8f0d4 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -16,6 +16,7 @@ execution that bundles `colab new` + `colab exec` + `colab stop`. """ +import logging from datetime import datetime, timezone from unittest.mock import MagicMock @@ -490,6 +491,7 @@ def test_run_teardown_keeps_local_session_when_unassign_fails( mock_runtime_class, assign_response, script_path, + caplog, ): mock_client.assign.return_value = assign_response mock_runtime_class.return_value.execute_code.return_value = [] @@ -499,9 +501,11 @@ def test_run_teardown_keeps_local_session_when_unassign_fails( 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)]) + with caplog.at_level(logging.WARNING, logger="colab_cli.commands.run"): + result = runner.invoke(app, ["run", "-s", "demo", str(script_path)]) assert result.exit_code == 0, result.output + mock_runtime_class.return_value.stop.assert_any_call(shutdown_kernel=True) mock_client.unassign.assert_called_once_with("ep-123") mock_store.remove.assert_not_called() terminated_events = [ @@ -510,8 +514,9 @@ def test_run_teardown_keeps_local_session_when_unassign_fails( 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 "Failed to unassign session" in caplog.text + assert "[colab] Failed to stop session 'demo' (network down)." in result.stderr + assert "Run `colab stop -s demo` to retry." in result.stderr assert "Session terminated." not in result.stderr @@ -897,30 +902,6 @@ def add_attached_mid_run(code, **kwargs): assert "colab stop -s job1" in result.stderr -def test_teardown_keeps_record_and_prints_retry_hint_when_unassign_fails( - mock_common_state, - mock_client, - mock_runtime_class, - assign_response, - script_path, - tmp_path, -): - store = StateStore(str(tmp_path / "sessions.json")) - mock_common_state.store = store - mock_common_state.get_session.side_effect = lambda name, **_: store.get(name) - mock_client.assign.return_value = assign_response - mock_runtime_class.return_value.execute_code.return_value = [] - mock_client.unassign.side_effect = RuntimeError("network error") - - result = runner.invoke(app, ["run", "-s", "job1", str(script_path)]) - - assert result.exit_code == 0, result.output - mock_runtime_class.return_value.stop.assert_any_call(shutdown_kernel=True) - assert store.get("job1") is not None - assert "[colab] Failed to stop session 'job1' (network error)." in result.stderr - assert "Run `colab stop -s job1` to retry." in result.stderr - - def test_teardown_skips_kernel_shutdown_when_fresh_record_attached( mock_client, mock_store,