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
9 changes: 9 additions & 0 deletions docs/02_execution_and_interactive.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
---
log:
2026-11-23: Shared `colab run`'s CPython `SystemExit` handling (`_exit_code_from_outputs`, `_make_script_output_hook`) with `colab exec` and muted IPython's `"To exit: use ..."` warning during `exec` setup. Because a persistent IPython kernel catches `SystemExit` and emits it as `output_type == "error"` to avoid killing the kernel process, treating every kernel error output as exit 1 wrongly failed scripts that call `sys.exit(0)` (e.g. `argparse --help`, `unittest.main()`) and collapsed `sys.exit(N)` codes into 1.

2026-11-23: `colab exec` now exits 1 when executed code produces a kernel `error` output (after recording history and saving `*_output.ipynb` for notebooks, stopping further notebook cells) (#250).

2026-05-07: Fixed `colab console` piped-stdin handling. Previously a piped invocation (e.g. `echo 'cmd' | colab console -s s`) sent the command and then hung indefinitely because the previous EOF handler emitted a bare `\x04` (Ctrl-D), which the remote `tmux`-wrapped bash treats as a literal character rather than a session terminator. The new handler sends `exit\n` (which bash actually exits on) and then closes the websocket from the client side after a short grace period (`PIPED_EOF_GRACE_SECONDS = 0.5s`) so any tail output (bash `logout`, tmux `[exited]`) makes it back to the user. TTY mode is unchanged: real-terminal EOF is left to the remote shell. Verified live: `echo 'echo HELLO' | colab console -s s` now exits in ~1.2s instead of hanging.

2026-05-07: Fixed `print_kitty` (used by `colab exec --output-image` and any image-producing exec) to no-op when `sys.stdout.isatty()` is false. The Kitty Graphics Protocol escape sequence is meaningless when stdout is a file or pipe and was visually corrupting captured output (a multi-KB base64 PNG blob would land in log files, grep targets, or showboat captures). Image bytes are still saved to disk via `handle_image`'s file-write path; only the inline-render attempt is suppressed.
Expand Down Expand Up @@ -33,6 +37,9 @@ Execution involves sending Python code (or shell commands) to the Jupyter kernel
- If file path is remote: Execute `!python <path>`.
- **Multi-Modal Output**: Handle `display_data` messages (e.g., `image/png`, `text/html`). For the CLI, we'll save images to temporary files and print their paths, or if the terminal supports it (e.g., iTerm2), inline them.
- **Timeout Configuration**: Exposes a `--timeout` flag (default 30s): the longest silence allowed before execution fails. Raise it so long-running silent tasks (like model compilation or data downloading) are not prematurely killed; `0` means no limit.
- **Error & `SystemExit` Semantics**:
- Any uncaught exception (`ValueError`, `SyntaxError`, etc.) causes `colab exec` to exit with status `1` (stopping remaining cells in a `.ipynb` notebook while still writing `*_output.ipynb`).
- **Why `SystemExit` is handled specially**: Unlike CPython—where `sys.exit(...)` terminates the process directly—an IPython/Jupyter kernel must stay alive across executions, so it catches `SystemExit` and reports it as `output_type == "error"` (`ename == "SystemExit"`), accompanied by an interactive `"An exception has occurred, use %tb..."` banner and `"To exit: use 'exit', 'quit', or Ctrl-D."` `UserWarning`. Treating `SystemExit` like an uncaught exception breaks well-formed scripts passed to `colab exec -f script.py` (such as `argparse --help`, `unittest.main()`, or early-exit guards calling `sys.exit(0)`) and loses custom integer exit codes (`sys.exit(N)`). `colab exec` therefore shares `colab run`'s CPython mapping: `sys.exit()` / `sys.exit(None)` / `sys.exit(0)` exit `0` silently, `sys.exit(N)` exits `N` silently, and `sys.exit("msg")` prints `msg` to `stderr` and exits `1`.

## Implementation Details
- **Kernel Management**: `ColabRuntime` (from `colab-agent`) already handles message signing and message types.
Expand All @@ -46,6 +53,8 @@ TDD is mandatory for all execution features.
- **Test Case**: Verify `ColabRuntime` correctly sends an `execute_request` message over the websocket.
- **Test Case**: Verify `iopub.stream` messages are correctly handled and printed to `stdout` in real-time.
- **Test Case**: Verify `display_data` (specifically `image/png`) triggers the correct local handling (saving or display).
- **Test Case**: Verify `colab exec` exits with status 1 when the kernel emits an `error` output, and halts multi-cell `.ipynb` execution at the failing cell while still saving `*_output.ipynb`.
- **Test Case**: Verify `colab exec` applies CPython `SystemExit` semantics (`sys.exit(0)`/`None` → `0` silently, `sys.exit(N)` → `N`, `sys.exit("msg")` → prints `msg` to `stderr` and exits `1`) without IPython `%tb` or exit-warning noise.

### 2. TTY and Piping
- **Test Case**: Mock `sys.stdin.isatty()` to verify `colab repl` correctly switches between interactive mode and one-shot piped execution.
Expand Down
1 change: 1 addition & 0 deletions docs/05_run_command.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
log:
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-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
1 change: 1 addition & 0 deletions skills/colab-operator/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ by running `uv tool install google-colab-cli` or `pip install google-colab-cli`.
- **Preferred**: `colab exec -s <name> -f <script.py>` runs a local script on the remote VM (read locally, sent to the kernel — no manual upload needed).
- **Piped code**: `echo "print(1)" | colab exec -s <name>` or `cat script.py | colab exec -s <name>`.
- **Notebooks**: `colab exec -s <name> -f nb.ipynb` runs each code cell and writes results to `<basename>_output.ipynb` next to the input. A `# @title Foo` first line labels the cell in progress output.
- **Exit status**: `colab exec` propagates exit codes with CPython semantics, matching `colab run`: uncaught exceptions exit `1`, `sys.exit()`/`sys.exit(0)` exit `0` silently, `sys.exit(N)` exits `N`, and `sys.exit("msg")` prints `msg` to `stderr` and exits `1` (the persistent IPython kernel reports `SystemExit` as an error message to stay alive, so the CLI translates it back rather than failing `sys.exit(0)` scripts like `argparse`/`unittest`). For `.ipynb` notebooks, execution stops at the first non-zero cell and still writes `<basename>_output.ipynb`. IPython `!cmd` shell escapes do **not** emit a kernel error on a non-zero shell exit — use `colab ssh -s <name> -- <cmd>` or `subprocess.run(..., check=True)` when shell exit status matters.
- **Plots/images**: PNG/JPEG outputs are intercepted. Use `--output-image <path>` on `exec`/`repl` to save to a known location (otherwise a temp path is printed). Inline terminal-image escapes are auto-suppressed when stdout isn't a TTY, so piped/captured output stays clean.
- **Shell**: run a one-shot shell command with `colab ssh -s <name> -- <cmd>`: it runs in `/content` and exits with the command's status. Output is byte-exact when stdout is piped or redirected; ssh allocates a PTY only when stdin and stdout are both terminals, so a shell tool that runs commands in a terminal should add `</dev/null` and redirect the output to a file (a pipe keeps `colab ssh`'s exit status only under `set -o pipefail`). One argument is a shell command line (quote it for pipes or globs: `colab ssh -s <name> -- 'nvidia-smi | head -5'`); several arguments are an exact argv, so pass untrusted values as separate arguments after `--` where the program accepts it (e.g. `colab ssh -s <name> -- ls -- "$f"`), never inside a shell line or a piped script. Pipe a multi-line script to `colab ssh -s <name> -- bash`. Use `colab exec` for Python code. When ssh can't work (no local `ssh` client, no `~/.ssh/id_ed25519` or `id_ecdsa` key and no `-i KEY`, a tool not on the minimal ssh environment's `PATH` such as `gcloud` or `node`, or the runtime's limited concurrent SSH connections in use, which the server answers with 429, e.g. while a person or an IDE is connected), fall back to `exec` with IPython's `!` prefix: `echo '!df -h /content' | colab exec -s <name>` (single quotes stop your local shell expanding `!`). Each `!` line runs in its own shell with no input (a command that prompts hangs), and IPython evaluates `{expr}` as Python even inside quotes and expands `$name` outside single quotes. Start a multi-line script with a `%%bash` line (not with `--env`, which prepends Python lines), use non-interactive flags such as `apt-get -y`, and never put untrusted text in a `%%bash` script or a `!` line (even via `{var}` or `$var`): pass it with `--env NAME=VALUE` and run `subprocess.run(["cmd", "--", os.environ["NAME"]])` from Python. For an interactive shell on the VM, a human runs `colab ssh -s <name>`.
- **Never run `colab repl`, `colab ssh` without `-- CMD`, `colab auth`, or `colab drivemount` interactively from an agent** — `repl`, `auth` and `drivemount` expect a TTY and will hang or fail, and bare `colab ssh` with no saved session creates a billable runtime; an interactive shell is for a human. `repl` accepts piped stdin and exits on EOF; `auth`/`drivemount` genuinely require a human at the terminal.
Expand Down
80 changes: 76 additions & 4 deletions src/colab_cli/commands/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,75 @@ def display_output(out, output_image=None):
pass


