From ea6bd4e541b451a04b053666594ceeca540112e3 Mon Sep 17 00:00:00 2001 From: Seth Troisi Date: Mon, 23 Nov 2026 18:42:14 -0800 Subject: [PATCH 1/3] fix(exec): exit 1 when remote code produces an error output Raise typer.Exit(1) in exec_command when any kernel output has output_type == 'error' (after saving notebook cell outputs and logging execution history). For multi-cell .ipynb notebooks, execution stops at the failing cell while still writing *_output.ipynb. Refs https://github.com/googlecolab/google-colab-cli/discussions/250 --- docs/02_execution_and_interactive.md | 4 +++ src/colab_cli/commands/execution.py | 2 ++ tests/test_exec.py | 41 ++++++++++++++++++++++++- tests/test_ipynb_exec.py | 46 ++++++++++++++++++++++++++++ 4 files changed, 92 insertions(+), 1 deletion(-) diff --git a/docs/02_execution_and_interactive.md b/docs/02_execution_and_interactive.md index f8bbb18f..50309f19 100644 --- a/docs/02_execution_and_interactive.md +++ b/docs/02_execution_and_interactive.md @@ -1,5 +1,7 @@ --- log: +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. @@ -33,6 +35,7 @@ Execution involves sending Python code (or shell commands) to the Jupyter kernel - If file path is remote: Execute `!python `. - **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 Exit Status**: Exits with status 1 if any executed code block returns an `output_type == "error"` output from the kernel (stopping remaining cells when executing a `.ipynb` notebook while still writing `*_output.ipynb`). ## Implementation Details - **Kernel Management**: `ColabRuntime` (from `colab-agent`) already handles message signing and message types. @@ -46,6 +49,7 @@ 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`. ### 2. TTY and Piping - **Test Case**: Mock `sys.stdin.isatty()` to verify `colab repl` correctly switches between interactive mode and one-shot piped execution. diff --git a/src/colab_cli/commands/execution.py b/src/colab_cli/commands/execution.py index a21d2063..20e62607 100644 --- a/src/colab_cli/commands/execution.py +++ b/src/colab_cli/commands/execution.py @@ -280,6 +280,8 @@ def on_sess_started(sid): "cell_id": block.get("id"), }, ) + if any(o.get("output_type") == "error" for o in outputs): + raise typer.Exit(1) finally: s.running = None state.store.add(s) diff --git a/tests/test_exec.py b/tests/test_exec.py index bd0d6477..b9122955 100644 --- a/tests/test_exec.py +++ b/tests/test_exec.py @@ -253,7 +253,7 @@ def mock_execute_code(code, output_hook=None, **kwargs): mock_runtime.execute_code.side_effect = mock_execute_code result = runner.invoke(app, ["exec", "-s", "s1"], input="do_stuff()") - assert result.exit_code == 0 + assert result.exit_code == 1 mock_handle_image.assert_any_call("png_data", "image/png", target_path=None) mock_handle_image.assert_any_call("jpeg_data", "image/jpeg", target_path=None) @@ -262,6 +262,45 @@ def mock_execute_code(code, output_hook=None, **kwargs): assert "line1\nline2\n" in result.stderr +def test_cli_exec_file_error_exits_nonzero( + mock_store, mock_runtime_class, mock_common_state, tmp_path +): + mock_session = MagicMock() + mock_session.name = "s1" + mock_session.url = "http://url" + mock_session.token = "token" + mock_session.kernel_id = None + mock_session.session_id = None + mock_store.get.return_value = mock_session + mock_common_state.resolve_session.return_value = "s1" + + def mock_execute_code(code, output_hook=None, **kwargs): + if output_hook is None: + return [] + err = { + "output_type": "error", + "ename": "ValueError", + "evalue": "boom", + "traceback": ["Traceback (most recent call last):\n", "ValueError: boom"], + } + output_hook(err) + return [err] + + mock_runtime = mock_runtime_class.return_value + mock_runtime.execute_code.side_effect = mock_execute_code + + script = tmp_path / "raise.py" + script.write_text('raise ValueError("boom")\n') + + result = runner.invoke(app, ["exec", "-s", "s1", "-f", str(script)]) + + assert result.exit_code == 1 + assert "ValueError: boom" in result.stderr + assert mock_session.running is None + mock_common_state.history.log_event.assert_called_once() + mock_runtime.stop.assert_called_once() + + def test_cli_exec_empty_code(mock_runtime_class, mock_store, mock_common_state): mock_session = MagicMock() mock_session.name = "s1" diff --git a/tests/test_ipynb_exec.py b/tests/test_ipynb_exec.py index b662098a..ff95a82c 100644 --- a/tests/test_ipynb_exec.py +++ b/tests/test_ipynb_exec.py @@ -211,6 +211,52 @@ def test_exec_ipynb_creates_output_file( self.assertEqual(len(output_nb.cells[2].outputs), 1) self.assertEqual(output_nb.cells[2].outputs[0].text, "cell 2\n") + @patch("colab_cli.commands.execution.ColabRuntime") + @patch("colab_cli.state.StateStore") + @patch("colab_cli.commands.execution.typer.echo") + def test_exec_ipynb_cell_error_stops_and_exits_nonzero( + self, + mock_echo, + mock_store_class, + mock_runtime_class, + ): + with patch.object( + sys, "argv", ["colab", "exec", "-s", "test-s", "-f", self.nb_path] + ): + mock_store = mock_store_class.return_value + mock_store.get.return_value = MagicMock( + name="test-s", url="http://url", token="token" + ) + + mock_runtime = mock_runtime_class.return_value + mock_runtime.execute_code.side_effect = [ + [], + [ + { + "output_type": "error", + "ename": "RuntimeError", + "evalue": "cell 1 failed", + "traceback": ["RuntimeError: cell 1 failed"], + } + ], + [{"output_type": "stream", "name": "stdout", "text": "cell 2\n"}], + ] + + with patch("builtins.print"), pytest.raises(SystemExit) as error: + main() + + assert error.value.code == 1 + self.assertEqual(mock_runtime.execute_code.call_count, 2) + + output_nb_path = self.nb_path.replace(".ipynb", "_output.ipynb") + self.assertTrue(os.path.exists(output_nb_path)) + with open(output_nb_path, "r", encoding="utf-8") as f: + output_nb = nbformat.read(f, as_version=4) + + self.assertEqual(len(output_nb.cells[0].outputs), 1) + self.assertEqual(output_nb.cells[0].outputs[0].output_type, "error") + self.assertEqual(len(output_nb.cells[2].outputs), 0) + if __name__ == "__main__": unittest.main() From a255d6333168b2e7d94d87deb5674e00fa236cb0 Mon Sep 17 00:00:00 2001 From: Seth Troisi Date: Mon, 23 Nov 2026 18:54:16 -0800 Subject: [PATCH 2/3] docs(skill): document colab exec error exit status in SKILL.md --- skills/colab-operator/SKILL.md | 1 + 1 file changed, 1 insertion(+) diff --git a/skills/colab-operator/SKILL.md b/skills/colab-operator/SKILL.md index a9e8e67d..6c55cc6b 100644 --- a/skills/colab-operator/SKILL.md +++ b/skills/colab-operator/SKILL.md @@ -49,6 +49,7 @@ by running `uv tool install google-colab-cli` or `pip install google-colab-cli`. - **Preferred**: `colab exec -s -f ` 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 ` or `cat script.py | colab exec -s `. - **Notebooks**: `colab exec -s -f nb.ipynb` runs each code cell and writes results to `_output.ipynb` next to the input. A `# @title Foo` first line labels the cell in progress output. +- **Exit status**: `colab exec` exits `1` when the kernel emits an error output (uncaught Python exception, syntax error, or `SystemExit`); for `.ipynb` notebooks it stops at the failing cell and still writes `_output.ipynb`. IPython `!cmd` shell escapes do **not** emit a kernel error on a non-zero shell exit — use `colab ssh -s -- ` or `subprocess.run(..., check=True)` when shell exit status matters. - **Plots/images**: PNG/JPEG outputs are intercepted. Use `--output-image ` 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 -- `: 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 ` -- '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 -- ls -- "$f"`), never inside a shell line or a piped script. Pipe a multi-line script to `colab ssh -s -- 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 ` (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 `. - **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. From 6d154cd3744c85b5992233dd498d02bb284d561a Mon Sep 17 00:00:00 2001 From: Seth Troisi Date: Mon, 23 Nov 2026 19:00:12 -0800 Subject: [PATCH 3/3] feat(exec): share CPython SystemExit semantics with colab run Because a persistent IPython kernel catches SystemExit and emits it as output_type == 'error' (with REPL traceback/warning noise) so the kernel stays alive, treating every kernel error output as exit 1 broke scripts calling sys.exit(0) (e.g. argparse --help, unittest.main()) and collapsed sys.exit(N) into 1. Move _exit_code_from_outputs and _make_script_output_hook into commands/execution.py for both colab exec and colab run, mute IPython's 'To exit: use ...' warning during exec setup, write non-integer sys.exit('msg') messages cleanly to stderr, and document why. --- docs/02_execution_and_interactive.md | 7 +- docs/05_run_command.md | 1 + skills/colab-operator/SKILL.md | 2 +- src/colab_cli/commands/execution.py | 82 ++++++++++++++++++++-- src/colab_cli/commands/run.py | 74 ++------------------ tests/test_exec.py | 101 ++++++++++++++++++++++++++- tests/test_run.py | 2 + 7 files changed, 193 insertions(+), 76 deletions(-) diff --git a/docs/02_execution_and_interactive.md b/docs/02_execution_and_interactive.md index 50309f19..11f6e984 100644 --- a/docs/02_execution_and_interactive.md +++ b/docs/02_execution_and_interactive.md @@ -1,5 +1,7 @@ --- 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. @@ -35,7 +37,9 @@ Execution involves sending Python code (or shell commands) to the Jupyter kernel - If file path is remote: Execute `!python `. - **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 Exit Status**: Exits with status 1 if any executed code block returns an `output_type == "error"` output from the kernel (stopping remaining cells when executing a `.ipynb` notebook while still writing `*_output.ipynb`). +- **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. @@ -50,6 +54,7 @@ TDD is mandatory for all execution features. - **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. diff --git a/docs/05_run_command.md b/docs/05_run_command.md index f8414616..0c77ce82 100644 --- a/docs/05_run_command.md +++ b/docs/05_run_command.md @@ -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 [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__"`. diff --git a/skills/colab-operator/SKILL.md b/skills/colab-operator/SKILL.md index 6c55cc6b..1c8570d1 100644 --- a/skills/colab-operator/SKILL.md +++ b/skills/colab-operator/SKILL.md @@ -49,7 +49,7 @@ by running `uv tool install google-colab-cli` or `pip install google-colab-cli`. - **Preferred**: `colab exec -s -f ` 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 ` or `cat script.py | colab exec -s `. - **Notebooks**: `colab exec -s -f nb.ipynb` runs each code cell and writes results to `_output.ipynb` next to the input. A `# @title Foo` first line labels the cell in progress output. -- **Exit status**: `colab exec` exits `1` when the kernel emits an error output (uncaught Python exception, syntax error, or `SystemExit`); for `.ipynb` notebooks it stops at the failing cell and still writes `_output.ipynb`. IPython `!cmd` shell escapes do **not** emit a kernel error on a non-zero shell exit — use `colab ssh -s -- ` or `subprocess.run(..., check=True)` when shell exit status matters. +- **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 `_output.ipynb`. IPython `!cmd` shell escapes do **not** emit a kernel error on a non-zero shell exit — use `colab ssh -s -- ` or `subprocess.run(..., check=True)` when shell exit status matters. - **Plots/images**: PNG/JPEG outputs are intercepted. Use `--output-image ` 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 -- `: 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 ` -- '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 -- ls -- "$f"`), never inside a shell line or a piped script. Pipe a multi-line script to `colab ssh -s -- 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 ` (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 `. - **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. diff --git a/src/colab_cli/commands/execution.py b/src/colab_cli/commands/execution.py index 20e62607..30255096 100644 --- a/src/colab_cli/commands/execution.py +++ b/src/colab_cli/commands/execution.py @@ -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()` -> + - `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") @@ -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): @@ -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: @@ -280,8 +350,9 @@ def on_sess_started(sid): "cell_id": block.get("id"), }, ) - if any(o.get("output_type") == "error" for o in outputs): - raise typer.Exit(1) + 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) @@ -324,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')" ) diff --git a/src/colab_cli/commands/run.py b/src/colab_cli/commands/run.py index 6dc92b21..ae3695c8 100644 --- a/src/colab_cli/commands/run.py +++ b/src/colab_cli/commands/run.py @@ -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, @@ -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()` -> - - `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[ @@ -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 diff --git a/tests/test_exec.py b/tests/test_exec.py index b9122955..48d83c15 100644 --- a/tests/test_exec.py +++ b/tests/test_exec.py @@ -56,7 +56,9 @@ def test_cli_exec_file(mock_store, mock_runtime_class, mock_common_state, tmp_pa assert mock_session.last_execution[2] is not None mock_store.add.assert_called_with(mock_session) mock_runtime.execute_code.assert_any_call( - "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')" ) mock_runtime.execute_code.assert_any_call( "print('hello')", output_hook=ANY, timeout=30.0 @@ -301,6 +303,103 @@ def mock_execute_code(code, output_hook=None, **kwargs): mock_runtime.stop.assert_called_once() +def _systemexit_output(evalue: str) -> dict: + return { + "output_type": "error", + "ename": "SystemExit", + "evalue": evalue, + "traceback": [ + "An exception has occurred, use %tb to see the full traceback.\n", + f"\x1b[0;31mSystemExit\x1b[0m\x1b[0;31m:\x1b[0m {evalue}\n", + ], + } + + +@pytest.mark.parametrize("evalue", ["", "None", "0"]) +def test_cli_exec_systemexit_zero_exits_zero_silently( + mock_store, mock_runtime_class, mock_common_state, evalue +): + mock_session = MagicMock() + mock_session.name = "s1" + mock_session.url = "http://url" + mock_session.token = "token" + mock_session.kernel_id = None + mock_session.session_id = None + mock_store.get.return_value = mock_session + mock_common_state.resolve_session.return_value = "s1" + + def mock_execute_code(code, output_hook=None, **kwargs): + if output_hook is None: + return [] + out = _systemexit_output(evalue) + output_hook(out) + return [out] + + mock_runtime_class.return_value.execute_code.side_effect = mock_execute_code + + result = runner.invoke(app, ["exec", "-s", "s1"], input="import sys; sys.exit(0)\n") + + assert result.exit_code == 0 + assert "An exception has occurred" not in result.output + result.stderr + + +def test_cli_exec_systemexit_nonzero_propagates_code( + mock_store, mock_runtime_class, mock_common_state +): + mock_session = MagicMock() + mock_session.name = "s1" + mock_session.url = "http://url" + mock_session.token = "token" + mock_session.kernel_id = None + mock_session.session_id = None + mock_store.get.return_value = mock_session + mock_common_state.resolve_session.return_value = "s1" + + def mock_execute_code(code, output_hook=None, **kwargs): + if output_hook is None: + return [] + out = _systemexit_output("7") + output_hook(out) + return [out] + + mock_runtime_class.return_value.execute_code.side_effect = mock_execute_code + + result = runner.invoke(app, ["exec", "-s", "s1"], input="import sys; sys.exit(7)\n") + + assert result.exit_code == 7 + assert "An exception has occurred" not in result.output + result.stderr + + +def test_cli_exec_systemexit_string_prints_message_and_exits_one( + mock_store, mock_runtime_class, mock_common_state +): + mock_session = MagicMock() + mock_session.name = "s1" + mock_session.url = "http://url" + mock_session.token = "token" + mock_session.kernel_id = None + mock_session.session_id = None + mock_store.get.return_value = mock_session + mock_common_state.resolve_session.return_value = "s1" + + def mock_execute_code(code, output_hook=None, **kwargs): + if output_hook is None: + return [] + out = _systemexit_output("fatal config error") + output_hook(out) + return [out] + + mock_runtime_class.return_value.execute_code.side_effect = mock_execute_code + + result = runner.invoke( + app, ["exec", "-s", "s1"], input="import sys; sys.exit('fatal config error')\n" + ) + + assert result.exit_code == 1 + assert "fatal config error\n" in result.stderr + assert "An exception has occurred" not in result.output + result.stderr + + def test_cli_exec_empty_code(mock_runtime_class, mock_store, mock_common_state): mock_session = MagicMock() mock_session.name = "s1" diff --git a/tests/test_run.py b/tests/test_run.py index 9834da37..be3322af 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -663,6 +663,8 @@ def execute_with_systemexit(code, output_hook=None, **kwargs): result = runner.invoke(app, ["run", str(script_path)]) assert result.exit_code == 1 + assert "boom\n" in result.stderr + assert "An exception has occurred" not in result.output + result.stderr mock_client.unassign.assert_called_once_with("ep-123")