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/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. 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()