def _is_systemexit(out: dict) -> bool:
"""True iff this kernel output represents `raise SystemExit(...)` / `sys.exit(...)`."""
return out.get("output_type") == "error" and out.get("ename") == "SystemExit"


def _systemexit_code(out: dict) -> int:
"""Map an IPython SystemExit error output to CPython's integer exit status.

Because a Colab Jupyter kernel must stay alive across executions, IPython
catches `SystemExit` and reports it as `output_type == "error"`
(`ename == "SystemExit"`) instead of terminating the kernel process.
Treating it like an uncaught exception would turn `sys.exit(0)` (e.g.
`argparse --help`, `unittest.main()`) into exit 1 and collapse `sys.exit(N)`
into 1. Mirror CPython instead:
- `sys.exit()` / `sys.exit(None)` / `sys.exit(0)` -> 0
- `sys.exit(<int>)` -> <int>
- `sys.exit('msg')` (any non-int) -> 1
"""
evalue = (out.get("evalue") or "").strip()
if evalue in ("", "None", "0"):
return 0
try:
return int(evalue)
except ValueError:
return 1


def _exit_code_from_outputs(outputs: list[dict]) -> int:
"""Derive the CLI exit code from a cell's kernel outputs.

`SystemExit` follows CPython exit-code semantics (see `_systemexit_code`);
any other `output_type == "error"` (uncaught exception, SyntaxError) is 1.
"""
code = 0
for out in outputs:
if out.get("output_type") != "error":
continue
if _is_systemexit(out):
ec = _systemexit_code(out)
code = ec if ec != 0 else code
else:
return 1
return code


