Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Chunked resumable Google Drive upload with resume-on-failure (SKY-12394) (#7391)
Suchintan4c1c50c7b906
diff --git a/skyvern/forge/sdk/services/google_drive_service.py b/skyvern/forge/sdk/services/google_drive_service.pyindex 9e9b841a1..12245c139 100644--- a/skyvern/forge/sdk/services/google_drive_service.py+++ b/skyvern/forge/sdk/services/google_drive_service.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport asyncioimport jsonimport uuid-from collections.abc import AsyncIterator, Mapping+from collections.abc import Awaitable, Callable, Mappingfrom dataclasses import dataclassfrom datetime import datetime, timezonefrom email.utils import parsedate_to_datetime@@ -21,9 +21,11 @@ DRIVE_UPLOAD_API_BASE = "https://www.googleapis.com/upload/drive/v3"DRIVE_MULTIPART_UPLOAD_MAX_BYTES = 5 * 1024 * 1024# Reserve headroom for JSON metadata and MIME boundaries below the 5 MiB multipart request cap.DRIVE_MULTIPART_FILE_MAX_BYTES = DRIVE_MULTIPART_UPLOAD_MAX_BYTES - 10 * 1024-DRIVE_RESUMABLE_UPLOAD_CHUNK_BYTES = 8 * 1024 * 1024+# 8 MiB is a multiple of Drive's required 256 KiB unit for non-final chunks.+DRIVE_RESUMABLE_CHUNK_BYTES = 8 * 1024 * 1024_DEFAULT_BACKOFF_SECONDS = 1.0+_RATE_LIMIT_403_REASONS = frozenset({"ratelimitexceeded", "userratelimitexceeded"})class GoogleDriveAPIError(RuntimeError):@@ -34,6 +36,10 @@ class GoogleDriveAPIError(RuntimeError):self.message = message+class GoogleDriveResumableTransportError(Exception):+ """Retryable transport failure during a resumable chunk PUT — the loop should query offset and resume."""++@dataclass(frozen=True)class UploadedDriveFile:id: str@@ -55,10 +61,69 @@ class GoogleDriveResumableInitiateRequest:@dataclass(frozen=True)-class GoogleDriveResumableUploadRequest:- target_url: str- headers: dict[str, str]- file_path: str+class ResumableChunkResponse:+ status_code: int+ range_header: str | None+ body_text: str | None+++def build_resumable_chunk_headers(+ *,+ content_type: str,+ start: int,+ end: int,+ total: int,+ chunk_len: int,+) -> dict[str, str]:+ return {+ "Content-Type": content_type,+ "Content-Length": str(chunk_len),+ "Content-Range": f"bytes {start}-{end}/{total}",+ }+++def build_resumable_status_query_headers(*, total: int) -> dict[str, str]:+ return {+ "Content-Range": f"bytes */{total}",+ "Content-Length": "0",+ }+++def parse_resumable_range_offset(range_header: str | None) -> int:+ if not range_header:+ return 0+ try:+ unit, byte_range = range_header.strip().split("=", 1)+ start_text, last_byte_text = byte_range.split("-", 1)+ start = int(start_text.strip())+ last_byte = int(last_byte_text.strip())+ except (TypeError, ValueError):+ return 0+ if unit.lower() != "bytes" or start != 0 or last_byte < 0:+ return 0+ return last_byte + 1+++def is_retryable_resumable_status(status_code: int) -> bool:+ return status_code == 429 or 500 <= status_code < 600+++def is_retryable_resumable_response(status_code: int, body_text: str | None) -> bool:+ if is_retryable_resumable_status(status_code):+ return True+ if status_code == 403 and body_text:+ try:+ payload = json.loads(body_text)+ except ValueError:+ return False+ error = payload.get("error") if isinstance(payload, dict) else None+ errors = error.get("errors") if isinstance(error, dict) else None+ if isinstance(errors, list):+ return any(+ isinstance(item, dict) and str(item.get("reason", "")).lower() in _RATE_LIMIT_403_REASONS+ for item in errors+ )+ return Falsedef _compute_backoff(attempt: int, retry_after: str | None) -> float:@@ -252,19 +317,6 @@ def extract_resumable_session_uri(headers: Mapping[str, str]) -> str:)-def build_resumable_upload_request(*, file_path: str, session_uri: str) -> GoogleDriveResumableUploadRequest:- file_size = Path(file_path).stat().st_size- content_type = guess_type(file_path)[0] or "application/octet-stream"- return GoogleDriveResumableUploadRequest(- target_url=session_uri,- headers={- "Content-Type": content_type,- "Content-Length": str(file_size),- },- file_path=file_path,- )--def uploaded_file_from_payload(payload: Any) -> UploadedDriveFile:if not isinstance(payload, dict):raise GoogleDriveAPIError(status=500, code="malformed_response", message="Malformed Drive upload response")@@ -277,6 +329,99 @@ def uploaded_file_from_payload(payload: Any) -> UploadedDriveFile:)+def _uploaded_file_from_resumable_response(response: ResumableChunkResponse) -> UploadedDriveFile:+ try:+ payload = json.loads(response.body_text or "{}")+ except ValueError as exc:+ raise GoogleDriveAPIError(+ status=500,+ code="malformed_response",+ message="Drive response was not valid JSON",+ ) from exc+ return uploaded_file_from_payload(payload)+++def _raise_unexpected_resumable_status(status_code: int) -> None:+ raise GoogleDriveAPIError(+ status=502,+ code="resumable_unexpected_status",+ message=f"Google Drive resumable upload returned unexpected status {status_code}",+ )+++async def run_chunked_resumable_upload(+ *,+ file_path: str,+ total: int,+ send: Callable[[bytes, dict[str, str]], Awaitable[ResumableChunkResponse]],+ max_attempts: int,+) -> UploadedDriveFile:+ content_type = guess_type(file_path)[0] or "application/octet-stream"+ offset = 0+ attempts = 0+ probe_first = False # after a chunk transport failure, learn Drive's committed offset before re-sending++ async with aiofiles.open(file_path, "rb") as file:+ while True:+ if probe_first:+ try:+ response = await send(b"", build_resumable_status_query_headers(total=total))+ except GoogleDriveResumableTransportError:+ attempts += 1+ if attempts >= max_attempts:+ raise GoogleDriveAPIError(+ status=503,+ code="resumable_upload_failed",+ message="Google Drive resumable upload failed after exhausting resume attempts",+ ) from None+ await asyncio.sleep(_compute_backoff(attempts, None))+ continue+ probe_first = False+ else:+ await file.seek(offset)+ chunk = await file.read(DRIVE_RESUMABLE_CHUNK_BYTES)+ if not chunk:+ raise GoogleDriveAPIError(+ status=500,+ code="resumable_incomplete",+ message="Google Drive resumable upload could not read the expected file bytes",+ )+ end = offset + len(chunk) - 1+ headers = build_resumable_chunk_headers(+ content_type=content_type,+ start=offset,+ end=end,+ total=total,+ chunk_len=len(chunk),+ )+ try:+ response = await send(chunk, headers)+ except GoogleDriveResumableTransportError:+ # Do not count an attempt here: always reconcile via a status query first, so a lost-but-committed+ # chunk is detected instead of re-uploaded into a duplicate.+ probe_first = True+ continue++ if response.status_code in (200, 201):+ return _uploaded_file_from_resumable_response(response)+ if response.status_code == 308:+ new_offset = parse_resumable_range_offset(response.range_header)+ if new_offset > offset:+ offset = new_offset+ attempts = 0+ else:+ attempts += 1+ if attempts >= max_attempts:+ raise GoogleDriveAPIError(+ status=503,+ code="resumable_upload_failed",+ message="Google Drive resumable upload made no progress after exhausting resume attempts",+ ) from None+ await asyncio.sleep(_compute_backoff(attempts, None))+ continue+ _raise_unexpected_resumable_status(response.status_code)++async def _post_multipart_with_retry(client: httpx.AsyncClient,request: GoogleDriveMultipartUploadRequest,@@ -346,12 +491,6 @@ async def _post_resumable_initiate_with_retry(raise AssertionError("Drive resumable upload retry loop exited without a response")-async def _iter_file_chunks(file_path: str) -> AsyncIterator[bytes]:- async with aiofiles.open(file_path, "rb") as file:- while chunk := await file.read(DRIVE_RESUMABLE_UPLOAD_CHUNK_BYTES):- yield chunk--async def _upload_file_resumable(*,access_token: str,@@ -368,36 +507,41 @@ async def _upload_file_resumable(initiate_response = await _post_resumable_initiate_with_retry(client, initiate_request)_raise_for_error(initiate_response)session_uri = extract_resumable_session_uri(initiate_response.headers)- upload_request = build_resumable_upload_request(file_path=file_path, session_uri=session_uri)- try:- upload_response = await client.put(- upload_request.target_url,- headers=upload_request.headers,- content=_iter_file_chunks(upload_request.file_path),- )- except (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout) as exc:- raise GoogleDriveAPIError(- status=503,- code="upstream_unavailable",- message=f"Google Drive resumable upload connection failure: {exc}",- ) from exc- except (httpx.TransportError, httpx.TimeoutException) as exc:++ async def send(body: bytes, headers: dict[str, str]) -> ResumableChunkResponse:+ try:+ response = await client.put(session_uri, headers=headers, content=body)+ except (+ httpx.ConnectError,+ httpx.ConnectTimeout,+ httpx.PoolTimeout,+ httpx.TransportError,+ httpx.TimeoutException,+ ) as exc:+ raise GoogleDriveResumableTransportError(str(exc)) from exc+ if response.status_code in (200, 201, 308):+ return ResumableChunkResponse(+ status_code=response.status_code,+ range_header=response.headers.get("Range"),+ body_text=response.text,+ )+ if is_retryable_resumable_response(response.status_code, response.text):+ raise GoogleDriveResumableTransportError(+ f"Google Drive returned retryable status {response.status_code}"+ )+ _raise_for_error(response)raise GoogleDriveAPIError(- status=503,- code="ambiguous_upload_status",- message="Google Drive upload status is unknown after a transport failure.",- ) from exc+ status=502,+ code="resumable_unexpected_status",+ message=f"Google Drive resumable upload returned unexpected status {response.status_code}",+ )- _raise_for_error(upload_response)- try:- payload = upload_response.json() or {}- except ValueError as exc:- raise GoogleDriveAPIError(- status=500,- code="malformed_response",- message="Drive response was not valid JSON",- ) from exc- return uploaded_file_from_payload(payload)+ return await run_chunked_resumable_upload(+ file_path=file_path,+ total=Path(file_path).stat().st_size,+ send=send,+ max_attempts=max(1, settings.GOOGLE_DRIVE_API_MAX_RETRIES),+ )async def upload_file(diff --git a/tests/unit/google/test_google_oauth.py b/tests/unit/google/test_google_oauth.pyindex 3c1eaaed8..8f071550f 100644--- a/tests/unit/google/test_google_oauth.py+++ b/tests/unit/google/test_google_oauth.py@@ -1,7 +1,8 @@+import asyncioimport datetimefrom types import SimpleNamespacefrom typing import Any, Awaitable, Callable-from unittest.mock import AsyncMock+from unittest.mock import AsyncMock, callfrom urllib.parse import parse_qs, urlparseimport httpx@@ -351,17 +352,80 @@ def test_google_drive_file_near_multipart_cap_uses_resumable(tmp_path) -> None:assert google_drive_service.should_use_resumable_upload(str(small_file)) is False+ ("range_header", "expected"),+ [+ ("bytes=0-262143", 262144),+ (None, 0),+ ("", 0),+ ("malformed", 0),+ ],+)+def test_google_drive_parse_resumable_range_offset(range_header: str | None, expected: int) -> None:+ assert google_drive_service.parse_resumable_range_offset(range_header) == expected+++def test_google_drive_is_retryable_resumable_status() -> None:+ for status_code in (429, 500, 502, 503, 504):+ assert google_drive_service.is_retryable_resumable_status(status_code) is True+ for status_code in (200, 308, 400, 403, 404):+ assert google_drive_service.is_retryable_resumable_status(status_code) is False+++ ("status_code", "body_text", "expected"),+ [+ (429, None, True),+ (503, None, True),+ (403, '{"error":{"errors":[{"reason":"rateLimitExceeded"}]}}', True),+ (403, '{"error":{"errors":[{"reason":"insufficientPermissions"}]}}', False),+ (403, None, False),+ (200, None, False),+ ],+)+def test_google_drive_is_retryable_resumable_response(+ status_code: int,+ body_text: str | None,+ expected: bool,+) -> None:+ assert google_drive_service.is_retryable_resumable_response(status_code, body_text) is expected+++def test_google_drive_builds_resumable_chunk_headers() -> None:+ assert google_drive_service.build_resumable_chunk_headers(+ content_type="application/octet-stream",+ start=262144,+ end=524287,+ total=700000,+ chunk_len=262144,+ ) == {+ "Content-Type": "application/octet-stream",+ "Content-Length": "262144",+ "Content-Range": "bytes 262144-524287/700000",+ }+++def test_google_drive_builds_resumable_status_query_headers() -> None:+ assert google_drive_service.build_resumable_status_query_headers(total=700000) == {+ "Content-Range": "bytes */700000",+ "Content-Length": "0",+ }++@pytest.mark.asyncioasync def test_google_drive_uploads_resumable_for_large_files(monkeypatch: pytest.MonkeyPatch,tmp_path,) -> None:monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 4)+ monkeypatch.setattr(google_drive_service, "DRIVE_RESUMABLE_CHUNK_BYTES", 4)source = tmp_path / "report.txt"file_bytes = b"hello-drive"source.write_bytes(file_bytes)session_uri = "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=sess_1"requests: list[tuple[str, str]] = []+ chunks: list[bytes] = []+ content_ranges: list[str] = []async def handler(request: httpx.Request) -> httpx.Response:url = str(request.url)@@ -380,10 +444,16 @@ async def test_google_drive_uploads_resumable_for_large_files(assert request.method == "PUT"assert url == session_uriassert request.headers["Content-Type"] == "text/plain"- assert request.headers["Content-Length"] == str(len(file_bytes))assert "Transfer-Encoding" not in request.headersassert "Authorization" not in request.headers- assert await request.aread() == file_bytes+ chunk = await request.aread()+ content_range = request.headers["Content-Range"]+ chunks.append(chunk)+ content_ranges.append(content_range)+ assert request.headers["Content-Length"] == str(len(chunk))+ if content_range != f"bytes 8-10/{len(file_bytes)}":+ end = int(content_range.split("-", 1)[1].split("/", 1)[0])+ return httpx.Response(308, headers={"Range": f"bytes=0-{end}"})return httpx.Response(200,json={@@ -402,30 +472,42 @@ async def test_google_drive_uploads_resumable_for_large_files()assert uploaded.id == "file_789"- assert [method for method, _url in requests] == ["POST", "PUT"]+ assert [method for method, _url in requests] == ["POST", "PUT", "PUT", "PUT"]assert requests[1][1] == session_uri+ assert b"".join(chunks) == file_bytes+ assert content_ranges == [+ f"bytes 0-3/{len(file_bytes)}",+ f"bytes 4-7/{len(file_bytes)}",+ f"bytes 8-10/{len(file_bytes)}",+ ]@pytest.mark.asyncio-async def test_google_drive_resumable_initiation_accepts_201_and_streams_multiple_chunks(+async def test_google_drive_resumable_initiation_accepts_201_and_uploads_multiple_chunks(monkeypatch: pytest.MonkeyPatch,tmp_path,) -> None:monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)- monkeypatch.setattr(google_drive_service, "DRIVE_RESUMABLE_UPLOAD_CHUNK_BYTES", 3)+ monkeypatch.setattr(google_drive_service, "DRIVE_RESUMABLE_CHUNK_BYTES", 3)source = tmp_path / "payload"file_bytes = b"0123456789"source.write_bytes(file_bytes)session_uri = "https://www.googleapis.com/upload/session"- received_body: bytes | None = None+ chunks: list[bytes] = []+ content_ranges: list[str] = []async def handler(request: httpx.Request) -> httpx.Response:- nonlocal received_bodyif request.method == "POST":assert request.headers["X-Upload-Content-Type"] == "application/octet-stream"return httpx.Response(201, headers={"Location": session_uri})assert request.headers["Content-Type"] == "application/octet-stream"- received_body = await request.aread()+ chunk = await request.aread()+ content_range = request.headers["Content-Range"]+ chunks.append(chunk)+ content_ranges.append(content_range)+ if content_range != f"bytes 9-9/{len(file_bytes)}":+ end = int(content_range.split("-", 1)[1].split("/", 1)[0])+ return httpx.Response(308, headers={"Range": f"bytes=0-{end}"})return httpx.Response(200, json={"id": "file_chunked"})_install_google_drive_transport(monkeypatch, handler)@@ -437,7 +519,8 @@ async def test_google_drive_resumable_initiation_accepts_201_and_streams_multipl)assert uploaded.id == "file_chunked"- assert received_body == file_bytes+ assert b"".join(chunks) == file_bytes+ assert content_ranges == ["bytes 0-2/10", "bytes 3-5/10", "bytes 6-8/10", "bytes 9-9/10"]@pytest.mark.asyncio@@ -624,26 +707,512 @@ async def test_google_drive_resumable_initiation_does_not_retry_read_timeout(@pytest.mark.asyncio-async def test_google_drive_resumable_put_does_not_retry_read_timeout(+async def test_google_drive_resumable_resumes_after_put_transport_failure(monkeypatch: pytest.MonkeyPatch,tmp_path,) -> None:monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)+ monkeypatch.setattr(google_drive_service, "DRIVE_RESUMABLE_CHUNK_BYTES", 4)source = tmp_path / "payload.bin"- source.write_bytes(b"large")+ file_bytes = b"abcdefghijkl"+ source.write_bytes(file_bytes)session_uri = "https://www.googleapis.com/upload/session"post_calls = 0- put_calls = 0+ content_ranges: list[str] = []+ query_calls = 0+ failed_once = Falseasync def handler(request: httpx.Request) -> httpx.Response:- nonlocal post_calls, put_calls+ nonlocal failed_once, post_calls, query_callsif request.method == "POST":post_calls += 1return httpx.Response(200, headers={"Location": session_uri})- put_calls += 1+ content_range = request.headers["Content-Range"]+ content_ranges.append(content_range)+ if content_range == f"bytes */{len(file_bytes)}":+ query_calls += 1+ assert request.headers["Content-Length"] == "0"+ assert await request.aread() == b""+ return httpx.Response(308, headers={"Range": "bytes=0-7"})++ chunk = await request.aread()+ if content_range == f"bytes 0-3/{len(file_bytes)}":+ assert chunk == file_bytes[0:4]+ return httpx.Response(308, headers={"Range": "bytes=0-3"})+ if content_range == f"bytes 4-7/{len(file_bytes)}" and not failed_once:+ failed_once = True+ assert chunk == file_bytes[4:8]+ raise httpx.ReadTimeout("read timed out", request=request)+ assert content_range == f"bytes 8-11/{len(file_bytes)}"+ assert chunk == file_bytes[8:12]+ return httpx.Response(200, json={"id": "file_resumed"})++ _install_google_drive_transport(monkeypatch, handler)++ uploaded = await google_drive_service.upload_file(+ access_token="at-1",+ file_path=str(source),+ folder_id="folder_123",+ )++ assert uploaded.id == "file_resumed"+ assert post_calls == 1+ assert query_calls == 1+ assert content_ranges == ["bytes 0-3/12", "bytes 4-7/12", "bytes */12", "bytes 8-11/12"]+++async def test_google_drive_resumable_requeries_offset_after_double_transport_failure(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)+ monkeypatch.setattr(google_drive_service, "DRIVE_RESUMABLE_CHUNK_BYTES", 4)+ source = tmp_path / "payload.bin"+ file_bytes = b"abcdefgh"+ source.write_bytes(file_bytes)+ session_uri = "https://www.googleapis.com/upload/session"+ content_ranges: list[str] = []+ query_calls = 0++ async def handler(request: httpx.Request) -> httpx.Response:+ nonlocal query_calls+ if request.method == "POST":+ return httpx.Response(200, headers={"Location": session_uri})+ content_range = request.headers["Content-Range"]+ content_ranges.append(content_range)+ if content_range == f"bytes */{len(file_bytes)}":+ query_calls += 1+ if query_calls == 1:+ raise httpx.ReadTimeout("status query timed out", request=request)+ return httpx.Response(308, headers={"Range": "bytes=0-3"})+ if content_range == f"bytes 0-3/{len(file_bytes)}":+ raise httpx.ReadTimeout("chunk response timed out", request=request)+ assert content_range == f"bytes 4-7/{len(file_bytes)}"+ return httpx.Response(200, json={"id": "file_requeried"})++ _install_google_drive_transport(monkeypatch, handler)+ sleep_mock = AsyncMock()+ monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)++ uploaded = await google_drive_service.upload_file(+ access_token="at-1",+ file_path=str(source),+ folder_id="folder_123",+ )++ assert uploaded.id == "file_requeried"+ assert content_ranges == ["bytes 0-3/8", "bytes */8", "bytes */8", "bytes 4-7/8"]+ sleep_mock.assert_awaited_once_with(1.0)+++async def test_google_drive_resumable_resumes_after_chunk_5xx(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)+ monkeypatch.setattr(google_drive_service, "DRIVE_RESUMABLE_CHUNK_BYTES", 4)+ source = tmp_path / "payload.bin"+ file_bytes = b"abcdefgh"+ source.write_bytes(file_bytes)+ session_uri = "https://www.googleapis.com/upload/session"+ chunk_ranges: list[str] = []+ query_calls = 0++ async def handler(request: httpx.Request) -> httpx.Response:+ nonlocal query_calls+ if request.method == "POST":+ return httpx.Response(200, headers={"Location": session_uri})+ content_range = request.headers["Content-Range"]+ if content_range == f"bytes */{len(file_bytes)}":+ query_calls += 1+ return httpx.Response(308, headers={"Range": "bytes=0-3"})++ chunk_ranges.append(content_range)+ if content_range == f"bytes 0-3/{len(file_bytes)}":+ return httpx.Response(503, text="temporarily unavailable")+ assert content_range == f"bytes 4-7/{len(file_bytes)}"+ return httpx.Response(200, json={"id": "file_resumed_after_503"})++ _install_google_drive_transport(monkeypatch, handler)++ uploaded = await google_drive_service.upload_file(+ access_token="at-1",+ file_path=str(source),+ folder_id="folder_123",+ )++ assert uploaded.id == "file_resumed_after_503"+ assert query_calls == 1+ assert chunk_ranges == ["bytes 0-3/8", "bytes 4-7/8"]+++async def test_google_drive_resumable_resumes_after_chunk_429(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)+ monkeypatch.setattr(google_drive_service, "DRIVE_RESUMABLE_CHUNK_BYTES", 4)+ source = tmp_path / "payload.bin"+ file_bytes = b"abcdefgh"+ source.write_bytes(file_bytes)+ session_uri = "https://www.googleapis.com/upload/session"+ chunk_ranges: list[str] = []+ query_calls = 0++ async def handler(request: httpx.Request) -> httpx.Response:+ nonlocal query_calls+ if request.method == "POST":+ return httpx.Response(200, headers={"Location": session_uri})+ content_range = request.headers["Content-Range"]+ if content_range == f"bytes */{len(file_bytes)}":+ query_calls += 1+ return httpx.Response(308, headers={"Range": "bytes=0-3"})++ chunk_ranges.append(content_range)+ if content_range == f"bytes 0-3/{len(file_bytes)}":+ return httpx.Response(429, text="rate limited")+ assert content_range == f"bytes 4-7/{len(file_bytes)}"+ return httpx.Response(200, json={"id": "file_resumed_after_429"})++ _install_google_drive_transport(monkeypatch, handler)+ sleep_mock = AsyncMock()+ monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)++ uploaded = await google_drive_service.upload_file(+ access_token="at-1",+ file_path=str(source),+ folder_id="folder_123",+ )++ assert uploaded.id == "file_resumed_after_429"+ assert query_calls == 1+ assert chunk_ranges == ["bytes 0-3/8", "bytes 4-7/8"]+ sleep_mock.assert_not_awaited()+++async def test_google_drive_resumable_resumes_after_chunk_rate_limit_403(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)+ monkeypatch.setattr(google_drive_service, "DRIVE_RESUMABLE_CHUNK_BYTES", 4)+ source = tmp_path / "payload.bin"+ file_bytes = b"abcdefgh"+ source.write_bytes(file_bytes)+ session_uri = "https://www.googleapis.com/upload/session"+ content_ranges: list[str] = []++ async def handler(request: httpx.Request) -> httpx.Response:+ if request.method == "POST":+ return httpx.Response(200, headers={"Location": session_uri})+ content_range = request.headers["Content-Range"]+ content_ranges.append(content_range)+ if content_range == f"bytes */{len(file_bytes)}":+ return httpx.Response(308, headers={"Range": "bytes=0-3"})+ if content_range == f"bytes 0-3/{len(file_bytes)}":+ return httpx.Response(+ 403,+ json={"error": {"errors": [{"reason": "userRateLimitExceeded"}], "message": "rate limited"}},+ )+ assert content_range == f"bytes 4-7/{len(file_bytes)}"+ return httpx.Response(200, json={"id": "file_resumed_after_403"})++ _install_google_drive_transport(monkeypatch, handler)+ sleep_mock = AsyncMock()+ monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)++ uploaded = await google_drive_service.upload_file(+ access_token="at-1",+ file_path=str(source),+ folder_id="folder_123",+ )++ assert uploaded.id == "file_resumed_after_403"+ assert content_ranges == ["bytes 0-3/8", "bytes */8", "bytes 4-7/8"]+ sleep_mock.assert_not_awaited()+++async def test_google_drive_resumable_non_rate_limit_403_is_fatal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)+ monkeypatch.setattr(google_drive_service, "DRIVE_RESUMABLE_CHUNK_BYTES", 4)+ source = tmp_path / "payload.bin"+ source.write_bytes(b"abcdefgh")+ session_uri = "https://www.googleapis.com/upload/session"+ chunk_ranges: list[str] = []+ query_calls = 0++ async def handler(request: httpx.Request) -> httpx.Response:+ nonlocal query_calls+ if request.method == "POST":+ return httpx.Response(200, headers={"Location": session_uri})+ content_range = request.headers["Content-Range"]+ if content_range == "bytes */8":+ query_calls += 1+ return httpx.Response(308, headers={"Range": "bytes=0-3"})++ chunk_ranges.append(content_range)+ return httpx.Response(+ 403,+ json={"error": {"message": "forbidden", "errors": [{"reason": "insufficientPermissions"}]}},+ )++ _install_google_drive_transport(monkeypatch, handler)++ with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:+ await google_drive_service.upload_file(+ access_token="at-1",+ file_path=str(source),+ folder_id="folder_123",+ )++ assert exc_info.value.status == 403+ assert query_calls == 0+ assert chunk_ranges == ["bytes 0-3/8"]+++async def test_google_drive_resumable_commit_but_response_lost_does_not_exhaust(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)+ monkeypatch.setattr(google_drive_service, "DRIVE_RESUMABLE_CHUNK_BYTES", 2)+ monkeypatch.setattr(google_drive_service.settings, "GOOGLE_DRIVE_API_MAX_RETRIES", 3)+ source = tmp_path / "payload.bin"+ file_bytes = b"abcdefgh"+ source.write_bytes(file_bytes)+ session_uri = "https://www.googleapis.com/upload/session"+ committed_offset = 0+ chunk_calls = 0+ query_calls = 0++ async def handler(request: httpx.Request) -> httpx.Response:+ nonlocal chunk_calls, committed_offset, query_calls+ if request.method == "POST":+ return httpx.Response(200, headers={"Location": session_uri})+ content_range = request.headers["Content-Range"]+ if content_range == f"bytes */{len(file_bytes)}":+ query_calls += 1+ if committed_offset == len(file_bytes):+ return httpx.Response(200, json={"id": "file_committed"})+ return httpx.Response(308, headers={"Range": f"bytes=0-{committed_offset - 1}"})++ chunk_calls += 1+ start_text, remainder = content_range.removeprefix("bytes ").split("-", 1)+ end_text = remainder.split("/", 1)[0]+ assert int(start_text) == committed_offset+ committed_offset = int(end_text) + 1+ raise httpx.ReadTimeout("read timed out", request=request)++ _install_google_drive_transport(monkeypatch, handler)++ uploaded = await google_drive_service.upload_file(+ access_token="at-1",+ file_path=str(source),+ folder_id="folder_123",+ )++ assert uploaded.id == "file_committed"+ assert chunk_calls == 4+ assert query_calls == 4+++async def test_google_drive_resumable_final_chunk_completion_reconciled_after_lost_response(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)+ monkeypatch.setattr(google_drive_service, "DRIVE_RESUMABLE_CHUNK_BYTES", 4)+ monkeypatch.setattr(google_drive_service.settings, "GOOGLE_DRIVE_API_MAX_RETRIES", 1)+ source = tmp_path / "payload.bin"+ file_bytes = b"abcdefgh"+ source.write_bytes(file_bytes)+ session_uri = "https://www.googleapis.com/upload/session"+ chunk_ranges: list[str] = []+ query_calls = 0++ async def handler(request: httpx.Request) -> httpx.Response:+ nonlocal query_calls+ if request.method == "POST":+ return httpx.Response(200, headers={"Location": session_uri})+ content_range = request.headers["Content-Range"]+ if content_range == f"bytes */{len(file_bytes)}":+ query_calls += 1+ return httpx.Response(200, json={"id": "file_completed"})++ chunk_ranges.append(content_range)+ if content_range == f"bytes 0-3/{len(file_bytes)}":+ return httpx.Response(308, headers={"Range": "bytes=0-3"})+ assert content_range == f"bytes 4-7/{len(file_bytes)}"+ raise httpx.ReadTimeout("read timed out", request=request)++ _install_google_drive_transport(monkeypatch, handler)++ uploaded = await google_drive_service.upload_file(+ access_token="at-1",+ file_path=str(source),+ folder_id="folder_123",+ )++ assert uploaded.id == "file_completed"+ assert query_calls == 1+ assert chunk_ranges == ["bytes 0-3/8", "bytes 4-7/8"]+++async def test_google_drive_resumable_non_advancing_308_bails(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)+ monkeypatch.setattr(google_drive_service, "DRIVE_RESUMABLE_CHUNK_BYTES", 4)+ monkeypatch.setattr(google_drive_service.settings, "GOOGLE_DRIVE_API_MAX_RETRIES", 2)+ source = tmp_path / "payload.bin"+ source.write_bytes(b"abcdefgh")+ session_uri = "https://www.googleapis.com/upload/session"+ chunk_calls = 0++ async def handler(request: httpx.Request) -> httpx.Response:+ nonlocal chunk_calls+ if request.method == "POST":+ return httpx.Response(200, headers={"Location": session_uri})+ chunk_calls += 1+ return httpx.Response(308, headers={"Range": "bytes=0-3"})++ _install_google_drive_transport(monkeypatch, handler)+ sleep_mock = AsyncMock()+ monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)++ with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:+ await asyncio.wait_for(+ google_drive_service.upload_file(+ access_token="at-1",+ file_path=str(source),+ folder_id="folder_123",+ ),+ timeout=1,+ )++ assert exc_info.value.status == 503+ assert exc_info.value.code == "resumable_upload_failed"+ assert chunk_calls == 3+ sleep_mock.assert_awaited_once_with(1.0)+++async def test_google_drive_resumable_malformed_range_after_progress_does_not_rewind(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)+ monkeypatch.setattr(google_drive_service, "DRIVE_RESUMABLE_CHUNK_BYTES", 4)+ monkeypatch.setattr(google_drive_service.settings, "GOOGLE_DRIVE_API_MAX_RETRIES", 2)+ source = tmp_path / "payload.bin"+ source.write_bytes(b"abcdefgh")+ session_uri = "https://www.googleapis.com/upload/session"+ content_ranges: list[str] = []++ async def handler(request: httpx.Request) -> httpx.Response:+ if request.method == "POST":+ return httpx.Response(200, headers={"Location": session_uri})+ content_ranges.append(request.headers["Content-Range"])+ if len(content_ranges) == 1:+ return httpx.Response(308, headers={"Range": "bytes=0-3"})+ return httpx.Response(308)++ _install_google_drive_transport(monkeypatch, handler)+ sleep_mock = AsyncMock()+ monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)++ with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:+ await google_drive_service.upload_file(+ access_token="at-1",+ file_path=str(source),+ folder_id="folder_123",+ )++ assert exc_info.value.code == "resumable_upload_failed"+ assert content_ranges == ["bytes 0-3/8", "bytes 4-7/8", "bytes 4-7/8"]+ sleep_mock.assert_awaited_once_with(1.0)+++async def test_google_drive_resumable_query_reports_already_complete(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)+ monkeypatch.setattr(google_drive_service, "DRIVE_RESUMABLE_CHUNK_BYTES", 4)+ source = tmp_path / "payload.bin"+ file_bytes = b"abcdefgh"+ source.write_bytes(file_bytes)+ session_uri = "https://www.googleapis.com/upload/session"+ chunk_ranges: list[str] = []+ query_calls = 0++ async def handler(request: httpx.Request) -> httpx.Response:+ nonlocal query_calls+ if request.method == "POST":+ return httpx.Response(200, headers={"Location": session_uri})+ content_range = request.headers["Content-Range"]+ if content_range == f"bytes */{len(file_bytes)}":+ query_calls += 1+ return httpx.Response(200, json={"id": "file_already_complete"})++ chunk_ranges.append(content_range)+ if content_range == f"bytes 0-3/{len(file_bytes)}":+ return httpx.Response(308, headers={"Range": "bytes=0-3"})+ raise httpx.ReadTimeout("read timed out", request=request)++ _install_google_drive_transport(monkeypatch, handler)++ uploaded = await google_drive_service.upload_file(+ access_token="at-1",+ file_path=str(source),+ folder_id="folder_123",+ )++ assert uploaded.id == "file_already_complete"+ assert query_calls == 1+ assert chunk_ranges == ["bytes 0-3/8", "bytes 4-7/8"]+++async def test_google_drive_resumable_exhausts_attempts_raises(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ monkeypatch.setattr(google_drive_service, "DRIVE_MULTIPART_FILE_MAX_BYTES", 1)+ monkeypatch.setattr(google_drive_service, "DRIVE_RESUMABLE_CHUNK_BYTES", 4)+ monkeypatch.setattr(google_drive_service.settings, "GOOGLE_DRIVE_API_MAX_RETRIES", 3)+ source = tmp_path / "payload.bin"+ source.write_bytes(b"abcdefgh")+ session_uri = "https://www.googleapis.com/upload/session"+ chunk_calls = 0+ query_calls = 0++ async def handler(request: httpx.Request) -> httpx.Response:+ nonlocal chunk_calls, query_calls+ if request.method == "POST":+ return httpx.Response(200, headers={"Location": session_uri})+ if request.headers["Content-Range"] == "bytes */8":+ query_calls += 1+ raise httpx.ReadTimeout("status query timed out", request=request)+ chunk_calls += 1raise httpx.ReadTimeout("read timed out", request=request)_install_google_drive_transport(monkeypatch, handler)+ sleep_mock = AsyncMock()+ monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:await google_drive_service.upload_file(@@ -652,9 +1221,12 @@ async def test_google_drive_resumable_put_does_not_retry_read_timeout(folder_id="folder_123",)- assert exc_info.value.code == "ambiguous_upload_status"- assert post_calls == 1- assert put_calls == 1+ assert exc_info.value.status == 503+ assert exc_info.value.code == "resumable_upload_failed"+ assert chunk_calls == 1+ assert query_calls == 3+ sleep_mock.assert_has_awaits([call(1.0), call(2.0)])+ assert sleep_mock.await_count == 2@pytest.mark.asyncio