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..64dcaf0b 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 eceddeaa..468bb327 100644 --- a/docs/01_session_management.md +++ b/docs/01_session_management.md @@ -3,6 +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 `-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. @@ -118,6 +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). - **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. @@ -126,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`) @@ -154,7 +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. +- **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. @@ -166,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/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/src/colab_cli/client.py b/src/colab_cli/client.py index a094b1c3..7614233e 100644 --- a/src/colab_cli/client.py +++ b/src/colab_cli/client.py @@ -18,6 +18,7 @@ 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 @@ -235,6 +236,10 @@ class TooManyAssignmentsError(Exception): pass +class AttachedRuntimeError(Exception): + """Unassign was refused for an attached runtime.""" + + class Client: def __init__( self, @@ -243,7 +248,18 @@ def __init__( logger=None, use_public_api: bool = False, settings_store=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 @@ -251,6 +267,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 +443,18 @@ 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): + 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..c4dd919f 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 is not None + 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) 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 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 27177cad..f1cbb0d4 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: 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) -> 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=s.name, + name=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,14 +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 name, s in local_sessions.items(): + _print_status_for(s, name=name) -def _stopOne(name: str, s: SessionState) -> None: - """Terminate a single session (kernel, backend, local store).""" +def attached_not_stopped_message(name: str) -> str: + """Return 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, *, attached_endpoint: bool = False) -> bool: + """Terminate a session, or remove it locally if attached.""" from colab_cli.common import state + 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 + typer.echo(f"[colab] Stopping session '{name}'...") try: ColabRuntime(s.url, s.token, kernel_id=s.kernel_id).stop(shutdown_kernel=True) @@ -389,6 +409,45 @@ 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_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 or state.store.is_attached_endpoint(record.endpoint) + ): + _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: + """Stop a named session, or remove it locally if attached. + + Args: + name: Session name in the local store. + """ + _stop_by_name(name, ignore_missing=False) + + +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: + state.store.remove(local_name) + removed.append(local_name) + return removed def stop( @@ -408,16 +467,22 @@ def stop( if not sessions: typer.echo("[colab] No active sessions.") return + attached_endpoints = {s.endpoint for s in sessions.values() if s.attached} + stopped = 0 for name, s in sessions.items(): - _stopOne(name, s) - typer.echo(f"[colab] Stopped {len(sessions)} session(s).") + if _stopOne(name, s, attached_endpoint=s.endpoint in attached_endpoints): + stopped += 1 + 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 s is not None: - _stopOne(name, s) - typer.echo("[colab] Session terminated.") + if _stop_by_name(name, ignore_missing=True): + return + + if state.store.is_attached_endpoint(name): + for local_name in _remove_local_endpoint_records(name): + typer.echo(attached_not_stopped_message(local_name)) return match = next( @@ -429,9 +494,7 @@ def stop( typer.echo(f"[colab] Stopping session '{name}'...") state.client.unassign(match.endpoint) - for local_name, local_s in state.store.list().items(): - if local_s.endpoint == match.endpoint: - state.store.remove(local_name) + _remove_local_endpoint_records(match.endpoint) state.history.log_event(name, "session_terminated", {"reason": "user_requested"}) typer.echo("[colab] Session terminated.") diff --git a/src/colab_cli/commands/ssh.py b/src/colab_cli/commands/ssh.py index cbf6a42b..d2e8c7de 100644 --- a/src/colab_cli/commands/ssh.py +++ b/src/colab_cli/commands/ssh.py @@ -231,7 +231,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 2cf4c744..5c8910ea 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: str | None = 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 endpoint: self.store.is_attached_endpoint(endpoint), ) return self._client @@ -248,7 +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) - log_dir = os.path.expanduser("~/.config/colab-cli") + 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/src/colab_cli/state.py b/src/colab_cli/state.py index 6d08b7b3..06bf902d 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 and session.endpoint == endpoint + for session in self.list().values() + ) diff --git a/tests/conftest.py b/tests/conftest.py index 0f5eda5a..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(): @@ -40,12 +41,14 @@ 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.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() mock_state.auth_provider = AuthProvider.OAUTH2 diff --git a/tests/test_automation.py b/tests/test_automation.py index e880f61d..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() @@ -44,9 +44,17 @@ 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 + + @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 +78,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 +101,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 +126,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 +199,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 +231,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 +253,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 +272,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 2aa8c33e..71a0f0f2 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 @@ -25,19 +26,43 @@ 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, + Client, ColabRequestError, + ListedAssignment, PostAssignmentResponse, 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.history import HistoryLogger +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 @@ -316,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" @@ -333,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" @@ -438,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"]) @@ -987,3 +1009,205 @@ 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", 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 = 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 + + +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 == 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() + 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 == 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 + 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}, []), + autospec=True, + ) + + 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 "[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}, []), + autospec=True, + ) + + result = runner.invoke(app, ["stop", "--all"]) + + assert result.exit_code == 0, result.output + assert result.output == f"{session_cmd.attached_not_stopped_message('nb1')}\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}, []), + autospec=True, + ) + + 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_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): + 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}, + [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 |") + + +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 diff --git a/tests/test_client.py b/tests/test_client.py index 46fa8f66..92ada4cb 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -14,14 +14,16 @@ import json import uuid -from unittest.mock import MagicMock +from unittest.mock import MagicMock, create_autospec import pytest import requests +from google.auth.transport.requests import AuthorizedSession from colab_cli.client import ( Accelerator, Assignment, + AttachedRuntimeError, Client, ColabRequestError, ConnectionInfo, @@ -35,6 +37,8 @@ Variant, resolve_assign_shape, ) +from colab_cli.common import State +from colab_cli.state import SessionState, SettingsStore, StateStore @pytest.fixture @@ -551,3 +555,30 @@ 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): + 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 = create_autospec(AuthorizedSession, instance=True) + 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") + + mock_http.request.assert_not_called() diff --git a/tests/test_common.py b/tests/test_common.py index 3ec4d473..64b609eb 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,62 @@ 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: + for handler in root_logger.handlers: + handler.close() + + assert "hello-from-settings-dir" in (settings_dir / "colab.log").read_text() 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_run.py b/tests/test_run.py index ab65fabd..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 @@ -26,13 +27,14 @@ 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.state import SessionState, StateStore runner = CliRunner() @@ -489,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 = [] @@ -498,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 = [ @@ -509,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 @@ -819,3 +825,109 @@ 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_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, + 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_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_store.is_attached_endpoint.return_value = False + 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)]) + + 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") diff --git a/tests/test_ssh.py b/tests/test_ssh.py index 1c57e5ea..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", 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 b23132f0..7c779691 100644 --- a/tests/test_ssh_autocreate.py +++ b/tests/test_ssh_autocreate.py @@ -23,11 +23,14 @@ 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 import pytest from typer.testing import CliRunner import typer @@ -238,7 +241,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", autospec=True) mocker.patch("signal.signal") # don't install real handlers during tests _patch_proxy(mocker) @@ -248,7 +251,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 +273,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", autospec=True) _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 +302,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", autospec=True) _patch_proxy(mocker) args = ["ssh", "--proxy-mode", "-s", "colab"] @@ -331,3 +334,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, autospec=True + ) + runtime = mocker.patch( + "colab_cli.commands.session.ColabRuntime", create_autospec(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 session_cmd.attached_not_stopped_message(name) 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", create_autospec(ColabRuntime) + ) + mocker.patch("signal.signal", autospec=True) + _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 session_cmd.attached_not_stopped_message("cli2") in result.stderr diff --git a/tests/test_ssh_lifecycle.py b/tests/test_ssh_lifecycle.py index 7a9575d7..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") + 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( @@ -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", autospec=True) 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,12 @@ 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, 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") + 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()) @@ -250,7 +252,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 +265,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", autospec=True) _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 94285a3e..9b132b27 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import json import multiprocessing import os import pytest @@ -356,3 +357,84 @@ def test_state_store_multiprocess_concurrency(temp_config): assert p1.exitcode == 0 assert p2.exitcode == 0 assert len(StateStore(temp_config).list()) == 80 + + +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 + + +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