From 5cd07617bebd67cd5ee66b54769884782852c0b8 Mon Sep 17 00:00:00 2001 From: yschoi9733 <129668673+yschoi9733@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:43:32 +0900 Subject: [PATCH] fix(upload): upload large files in chunks Colab runtimes reject Contents API request bodies over 100 MiB with HTTP 400, and `colab upload` sent the whole file base64-encoded in one PUT, so files larger than about 75 MiB could not be uploaded. A file that fits in one request is still sent as a single "chunk": 1 PUT. Larger files are sent in 64 MiB chunks with the Jupyter Contents API chunked protocol (1, 2, ..., -1). A failed chunk raises IncompleteUploadError, and an optional refresh_session callable picks up a renewed runtime proxy token between chunks. Errors are described without the request URL, which contains the proxy token. Also adds a live integration scenario (integration/repro_large_upload) and updates the file management design doc. --- docs/03_file_management.md | 16 +- integration/README.md | 1 + integration/repro_large_upload/test.sh | 122 +++++++++++ src/colab_cli/commands/files.py | 8 +- src/colab_cli/contents.py | 135 +++++++++++-- tests/test_cli.py | 23 +++ tests/test_contents.py | 267 ++++++++++++++++++++++++- 7 files changed, 548 insertions(+), 24 deletions(-) create mode 100644 integration/repro_large_upload/test.sh diff --git a/docs/03_file_management.md b/docs/03_file_management.md index 0a14d302..b1515c4a 100644 --- a/docs/03_file_management.md +++ b/docs/03_file_management.md @@ -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 @@ -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. @@ -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`. diff --git a/integration/README.md b/integration/README.md index 5ad646d2..92348e9a 100644 --- a/integration/README.md +++ b/integration/README.md @@ -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. | diff --git a/integration/repro_large_upload/test.sh b/integration/repro_large_upload/test.sh new file mode 100644 index 00000000..f9218a09 --- /dev/null +++ b/integration/repro_large_upload/test.sh @@ -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" <&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 diff --git a/src/colab_cli/commands/files.py b/src/colab_cli/commands/files.py index fa1c9050..e5408c5c 100644 --- a/src/colab_cli/commands/files.py +++ b/src/colab_cli/commands/files.py @@ -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( @@ -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( @@ -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) @@ -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): diff --git a/src/colab_cli/contents.py b/src/colab_cli/contents.py index d794b5cb..99a7c82f 100644 --- a/src/colab_cli/contents.py +++ b/src/colab_cli/contents.py @@ -14,6 +14,8 @@ import base64 import json +import os +from typing import Callable, Optional from urllib.parse import quote import requests @@ -21,11 +23,58 @@ 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 @@ -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): diff --git a/tests/test_cli.py b/tests/test_cli.py index f08fdc19..ad1148fc 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -18,6 +18,7 @@ import click import pytest +import requests import typer from typer.testing import CliRunner @@ -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() diff --git a/tests/test_contents.py b/tests/test_contents.py index 26d0f3c1..e8cd6ffe 100644 --- a/tests/test_contents.py +++ b/tests/test_contents.py @@ -13,12 +13,19 @@ # limitations under the License. import base64 +import io import json from unittest.mock import MagicMock, patch import pytest -from colab_cli.contents import ContentsClient -from requests import Response +from colab_cli.contents import ( + UPLOAD_CHUNK_SIZE, + ContentsClient, + IncompleteUploadError, + _upload_payload, + fits_in_one_request, +) +from requests import HTTPError, Response from colab_cli.state import SessionState @@ -187,3 +194,259 @@ def test_upload_file(mock_request, client, tmp_path): "chunk": 1, }, ) + + +class FakeContentsServer: + """Minimal stand-in for the runtime's Contents API, as observed on Colab. + + PUT follows the Jupyter chunked protocol: chunk 1 replaces the file and + other chunks are appended. `fail` maps a chunk number to an HTTP status + (or True for 500) to answer that PUT with; a failed request changes + nothing, and, like requests, its error text carries the URL and token. + """ + + REASONS = {200: "OK", 403: "Forbidden", 404: "Not Found", 500: "Server Error"} + + def __init__(self, files=None, fail=None): + self.files = dict(files or {}) + self.fail = fail + self.calls = [] + self.tokens = [] + + def __call__(self, method, url, params=None, json=None): + assert method == "PUT" + path = url.split("/api/contents/", 1)[1] + chunk = json["chunk"] + self.calls.append((path, chunk)) + self.tokens.append(params["colab-runtime-proxy-token"]) + status = self.fail(chunk) if self.fail else None + if status: + status = 500 if status is True else status + token = params["colab-runtime-proxy-token"] + return self._response( + status, error=f"{status} Error for url: {url}?token={token}" + ) + data = base64.b64decode(json["content"]) + old = b"" if chunk == 1 else self.files.get(path, b"") + self.files[path] = old + data + return self._response(200, {"type": "file"}) + + @classmethod + def _response(cls, status, body=None, error=None): + resp = MagicMock(spec=Response) + resp.status_code = status + resp.reason = cls.REASONS[status] + resp.json.return_value = body + if error: + resp.raise_for_status.side_effect = HTTPError(error, response=resp) + return resp + + +@pytest.fixture +def small_requests(): + """Shrinks the request limit so that, for content/big.bin, files of up to + 6 bytes fit in one request and larger ones do not. 4-byte chunks fit, + also as chunk -1, whose envelope is one byte longer than chunk 1's.""" + envelope = len(json.dumps(_upload_payload("content/big.bin", "", 1))) + with patch("colab_cli.contents.MAX_REQUEST_BODY", envelope + 9): + yield + + +def _upload(client, tmp_path, server, content, chunk_size=4): + local_file = tmp_path / "big.bin" + local_file.write_bytes(content) + with patch("colab_cli.contents.requests.request", side_effect=server): + client.upload(str(local_file), "content/big.bin", chunk_size=chunk_size) + + +def test_upload_large_file_in_chunks(client, tmp_path, small_requests): + """Files that do not fit in one request are sent as chunks 1, 2, ..., -1.""" + server = FakeContentsServer({"content/big.bin": b"old contents"}) + + _upload(client, tmp_path, server, b"0123456789") + + assert server.files == {"content/big.bin": b"0123456789"} + assert server.calls == [ + ("content/big.bin", 1), + ("content/big.bin", 2), + ("content/big.bin", -1), + ] + + +def test_upload_exact_multiple_of_chunk_size(client, tmp_path, small_requests): + """The last full chunk is marked -1; no empty trailing request is sent.""" + server = FakeContentsServer() + + _upload(client, tmp_path, server, b"01234567") + + assert server.files == {"content/big.bin": b"01234567"} + assert server.calls == [("content/big.bin", 1), ("content/big.bin", -1)] + + +@pytest.mark.parametrize("content", [b"", b"0123", b"012345"]) +def test_upload_that_fits_is_one_request(client, tmp_path, small_requests, content): + """A file that fits in one request is sent as a single chunk=1 request, + even when it is larger than one chunk. A lone chunk=-1 would append to + the old file instead of replacing it.""" + server = FakeContentsServer({"content/big.bin": b"old contents"}) + + _upload(client, tmp_path, server, content) + + assert server.files == {"content/big.bin": content} + assert server.calls == [("content/big.bin", 1)] + + +def test_one_request_limit_matches_colab(): + """Pinned to a live Colab measurement for this path: a 78,643,113-byte file + (a 104,857,600-byte request body) uploaded in one request, and larger + files were refused with HTTP 400.""" + assert fits_in_one_request("/content/p_edge.bin", 78_643_113) + assert not fits_in_one_request("/content/p_edge.bin", 78_643_114) + + +def test_default_chunk_fits_in_one_request(): + long_path = "content/" + "x" * 1000 + assert fits_in_one_request(long_path, UPLOAD_CHUNK_SIZE) + + +@pytest.mark.parametrize("status, error", [(404, FileNotFoundError), (403, HTTPError)]) +def test_rejected_first_chunk_raises_original_error( + client, tmp_path, small_requests, status, error +): + """A runtime that refuses chunk 1 wrote nothing, so the plain error is kept.""" + server = FakeContentsServer( + {"content/big.bin": b"old contents"}, + fail=lambda chunk: status if chunk == 1 else None, + ) + + with pytest.raises(error): + _upload(client, tmp_path, server, b"0123456789") + + assert server.files == {"content/big.bin": b"old contents"} + + +def test_failed_single_request_raises_original_error(client, tmp_path): + """A one-request upload either replaces the file or leaves it as it was.""" + server = FakeContentsServer( + {"content/big.bin": b"old contents"}, fail=lambda chunk: True + ) + + with pytest.raises(HTTPError): + _upload(client, tmp_path, server, b"0123") + + assert server.files == {"content/big.bin": b"old contents"} + + +@pytest.mark.parametrize("failed_chunk", [1, 2]) +def test_failed_chunk_reports_possibly_incomplete_file( + client, tmp_path, small_requests, failed_chunk +): + """Any failed chunk may have been stored (e.g. the response was lost), so + the error says the file may be incomplete. The HTTPError text has the + token, so it must reach neither the message nor a chained traceback.""" + server = FakeContentsServer(fail=lambda chunk: chunk == failed_chunk) + + with pytest.raises(IncompleteUploadError) as excinfo: + _upload(client, tmp_path, server, b"0123456789") + + message = str(excinfo.value) + assert "content/big.bin" in message + sent = failed_chunk - 1 + assert f"after {sent} of its chunks were sent (HTTPError 500 Server Error)" in ( + message + ) + assert "may be incomplete" in message + assert "test-token" not in message + assert excinfo.value.__cause__ is None + assert excinfo.value.__context__ is None + assert len(server.calls) == failed_chunk + + +def test_later_chunks_use_a_refreshed_token(session, tmp_path, small_requests): + """Long uploads can outlast the proxy token, so every chunk after the first + asks the session for a possibly renewed one.""" + renewed = session.model_copy(update={"token": "renewed-token"}) + client = ContentsClient(session, refresh_session=lambda: renewed) + server = FakeContentsServer() + + _upload(client, tmp_path, server, b"0123456789") + + assert server.tokens == ["test-token", "renewed-token", "renewed-token"] + + +def test_failed_token_refresh_reports_possibly_incomplete_file( + session, tmp_path, small_requests +): + """Refreshing can end in sys.exit (e.g. failed ADC credentials) after chunk 1 + replaced the remote file, so it is reported like a failed chunk.""" + + def refresh_session(): + raise SystemExit(1) + + client = ContentsClient(session, refresh_session=refresh_session) + server = FakeContentsServer() + + with pytest.raises( + IncompleteUploadError, match=r"after 1 of its chunks.*SystemExit" + ): + _upload(client, tmp_path, server, b"0123456789") + + assert server.calls == [("content/big.bin", 1)] + + +@pytest.mark.parametrize("content", [b"", b"0123"]) +def test_file_that_shrank_after_its_size_was_read( + client, tmp_path, small_requests, content +): + """If the file is truncated between the size check and the first read, the + rest is sent as one chunk=1 request instead of failing.""" + server = FakeContentsServer({"content/big.bin": b"old contents"}) + + with patch("colab_cli.contents.os.fstat", return_value=MagicMock(st_size=10**9)): + _upload(client, tmp_path, server, content) + + assert server.files == {"content/big.bin": content} + assert server.calls == [("content/big.bin", 1)] + + +class FailingReader(io.BytesIO): + """A local file whose reads fail after the first `ok_reads`.""" + + def __init__(self, data, ok_reads): + super().__init__(data) + self.ok_reads = ok_reads + + def fileno(self): + return -1 + + def read(self, size=-1): + if self.ok_reads == 0: + raise OSError(5, "Input/output error") + self.ok_reads -= 1 + return super().read(size) + + +def test_failed_local_read_reports_possibly_incomplete_file(client, small_requests): + """Chunk 1 already replaced the remote file, so a local read error later + on must also say the remote file may be incomplete.""" + server = FakeContentsServer({"content/big.bin": b"old contents"}) + reader = FailingReader(b"0123456789", ok_reads=2) + + with ( + patch("colab_cli.contents.open", create=True, return_value=reader), + patch("colab_cli.contents.os.fstat", return_value=MagicMock(st_size=10)), + patch("colab_cli.contents.requests.request", side_effect=server), + pytest.raises(IncompleteUploadError) as excinfo, + ): + client.upload("big.bin", "content/big.bin", chunk_size=4) + + assert "Input/output error" in str(excinfo.value) + assert "may be incomplete" in str(excinfo.value) + assert server.files == {"content/big.bin": b"0123"} + + +@pytest.mark.parametrize("chunk_size", [0, -1, 7]) +def test_upload_rejects_bad_chunk_size(client, tmp_path, small_requests, chunk_size): + """Chunks must be positive and fit in one request (7 bytes do not here).""" + with pytest.raises(ValueError): + _upload(client, tmp_path, FakeContentsServer(), b"0123", chunk_size)