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
16 changes: 14 additions & 2 deletions docs/03_file_management.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
---
log:
2026-11-23: `colab upload` sends a file that does not fit in one request (about 75 MiB) in 64 MiB chunks with the Jupyter Contents API chunked protocol. Colab runtimes reject request bodies over 100 MiB with HTTP 400, so such uploads used to fail. This replaces the planned kernel-streaming fallback.
---

# Design: File Management (`ls`, `rm`, `upload`, `download`, `edit`)

## Overview
Expand Down Expand Up @@ -45,7 +50,12 @@ File management on the Colab VM will be implemented using the Jupyter Contents A
- **Base URL**: The backend URL obtained during session assignment.
- **Proxy Token**: The `colab-runtime-proxy-token` is required for each request.
- **Error Handling**: Handle 404 (not found) and 403 (unauthorized).
- **Large Files**: The Contents API might have limitations for very large files. If so, we'll implement a fallback via the kernel (streaming chunks).
- **Large Files**: Colab runtimes reject request bodies over 100 MiB with HTTP 400, and uploads are base64-encoded inside JSON (4/3 of the file size). `fits_in_one_request` computes the exact JSON body size for the path. A file that fits (about 75 MiB, depending on the path length) is still sent in one `"chunk": 1` request, as before, so every upload that used to work behaves the same. A larger file is sent in chunks of `UPLOAD_CHUNK_SIZE` (64 MiB, about 85 MiB once encoded) with the Jupyter Contents API chunked protocol, the same one JupyterLab's file browser uses: chunk `1` replaces the file in one save, later chunks are appended, and `-1` marks the last chunk.
- A lone `-1` chunk would be appended to an existing file, so it is only ever sent after chunk `1`.
- If any chunk fails, the remote file may be partly written (even a failed chunk `1` may have been stored if only the response was lost). `IncompleteUploadError` says so, with how many chunks were sent and the cause (for `requests` errors only the type, HTTP status and reason, because their text includes the URL with the proxy token), and the upload has to be run again. A local read error after chunk `1` is reported the same way. If the runtime refuses chunk `1` (404 or another 4xx), nothing was written and that error is raised unchanged. An upload interrupted with Ctrl-C after chunk `1` also leaves a partial file. A single-request upload is never partial: it either replaces the file or leaves it as it was.
- A chunked upload can outlast the runtime proxy token. `colab upload` and `colab edit` pass `refresh_session` (`State.get_session`, which renews the token when it is close to expiry) to `ContentsClient`, which calls it before every chunk after the first. If that refresh fails (including a `sys.exit` from the credential code), the upload is reported as incomplete too.
- Chunks are written straight to `remote_path` rather than to a temporary file that is renamed at the end. The Contents API refuses to rename onto an existing path (HTTP 409), so a rename would need a delete first. If the connection drops between the two calls, the old file is deleted and the new data is left under the temporary name, and deleting and renaming replaces a symlinked destination with a regular file instead of writing through it.
- The stored size is not compared with the local size after the upload: the Contents API reports `os.lstat` sizes, so an upload through a symlinked destination would look incomplete.

## Testing Strategy
TDD is mandatory for all file management features.
Expand All @@ -59,4 +69,6 @@ TDD is mandatory for all file management features.

