Skip to content

Automate browser based workflows with AI

Stream large captured downloads to disk instead of replaying the body (SKY-12642) (#7804)

LawyZhengb3537036e570
diff --git a/skyvern/webeye/cdp_download_interceptor.py b/skyvern/webeye/cdp_download_interceptor.py
index 67b1262a4..71b925bfc 100644
--- a/skyvern/webeye/cdp_download_interceptor.py
+++ b/skyvern/webeye/cdp_download_interceptor.py
@@ -31,8 +31,9 @@ import urllib.request
import uuid
from collections.abc import AsyncIterator, Coroutine
from contextlib import asynccontextmanager
+from dataclasses import dataclass
from pathlib import Path
-from typing import Any
+from typing import IO, Any, Literal
from urllib.parse import unquote, urlparse
import structlog
@@ -64,12 +65,53 @@ def _own_detached_disable(task: asyncio.Task[None]) -> None:
task.add_done_callback(_retrieve_detached_disable_exception)
-# Chunk size for IO.read streaming
-IO_READ_CHUNK_SIZE = 64 * 1024 # 64 KB
-
-# Maximum file size we'll attempt to download
+# Maximum file size we'll attempt to download (data-url / direct-url / blob capture paths)
MAX_FILE_SIZE_BYTES = 100 * 1024 * 1024 # 100 MB
+# At/above this size a captured download is streamed straight to a temp file and the browser is
+# fulfilled with an empty body, instead of buffering the whole body in RAM and base64-replaying it —
+# which can OOM the browser target (SKY-12642). Set just below the largest download that completed on
+# the local browser stack (~67.6 MiB); larger PDFs crashed that local native-download stack,
+# and a separate local harness reproduced the interceptor replay materializing ~4/3x the body as base64.
+# Those are local-stack / replay-harness observations, not interceptor-path production measurements.
+STREAM_TO_DISK_THRESHOLD_BYTES = 64 * 1024 * 1024 # 64 MiB
+# Hard ceiling for a streamed captured download. Above this we abort: clean up the temp file, save no
+# artifact, and fail the paused request so the browser neither hangs nor materializes the body.
+MAX_STREAMED_FILE_SIZE_BYTES = 512 * 1024 * 1024 # 512 MiB
+# IO.read chunk size for the streaming path — larger than a per-page render buffer to cut CDP round
+# trips on large files (the cdp_proxy websocket is max_size=None, base64 inflation stays well bounded).
+STREAM_IO_READ_CHUNK_SIZE = 256 * 1024 # 256 KiB
+# Inactivity bound applied to every CDP send made while holding the single-active extraction lock —
+# takeResponseBodyAsStream, each IO.read, fulfill (body replay or empty), failRequest, and IO.close. A
+# healthy call completes well within this even over a slow remote-CDP transport; one that stalls past it is
+# treated as dead so the extraction aborts instead of holding the lock forever (which would deadlock later
+# captures and hang teardown's task drain).
+STREAM_IO_READ_TIMEOUT_SECONDS = 120.0
+
+
+@dataclass
+class _StreamOutcome:
+ """Result of streaming a captured response body. `streamed` = already on disk (empty-body fulfill);
+ `buffered` = held in memory below the threshold (legacy full replay)."""
+
+ mode: Literal["buffered", "streamed"]
+ data: bytes | None
+ save_path: Path | None
+ total_bytes: int
+
+
+class _StreamStartError(Exception):
+ """Fetch.takeResponseBodyAsStream failed before any body bytes were consumed (body not taken)."""
+
+
+class _StreamAborted(Exception):
+ """A streamed download exceeded MAX_STREAMED_FILE_SIZE_BYTES; its temp file was cleaned up."""
+
+ def __init__(self, total_bytes: int) -> None:
+ super().__init__(f"streamed download exceeded {MAX_STREAMED_FILE_SIZE_BYTES} bytes ({total_bytes} read)")
+ self.total_bytes = total_bytes
+
+
# Resource types that should NEVER be treated as downloads.
# Sub-resources (Font, Stylesheet, etc.) are loaded by the page, not user-initiated.
# Real user downloads come through as "Document" (link click / navigation).
@@ -507,6 +549,10 @@ class CDPDownloadInterceptor:
# Track URLs already downloaded (dedup between Fetch interception and browser download monitor)
self._downloaded_urls: set[str] = set()
self._data_download_lock = asyncio.Lock()
+ # Serialize CDP download body extraction: at most one capture streams/buffers at a time per
+ # interceptor, so concurrent large downloads cannot each write up to the cap and exhaust the
+ # worker's ephemeral disk. Bounds in-flight disk use to a single capture (<= the stream cap).
+ self._download_extraction_lock = asyncio.Lock()
self._browser_download_monitor_lock = asyncio.Lock()
self._browser_download_tasks: set[asyncio.Task[None]] = set()
self._browser_download_generation = 0
@@ -519,6 +565,10 @@ class CDPDownloadInterceptor:
self._page_enable_tasks: set[asyncio.Task[None]] = set()
self._accepting_pages = False
self._cdp_handler_tasks: set[asyncio.Task[None]] = set()
+ # Bumped when a Fetch handler is scheduled; settle drains these to quiescence (a download capture
+ # runs inside one, and a just-scheduled handler may not have created its .crdownload yet) so
+ # artifact collection can't finalize before a queued/scheduled capture lands and omit it.
+ self._cdp_handler_generation = 0
self._accepting_cdp_handlers = True
def set_download_dir(self, download_dir: str) -> None:
@@ -813,7 +863,7 @@ class CDPDownloadInterceptor:
LOG.debug("Data URL already captured, skipping", identity=download_identity)
return False
save_path, filename = self._resolve_save_path(suggested_filename, content_type)
- _, cancelled = await self._run_data_worker(self._atomically_write_data_url, save_path, data)
+ _, cancelled = await self._run_data_worker(self._atomically_write_bytes, save_path, data)
# A rebind may have cleared the dedupe set and repointed _output_dir while this write
# was off-loop. The file published into save_path's dir; only record its identity if
# that dir is still the current scope, else it would skip an identical download in the
@@ -856,7 +906,7 @@ class CDPDownloadInterceptor:
return _download_identity(url), content_type, data
@staticmethod
- def _atomically_write_data_url(save_path: Path, data: bytes | bytearray) -> None:
+ def _atomically_write_bytes(save_path: Path, data: bytes | bytearray) -> None:
temporary_path = save_path.with_name(f"{save_path.name}.{uuid.uuid4().hex}{BROWSER_DOWNLOADING_SUFFIX}")
try:
with open(temporary_path, "wb") as file:
@@ -1019,6 +1069,16 @@ class CDPDownloadInterceptor:
suggested_filename=suggested_filename,
)
return
+ # An empty blob must never be persisted: _resolve_save_path overwrites on filename collision, so
+ # a 0-byte blob re-emitted with the same name as a just-captured download (which the large-response
+ # empty-body fulfill can trigger) would truncate the real artifact to zero bytes (SKY-12642).
+ if not data:
+ LOG.warning(
+ "Blob download is empty, skipping to avoid clobbering a captured artifact",
+ url=url,
+ suggested_filename=suggested_filename,
+ )
+ return
# Defense-in-depth: read_blob_url_bytes already rejects oversized blobs in-page before
# serialization, but guard again in case a caller passes no limit.
if len(data) > MAX_FILE_SIZE_BYTES:
@@ -1119,10 +1179,27 @@ class CDPDownloadInterceptor:
async def _drain_browser_downloads_to_quiescence(self) -> None:
while True:
generation = self._browser_download_generation
+ cdp_generation = self._cdp_handler_generation
if self._browser_download_tasks:
await asyncio.gather(*tuple(self._browser_download_tasks), return_exceptions=True)
+ # A download capture runs inside a _cdp_handler_task, and a second Fetch.requestPaused may be
+ # scheduled but not yet classified as a download (no .crdownload yet → invisible to the
+ # file-snapshot waiter). Wait for in-flight/scheduled handlers too, or collection could finalize
+ # before a queued/just-scheduled capture lands and omit it. Use a NON-cancelling wait: a
+ # settle-timeout cancellation here must never cancel a handler task — gather would cancel its
+ # children and destroy an in-flight capture's temp file. Only teardown (which follows with
+ # Fetch.disable) may cancel handlers. The per-call send/read/close timeouts keep a dead handler
+ # from making this hang.
+ cdp_snapshot = tuple(self._cdp_handler_tasks)
+ if cdp_snapshot:
+ await asyncio.wait(cdp_snapshot)
await asyncio.sleep(0)
- if generation == self._browser_download_generation and not self._browser_download_tasks:
+ if (
+ generation == self._browser_download_generation
+ and cdp_generation == self._cdp_handler_generation
+ and not self._browser_download_tasks
+ and not self._cdp_handler_tasks
+ ):
return
def _schedule_browser_download_handler(self, event: dict[str, Any]) -> None:
@@ -1145,6 +1222,7 @@ class CDPDownloadInterceptor:
if not self._accepting_cdp_handlers:
handler.close()
return
+ self._cdp_handler_generation += 1
task = asyncio.create_task(handler)
self._cdp_handler_tasks.add(task)
task.add_done_callback(self._cdp_handler_done)
@@ -1305,7 +1383,11 @@ class CDPDownloadInterceptor:
response_status: int,
raw_response_headers: list[dict[str, str]],
) -> None:
- """Extract a download file, save it to disk, and replay the response to the browser."""
+ """Capture a download to disk and complete the browser side.
+
+ Small responses (< STREAM_TO_DISK_THRESHOLD_BYTES) are buffered and replayed to the browser
+ unchanged. Large responses stream straight to a temp file and are fulfilled with an empty body,
+ so the browser never materializes a large base64 payload (the OOM in SKY-12642)."""
if not self._output_dir:
LOG.warning("CDP download intercepted but no output_dir set, passing through", url=url)
await self._continue_response(cdp_session, request_id)
@@ -1324,44 +1406,194 @@ class CDPDownloadInterceptor:
content_length=content_length,
)
- if content_length and content_length > MAX_FILE_SIZE_BYTES:
- LOG.warning(
- "CDP download file exceeds size limit, passing through",
+ # Mark URL as handled up front — BEFORE the oversized-by-header fast-fail and the (potentially
+ # slow) body extraction — so the browser download monitor (_handle_browser_download) never races
+ # to re-fetch the same URL via _download_url_directly, which reads the whole body before its own
+ # size check and would materialize an oversized payload the cap exists to block. We intentionally
+ # do NOT remove the URL on failure: if Fetch handling fails or we abort an oversized response, a
+ # direct HTTP re-download would fail or OOM too.
+ self._downloaded_urls.add(url)
+
+ # Known oversized by header: fail fast without streaming. Streaming a lying/huge Content-Length
+ # up to the cap before aborting would waste minutes over CDP and amplify page-JS retry loops.
+ if content_length is not None and content_length > MAX_STREAMED_FILE_SIZE_BYTES:
+ LOG.error(
+ "CDP download exceeds stream cap (by Content-Length), failing request",
filename=filename,
content_length=content_length,
- max_size=MAX_FILE_SIZE_BYTES,
+ cap=MAX_STREAMED_FILE_SIZE_BYTES,
)
- await self._continue_response(cdp_session, request_id)
+ await self._fail_request(cdp_session, request_id, filename=filename, url=url)
return
- # Mark URL as handled BEFORE starting the (potentially slow) body extraction.
- # This prevents the browser download monitor (_handle_browser_download) from
- # racing to download the same URL while we're still streaming the body.
- # We intentionally do NOT remove the URL on failure — if Fetch extraction fails,
- # a direct HTTP re-download of the same URL would likely fail too.
- self._downloaded_urls.add(url)
-
t0 = time.monotonic()
- try:
- # Stream-first strategy: try takeResponseBodyAsStream, fallback to getResponseBody.
- # Note: if stream partially consumes the body before failing, the direct fallback
- # will also fail since the body is already consumed. The outer handler catches this.
- extraction_method = "stream"
+ # Known-large → stream to disk from the first chunk. Unknown/known-small → buffer, but spill to
+ # disk the instant streamed bytes cross the threshold (never assume a missing/lying size is small).
+ start_on_disk = content_length is not None and content_length >= STREAM_TO_DISK_THRESHOLD_BYTES
+
+ # Serialize extraction so only one download streams/buffers at a time per interceptor: concurrent
+ # captures cannot each write up to the cap and exhaust the worker's ephemeral disk. This capture
+ # runs inside a _cdp_handler_task, which settle drains to quiescence — so a queued/scheduled capture
+ # is waited on before artifact collection even before it owns a .crdownload. The lock releases on
+ # every exit (success, error, abort, cancellation).
+ async with self._download_extraction_lock:
try:
- data = await self._extract_body_stream(cdp_session, request_id)
+ try:
+ outcome = await self._stream_response_body(
+ cdp_session, request_id, save_path, start_on_disk=start_on_disk
+ )
+ except _StreamAborted as e:
+ LOG.error(
+ "CDP download exceeds stream cap, aborting",
+ filename=filename,
+ url=url,
+ total_bytes=e.total_bytes,
+ cap=MAX_STREAMED_FILE_SIZE_BYTES,
+ )
+ await self._fail_request(cdp_session, request_id, filename=filename, url=url)
+ return
+ except _StreamStartError as e:
+ # The body was never taken. We do NOT fall back to getResponseBody: it returns the whole
+ # decoded body in one shot, so a lying/understated Content-Length could materialize an
+ # unbounded payload and OOM the process — the exact failure this streaming path removes.
+ # Fail the request instead so nothing is ever materialized.
+ LOG.error(
+ "takeResponseBodyAsStream failed, failing request (no whole-body fallback)",
+ filename=filename,
+ url=url,
+ error=str(e.__cause__ or e),
+ )
+ await self._fail_request(cdp_session, request_id, filename=filename, url=url)
+ return
+ except asyncio.CancelledError:
+ # _stream_response_body's finally already removed any temp file. Never perform I/O during
+ # cancellation; the following Fetch.disable tears the paused request down.
+ raise
except Exception as e:
- extraction_method = "direct"
- LOG.warning(
- "takeResponseBodyAsStream failed, trying getResponseBody",
+ # The stream was taken and then failed mid-body (body consumed → continueResponse invalid).
+ LOG.error(
+ "Failed to extract CDP download",
filename=filename,
url=url,
+ content_type=content_type,
+ content_length=content_length,
error=str(e),
+ exc_info=True,
)
- data = await self._extract_body_direct(cdp_session, request_id)
+ await self._fail_request(cdp_session, request_id, filename=filename, url=url)
+ return
+
+ await self._finalize_download(
+ cdp_session, request_id, response_status, raw_response_headers, outcome, save_path, filename, url, t0
+ )
+
+ async def _fulfill_with_body(
+ self,
+ cdp_session: CDPSession,
+ request_id: str,
+ response_status: int,
+ raw_response_headers: list[dict[str, str]],
+ body: bytes,
+ ) -> None:
+ """Fulfill a request by replaying the original response with the extracted body.
+
+ This allows both server-side capture AND browser-side download to happen.
+ """
+ await asyncio.wait_for(
+ cdp_session.send(
+ "Fetch.fulfillRequest",
+ {
+ "requestId": request_id,
+ "responseCode": response_status,
+ "responseHeaders": raw_response_headers,
+ "body": base64.b64encode(body).decode(),
+ },
+ ),
+ timeout=STREAM_IO_READ_TIMEOUT_SECONDS,
+ )
+
+ async def _fulfill_without_body(
+ self,
+ cdp_session: CDPSession,
+ request_id: str,
+ response_status: int,
+ raw_response_headers: list[dict[str, str]],
+ ) -> None:
+ """Fulfill a captured download with an empty body (Content-Length forced to 0).
+
+ The bytes are already on disk and the browser download is denied, so the browser never needs
+ them. A stale non-zero Content-Length — or a Content-Encoding/Transfer-Encoding for a body that
+ is not there — would make the browser wait for or try to decode bytes that never arrive, so
+ those headers are dropped. Content-Disposition is deliberately kept: dropping it turns an empty
+ 200 on a Document request into a committed navigation to a blank page.
+ """
+ dropped = {"content-length", "content-encoding", "transfer-encoding", "content-range"}
+ response_headers = [h for h in raw_response_headers if h.get("name", "").lower() not in dropped]
+ response_headers.append({"name": "Content-Length", "value": "0"})
+ await asyncio.wait_for(
+ cdp_session.send(
+ "Fetch.fulfillRequest",
+ {
+ "requestId": request_id,
+ "responseCode": response_status,
+ "responseHeaders": response_headers,
+ "body": "",
+ },
+ ),
+ timeout=STREAM_IO_READ_TIMEOUT_SECONDS,
+ )
+
+ async def _fail_request(
+ self,
+ cdp_session: CDPSession,
+ request_id: str,
+ *,
+ filename: str = "",
+ url: str = "",
+ error_reason: str = "Aborted",
+ ) -> None:
+ """Terminate a paused download whose body was taken or is oversized.
- with open(save_path, "wb") as f:
- f.write(data)
+ Once the response body stream is taken, Fetch.continueResponse is invalid, so failRequest is the
+ sanctioned way to end the request without a hung Fetch or browser materialization. errorReason
+ "Aborted" makes an aborted Document navigation silently ignored rather than painting an error page.
+ """
+ try:
+ await asyncio.wait_for(
+ cdp_session.send("Fetch.failRequest", {"requestId": request_id, "errorReason": error_reason}),
+ timeout=STREAM_IO_READ_TIMEOUT_SECONDS,
+ )
+ except Exception as e:
+ if _is_stale_interception_error(e):
+ LOG.debug("failRequest hit stale interception (benign race)", filename=filename, url=url, error=str(e))
+ else:
+ LOG.warning("failRequest failed", filename=filename, url=url, error=str(e))
+
+ async def _finalize_download(
+ self,
+ cdp_session: CDPSession,
+ request_id: str,
+ response_status: int,
+ raw_response_headers: list[dict[str, str]],
+ outcome: _StreamOutcome,
+ save_path: Path,
+ filename: str,
+ url: str,
+ t0: float,
+ ) -> None:
+ """Persist a buffered body (if any) and complete the browser side: empty fulfill for large
+ downloads, full replay for small ones."""
+ if outcome.mode == "buffered":
+ data = outcome.data or b""
+ try:
+ # Off-loop the write so a large buffered body never blocks the event loop,
+ # matching the data-URL path (_download_data_url).
+ _, cancelled = await self._run_data_worker(self._atomically_write_bytes, save_path, data)
+ except Exception as e:
+ LOG.error("Failed to save CDP download", filename=filename, url=url, error=str(e), exc_info=True)
+ await self._fail_request(cdp_session, request_id, filename=filename, url=url)
+ return
elapsed_ms = (time.monotonic() - t0) * 1000
LOG.info(
"CDP download saved",
@@ -1369,33 +1601,33 @@ class CDPDownloadInterceptor:
size=len(data),
duration_ms=round(elapsed_ms, 1),
save_path=str(save_path),
- extraction_method=extraction_method,
+ extraction_method="buffered",
download_index=self._download_index,
)
-
- except Exception as e:
- LOG.error(
- "Failed to extract CDP download",
+ if cancelled:
+ raise asyncio.CancelledError
+ body: bytes | None = data
+ else:
+ elapsed_ms = (time.monotonic() - t0) * 1000
+ LOG.info(
+ "CDP download saved",
filename=filename,
- url=url,
- content_type=content_type,
- content_length=content_length,
- error=str(e),
- exc_info=True,
+ size=outcome.total_bytes,
+ duration_ms=round(elapsed_ms, 1),
+ save_path=str(save_path),
+ extraction_method="streamed",
+ download_index=self._download_index,
)
- try:
- await self._continue_response(cdp_session, request_id)
- except Exception:
- pass
- return
+ body = None
- # Replay the original response to the browser so it also gets the download.
- # After body extraction, we fulfill with the same status, headers, and body.
try:
- await self._fulfill_with_body(cdp_session, request_id, response_status, raw_response_headers, data)
+ if body is None:
+ await self._fulfill_without_body(cdp_session, request_id, response_status, raw_response_headers)
+ else:
+ await self._fulfill_with_body(cdp_session, request_id, response_status, raw_response_headers, body)
except Exception as e:
- # The file is already saved to disk at this point; only the browser-side replay failed.
- # A stale interception here (target navigated/closed) is a benign race, not an error.
+ # The file is already saved; only the browser-side completion failed. A stale interception
+ # here (target navigated/closed) is a benign race, not an error.
if _is_stale_interception_error(e):
LOG.debug(
"fulfillRequest hit stale interception after download (benign race)",
@@ -1406,56 +1638,58 @@ class CDPDownloadInterceptor:
else:
LOG.warning("fulfillRequest failed after download", filename=filename, url=url, error=str(e))
- async def _fulfill_with_body(
+ def _open_stream_temp_file(self, save_path: Path) -> tuple[Path, IO[bytes]]:
+ """Open a same-directory ``.crdownload`` temp file for streaming (atomic os.replace on finalize;
+ the suffix also makes the download waiter block until the stream completes)."""
+ temp_path = save_path.with_name(f"{save_path.name}.{uuid.uuid4().hex}{BROWSER_DOWNLOADING_SUFFIX}")
+ return temp_path, open(temp_path, "wb")
+
+ @staticmethod
+ def _write_chunks(handle: IO[bytes], chunks: list[bytes]) -> None:
+ for chunk in chunks:
+ handle.write(chunk)
+
+ async def _stream_response_body(
self,
cdp_session: CDPSession,
request_id: str,
- response_status: int,
- raw_response_headers: list[dict[str, str]],
- body: bytes,
- ) -> None:
- """Fulfill a request by replaying the original response with the extracted body.
-
- This allows both server-side capture AND browser-side download to happen.
- """
- await cdp_session.send(
- "Fetch.fulfillRequest",
- {
- "requestId": request_id,
- "responseCode": response_status,
- "responseHeaders": raw_response_headers,
- "body": base64.b64encode(body).decode(),
- },
- )
-
- async def _extract_body_direct(self, cdp_session: CDPSession, request_id: str) -> bytes:
- """Extract response body using Fetch.getResponseBody (single call, base64)."""
- result = await cdp_session.send(
- "Fetch.getResponseBody",
- {"requestId": request_id},
- )
- body = result.get("body", "")
- is_base64 = result.get("base64Encoded", False)
- if is_base64:
- return base64.b64decode(body)
- return body.encode("utf-8")
-
- async def _extract_body_stream(self, cdp_session: CDPSession, request_id: str) -> bytes:
- """Extract response body using Fetch.takeResponseBodyAsStream + IO.read."""
- result = await cdp_session.send(
- "Fetch.takeResponseBodyAsStream",
- {"requestId": request_id},
- )
- stream_handle = result["stream"]
+ save_path: Path,
+ *,
+ start_on_disk: bool,
+ ) -> _StreamOutcome:
+ """Read the response body via Fetch.takeResponseBodyAsStream + IO.read into either memory
+ (small) or a temp file (large), enforcing the threshold and hard cap.
+
+ Buffered chunks spill to a temp file the moment total bytes cross STREAM_TO_DISK_THRESHOLD_BYTES,
+ after which no whole-body ``bytes`` is ever built. Raises _StreamStartError if the stream can't be
+ taken (body untouched) and _StreamAborted if the cap is exceeded (temp cleaned up)."""
+ try:
+ result = await asyncio.wait_for(
+ cdp_session.send("Fetch.takeResponseBodyAsStream", {"requestId": request_id}),
+ timeout=STREAM_IO_READ_TIMEOUT_SECONDS,
+ )
+ stream_handle = result["stream"]
+ except Exception as e:
+ raise _StreamStartError() from e
- chunks: list[bytes] = []
- total_read = 0
+ buffer: list[bytes] | None = None if start_on_disk else []
+ temp_path: Path | None = None
+ temp_file: IO[bytes] | None = None
+ total = 0
try:
+ if start_on_disk:
+ temp_path, temp_file = self._open_stream_temp_file(save_path)
+
while True:
- read_result = await cdp_session.send(
- "IO.read",
- {"handle": stream_handle, "size": IO_READ_CHUNK_SIZE},
+ # Bound each read so a stalled IO.read can't hold the extraction lock (and hang teardown's
+ # drain) indefinitely; on timeout the stream is aborted and the temp cleaned up in finally.
+ read_result = await asyncio.wait_for(
+ cdp_session.send(
+ "IO.read",
+ {"handle": stream_handle, "size": STREAM_IO_READ_CHUNK_SIZE},
+ ),
+ timeout=STREAM_IO_READ_TIMEOUT_SECONDS,
)
data = read_result.get("data", "")
is_base64 = read_result.get("base64Encoded", False)
@@ -1463,23 +1697,61 @@ class CDPDownloadInterceptor:
if data:
chunk = base64.b64decode(data) if is_base64 else data.encode("utf-8")
- chunks.append(chunk)
- total_read += len(chunk)
-
- if total_read > MAX_FILE_SIZE_BYTES:
- LOG.warning("Stream exceeded max file size during read", total_read=total_read)
- break
+ total += len(chunk)
+ if total > MAX_STREAMED_FILE_SIZE_BYTES:
+ raise _StreamAborted(total)
+
+ if temp_file is None:
+ assert buffer is not None
+ buffer.append(chunk)
+ if total >= STREAM_TO_DISK_THRESHOLD_BYTES:
+ # Spill to disk: this one-shot flush writes the whole buffered ≤64 MiB in a
+ # single loop iteration (no interleaved IO.read await), so off-load it via
+ # _run_data_worker to keep it off the event loop. The worker is shielded, so
+ # on cancellation the write finishes before the sync finally removes the temp.
+ temp_path, temp_file = self._open_stream_temp_file(save_path)
+ spilled, buffer = buffer, None
+ _, cancelled = await self._run_data_worker(self._write_chunks, temp_file, spilled)
+ # Release the spilled chunks (up to the threshold) now they are on disk, so a
+ # slow subsequent stream never retains a whole buffered copy in memory.
+ del spilled
+ if cancelled:
+ raise asyncio.CancelledError
+ else:
+ temp_file.write(chunk)
if eof:
break
+
+ if temp_file is not None:
+ assert temp_path is not None # temp_file and temp_path are always opened together
+ temp_file.flush()
+ temp_file.close()
+ temp_file = None
+ os.replace(temp_path, save_path)
+ return _StreamOutcome(mode="streamed", data=None, save_path=save_path, total_bytes=total)
+ return _StreamOutcome(mode="buffered", data=b"".join(buffer or []), save_path=None, total_bytes=total)
finally:
+ # Sync cleanup first (uninterruptible): close the temp handle and remove any unfinalized temp
+ # file, so no partial artifact survives an error, abort, or cancellation. The unlink is
+ # unconditional — after os.replace the temp name no longer exists, so it is a missing_ok no-op.
+ if temp_file is not None:
+ try:
+ temp_file.close()
+ except Exception:
+ pass
+ if temp_path is not None:
+ temp_path.unlink(missing_ok=True)
try:
- await cdp_session.send("IO.close", {"handle": stream_handle})
+ # Bound the close too: if the session/target is dead (the same condition that stalls a
+ # read), an unbounded IO.close would hold the extraction lock and hang teardown's drain.
+ await asyncio.wait_for(
+ cdp_session.send("IO.close", {"handle": stream_handle}),
+ timeout=STREAM_IO_READ_TIMEOUT_SECONDS,
+ )
except Exception:
pass
- return b"".join(chunks)
-
@asynccontextmanager
async def settle_browser_downloads_for_context(browser_context: BrowserContext | None) -> AsyncIterator[None]:
diff --git a/tests/unit/test_cdp_download_interceptor.py b/tests/unit/test_cdp_download_interceptor.py
index aac032dfb..2bf5cf5f8 100644
--- a/tests/unit/test_cdp_download_interceptor.py
+++ b/tests/unit/test_cdp_download_interceptor.py
@@ -1,7 +1,12 @@
"""Unit tests for CDPDownloadInterceptor pure functions and proxy auth handling."""
+import ast
import asyncio
+import base64
+import contextlib
import gc
+import inspect
+import textwrap
import threading
import weakref
from pathlib import Path
@@ -939,6 +944,37 @@ class TestBlobDownloadCapture:
read.assert_not_awaited()
assert list(tmp_path.iterdir()) == []
+ @pytest.mark.asyncio
+ async def test_empty_blob_does_not_clobber_captured_artifact(self, tmp_path: Path) -> None:
+ # A large-response empty-body fulfill can make page JS re-emit a 0-byte blob with the same
+ # suggestedFilename as a just-captured real download. Since _resolve_save_path overwrites on
+ # collision, an empty blob must never be persisted — else it truncates the real artifact.
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ interceptor._browser_context = self._context()
+ real_bytes = b"%PDF-1.4 real captured document bytes"
+ (tmp_path / "report.pdf").write_bytes(real_bytes)
+
+ with patch(self._READ_BLOB, new=AsyncMock(return_value=b"")):
+ await interceptor._handle_browser_download(
+ {"url": "blob:https://example.com/empty", "suggestedFilename": "report.pdf"}
+ )
+
+ assert (tmp_path / "report.pdf").read_bytes() == real_bytes
+ assert [p.name for p in tmp_path.iterdir()] == ["report.pdf"]
+
+ @pytest.mark.asyncio
+ async def test_empty_blob_writes_no_artifact(self, tmp_path: Path) -> None:
+ # A genuinely empty blob is not a useful download and is skipped (no 0-byte file created).
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ interceptor._browser_context = self._context()
+
+ with patch(self._READ_BLOB, new=AsyncMock(return_value=b"")):
+ await interceptor._handle_browser_download(
+ {"url": "blob:https://example.com/empty2", "suggestedFilename": "x.pdf"}
+ )
+
+ assert list(tmp_path.iterdir()) == []
+
class TestDataUrlDownloadCapture:
@pytest.mark.asyncio
@@ -2192,3 +2228,540 @@ class TestDownloadDirRebindDedup:
await interceptor._handle_browser_download(event)
assert (target / "note.txt").read_bytes() == b"hello"
assert len(interceptor._downloaded_urls) == 1
+
+
+class _StreamCDP:
+ """Fake CDP session that dispatches Fetch/IO calls by method, for _handle_download streaming tests.
+
+ IO.read emits the configured `chunks` one per call (last one carries eof), so a chunk and eof can
+ arrive in the same message — mirroring real Chromium behavior.
+ """
+
+ def __init__(
+ self,
+ *,
+ chunks: list[bytes] | None = None,
+ take_error: BaseException | None = None,
+ stream_missing: bool = False,
+ read_error: BaseException | None = None,
+ read_error_after: int = 0,
+ getbody: bytes | None = None,
+ getbody_error: BaseException | None = None,
+ fulfill_error: BaseException | None = None,
+ read_hang: bool = False,
+ close_hang: bool = False,
+ take_hang: bool = False,
+ fulfill_hang: bool = False,
+ ) -> None:
+ self.calls: list[tuple[str, dict[str, Any]]] = []
+ self._chunks = list(chunks or [])
+ self._take_error = take_error
+ self._stream_missing = stream_missing
+ self._read_error = read_error
+ self._read_error_after = read_error_after
+ self._getbody = getbody
+ self._getbody_error = getbody_error
+ self._fulfill_error = fulfill_error
+ self._read_hang = read_hang
+ self._close_hang = close_hang
+ self._take_hang = take_hang
+ self._fulfill_hang = fulfill_hang
+ self._read_idx = 0
+
+ async def send(self, method: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
+ params = params or {}
+ self.calls.append((method, params))
+ if method == "Fetch.takeResponseBodyAsStream":
+ if self._take_hang:
+ await asyncio.Event().wait() # never returns — simulates a stalled stream-start
+ if self._take_error is not None:
+ raise self._take_error
+ return {} if self._stream_missing else {"stream": "handle-1"}
+ if method == "IO.read":
+ if self._read_hang:
+ await asyncio.Event().wait() # never returns — simulates a stalled CDP read
+ if self._read_error is not None and self._read_idx >= self._read_error_after:
+ raise self._read_error
+ if self._read_idx < len(self._chunks):
+ chunk = self._chunks[self._read_idx]
+ self._read_idx += 1
+ eof = self._read_idx >= len(self._chunks)
+ return {"data": base64.b64encode(chunk).decode(), "base64Encoded": True, "eof": eof}
+ return {"data": "", "base64Encoded": False, "eof": True}
+ if method == "IO.close":
+ if self._close_hang:
+ await asyncio.Event().wait() # never returns — simulates a stalled close on a dead session
+ return {}
+ if method == "Fetch.getResponseBody":
+ if self._getbody_error is not None:
+ raise self._getbody_error
+ if self._getbody is None:
+ raise RuntimeError("getResponseBody not configured")
+ return {"body": base64.b64encode(self._getbody).decode(), "base64Encoded": True}
+ if method == "Fetch.fulfillRequest":
+ if self._fulfill_hang:
+ await asyncio.Event().wait() # never returns — simulates a stalled fulfill on a dead session
+ if self._fulfill_error is not None:
+ raise self._fulfill_error
+ return {}
+ return {}
+
+ def count(self, method: str) -> int:
+ return sum(1 for m, _ in self.calls if m == method)
+
+ def last(self, method: str) -> dict[str, Any] | None:
+ for m, p in reversed(self.calls):
+ if m == method:
+ return p
+ return None
+
+
+def _raw_headers(
+ *,
+ content_length: int | None = None,
+ content_type: str = "application/pdf",
+ content_disposition: str | None = 'attachment; filename="doc.pdf"',
+ content_encoding: str | None = None,
+ transfer_encoding: str | None = None,
+ content_range: str | None = None,
+) -> list[dict[str, str]]:
+ raw: list[dict[str, str]] = []
+ if content_type:
+ raw.append({"name": "Content-Type", "value": content_type})
+ if content_disposition:
+ raw.append({"name": "Content-Disposition", "value": content_disposition})
+ if content_length is not None:
+ raw.append({"name": "Content-Length", "value": str(content_length)})
+ if content_encoding:
+ raw.append({"name": "Content-Encoding", "value": content_encoding})
+ if transfer_encoding:
+ raw.append({"name": "Transfer-Encoding", "value": transfer_encoding})
+ if content_range:
+ raw.append({"name": "Content-Range", "value": content_range})
+ return raw
+
+
+def _stream_limits(threshold: int = 1024, cap: int = 4096) -> Any:
+ """Shrink the stream threshold/cap so state-machine transitions can be tested on tiny payloads."""
+ with (
+ patch.object(mod, "STREAM_TO_DISK_THRESHOLD_BYTES", threshold),
+ patch.object(mod, "MAX_STREAMED_FILE_SIZE_BYTES", cap),
+ ):
+ yield
+
+
+async def _drive_download(
+ interceptor: CDPDownloadInterceptor,
+ cdp: _StreamCDP,
+ raw: list[dict[str, str]],
+ *,
+ url: str = "https://example.com/doc.pdf",
+ status: int = 200,
+) -> None:
+ await interceptor._handle_download(cdp, "req-1", url, mod._parse_headers(raw), status, raw) # type: ignore[arg-type]
+
+
+def _fulfill_body(cdp: _StreamCDP) -> str | None:
+ p = cdp.last("Fetch.fulfillRequest")
+ return None if p is None else p.get("body", "")
+
+
+def _fulfill_headers(cdp: _StreamCDP) -> dict[str, str]:
+ p = cdp.last("Fetch.fulfillRequest")
+ if p is None:
+ return {}
+ return {h["name"].lower(): h["value"] for h in p.get("responseHeaders", [])}
+
+
+def _only_file(tmp_path: Path) -> Path:
+ files = list(tmp_path.iterdir())
+ assert len(files) == 1, f"expected exactly one file, found {[f.name for f in files]}"
+ return files[0]
+
+
+async def _settle(interceptor: CDPDownloadInterceptor) -> None:
+ async with interceptor.settle_browser_downloads():
+ pass
+
+
+def test_finalize_download_has_no_dead_buffered_threshold_or_fallback_branch() -> None:
+ """A buffered outcome reaching _finalize_download is always below STREAM_TO_DISK_THRESHOLD_BYTES: the
+ stream loop spills to disk (→ "streamed") the instant total bytes cross the threshold, so the buffered
+ branch can never carry a body at/over the threshold or the removed getResponseBody-fallback cap. Guard
+ against reintroducing a dead re-check of either size constant or a reference to the removed fallback."""
+ source = inspect.getsource(CDPDownloadInterceptor._finalize_download)
+ referenced_names = {node.id for node in ast.walk(ast.parse(textwrap.dedent(source))) if isinstance(node, ast.Name)}
+ assert "MAX_STREAMED_FILE_SIZE_BYTES" not in referenced_names
+ assert "STREAM_TO_DISK_THRESHOLD_BYTES" not in referenced_names
+ assert "getResponseBody" not in source
+
+
+class TestTwoPathDownloadStreaming:
+ """SKY-12642: large captured downloads stream to a temp file and fulfill the browser with an empty
+ body; small ones keep the legacy buffer + full replay. Threshold/cap patched tiny per test."""
+
+ @pytest.mark.asyncio
+ async def test_small_body_buffered_full_replay(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ payload = b"A" * 500
+ cdp = _StreamCDP(chunks=[payload])
+ with _stream_limits():
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=500))
+
+ assert _only_file(tmp_path).read_bytes() == payload
+ assert _fulfill_body(cdp) == base64.b64encode(payload).decode() # full-body replay preserved
+ assert cdp.count("Fetch.getResponseBody") == 0
+ assert cdp.count("Fetch.failRequest") == 0
+
+ @pytest.mark.asyncio
+ async def test_at_threshold_streams_to_disk_empty_fulfill(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ payload = b"B" * 1024 # exactly the threshold → large path
+ cdp = _StreamCDP(chunks=[payload])
+ with _stream_limits(threshold=1024):
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=1024))
+
+ assert _only_file(tmp_path).read_bytes() == payload
+ assert _fulfill_body(cdp) == "" # empty body, no base64 replay
+ assert _fulfill_headers(cdp).get("content-length") == "0"
+ assert cdp.count("Fetch.failRequest") == 0
+
+ @pytest.mark.asyncio
+ async def test_above_threshold_known_large_streams(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ payload = b"C" * 2000
+ cdp = _StreamCDP(chunks=[b"C" * 800, b"C" * 800, b"C" * 400])
+ with _stream_limits(threshold=1024, cap=4096):
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=2000))
+
+ assert _only_file(tmp_path).read_bytes() == payload
+ assert _fulfill_body(cdp) == ""
+
+ @pytest.mark.asyncio
+ async def test_unknown_content_length_spills_to_disk(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ # No Content-Length: must not assume small. Buffers, then spills once bytes cross the threshold.
+ chunks = [b"D" * 400, b"D" * 400, b"D" * 400, b"D" * 400, b"D" * 400] # 2000 total
+ cdp = _StreamCDP(chunks=list(chunks))
+ with _stream_limits(threshold=1024, cap=4096):
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=None))
+
+ assert _only_file(tmp_path).read_bytes() == b"D" * 2000 # early buffered bytes preserved on spill
+ assert _fulfill_body(cdp) == ""
+
+ @pytest.mark.asyncio
+ async def test_lying_small_content_length_spills(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ # Header claims 100 bytes but the body is 2000 → must spill to the large path, not trust the header.
+ cdp = _StreamCDP(chunks=[b"E" * 700, b"E" * 700, b"E" * 600])
+ with _stream_limits(threshold=1024, cap=4096):
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=100))
+
+ assert _only_file(tmp_path).read_bytes() == b"E" * 2000
+ assert _fulfill_body(cdp) == ""
+
+ @pytest.mark.asyncio
+ async def test_lying_large_content_length_tiny_body_finalizes(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ # Header claims large (>= threshold) → disk path from chunk 1, but the actual body is tiny.
+ cdp = _StreamCDP(chunks=[b"F" * 300])
+ with _stream_limits(threshold=1024, cap=4096):
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=2000))
+
+ assert _only_file(tmp_path).read_bytes() == b"F" * 300
+ assert _fulfill_body(cdp) == ""
+ assert cdp.count("Fetch.failRequest") == 0
+
+ @pytest.mark.asyncio
+ async def test_cap_breach_unknown_cl_aborts_no_artifact(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ cdp = _StreamCDP(chunks=[b"G" * 1500, b"G" * 1500, b"G" * 1500, b"G" * 1500]) # 6000 > cap 4096
+ with _stream_limits(threshold=1024, cap=4096):
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=None))
+
+ assert list(tmp_path.iterdir()) == [] # no artifact, no leftover .crdownload temp
+ assert cdp.count("Fetch.failRequest") == 1
+ assert cdp.count("Fetch.fulfillRequest") == 0
+
+ @pytest.mark.asyncio
+ async def test_header_content_length_over_cap_fast_fails(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ cdp = _StreamCDP(chunks=[b"H" * 10])
+ with _stream_limits(threshold=1024, cap=4096):
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=5000)) # > cap
+
+ assert list(tmp_path.iterdir()) == []
+ assert cdp.count("Fetch.takeResponseBodyAsStream") == 0 # fast-fail without streaming
+ assert cdp.count("Fetch.failRequest") == 1
+
+ @pytest.mark.asyncio
+ async def test_header_content_length_over_cap_marks_url_handled(self, tmp_path: Path) -> None:
+ # The oversized-by-header fast-fail must still mark the URL handled, or a queued
+ # Browser.downloadWillBegin lets _handle_browser_download re-fetch it via _download_url_directly
+ # (which reads the whole body before its 100 MiB check) and materializes the very payload the cap
+ # exists to block (SKY-12642).
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ cdp = _StreamCDP(chunks=[b"H" * 10])
+ url = "https://example.com/huge.pdf"
+ with _stream_limits(threshold=1024, cap=4096):
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=5000), url=url) # > cap
+
+ assert cdp.count("Fetch.failRequest") == 1
+ assert interceptor._downloaded_urls == {url}
+
+ @pytest.mark.asyncio
+ async def test_midstream_read_error_cleans_temp_and_fails(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ # Known-large → disk path; the second IO.read raises after one chunk is on disk.
+ cdp = _StreamCDP(
+ chunks=[b"I" * 800, b"I" * 800, b"I" * 800],
+ read_error=RuntimeError("CDP IO.read boom"),
+ read_error_after=1,
+ )
+ with _stream_limits(threshold=1024, cap=4096):
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=2400))
+
+ assert list(tmp_path.iterdir()) == [] # partial temp cleaned up
+ assert cdp.count("Fetch.fulfillRequest") == 0
+ assert cdp.count("Fetch.failRequest") == 1
+
+ @pytest.mark.asyncio
+ async def test_cancelled_error_cleans_temp_and_propagates(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ cdp = _StreamCDP(
+ chunks=[b"J" * 800, b"J" * 800, b"J" * 800],
+ read_error=asyncio.CancelledError(),
+ read_error_after=1,
+ )
+ with _stream_limits(threshold=1024, cap=4096):
+ with pytest.raises(asyncio.CancelledError):
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=2400))
+
+ assert list(tmp_path.iterdir()) == [] # no partial artifact
+ assert cdp.count("Fetch.failRequest") == 0 # never do I/O during cancellation
+
+ @pytest.mark.asyncio
+ async def test_streamed_empty_fulfill_normalizes_headers(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ cdp = _StreamCDP(chunks=[b"K" * 2000])
+ raw = _raw_headers(
+ content_length=2000,
+ content_type="application/pdf",
+ content_disposition='attachment; filename="report.pdf"',
+ content_encoding="gzip",
+ transfer_encoding="chunked",
+ content_range="bytes 0-1999/2000",
+ )
+ with _stream_limits(threshold=1024, cap=8192):
+ await _drive_download(interceptor, cdp, raw)
+
+ h = _fulfill_headers(cdp)
+ assert h.get("content-length") == "0"
+ assert "content-encoding" not in h # empty body must not be content-decoded
+ assert "transfer-encoding" not in h
+ assert "content-range" not in h
+ assert h.get("content-disposition") == 'attachment; filename="report.pdf"' # MUST survive
+ assert h.get("content-type") == "application/pdf"
+
+ @pytest.mark.asyncio
+ async def test_stream_start_fail_fails_request_never_falls_back_to_whole_body(self, tmp_path: Path) -> None:
+ # takeResponseBodyAsStream failing must fail the request — we never fall back to getResponseBody,
+ # whose whole-body materialization could OOM on a lying/understated Content-Length (SKY-12642).
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ cdp = _StreamCDP(take_error=RuntimeError("takeResponseBodyAsStream unavailable"), getbody=b"L" * 300)
+ with _stream_limits(threshold=1024, cap=4096):
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=300))
+
+ assert list(tmp_path.iterdir()) == [] # nothing materialized or persisted
+ assert cdp.count("Fetch.getResponseBody") == 0 # whole-body fallback removed
+ assert cdp.count("Fetch.failRequest") == 1
+ assert cdp.count("Fetch.fulfillRequest") == 0
+
+ @pytest.mark.asyncio
+ async def test_stream_start_fail_with_content_encoding_no_direct_fallback(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ # Encoded small CL can decode to an unbounded body → getResponseBody would materialize it. Refuse.
+ cdp = _StreamCDP(take_error=RuntimeError("take failed"), getbody=b"L" * 300)
+ with _stream_limits(threshold=1024, cap=4096):
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=300, content_encoding="gzip"))
+
+ assert list(tmp_path.iterdir()) == []
+ assert cdp.count("Fetch.getResponseBody") == 0
+ assert cdp.count("Fetch.failRequest") == 1
+
+ @pytest.mark.asyncio
+ async def test_extraction_serialized_second_download_waits_for_lock(self, tmp_path: Path) -> None:
+ # Single-active guard: while one extraction holds the lock, a second _handle_download must block
+ # (not stream concurrently), so N parallel downloads cannot each write up to the cap to disk.
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ cdp = _StreamCDP(chunks=[b"A" * 200])
+ await interceptor._download_extraction_lock.acquire()
+ task = asyncio.create_task(_drive_download(interceptor, cdp, _raw_headers(content_length=200)))
+ await asyncio.sleep(0.05)
+ # Blocked on the lock: no extraction started, nothing written to disk.
+ assert not task.done()
+ assert cdp.count("Fetch.takeResponseBodyAsStream") == 0
+ assert list(tmp_path.iterdir()) == []
+ interceptor._download_extraction_lock.release()
+ await asyncio.wait_for(task, timeout=2)
+ assert _only_file(tmp_path).read_bytes() == b"A" * 200 # proceeds once serialized
+ assert not interceptor._download_extraction_lock.locked()
+
+ @pytest.mark.asyncio
+ async def test_extraction_lock_released_on_success_error_and_start_failure(self, tmp_path: Path) -> None:
+ # The single-active lock must be released on every exit path, or one failed download deadlocks all
+ # later downloads on this interceptor.
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ await _drive_download(interceptor, _StreamCDP(chunks=[b"S" * 100]), _raw_headers(content_length=100))
+ assert not interceptor._download_extraction_lock.locked() # success
+ with _stream_limits(threshold=1024, cap=4096):
+ await _drive_download(interceptor, _StreamCDP(chunks=[b"B" * 5000]), _raw_headers(content_length=None))
+ assert not interceptor._download_extraction_lock.locked() # cap abort
+ await _drive_download(interceptor, _StreamCDP(stream_missing=True), _raw_headers(content_length=100))
+ assert not interceptor._download_extraction_lock.locked() # stream-start failure
+
+ @pytest.mark.asyncio
+ async def test_settle_drains_scheduled_cdp_handler(self, tmp_path: Path) -> None:
+ # A capture runs inside a _cdp_handler_task (and a second Fetch.requestPaused may be scheduled but
+ # not yet classified as a download). settle drains those to quiescence, so a capture queued behind
+ # the lock — which owns no .crdownload yet — is still waited on before artifact collection instead
+ # of being silently omitted.
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ cdp = _StreamCDP(chunks=[b"Q" * 150])
+ await interceptor._download_extraction_lock.acquire() # hold the lock so the capture queues
+ interceptor._schedule_cdp_handler(_drive_download(interceptor, cdp, _raw_headers(content_length=150)))
+ await asyncio.sleep(0.05)
+ assert len(interceptor._cdp_handler_tasks) == 1 # scheduled + queued on the lock, no .crdownload yet
+ settling = asyncio.create_task(_settle(interceptor))
+ await asyncio.sleep(0.05)
+ assert not settling.done() # settle blocks while the scheduled handler is in flight
+ interceptor._download_extraction_lock.release()
+ await asyncio.wait_for(settling, timeout=2) # unblocks once the handler finishes
+ assert _only_file(tmp_path).read_bytes() == b"Q" * 150
+ assert not interceptor._cdp_handler_tasks # drained to quiescence
+
+ @pytest.mark.asyncio
+ async def test_stalled_close_times_out_and_releases_lock(self, tmp_path: Path) -> None:
+ # The IO.close cleanup is bounded too: a hung close on a dead session must not hold the extraction
+ # lock or hang teardown. The streamed file is already published, so the download still finalizes.
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ cdp = _StreamCDP(chunks=[b"C" * 2000], close_hang=True) # IO.close never returns
+ with _stream_limits(threshold=1024, cap=4096), patch.object(mod, "STREAM_IO_READ_TIMEOUT_SECONDS", 0.05):
+ await asyncio.wait_for(_drive_download(interceptor, cdp, _raw_headers(content_length=2000)), timeout=5)
+ assert _only_file(tmp_path).read_bytes() == b"C" * 2000 # saved despite the hung close
+ assert not interceptor._download_extraction_lock.locked()
+
+ @pytest.mark.asyncio
+ async def test_settle_cancellation_does_not_cancel_capture(self, tmp_path: Path) -> None:
+ # A settle-timeout cancellation must NOT cancel the in-flight/queued capture handlers (gather would,
+ # destroying the temp mid-stream); the capture keeps running and its artifact still lands.
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ cdp = _StreamCDP(chunks=[b"K" * 150])
+ await interceptor._download_extraction_lock.acquire() # hold the lock so the capture queues
+ interceptor._schedule_cdp_handler(_drive_download(interceptor, cdp, _raw_headers(content_length=150)))
+ await asyncio.sleep(0.05)
+ handler_task = next(iter(interceptor._cdp_handler_tasks))
+ settling = asyncio.create_task(_settle(interceptor))
+ await asyncio.sleep(0.05)
+ settling.cancel() # the outer download-timeout cancels settle
+ with pytest.raises(asyncio.CancelledError):
+ await settling
+ assert not handler_task.cancelled() # the capture survives the settle cancellation
+ interceptor._download_extraction_lock.release()
+ await asyncio.wait_for(handler_task, timeout=2)
+ assert _only_file(tmp_path).read_bytes() == b"K" * 150 # artifact lands, not destroyed
+
+ @pytest.mark.asyncio
+ async def test_stalled_take_stream_times_out_and_releases_lock(self, tmp_path: Path) -> None:
+ # takeResponseBodyAsStream on a dead session is bounded too: on timeout it becomes _StreamStartError
+ # → failRequest, so it can't hold the lock or hang settle's drain.
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ cdp = _StreamCDP(take_hang=True) # takeResponseBodyAsStream never returns
+ with _stream_limits(threshold=1024, cap=4096), patch.object(mod, "STREAM_IO_READ_TIMEOUT_SECONDS", 0.05):
+ await asyncio.wait_for(_drive_download(interceptor, cdp, _raw_headers(content_length=300)), timeout=5)
+ assert cdp.count("Fetch.failRequest") == 1
+ assert list(tmp_path.iterdir()) == []
+ assert not interceptor._download_extraction_lock.locked()
+
+ @pytest.mark.asyncio
+ async def test_stalled_fulfill_times_out_and_releases_lock(self, tmp_path: Path) -> None:
+ # A hung fulfillRequest (after the streamed file is already published) is bounded: the artifact is
+ # saved, the download still finalizes, and the lock is released.
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ cdp = _StreamCDP(chunks=[b"F" * 2000], fulfill_hang=True) # fulfillRequest never returns
+ with _stream_limits(threshold=1024, cap=4096), patch.object(mod, "STREAM_IO_READ_TIMEOUT_SECONDS", 0.05):
+ await asyncio.wait_for(_drive_download(interceptor, cdp, _raw_headers(content_length=2000)), timeout=5)
+ assert _only_file(tmp_path).read_bytes() == b"F" * 2000 # streamed artifact saved despite hung fulfill
+ assert not interceptor._download_extraction_lock.locked()
+
+ @pytest.mark.asyncio
+ async def test_stalled_read_times_out_and_releases_lock(self, tmp_path: Path) -> None:
+ # A stalled IO.read must not hold the extraction lock forever (which would deadlock later captures
+ # and hang teardown's drain). The per-read timeout aborts it, cleans the temp, and releases the lock.
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ cdp = _StreamCDP(read_hang=True) # IO.read never returns
+ with _stream_limits(threshold=1024, cap=4096), patch.object(mod, "STREAM_IO_READ_TIMEOUT_SECONDS", 0.05):
+ # Outer bound so a regression (no per-read timeout) fails fast instead of hanging the suite.
+ await asyncio.wait_for(_drive_download(interceptor, cdp, _raw_headers(content_length=2000)), timeout=5)
+ assert cdp.count("Fetch.failRequest") == 1
+ assert list(tmp_path.iterdir()) == [] # temp cleaned up, no artifact
+ assert not interceptor._download_extraction_lock.locked()
+
+ @pytest.mark.asyncio
+ async def test_stream_start_fail_unknown_cl_no_direct_fallback(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ cdp = _StreamCDP(take_error=RuntimeError("take failed"), getbody=b"M" * 300)
+ with _stream_limits(threshold=1024, cap=4096):
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=None))
+
+ assert list(tmp_path.iterdir()) == []
+ assert cdp.count("Fetch.getResponseBody") == 0 # unbounded getResponseBody not safe on unknown size
+ assert cdp.count("Fetch.continueResponse") == 0 # never let the browser materialize a large body
+ assert cdp.count("Fetch.failRequest") == 1
+
+ @pytest.mark.asyncio
+ async def test_os_replace_failure_cleans_temp_and_fails(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ cdp = _StreamCDP(chunks=[b"N" * 2000])
+ with _stream_limits(threshold=1024, cap=4096):
+ with patch.object(mod.os, "replace", side_effect=OSError("rename failed")):
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=2000))
+
+ assert list(tmp_path.iterdir()) == [] # temp cleaned even when finalize fails
+ assert cdp.count("Fetch.fulfillRequest") == 0
+ assert cdp.count("Fetch.failRequest") == 1
+
+ @pytest.mark.asyncio
+ async def test_read_data_and_eof_in_same_message_not_dropped(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ # Single IO.read returns the whole body AND eof in one message; the last chunk must not be lost.
+ cdp = _StreamCDP(chunks=[b"O" * 900])
+ with _stream_limits(threshold=1024, cap=4096):
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=900))
+
+ assert _only_file(tmp_path).read_bytes() == b"O" * 900
+ assert cdp.count("IO.read") == 1
+
+ @pytest.mark.asyncio
+ async def test_zero_byte_download_saved_and_replayed(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ cdp = _StreamCDP(chunks=[]) # immediate eof, no data
+ with _stream_limits(threshold=1024, cap=4096):
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=0))
+
+ assert _only_file(tmp_path).read_bytes() == b""
+ assert cdp.count("Fetch.fulfillRequest") == 1
+ assert cdp.count("Fetch.failRequest") == 0
+
+ @pytest.mark.asyncio
+ async def test_stale_interception_on_fulfill_is_benign_after_save(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ stale = Exception("Protocol error (Fetch.fulfillRequest): Invalid InterceptionId")
+ cdp = _StreamCDP(chunks=[b"P" * 2000], fulfill_error=stale)
+ with _stream_limits(threshold=1024, cap=4096):
+ with capture_logs() as logs:
+ await _drive_download(interceptor, cdp, _raw_headers(content_length=2000))
+
+ assert _only_file(tmp_path).read_bytes() == b"P" * 2000 # file saved despite the benign fulfill race
+ assert not [log for log in logs if log.get("log_level") == "error"]