Skip to content

Automate browser based workflows with AI

fix(SKY-9431): extend cached download grace period from 6s to 60s (#5785)

pedrohsdb1a4c2dc3cc89
diff --git a/skyvern/services/script_service.py b/skyvern/services/script_service.py
index c38bb526d..8579f994d 100644
--- a/skyvern/services/script_service.py
+++ b/skyvern/services/script_service.py
@@ -91,6 +91,10 @@ from skyvern.webeye.scraper.scraped_page import ElementTreeFormat
LOG = structlog.get_logger()
jinja_sandbox_env = SandboxedEnvironment()
+# Max wait for any download signal after a cached click; downstream
+# .crdownload polling handles in-progress completion separately. (SKY-9431)
+CACHED_DOWNLOAD_NO_FILE_GRACE_SECONDS = 60
+
class SkyvernLoopItem:
def __init__(
@@ -1926,16 +1930,17 @@ async def download(
# - Check immediately (catches fast CDP atomic writes).
# - If a .crdownload is detected, a browser-native download is in
# progress — keep polling until it completes or times out.
- # - If nothing appears within a short grace period, the cached click
+ # - If nothing appears within the grace period, the cached click
# likely did nothing (e.g. download_selector() returned None).
- # Shorter than agent-path constants (BROWSER_DOWNLOAD_TIMEOUT=600,
- # BROWSER_DOWNLOAD_MAX_WAIT_TIME=120) — cached fallback to AI is cheap.
+ # Grace accommodates slow report-generation backends; in-progress
+ # timeout is anchored at first detection so the grace doesn't eat
+ # the download budget. (SKY-9431)
_POLL_INTERVAL = 2 # seconds between filesystem checks
- _GRACE_PERIOD = 6 # seconds to wait when no download activity detected
_DOWNLOAD_TIMEOUT = 300 # max seconds to wait for an in-progress download
_DISAPPEARED_TIMEOUT = 30 # seconds to wait after .crdownload vanishes without completion
_download_detected = False
_disappeared_at: float | None = None
+ _first_detected_at: float | None = None
_loop = asyncio.get_running_loop()
_poll_start = _loop.time()
@@ -1959,9 +1964,10 @@ async def download(
workflow_run_id=run_id,
downloading_files=len(_new_downloading),
)
+ _first_detected_at = _now
_download_detected = True
_disappeared_at = None # reset — file is (still) present
- if _elapsed > _DOWNLOAD_TIMEOUT:
+ if _first_detected_at is not None and (_now - _first_detected_at) > _DOWNLOAD_TIMEOUT:
raise CachedDownloadError(
".crdownload file never completed. "
f"Files before: {len(local_files_before)}, after: {len(_local_files_now)}"
@@ -1984,7 +1990,7 @@ async def download(
continue
# Nothing new at all — wait a grace period then give up
- if _elapsed >= _GRACE_PERIOD:
+ if _elapsed >= CACHED_DOWNLOAD_NO_FILE_GRACE_SECONDS:
LOG.warning(
"Cached download produced no file after grace period",
workflow_run_id=run_id,
diff --git a/tests/unit/test_cached_download_s3_upload.py b/tests/unit/test_cached_download_s3_upload.py
index 7ca8038d7..aa69d5bde 100644
--- a/tests/unit/test_cached_download_s3_upload.py
+++ b/tests/unit/test_cached_download_s3_upload.py
@@ -203,7 +203,7 @@ async def test_verification_raises_when_no_new_file(setup):
def advancing_time():
nonlocal call_count
call_count += 1
- return call_count * 3.0
+ return call_count * 30.0
with (
patch(f"{MODULE}.asyncio.sleep", new_callable=AsyncMock),
@@ -436,8 +436,6 @@ async def test_poll_fails_when_no_file_downloaded(setup):
"""SKY-8433: When download_selector() returns None and click silently succeeds
without downloading anything, the poll loop should detect no new files
after the grace period and trigger AI fallback."""
- # The poll loop checks list_files once per iteration. With a 6s grace period
- # and 2s sleep, we need: 1 (before) + ~4 poll iterations of empty results.
refs = setup(
get_side_effect=[[]],
list_files_side_effect=[[] for _ in range(10)],
@@ -451,7 +449,7 @@ async def test_poll_fails_when_no_file_downloaded(setup):
def advancing_time():
nonlocal call_count
call_count += 1
- return call_count * 3.0 # each call advances 3s, exceeds 6s grace after 2 polls
+ return call_count * 30.0
with (
patch(f"{MODULE}.asyncio.sleep", new_callable=AsyncMock),
@@ -600,3 +598,44 @@ async def test_poll_crdownload_disappears_without_complete_file(setup, tmp_path)
assert "disappeared" in str(error_arg).lower() or "did not produce" in str(error_arg).lower()
finally:
_cleanup(refs)
+
+
+async def test_poll_succeeds_with_late_start_and_long_running_crdownload(setup, tmp_path):
+ """SKY-9431: a download that starts late within the new 60s grace and then
+ runs long enough that elapsed-from-poll-start crosses 300s should still
+ succeed, because the in-progress timeout is anchored at first detection."""
+ download_dir = tmp_path / "downloads"
+ incomplete_file = str(download_dir / "invoice.pdf.crdownload")
+ complete_file = str(download_dir / "invoice.pdf")
+ refs = setup(
+ get_side_effect=[[], [complete_file]],
+ list_files_side_effect=[
+ [], # idx 0: pre-loop snapshot
+ *[[] for _ in range(10)], # idx 1..10: iters 1..10, elapsed 5..50
+ *[[incomplete_file] for _ in range(51)], # idx 11..61: iters 11..61
+ [complete_file], # idx 62: iter 62, complete file appears
+ ],
+ )
+ try:
+ from skyvern.services.script_service import download
+
+ call_count = 0
+
+ def advancing_time():
+ nonlocal call_count
+ call_count += 1
+ return call_count * 5.0
+
+ with (
+ patch(f"{MODULE}.asyncio.sleep", new_callable=AsyncMock),
+ patch(f"{MODULE}.asyncio.get_running_loop") as mock_loop,
+ ):
+ mock_loop.return_value.time = advancing_time
+ await download(prompt="Download invoice", label="test_block")
+
+ refs["fallback"].assert_not_called()
+ refs["update_block"].assert_called_once()
+ refs["storage"].save_downloaded_files.assert_called_once()
+ finally:
+ _cleanup(refs)