### 2. Error Cases
- **Test Case**: Verify 404 responses are correctly caught and presented as a "File not found" error to the user.
- **Test Case**: Verify correct handling of large file uploads exceeding API limits via kernel streaming.
- **Test Case**: Verify a file larger than one chunk is sent as chunks `1, 2, ..., -1`, with no empty trailing chunk, and a file that fits in one chunk as a single `"chunk": 1` request.
- **Test Case**: Verify a failed single-request upload raises the original error, and a failed chunk of a multi-chunk upload raises `IncompleteUploadError` without the proxy token in its message or exception chain.
- **Test Case**: Verify a failed `colab upload` names the error without the proxy token, and a failed token refresh during a chunked upload raises `IncompleteUploadError`.
1 change: 1 addition & 0 deletions integration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ End-to-end tests that run against a **live Colab backend** (unlike the mocked un
| `repro_bundled_oauth/` | Fast smoke test (~5s): verifies that the fallback OAuth configuration is loaded and starts the OAuth flow with the default client ID when local config is missing. |
| `repro_legacy_token_migration/` | Fast smoke test (~5s, no VM): a pre-keyring `~/.config/colab-cli/token.json` is migrated into the keyring and deleted, deleted when the keyring already has a token, and kept (with a stderr warning) when the keyring is inaccessible. Uses a throwaway HOME and file-backed test keyring. |
| `repro_ssh/` | Fast smoke test (~5s): `--help` advertises the flags and an unknown session exits. Slow soak test (~95s): Live e2e allocates a CPU VM, runs a real remote command over `colab ssh --proxy-mode` |
| `repro_large_upload/` | Slow soak test (a few minutes, depending on upload speed): allocates a CPU VM, uploads a 100 MiB file (too large for one Contents API request, so it goes in chunks) and checks its remote sha256, then replaces it with a 1 MiB upload to the same path and checks again. Stops only the session it created. |
| `repro_windows_ssh/` | Native Windows live CPU test: Windows OpenSSH launches the generated ProxyCommand, executes a remote marker command, and releases the recorded runtime. Requires cached OAuth2 credentials; exits 77 if prerequisites are missing. |


Expand Down
122 changes: 122 additions & 0 deletions integration/repro_large_upload/test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
#!/bin/bash
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Integration Test: `colab upload` of a file too large for one request
#
# Colab runtimes reject Contents API request bodies over 100 MiB, so files
# larger than about 75 MiB (base64 inside JSON) are uploaded in chunks.
# 1. A 100 MiB file uploads in chunks and its remote sha256 matches.
# 2. Uploading a 1 MiB file to the same path replaces it completely.
# 3. The session this test created is stopped (other sessions are left alone).

# Don't `set -e` so we can capture failures and clean up explicitly.

# ---------- Auth detection ----------------------------------------------------
has_oauth2_token() {
uv run python -c "import sys, keyring; sys.exit(0 if keyring.get_password('google-colab-cli', 'oauth_token') else 1)" > /dev/null 2>&1
}
if has_oauth2_token; then
AUTH_FLAGS="--auth=oauth2"
elif command -v gcloud > /dev/null && gcloud auth application-default print-access-token > /dev/null 2>&1; then
AUTH_FLAGS="--auth=adc"
else
echo "Error: No usable auth provider found."
exit 1
fi
echo "[*] Using $AUTH_FLAGS"

# ---------- Isolated session state -------------------------------------------
TMP_DIR=$(mktemp -d)
SESSION_FILE="$TMP_DIR/sessions.json"
SESSION_NAME="repro-large-upload-$(date +%s)"
REMOTE_PATH="/content/repro_large_upload.bin"
BIG_FILE="$TMP_DIR/big.bin"
SMALL_FILE="$TMP_DIR/small.bin"
VERIFY_SCRIPT="$TMP_DIR/verify.py"

colab_cmd() {
uv run colab $AUTH_FLAGS --config "$SESSION_FILE" "$@"
}

cleanup() {
echo "[*] Cleaning up..."
colab_cmd stop -s "$SESSION_NAME" 2>/dev/null || true
rm -rf "$TMP_DIR"
}
trap cleanup EXIT

sha256_of() {
uv run python -c "import hashlib, sys; print(hashlib.sha256(open(sys.argv[1], 'rb').read()).hexdigest())" "$1"
}

cat > "$VERIFY_SCRIPT" <<PYEOF
import hashlib, os
path = "$REMOTE_PATH"
with open(path, "rb") as f:
digest = hashlib.sha256(f.read()).hexdigest()
print(f"REMOTE size={os.path.getsize(path)} sha256={digest}")
PYEOF

expect_remote() {
local local_file="$1" label="$2"
local want_size want_sha out
want_size=$(wc -c < "$local_file" | tr -d ' ')
want_sha=$(sha256_of "$local_file")
out=$(colab_cmd exec -s "$SESSION_NAME" --timeout 120 -f "$VERIFY_SCRIPT" 2>&1)
echo "$out" | grep "REMOTE"
if ! echo "$out" | grep -q "REMOTE size=$want_size sha256=$want_sha"; then
echo "[FAILURE] $label: remote file does not match (want size=$want_size sha256=$want_sha)."
exit 1
fi
}

uv run python -c "import os, sys; open(sys.argv[1], 'wb').write(os.urandom(100 * 1024 * 1024))" "$BIG_FILE"
uv run python -c "import os, sys; open(sys.argv[1], 'wb').write(os.urandom(1024 * 1024))" "$SMALL_FILE"

echo "[*] Creating CPU session $SESSION_NAME"
if ! colab_cmd new -s "$SESSION_NAME"; then
echo "[FAILURE] colab new failed."
exit 1
fi

# ---------- Phase 1: chunked upload ------------------------------------------
echo "[*] Phase 1: colab upload of a 100 MiB file"
if ! colab_cmd upload -s "$SESSION_NAME" "$BIG_FILE" "$REMOTE_PATH"; then
echo "[FAILURE] Uploading the 100 MiB file failed."
exit 1
fi
expect_remote "$BIG_FILE" "Phase 1"
echo "[SUCCESS] Phase 1 passed: the 100 MiB file arrived intact."

# ---------- Phase 2: a small upload replaces the large file ------------------
echo "[*] Phase 2: colab upload of a 1 MiB file to the same path"
if ! colab_cmd upload -s "$SESSION_NAME" "$SMALL_FILE" "$REMOTE_PATH"; then
echo "[FAILURE] Uploading the 1 MiB file failed."
exit 1
fi
expect_remote "$SMALL_FILE" "Phase 2"
echo "[SUCCESS] Phase 2 passed: the small upload replaced the large file."

# ---------- Phase 3: no session left behind ----------------------------------
colab_cmd stop -s "$SESSION_NAME"
SESSIONS_OUT=$(colab_cmd sessions 2>&1)
echo "$SESSIONS_OUT"
if echo "$SESSIONS_OUT" | grep -q "\[$SESSION_NAME\]"; then
echo "[FAILURE] Session $SESSION_NAME is still active after colab stop."
exit 1
fi
echo "[SUCCESS] Phase 3 passed: the test session was stopped."
echo "[SUCCESS] All phases passed."
exit 0
8 changes: 4 additions & 4 deletions src/colab_cli/commands/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from typing import Optional
from typing_extensions import Annotated

from colab_cli.contents import ContentsClient
from colab_cli.contents import ContentsClient, describe_error


def ls(
Expand Down Expand Up @@ -88,7 +88,7 @@ def upload(
if not os.path.isfile(local_path):
typer.echo(f"[colab] Local file '{local_path}' not found.")
raise typer.Exit(1)
contents = ContentsClient(s)
contents = ContentsClient(s, refresh_session=lambda: state.get_session(name))
try:
contents.upload(local_path, remote_path)
state.history.log_event(
Expand All @@ -98,7 +98,7 @@ def upload(
)
typer.echo(f"[colab] Uploaded '{local_path}' to '{remote_path}'")
except Exception as e:
typer.echo(f"[colab] Upload failed: {e}")
typer.echo(f"[colab] Upload failed: {describe_error(e)}")
raise typer.Exit(1)


Expand Down Expand Up @@ -144,7 +144,7 @@ def edit(
name = state.resolve_session(session)
s = state.get_session(name)

contents = ContentsClient(s)
contents = ContentsClient(s, refresh_session=lambda: state.get_session(name))

def get_file_hash(path):
if not os.path.exists(path):
Expand Down
135 changes: 119 additions & 16 deletions src/colab_cli/contents.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,67 @@

import base64
import json
import os
from typing import Callable, Optional
from urllib.parse import quote

import requests

from colab_cli.state import SessionState
from colab_cli.utils import get_status_code

# Colab runtimes reject request bodies over 100 MiB with HTTP 400. Files are
# sent base64-encoded (4/3 the size) inside JSON, so a file that does not fit
# in one request goes up in chunks of UPLOAD_CHUNK_SIZE (about 85 MiB encoded).
MAX_REQUEST_BODY = 100 * 1024 * 1024
UPLOAD_CHUNK_SIZE = 64 * 1024 * 1024


class IncompleteUploadError(IOError):
"""A chunked upload failed partway, so the remote file may hold only part of
the local file."""


def describe_error(e: Exception) -> str:
"""Describes an error without the request URL, which has the proxy token."""
if isinstance(e, requests.RequestException):
status = get_status_code(e)
reason = getattr(getattr(e, "response", None), "reason", None)
details = [str(part) for part in (status, reason) if part]
return " ".join([type(e).__name__, *details])
return f"{type(e).__name__}: {e}" if str(e) else type(e).__name__


def _upload_payload(remote_path: str, content: str, chunk: int) -> dict:
return {
"name": remote_path.split("/")[-1],
"path": remote_path,
"type": "file",
"format": "base64",
"content": content,
"chunk": chunk,
}


def fits_in_one_request(remote_path: str, size: int, chunk: int = 1) -> bool:
"""Whether `size` bytes can be uploaded to remote_path as `chunk` in one
request, i.e. whether its JSON body stays within MAX_REQUEST_BODY."""
envelope = len(json.dumps(_upload_payload(remote_path, "", chunk)))
return envelope + 4 * -(-size // 3) <= MAX_REQUEST_BODY


class ContentsClient:
def __init__(self, session_state: SessionState):
def __init__(
self,
session_state: SessionState,
refresh_session: Optional[Callable[[], SessionState]] = None,
):
"""refresh_session, if given, is called before every chunk after the
first to pick up a renewed runtime proxy token, so that uploads that
outlast the token do not fail partway."""
self.base_url = session_state.url.rstrip("/")
self.token = session_state.token
self._refresh_session = refresh_session

def _request(
self, method: str, path: str, params: dict = None, json_data: dict = None
Expand Down Expand Up @@ -54,22 +103,76 @@ def _request(
def list_dir(self, path: str):
return self._request("GET", path)

def upload(self, local_path: str, remote_path: str):
def upload(
self, local_path: str, remote_path: str, chunk_size: int = UPLOAD_CHUNK_SIZE
):
"""Uploads a file, in chunks if it does not fit in one request.

A file that fits is sent as before: one request with chunk 1, which
replaces the remote file in a single save, so the file is either
replaced completely or left as it was. A larger file uses the Jupyter
Contents API chunked protocol: chunk 1 replaces the file, later chunks
are appended, and -1 marks the last one. A lone -1 would append to an
existing file, so it is only ever sent after chunk 1.

If a chunk, or refresh_session before it, fails, IncompleteUploadError
is raised: the remote file may be partly written (even a failed chunk 1
may have been stored if only the response was lost) and the upload has
to be run again. A chunk 1 the runtime refused (404 or another 4xx)
wrote nothing, so that error is raised unchanged. IncompleteUploadError
is raised outside the `except` block so that it carries no reference
to the requests error, whose text includes the proxy token. An upload
interrupted with Ctrl-C after chunk 1 also leaves a partial file.

The stored size is not compared with the local one: the Contents API
reports a symlink's own size (lstat), so an upload that wrote through
a symlinked destination would look incomplete.
"""
if chunk_size <= 0 or not fits_in_one_request(remote_path, chunk_size, -1):
raise ValueError(f"chunk_size {chunk_size} does not fit in one request")
with open(local_path, "rb") as f:
content = f.read()

b64_content = base64.b64encode(content).decode("ascii")
filename = remote_path.split("/")[-1]

payload = {
"name": filename,
"path": remote_path,
"type": "file",
"format": "base64",
"content": b64_content,
"chunk": 1,
}

if fits_in_one_request(remote_path, os.fstat(f.fileno()).st_size):
return self._put_chunk(remote_path, f.read(), 1)
data = f.read(chunk_size)
next_data = f.read(chunk_size)
if not next_data:
return self._put_chunk(remote_path, data, 1)
sent = 0
failure = None
try:
while data:
if sent:
self._refresh_token()
model = self._put_chunk(
remote_path, data, sent + 1 if next_data else -1
)
sent += 1
data, next_data = next_data, f.read(chunk_size)
except (Exception, SystemExit) as e:
status = get_status_code(e)
rejected = isinstance(e, FileNotFoundError) or (
status is not None and 400 <= status < 500
)
if not sent and rejected:
raise
failure = (
f"Uploading {remote_path} failed after {sent} of its chunks "
f"were sent ({describe_error(e)}); "
"the remote file may be incomplete."
)
if failure:
raise IncompleteUploadError(failure)
return model

def _refresh_token(self):
if self._refresh_session:
session_state = self._refresh_session()
self.base_url = session_state.url.rstrip("/")
self.token = session_state.token

def _put_chunk(self, remote_path: str, data: bytes, chunk: int):
content = base64.b64encode(data).decode("ascii")
payload = _upload_payload(remote_path, content, chunk)
return self._request("PUT", remote_path, json_data=payload)

def download(self, remote_path: str, local_path: str):
Expand Down
23 changes: 23 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import click
import pytest
import requests
import typer
from typer.testing import CliRunner

Expand Down Expand Up @@ -616,6 +617,28 @@ def mock_edit_side_effect(filename, **kwargs):
assert "Edited and uploaded 'remote.txt'" in result.output


@patch("colab_cli.commands.files.os.path.isfile")
@patch("colab_cli.commands.files.ContentsClient")
def test_cli_upload_failure_hides_proxy_token(
mock_contents_class, mock_isfile, mock_store, mock_common_state
):
"""A requests error's text includes the URL with the runtime proxy token."""
mock_store.get.return_value = MagicMock()
mock_isfile.return_value = True
mock_common_state.resolve_session.return_value = "s1"
response = MagicMock(status_code=500, reason="Server Error")
mock_contents_class.return_value.upload.side_effect = requests.HTTPError(
"500 Server Error for url: https://x/api/contents/r?colab-runtime-proxy-token=SECRET",
response=response,
)

result = runner.invoke(app, ["upload", "-s", "s1", "local.txt", "remote.txt"])

assert result.exit_code == 1
assert "Upload failed: HTTPError 500 Server Error" in result.output
assert "SECRET" not in result.output


def _make_400_error(message="Bad Request"):
"""Build a ColabRequestError shaped like a 400 from the assign endpoint."""
response = MagicMock()
Expand Down
Loading