Skip to content
Merged
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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ Run `colab <command> --help` to view specific options, defaults, and detailed he
| `colab run [--gpu GPU] [--tpu TPU] [--high-mem] [--keep \| --detach] [--secret SPEC] [--json] [--budget CU] SCRIPT [ARGS...]` | Run a local script on a fresh VM, forwarding arguments, then release it; `--detach` starts it as a background `colab job` and keeps the VM |
| `colab exec [-s NAME] [-f FILE] [--output-image PATH] [--secret SPEC] [--var NAME=JSON] [--cells SPEC] [--stop-on-error] [--check \| --check-only] [--json \| --json-stream]` | Execute Python code from stdin, a local `.py` file, or a `.ipynb` notebook (exits 1 if the code or any cell raised an error) |
| `colab repl [-s NAME] [--output-image PATH]` | Start an interactive Python REPL on the VM (exits cleanly on piped EOF) |
| `colab ssh [-s NAME] [--proxy-mode] [-i KEY] [--gpu GPU] [--tpu TPU] [--high-mem] [-L PORT [-N]] [-- CMD ...]` | Open an SSH shell to the runtime over WebSocket, run a one-shot remote command (`-- CMD`), or act as an OpenSSH `ProxyCommand` bridge for IDE remote-dev |
| `colab ssh [-s NAME] [--proxy-mode] [-i KEY] [--gpu GPU] [--tpu TPU] [--high-mem] [-L PORT [-N]] [--force] [-- CMD ...]` | Open an SSH shell to the runtime over WebSocket, run a one-shot remote command (`-- CMD`), or act as an OpenSSH `ProxyCommand` bridge for IDE remote-dev |
| `colab job start [-s NAME] [--name N] [--env K=V] [--secret SPEC] [--budget CU] [--json] (-f SCRIPT [-- ARGS] \| -- CMD)` | Start a long job in the background on the runtime and return at once; `-f` also takes a notebook (`.ipynb`, its cells run in order in IPython); Python jobs report metrics, and `report(epoch=, epochs=)` the overall progress, with `colab_feedback.report()`; `--budget` stops the job once it has used about that many compute units |
| `colab job status\|tail\|wait\|stop\|list [-s NAME] [ID] [--json]` | Follow a job: state, tqdm progress, overall progress, epoch or notebook cell, metrics trend, last output, stall flag and a diagnosis of failures; `wait` keeps the runtime alive and exits with the job's code |
| `colab profile list\|show\|add\|edit\|rm\|path\|run` | Saved run setups in `profiles.toml`: `run NAME` starts a script or notebook as a background job (new runtime, or its fixed session), or runs a server in the kernel (`vars`), forwards its ports and opens its URL when ready |
Expand Down
2 changes: 2 additions & 0 deletions docs/01_session_management.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
log:
2026-11-20: Listed the fork code that keys runtimes by `endpoint` and has to follow upstream #260 (Public API assign/unassign) once it lands; see TODO.
2026-11-20: `colab stop --endpoint <id>` stops one runtime by the endpoint `colab sessions` lists, also one with no local session (`[?]`, e.g. opened in the Colab web UI); an endpoint of a local session stops that session as `-s` does, an unknown one exits 1, and it cannot be combined with `-s`, `--orphans` or `--all` (exit 2). The tray's Stop button uses it for such runtimes.
2026-11-20: After the last allocation POST fails with `ReadTimeout` or 502/503/504, `Client.assign` waits one more backoff step and queries the notebook hash again, so a runtime the backend created after the timeout is returned and `colab new` / `colab run` save it instead of leaving a `[?]` orphan (upstream issue #263). If it is still not there, a timeout raises `AssignmentTimeoutError` (a `TimeoutError`, printed as one `[colab]` line) that points to `colab sessions`, `colab stop --orphans` and `COLAB_CLI_REQUEST_TIMEOUT`. Verified live with `COLAB_CLI_REQUEST_TIMEOUT=1 COLAB_CLI_ASSIGN_RETRIES=0`.
2026-11-18: Merged upstream `colab stop --all` (#256) next to this fork's `--orphans`: `--all` stops every local session the server still knows (`sync_sessions`), `--orphans` the server runtimes with no local session; `--all` with `-s` or `--orphans` exits 2. `_stopOne` keeps passing `session_name` to `ColabRuntime`.
Expand Down Expand Up @@ -148,6 +149,7 @@ VM liveness is automatically maintained by the Colab backend based on active ker
The runtime proxy token (`runtimeProxyInfo.token`) authenticates every request to the VM and expires after `tokenExpiresInSeconds` (1 hour). `SessionState.token_expires_at` stores the absolute expiry, computed when the token is received. Commands that talk to the VM load their session through `State.get_session(name)`, which, when the token is missing an expiry or is within 5 minutes of it, calls `GET /tun/m/assignments`, takes the fresh token/URL for the matching endpoint, and persists it. If the endpoint is no longer assigned, the session is pruned. `sync_sessions` also writes back the fresh tokens it already fetches. Long-lived connections (`repl`, `ssh`) only present the token on initial connect and aren't refreshed mid-session.

## TODO / Future Work
- **Upstream #260 (Public API assign/unassign), when it is merged**: Public API runtimes are named `runtimes/r-...` and may have an empty `endpoint`. Upstream then stores `runtime_name`, calls `unassign(endpoint, runtime_name=..., url=...)` and matches sessions with `common.match_session` (runtime name, endpoint, proxy URL). These fork paths still key runtimes by `endpoint` and must move to that matching: `_stop_orphans` and `_stop_endpoint` (`commands/session.py`), the tray's session/assignment pairing (`tray_model.py`), `run.py`'s `unassign(s.endpoint)` and the fork's `_stopOne`, and keep-alive (`keepalive.py`, `job.py`, `share.py`, `ssh.py`), whose `/tun/m/{endpoint}/keep-alive/` route has no Public API equivalent yet. Only `--public-api` users are affected until upstream changes the default.
- **Backend Sync**: Implement a way to reconcile the local `sessions.json` with the output of `colab sessions`.
- **VM Resource Usage**: Add real-time resource usage (CPU/RAM/GPU) to the `status` output by executing a diagnostic snippet on the VM (distinct from account-level CU info, which is available via `colab usage`).

Expand Down
11 changes: 11 additions & 0 deletions docs/04_automation_and_utility.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
log:
2026-11-20 (upstream #212 and #259, not merged here): upstream made the inline Drive hook in `commands/automation.py` parse propagation responses defensively and report failures instead of dumping HTML and retrying. This fork already does all of that in `drive_auth.perform_drive_authorization` (`parse_colab_json`, `explain_propagation_failure` with the multi-account guidance, an error reply to the kernel so the mount does not wait out its timeout), so the sync kept the fork's hook and tests.
2026-11-20: The unsolicited upgrade banner (daily background fetch and the cached banner) is printed to stderr, not stdout. With an older install it ended up in machine-readable stdout and broke `colab exec --json`, `colab run --json`, `colab tray --snapshot --json` and the other JSON outputs. An explicit `colab update` still prints its result to stdout.
2026-11-13: `_get_adc_credentials` in `auth.py` now catches `DefaultCredentialsError` from `google.auth.default()` so missing local ADC prints the 4-scope `gcloud auth application-default login` command and exits 1 instead of surfacing `google-auth`'s stock unscoped setup message. Updated scope documentation to clarify that both `colaboratory` and `userinfo.email` are required by `colab.research.google.com`.
2026-11-12: `colab usage --json` prints one `colab.v1` record of type `usage` (`balance_cu`, `rate_cu_per_hour`, `hours_left_at_rate`, `assignments`); agents use it with the cost feedback of docs/08_agent_feedback.md.
Expand Down Expand Up @@ -151,6 +152,16 @@ How each provider supplies the scopes:
`jupyter_kernel_client` default raising `TimeoutError` mid-flow, this
subcommand passes `timeout=INTERACTIVE_AUTOMATION_TIMEOUT_SEC` (600s) to
`ColabRuntime.execute_code`. Same applies to `colab auth`.
- **Multi-account browsers**: Drive propagation is attributed to the Google
account that approves the consent page, which may not be the account the
CLI authenticated as. If the browser shows an account chooser, select the
account reported by `colab whoami`; approving with another account fails
with HTTP 400 even though the consent itself succeeded. A private window
only helps if it is already signed in to that account.
- **Failure reporting**: errors from the propagation endpoint never echo the
raw response body (often HTML). The CLI prints the status, points at
`colab whoami`, logs the body to the history file, and answers the waiting
kernel request so `drivemount` exits instead of hanging until its timeout.

### 4. Logging and Notebook Capture (`colab log`)

Expand Down
1 change: 1 addition & 0 deletions docs/06_ssh_access.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
log:
2026-11-20: Merged upstream `colab ssh --force` (#254): before connecting, it kills the runtime's existing SSH sessions through the kernel (`pkill -P $(pgrep -o -x sshd)`), for when a dead client keeps the session slot and the server answers 429. It works with the fork's interactive shell, `-N`/`-L` forwards, `-- CMD` and `--proxy-mode`.
2026-11-12: Linux: ssh is started with `preexec_fn=_ssh_preexec`, which sets `PR_SET_PDEATHSIG` (SIGTERM), so a SIGKILL of colab also ends ssh and, through ssh, its ProxyCommand; the standalone binary's CLI process ties itself to its PyInstaller launcher the same way (`_tie_to_launcher_linux`, only when the parent runs the same exe). macOS has no equivalent; a closed terminal (SIGHUP) still ends everything there. Git Bash: the remote `-- CMD` arguments are passed through `utils.undo_msys_args`, so `colab ssh -- ls /content` works without `MSYS_NO_PATHCONV`. Live on the Windows binary: ssh path and launcher kill; on the Linux binary: launcher SIGKILL.
2026-11-12: `colab ssh` (interactive, `-- CMD`, `-N`) and `colab forward` check that a key file exists before they create a runtime or start ssh (`_require_ssh_key`), and exit 2. Before, the ProxyCommand child found the key missing, so the user got ssh's exit 255 after an interactive `colab ssh` had already assigned a runtime. Without a default key, the message names other ed25519/ECDSA keys in `~/.ssh` and how to pass one with `-i`. Added `tests/test_ssh_key_precheck.py`.
2026-11-12: Standalone binary on Windows: the PyInstaller onefile launcher is the parent of the process that runs the CLI, from the same exe. That process now hands the only kill-on-close job handle to the launcher (`_hand_job_to_launcher`, `DuplicateHandle`), so a forced kill of the launcher (closed tab, `taskkill /F`) also ends the CLI process, ssh.exe and the proxy. Before, only the launcher died and they kept running. Verified with the venv python.exe launcher: after `taskkill /F` on it, neither its child nor the child's process was left.
Expand Down
2 changes: 1 addition & 1 deletion examples/finetune_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@

import os

# Keep training-library imports after the runtime dependency installation.
os.system("pip install -q -U 'bitsandbytes>=0.46.1'")

# These imports must follow the pip install above (runtime dependency).
import torch # noqa: E402
from datasets import load_dataset # noqa: E402
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig # noqa: E402
Expand Down
1 change: 0 additions & 1 deletion src/colab_cli/commands/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,4 +521,3 @@ def register(app: typer.Typer):
app.command(name="restart-kernel")(restart_kernel)
app.command()(status)
app.command()(stop)

40 changes: 38 additions & 2 deletions src/colab_cli/commands/ssh.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,13 +697,15 @@ def _explain_handshake_failure(status: Optional[int], body: bytes) -> str:
message = (
f"SSH session limit reached (HTTP 429): {limit} of {limit} "
"SSH sessions in use on this runtime. Close another "
"`colab ssh` or IDE connection to it and retry. The limit "
"`colab ssh` or IDE connection to it and retry. If the "
"previous client died, retry with `--force`. The limit "
"depends on your Colab plan."
)
case 429:
message = (
"Already-active SSH session (HTTP 429): another `colab ssh` "
"is connected to this runtime. Disconnect it and retry."
"is connected to this runtime. Disconnect it and retry. "
"If the previous client died, retry with `--force`."
)
case 502:
message = (
Expand Down Expand Up @@ -775,6 +777,23 @@ def _close_quietly(ws: websocket.WebSocket) -> None:
pass


def _killStaleSshd(session: SessionState) -> None:
"""Kills existing SSH sessions on the runtime via the kernel."""
from colab_cli.runtime import ColabRuntime

typer.echo("[colab] --force: killing stale SSH sessions...", err=True)
rt = ColabRuntime(session.url, session.token, kernel_id=session.kernel_id)
try:
rt.execute_code(
"import os; os.system('pkill -P $(pgrep -o -x sshd)')",
timeout=10.0,
)
except Exception as e:
typer.echo(f"[colab] --force: failed to kill sshd: {e}", err=True)
finally:
rt.stop()


_DATA_OPCODES = (websocket.ABNF.OPCODE_BINARY, websocket.ABNF.OPCODE_TEXT)


Expand Down Expand Up @@ -1290,6 +1309,17 @@ def ssh(
help="With -L: do not ping keep-alive; the runtime may idle out.",
),
] = False,
force: Annotated[
bool,
typer.Option(
"--force",
help=(
"Kill all existing SSH sessions on the runtime before "
"connecting. Use when a dead client causes HTTP 429 on "
"reconnect."
),
),
] = False,
ssh_mode: Annotated[
str, typer.Option("--colab-internal-mode", hidden=True)
] = _DEFAULT_SSH_MODE,
Expand Down Expand Up @@ -1332,6 +1362,8 @@ def ssh(
cmd = undo_msys_args(cmd)
with contextlib.redirect_stdout(sys.stderr):
s = _resolve_session(session)
if force:
_killStaleSshd(s)
_warn_accelerator_ignored(gpu, tpu, False, high_mem=high_mem)
if rm:
typer.echo("[colab] --rm ignored with -- CMD.", err=True)
Expand All @@ -1344,10 +1376,14 @@ def ssh(
raise typer.Exit(code=_run_proxy_bridge(s, identity, rm, ssh_mode))
if proxy_mode:
s, created = _select_proxy_session(session, gpu, tpu, high_mem=high_mem)
if force:
_killStaleSshd(s)
_warn_accelerator_ignored(gpu, tpu, created, high_mem=high_mem)
raise typer.Exit(code=_run_proxy_bridge(s, identity, rm, ssh_mode))

s, created = _select_interactive_session(session, gpu, tpu, high_mem=high_mem)
if force:
_killStaleSshd(s)
_warn_accelerator_ignored(gpu, tpu, created, high_mem=high_mem)
if no_shell:
raise typer.Exit(code=_run_forward_only(s, identity, forwards, keep_alive))
Expand Down
57 changes: 53 additions & 4 deletions tests/test_ssh.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,23 +299,27 @@ def test_explain_handshake_failure_mapping(status, body, must_contain):

_FALLBACK_429 = (
"Already-active SSH session (HTTP 429): another `colab ssh` is "
"connected to this runtime. Disconnect it and retry."
"connected to this runtime. Disconnect it and retry. "
"If the previous client died, retry with `--force`."
)
_LIMIT_BODY_PREFIX = b'{"error":"already-active-session","limit":'
_LIMIT_1_TEXT = (
"SSH session limit reached (HTTP 429): 1 of 1 SSH sessions in use on "
"this runtime. Close another `colab ssh` or IDE connection to it and "
"retry. The limit depends on your Colab plan."
"retry. If the previous client died, retry with `--force`. "
"The limit depends on your Colab plan."
)
_LIMIT_2_TEXT = (
"SSH session limit reached (HTTP 429): 2 of 2 SSH sessions in use on "
"this runtime. Close another `colab ssh` or IDE connection to it and "
"retry. The limit depends on your Colab plan."
"retry. If the previous client died, retry with `--force`. "
"The limit depends on your Colab plan."
)
_LIMIT_4_TEXT = (
"SSH session limit reached (HTTP 429): 4 of 4 SSH sessions in use on "
"this runtime. Close another `colab ssh` or IDE connection to it and "
"retry. The limit depends on your Colab plan."
"retry. If the previous client died, retry with `--force`. "
"The limit depends on your Colab plan."
)


Expand Down Expand Up @@ -739,3 +743,48 @@ def test_proxy_command_escapes_percent_for_openssh_tokens(mocker):

assert "a%%h" in cmd
assert "a%h" not in cmd.replace("a%%h", "")


# --- --force flag -----------------------------------------------------------


@pytest.mark.parametrize(
("argv", "kills"),
[
(["--force"], 1),
(["--proxy-mode", "--force"], 1),
(["--force", "--", "true"], 1),
([], 0),
],
ids=["interactive", "proxy-mode", "cmd", "no-force"],
)
def test_force_kills_stale_sshd(mock_common_state, mocker, argv, kills):
"""--force calls _killStaleSshd; without it, the helper is skipped."""
sess = _make_session()
mock_common_state.resolve_session.return_value = "s1"
mock_common_state.store.get.return_value = sess
mock_common_state.store.list.return_value = [sess]

killSshd = mocker.patch.object(ssh_module, "_killStaleSshd")
mocker.patch.object(ssh_module, "_run_interactive_ssh", return_value=0)
mocker.patch.object(ssh_module, "_run_proxy_bridge", return_value=0)
mocker.patch.object(ssh_module, "_run_remote_command", return_value=0)

result = runner.invoke(app, ["ssh", "-s", "s1", *argv])
assert result.exit_code == 0
assert killSshd.call_count == kills


def test_kill_stale_sshd_body(mock_common_state, mocker):
"""_killStaleSshd passes kernel_id and calls rt.stop()."""
sess = _make_session()
sess.kernel_id = "k123"
mockRt = MagicMock()
mockRt.execute_code.return_value = []
rtCls = mocker.patch("colab_cli.runtime.ColabRuntime", return_value=mockRt)

ssh_module._killStaleSshd(sess)

rtCls.assert_called_once_with(sess.url, sess.token, kernel_id="k123")
mockRt.execute_code.assert_called_once()
mockRt.stop.assert_called_once()
Loading