diff --git a/AGENTS.md b/AGENTS.md index e8236b4..85b47c8 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 8633acd..64dcaf0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +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 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/docs/01_session_management.md b/docs/01_session_management.md index e82756f..2c19536 100644 --- a/docs/01_session_management.md +++ b/docs/01_session_management.md @@ -1,5 +1,12 @@ --- log: +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. @@ -109,6 +116,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). - **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. @@ -143,7 +159,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. +- **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 f841461..2f04cbd 100644 --- a/docs/05_run_command.md +++ b/docs/05_run_command.md @@ -1,5 +1,9 @@ --- log: +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__"`. @@ -61,9 +65,13 @@ 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). - - Calls `state.client.unassign(endpoint)` to free the billable VM. - - Removes the session from `StateStore`. + - 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. If + unassignment fails (including `AttachedRuntimeError`), keeps the local + session record and prints a `colab stop -s ` retry hint. + - Removes the session from `StateStore` once unassigned, unless a concurrent + attached record replaced it under the same name. - Logs `session_terminated` with `reason="run_completed"` (or `"run_failed"`). 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/src/colab_cli/client.py b/src/colab_cli/client.py index f32d359..58fa0c2 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 @@ -237,6 +237,10 @@ class TooManyAssignmentsError(Exception): pass +class AttachedRuntimeError(Exception): + """Unassign was refused for an attached runtime.""" + + class Client: def __init__( self, @@ -245,6 +249,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 @@ -253,6 +258,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: @@ -421,6 +427,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 6dc92b2..beb602e 100644 --- a/src/colab_cli/commands/run.py +++ b/src/colab_cli/commands/run.py @@ -483,7 +483,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: @@ -492,10 +496,17 @@ def _teardown(name: str, s: SessionState, *, reason: str) -> None: try: state.client.unassign(s.endpoint) except Exception: - pass + typer.echo( + f"[colab] Could not release runtime '{s.endpoint}'; run" + f" 'colab stop -s {name}' to retry.", + err=True, + ) + 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/session.py b/src/colab_cli/commands/session.py index 2ee50b8..70198a8 100644 --- a/src/colab_cli/commands/session.py +++ b/src/colab_cli/commands/session.py @@ -287,7 +287,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); @@ -304,12 +304,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, @@ -335,7 +335,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.") return @@ -343,14 +343,38 @@ 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 _stopOne(name: str, s: SessionState) -> None: - """Terminate a single session (kernel, backend, local store).""" +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, *, 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 + ): + 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) @@ -359,6 +383,30 @@ 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_session(name: str) -> None: + """Stops a named session, or removes it locally if attached. + + Args: + name: Session name in the local store. + """ + 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 + s = state.get_session(name, ignore_missing_session=True) + if not s: + typer.echo(f"[colab] Session '{name}' not found.") + return + if _stopOne(name, s): + typer.echo("[colab] Session terminated.") def stop( @@ -377,18 +425,20 @@ 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).") + 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 name = state.resolve_session(session) - s = state.get_session(name, ignore_missing_session=True) - if not s: - typer.echo(f"[colab] Session '{name}' not found.") - return - _stopOne(name, s) - typer.echo("[colab] Session terminated.") + stop_session(name) def register(app: typer.Typer): diff --git a/src/colab_cli/commands/ssh.py b/src/colab_cli/commands/ssh.py index 55f9d3b..3645c89 100644 --- a/src/colab_cli/commands/ssh.py +++ b/src/colab_cli/commands/ssh.py @@ -230,7 +230,7 @@ def _stop_session(name: str) -> None: from colab_cli.commands import session as session_cmd try: - 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/src/colab_cli/common.py b/src/colab_cli/common.py index 2cf4c74..e72caf4 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 @@ -92,6 +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), ) return self._client @@ -248,7 +252,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 6d08b7b..5695c35 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,18 @@ def list(self) -> Dict[str, SessionState]: if f is None: return {} 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 f08fdc1..54a5adb 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -29,7 +29,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, StateStore runner = CliRunner() @@ -737,3 +740,170 @@ def test_cli_test_public_api_hidden_and_reports_status(mock_common_state): assert res.exit_code == 0 assert "Public API" in res.output assert "Tunnel API" 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() == {} + + +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 |") diff --git a/tests/test_client.py b/tests/test_client.py index 5868fa9..ac06359 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, @@ -507,3 +508,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_common.py b/tests/test_common.py index 3ec4d47..3146cae 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_run.py b/tests/test_run.py index 9834da3..c29aa7a 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -25,12 +25,13 @@ from colab_cli.cli import app from colab_cli.client import ( Accelerator, + AttachedRuntimeError, PostAssignmentResponse, RuntimeProxyInfo, TooManyAssignmentsError, Variant, ) -from colab_cli.state import SessionState +from colab_cli.state import SessionState, StateStore runner = CliRunner() @@ -717,3 +718,67 @@ 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_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_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 [] + + mock_runtime_class.return_value.execute_code.side_effect = add_attached_mid_run + + 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 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] Could not release runtime 'ep-123'; run 'colab stop -s job1'" + " to retry." in result.stderr + ) diff --git a/tests/test_ssh.py b/tests/test_ssh.py index 1c57e5e..9846d1b 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 b23132f..45e637c 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 @@ -238,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) @@ -248,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() @@ -270,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() @@ -299,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"] @@ -331,3 +332,73 @@ 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 +): + store = StateStore(str(tmp_path / "sessions.json")) + 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) + runtime = mocker.patch("colab_cli.commands.session.ColabRuntime") + _patch_interactive(mocker) + + result = runner.invoke(app, ["ssh", "--rm"]) + + assert result.exit_code == 0, result.output + assert len(created_names) == 1 + name = created_names[0] + 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 + ) + + +def test_ssh_rm_proxy_removes_shared_attached_endpoint( + mock_common_state, tmp_path, mocker +): + store = StateStore(str(tmp_path / "sessions.json")) + store.add( + SessionState( + name="nb1", token="t", url="https://u", endpoint="ep1", attached=True + ) + ) + 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) + 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 + 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 + assert ( + "[colab] 'cli2' wasn't created by the cli and isn't stopped," + " only removed from sessions list" in result.stderr + ) diff --git a/tests/test_ssh_lifecycle.py b/tests/test_ssh_lifecycle.py index 7a9575d..d9a9809 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") diff --git a/tests/test_state.py b/tests/test_state.py index 94285a3..1e0392e 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,116 @@ 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") + + +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