def _make_script_output_hook(output_image: Optional[str] = None):
"""Build an `output_hook` that renders outputs while giving `SystemExit` CPython UX.

IPython renders `SystemExit` with `"An exception has occurred, use %tb to
see the full traceback."` even for `sys.exit(0)`. Suppress that banner for
empty/None/integer exit codes (silent in CPython), and for a non-integer
message like `sys.exit("boom")` write only the message to stderr.
"""

def hook(out):
if _is_systemexit(out):
evalue = (out.get("evalue") or "").strip()
if evalue not in ("", "None"):
try:
int(evalue)
except ValueError:
sys.stderr.write(f"{evalue}\n")
sys.stderr.flush()
return
display_output(out, output_image)

return hook


def exec_command(
session: Annotated[
Optional[str], typer.Option("-s", "--session", help="Session name")
Expand Down Expand Up @@ -221,9 +290,10 @@ def on_sess_started(sid):
on_session_started=on_sess_started,
)
try:
# Ensure we are in /content which is the standard Colab working directory
runtime.execute_code(
"import os; os.makedirs('/content', exist_ok=True); os.chdir('/content')"
"import os, warnings; "
"warnings.filterwarnings('ignore', message='To exit: use'); "
"os.makedirs('/content', exist_ok=True); os.chdir('/content')"
)
except Exception as e:
if is_terminal_error(e):
Expand Down Expand Up @@ -265,7 +335,7 @@ def on_sess_started(sid):

outputs = runtime.execute_code(
code,
output_hook=lambda o: display_output(o, output_image),
output_hook=_make_script_output_hook(output_image),
timeout=timeout,
)
if "cell" in block:
Expand All @@ -280,6 +350,9 @@ def on_sess_started(sid):
"cell_id": block.get("id"),
},
)
cell_exit_code = _exit_code_from_outputs(outputs)
if cell_exit_code != 0:
raise typer.Exit(cell_exit_code)
finally:
s.running = None
state.store.add(s)
Expand Down Expand Up @@ -322,7 +395,6 @@ def on_sess_started(sid):
on_session_started=on_sess_started,
)
try:
# Ensure we are in /content which is the standard Colab working directory
runtime.execute_code(
"import os; os.makedirs('/content', exist_ok=True); os.chdir('/content')"
)
Expand Down
74 changes: 7 additions & 67 deletions src/colab_cli/commands/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,12 @@
Shape,
TooManyAssignmentsError,
)
from colab_cli.commands.execution import _build_env_prelude, _parse_env_vars
from colab_cli.commands.execution import (
_build_env_prelude,
_exit_code_from_outputs,
_make_script_output_hook,
_parse_env_vars,
)
from colab_cli.commands.session import (
GPU_ACCELERATORS,
TPU_ACCELERATORS,
Expand Down Expand Up @@ -134,71 +139,6 @@ def _strip_shebang(body: str) -> str:
return body


def _is_systemexit(out) -> bool:
"""True iff this output is a `raise SystemExit(...)` (a.k.a. `sys.exit`)."""
return out.get("output_type") == "error" and out.get("ename") == "SystemExit"


def _systemexit_code(out) -> int:
"""Map a SystemExit kernel output back to a CPython-style integer exit code.

CPython conventions (mirrored):
- `sys.exit()` / `sys.exit(None)` / `sys.exit(0)` -> 0
- `sys.exit(<int>)` -> <int>
- `sys.exit('msg')` (any non-int) -> 1
"""
evalue = (out.get("evalue") or "").strip()
if evalue in ("", "None", "0"):
return 0
try:
return int(evalue)
except ValueError:
return 1


def _exit_code_from_outputs(outputs) -> int:
"""Derive the CLI's exit code from the kernel's outputs for a single cell.

A `SystemExit` is treated like CPython would treat the same call from a
plain `python script.py` invocation. Any *other* error (uncaught
exception, NameError, etc.) is exit 1.
"""
code = 0
for o in outputs:
if o.get("output_type") != "error":
continue
if _is_systemexit(o):
ec = _systemexit_code(o)
# Last SystemExit wins, matching the runtime — and any non-zero
# eclipses any prior zero.
code = ec if ec != 0 else code
else:
return 1
return code


def _make_run_output_hook(output_image=None):
"""Build an `output_hook` for `runtime.execute_code` that:
- Routes normal output to `display_output` (stream/image/error).
- Suppresses the `SystemExit` traceback so `sys.exit(0)` is silent (it
wouldn't print anything under `python script.py` either) and
`sys.exit(N)` doesn't dump a noisy IPython-styled traceback when the
intent is "shell exit code N".

The kernel still RETURNS the SystemExit output to us (so we can derive the
exit code in `_exit_code_from_outputs`); we just don't render it.
"""
# Imported here to avoid a circular import via execution.py at module load.
from colab_cli.commands.execution import display_output

def hook(out):
if _is_systemexit(out):
return
display_output(out, output_image)

return hook


def run_command(
ctx: typer.Context,
script: Annotated[
Expand Down Expand Up @@ -436,7 +376,7 @@ def on_sess_started(sid):

try:
outputs = runtime.execute_code(
payload, output_hook=_make_run_output_hook(), timeout=timeout
payload, output_hook=_make_script_output_hook(), timeout=timeout
)
except Exception:
# Genuine transport-level failure. Cleanup still happens via the
Expand Down
Loading