Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
24 changes: 23 additions & 1 deletion docs/01_session_management.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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] '<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 Down Expand Up @@ -143,7 +159,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 Down
14 changes: 11 additions & 3 deletions docs/05_run_command.md
Original file line number Diff line number Diff line change
@@ -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 <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 @@ -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 <name>` 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 <name>`, `colab repl -s <name>`, etc., until the user runs `colab stop` (or the backend reclaims it due to inactivity).
Expand Down
12 changes: 11 additions & 1 deletion src/colab_cli/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -237,6 +237,10 @@ class TooManyAssignmentsError(Exception):
pass


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


class Client:
def __init__(
self,
Expand All @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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}
Expand Down
17 changes: 14 additions & 3 deletions src/colab_cli/commands/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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

Expand Down
84 changes: 67 additions & 17 deletions src/colab_cli/commands/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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,
Expand All @@ -335,22 +335,46 @@ 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

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)
Expand All @@ -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(
Expand All @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion src/colab_cli/commands/ssh.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
13 changes: 10 additions & 3 deletions src/colab_cli/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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.
Expand Down
Loading