Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
27 changes: 25 additions & 2 deletions docs/01_session_management.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ log:
2026-12-02: `colab stop -s <target>` now falls back to `list_assignments()` and matches by server endpoint when `<target>` 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 <name>` 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 <endpoint>`) 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.
Expand Down Expand Up @@ -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] '<name>' 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 <name>` retry hint).
- **API**: `POST https://colab.sandbox.google.com/tun/m/unassign/<endpoint>` (based on `tpu-v5e1-unassign.har`).
- **Flow**:
1. Perform a `GET` request to the unassign URL to obtain a fresh XSRF token.
Expand All @@ -126,7 +142,7 @@ end to end; mocked timeouts alone do not establish backend compatibility.
- `authuser`: 0.
- `<endpoint>`: 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 <target>` 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 <target>` does not match a local session name, `colab stop` removes local records locally when `<target>` 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 <name>`) 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`)
Expand Down Expand Up @@ -154,7 +170,13 @@ The runtime proxy token (`runtimeProxyInfo.token`) authenticates every request t
- Handle authentication headers (likely `Authorization: Bearer <token>` 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 (`<path>.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.
Expand All @@ -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 <endpoint>` 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 <endpoint>` removes local records for an attached endpoint without calling `list_assignments()` or `unassign()`.
- **Test Case**: Verify `colab stop -s <missing>` 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.
Expand Down
14 changes: 12 additions & 2 deletions docs/05_run_command.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
log:
2026-12-02: `_teardown` now keeps the local session record and logs/prints a retry hint (`colab stop -s <name>`) 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 <name>`
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 <script.py> [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__"`.
Expand Down Expand Up @@ -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 <name>` 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 <name>` 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 <name>`, `colab repl -s <name>`, etc., until the user runs `colab stop` (or the backend reclaims it due to inactivity).

Expand Down
29 changes: 29 additions & 0 deletions src/colab_cli/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -235,6 +236,10 @@ class TooManyAssignmentsError(Exception):
pass


class AttachedRuntimeError(Exception):
"""Unassign was refused for an attached runtime."""


class Client:
def __init__(
self,
Expand All @@ -243,14 +248,26 @@ 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
self.session = session
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:
Expand Down Expand Up @@ -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}
Expand Down
10 changes: 8 additions & 2 deletions src/colab_cli/commands/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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

Expand Down
Loading