Skip to content

Automate browser based workflows with AI

Turn on the Copilot runner lane in production as a 27 + 10 split of the sandbox node (SKY-17745) (#8805)

Shuchang Zheng90ed94ac25c3
diff --git a/skyvern/config.py b/skyvern/config.py
index 3d4713bde..ed8f9a24d 100644
--- a/skyvern/config.py
+++ b/skyvern/config.py
@@ -357,11 +357,6 @@ class Settings(BaseSettings):
AWS_S3_BUCKET_SCREENSHOTS: str = "skyvern-screenshots"
AWS_S3_BUCKET_BROWSER_SESSIONS: str = "skyvern-browser-sessions"
AWS_S3_BUCKET_UPLOADS: str = "skyvern-uploads"
- # ISO-8601 UTC timestamp. Runs created at/after it that have zero DOWNLOAD artifact
- # rows skip the legacy S3 LIST fallback in get_downloaded_files — such runs register
- # every download as a row at save time (SKY-8861), so the LIST can only return empty.
- # None keeps the LIST fallback for every run.
- DOWNLOADS_EMPTY_S3_LISTING_CUTOVER: str | None = None
# Azure Blob Storage settings
AZURE_STORAGE_ACCOUNT_NAME: str | None = None
diff --git a/skyvern/forge/sdk/artifact/storage/azure.py b/skyvern/forge/sdk/artifact/storage/azure.py
index 5123dab5f..4383e17a0 100644
--- a/skyvern/forge/sdk/artifact/storage/azure.py
+++ b/skyvern/forge/sdk/artifact/storage/azure.py
@@ -346,7 +346,7 @@ class AzureStorage(BaseStorage):
async def get_shared_downloaded_files_in_browser_session(
self, organization_id: str, browser_session_id: str
) -> list[FileInfo]:
- # Artifact-first when keyring is configured — see s3.py for rationale.
+ # Artifact-first when the keyring is configured. Unlike S3, Azure still lists blobs when there are no rows.
if settings.ARTIFACT_CONTENT_HMAC_KEYRING:
try:
artifacts = await app.DATABASE.artifacts.list_artifacts_for_browser_session_by_type(
@@ -363,7 +363,7 @@ class AzureStorage(BaseStorage):
)
artifacts = []
# Filter out in-progress partials — user-facing listing must only
- # show completed downloads. Mirrors s3.py.
+ # show completed downloads.
artifacts = [a for a in artifacts if a.uri and not a.uri.endswith(BROWSER_DOWNLOADING_SUFFIX)]
if artifacts:
return await _file_infos_from_download_artifacts(artifacts)
@@ -434,9 +434,9 @@ class AzureStorage(BaseStorage):
) -> list[FileInfo]:
"""Get recording files for a browser session.
- Artifact-first when the keyring is configured — see s3.py for the
- rationale. Falls back to direct Azure LIST + SAS URLs for legacy
- sessions and OSS-default deployments.
+ Artifact-first when the keyring is configured. Unlike S3, falls back to
+ direct Azure LIST + SAS URLs when there are no rows, as well as when the
+ lookup raises or the keyring is unset (OSS default).
"""
if settings.ARTIFACT_CONTENT_HMAC_KEYRING:
try:
@@ -666,10 +666,8 @@ class AzureStorage(BaseStorage):
async def get_downloaded_files(
self, organization_id: str, run_id: str | None, attempt_started_at: datetime | None = None
) -> list[FileInfo]:
- # Artifact-first — see s3.py::get_downloaded_files for rationale. When
- # the keyring isn't configured (OSS default) or no artifact rows exist
- # (legacy run pre-SKY-8861) we fall back to the legacy listing path so
- # downloaded files remain reachable.
+ # Artifact-first when the keyring is configured. Unlike S3, Azure lists blobs when the keyring is unset or
+ # the run has no artifact rows, so files saved before rows existed stay reachable.
download_artifacts: list[Artifact] | None = None
if run_id is not None and settings.ARTIFACT_CONTENT_HMAC_KEYRING:
download_artifacts = await self._list_download_artifacts_safe(
diff --git a/skyvern/forge/sdk/artifact/storage/gcs.py b/skyvern/forge/sdk/artifact/storage/gcs.py
index aeedc9b8c..a3402580f 100644
--- a/skyvern/forge/sdk/artifact/storage/gcs.py
+++ b/skyvern/forge/sdk/artifact/storage/gcs.py
@@ -365,7 +365,7 @@ class GcsStorage(BaseStorage):
async def get_shared_downloaded_files_in_browser_session(
self, organization_id: str, browser_session_id: str
) -> list[FileInfo]:
- # Artifact-first when keyring is configured — see s3.py for rationale.
+ # Artifact-first when the keyring is configured. Unlike S3, GCS still lists blobs when there are no rows.
if settings.ARTIFACT_CONTENT_HMAC_KEYRING:
try:
artifacts = await app.DATABASE.artifacts.list_artifacts_for_browser_session_by_type(
@@ -382,7 +382,7 @@ class GcsStorage(BaseStorage):
)
artifacts = []
# Filter out in-progress partials — user-facing listing must only
- # show completed downloads. Mirrors s3.py.
+ # show completed downloads.
artifacts = [a for a in artifacts if a.uri and not a.uri.endswith(BROWSER_DOWNLOADING_SUFFIX)]
if artifacts:
return await _file_infos_from_download_artifacts(artifacts)
@@ -453,9 +453,9 @@ class GcsStorage(BaseStorage):
) -> list[FileInfo]:
"""Get recording files for a browser session.
- Artifact-first when the keyring is configured — see s3.py for the
- rationale. Falls back to direct GCS LIST + signed URLs for legacy
- sessions and OSS-default deployments.
+ Artifact-first when the keyring is configured. Unlike S3, falls back to
+ direct GCS LIST + signed URLs when there are no rows, as well as when the
+ lookup raises or the keyring is unset (OSS default).
"""
if settings.ARTIFACT_CONTENT_HMAC_KEYRING:
try:
@@ -680,10 +680,8 @@ class GcsStorage(BaseStorage):
async def get_downloaded_files(
self, organization_id: str, run_id: str | None, attempt_started_at: datetime | None = None
) -> list[FileInfo]:
- # Artifact-first — see s3.py::get_downloaded_files for rationale. When
- # the keyring isn't configured (OSS default) or no artifact rows exist
- # (legacy run) we fall back to the legacy listing path so
- # downloaded files remain reachable.
+ # Artifact-first when the keyring is configured. Unlike S3, GCS lists blobs when the keyring is unset or
+ # the run has no artifact rows, so files saved before rows existed stay reachable.
download_artifacts: list[Artifact] | None = None
if run_id is not None and settings.ARTIFACT_CONTENT_HMAC_KEYRING:
download_artifacts = await self._list_download_artifacts_safe(
diff --git a/skyvern/forge/sdk/artifact/storage/s3.py b/skyvern/forge/sdk/artifact/storage/s3.py
index 0cd0475b7..8f88b9e04 100644
--- a/skyvern/forge/sdk/artifact/storage/s3.py
+++ b/skyvern/forge/sdk/artifact/storage/s3.py
@@ -99,11 +99,8 @@ def empty_read_decision(
class S3Storage(BaseStorage):
_PATH_VERSION = "v1"
- # Cap concurrent head_object fan-out in the legacy listing fallback.
- # /browser_sessions/history gathers across up to page_size=100 sessions
- # in parallel, so a per-call semaphore would still allow sessions x cap
- # in-flight requests. The semaphore is held on the instance so every
- # legacy listing call sharing this S3Storage shares the same cap.
+ # Caps concurrent head_object calls from S3 listing reads. /browser_sessions/history fans out over up to 100
+ # sessions at once, so the semaphore lives on the instance and every listing call on it shares one cap.
_LEGACY_LISTING_HEAD_CONCURRENCY = 32
def __init__(self, bucket: str | None = None, endpoint_url: str | None = None) -> None:
@@ -494,14 +491,13 @@ class S3Storage(BaseStorage):
) -> list[str]:
"""Return S3 URIs of completed downloads in the session.
- DB-backed (artifact rows are the source of truth) — see
- ``cloud_docs/BROWSER_SESSION_DOWNLOAD_ARTIFACTS.md``. Used by the agent
- for baseline-before / baseline-after diffs to detect newly-downloaded
- files. Excludes ``*.crdownload`` partials; those go through
- ``list_downloading_files_in_browser_session`` instead.
+ DB-backed: artifact rows are the source of truth when the keyring is set.
+ Used by the agent for baseline-before / baseline-after diffs to detect
+ newly-downloaded files. Excludes ``*.crdownload`` partials; those go
+ through ``list_downloading_files_in_browser_session`` instead.
- Falls back to S3 LIST when the keyring is unset (OSS default — no
- artifact rows exist) or when the DB lookup itself raises.
+ Lists S3 instead when the keyring is unset (OSS default, where the rows
+ are not consulted) or when the DB lookup itself raises.
"""
return await self._list_downloads_for_session(
organization_id=organization_id,
@@ -549,13 +545,9 @@ class S3Storage(BaseStorage):
async def get_shared_downloaded_files_in_browser_session(
self, organization_id: str, browser_session_id: str
) -> list[FileInfo]:
- # Artifact-first when keyring is configured: query rows scoped to the
- # session, build short signed /v1/artifacts URLs from them. See
- # cloud_docs/BROWSER_SESSION_DOWNLOAD_ARTIFACTS.md.
- #
- # OSS-default deployments without HMAC signing fall straight to the
- # legacy listing path so webhook consumers (no API key) can still
- # fetch the files via presigned URLs.
+ # With the keyring set, artifact rows are the source of truth: a lookup that succeeds and finds nothing
+ # means no downloads, so S3 is not listed. Without a keyring (OSS default) this lists S3 and presigns, so
+ # webhook consumers with no API key can still fetch the files.
if settings.ARTIFACT_CONTENT_HMAC_KEYRING:
try:
artifacts = await app.DATABASE.artifacts.list_artifacts_for_browser_session_by_type(
@@ -570,12 +562,11 @@ class S3Storage(BaseStorage):
browser_session_id=browser_session_id,
exc_info=True,
)
- artifacts = []
- # Filter out in-progress partials — the user-facing listing must
- # only show completed downloads. Partials still live as artifact
- # rows so the agent can detect "still downloading" via DB query.
- artifacts = [a for a in artifacts if a.uri and not a.uri.endswith(BROWSER_DOWNLOADING_SUFFIX)]
- if artifacts:
+ else:
+ # Filter out in-progress partials — the user-facing listing must
+ # only show completed downloads. Partials still live as artifact
+ # rows so the agent can detect "still downloading" via DB query.
+ artifacts = [a for a in artifacts if a.uri and not a.uri.endswith(BROWSER_DOWNLOADING_SUFFIX)]
return await _file_infos_from_download_artifacts(artifacts)
return await self._get_shared_downloaded_files_in_browser_session_via_listing(
@@ -633,10 +624,9 @@ class S3Storage(BaseStorage):
async def _get_shared_downloaded_files_in_browser_session_via_listing(
self, *, organization_id: str, browser_session_id: str
) -> list[FileInfo]:
- # Direct S3 LIST: legacy fallback for sessions pre-cutover (no artifact
- # rows) and OSS deployments without a keyring. We can't go through
- # ``list_downloaded_files_in_browser_session`` here — that now sources
- # from artifact rows and would short-circuit to [] on legacy sessions.
+ # Direct S3 LIST, only for OSS deployments without a keyring and for a
+ # failed row lookup. ``list_downloaded_files_in_browser_session`` returns
+ # S3 URIs, not presigned FileInfos, so it is not reused here.
bucket = settings.AWS_S3_BUCKET_ARTIFACTS
listing_uri = f"s3://{bucket}/{self._PATH_VERSION}/{settings.ENV}/{organization_id}/browser_sessions/{browser_session_id}/downloads"
object_keys = [
@@ -697,11 +687,11 @@ class S3Storage(BaseStorage):
) -> list[FileInfo]:
"""Get recording files for a browser session.
- Artifact-first when the keyring is configured: query RECORDING rows
- scoped to the session and build short signed ``/v1/artifacts/{id}/content``
- URLs from them — no S3 round-trip per file. Falls back to direct S3
- LIST + presigned URLs for legacy sessions and OSS-default deployments
- without HMAC signing.
+ When the keyring is configured, RECORDING rows scoped to the session are
+ the source of truth: build short signed ``/v1/artifacts/{id}/content``
+ URLs from them, and return nothing when there are none. The S3 LIST +
+ presigned URLs path runs only when the row lookup raises or the keyring
+ is unset (OSS default, no HMAC signing).
"""
if settings.ARTIFACT_CONTENT_HMAC_KEYRING:
try:
@@ -717,22 +707,19 @@ class S3Storage(BaseStorage):
browser_session_id=browser_session_id,
exc_info=True,
)
- artifacts = []
- # Defensive extension filter — same as the legacy listing path —
- # in case a non-recording row sneaks under the same browser_session_id.
- artifacts = [
- a for a in artifacts if a.uri and (a.uri.lower().endswith(".webm") or a.uri.lower().endswith(".mp4"))
- ]
- if artifacts:
+ else:
+ # Defensive extension filter — same as the listing path —
+ # in case a non-recording row sneaks under the same browser_session_id.
+ artifacts = [
+ a
+ for a in artifacts
+ if a.uri and (a.uri.lower().endswith(".webm") or a.uri.lower().endswith(".mp4"))
+ ]
file_infos = await _file_infos_from_artifacts(artifacts, artifact_type=ArtifactType.RECORDING)
- # Newest first — match the legacy listing path's ordering.
+ # Newest first — match the listing path's ordering.
file_infos.sort(key=lambda f: (f.modified_at is not None, f.modified_at), reverse=True)
return file_infos
- # Legacy fallback: keyring unset, DB raised, or session pre-cutover
- # with no rows at all. SKY-9286: drop entirely after the bake-in
- # window (target 2026-05-03) — every call here is a billable
- # ListObjects request.
return await self._get_shared_recordings_in_browser_session_via_listing(
organization_id=organization_id, browser_session_id=browser_session_id
)
@@ -740,10 +727,8 @@ class S3Storage(BaseStorage):
async def _get_shared_recordings_in_browser_session_via_listing(
self, *, organization_id: str, browser_session_id: str
) -> list[FileInfo]:
- # Direct S3 LIST: legacy fallback for sessions pre-cutover (no
- # RECORDING artifact rows) and OSS deployments without a keyring.
- # SKY-9286: scheduled for removal once production sessions all have
- # rows — every call here is a billable ListObjects request.
+ # Direct S3 LIST, only for OSS deployments without a keyring and for a
+ # failed row lookup. Every call is a billable ListObjects request.
bucket = settings.AWS_S3_BUCKET_ARTIFACTS
listing_uri = f"s3://{bucket}/{self._PATH_VERSION}/{settings.ENV}/{organization_id}/browser_sessions/{browser_session_id}/videos"
all_keys = [f"s3://{bucket}/{file}" for file in await self.async_client.list_files(uri=listing_uri)]
@@ -918,7 +903,7 @@ class S3Storage(BaseStorage):
)
except Exception:
LOG.warning(
- "Failed to register downloaded file as artifact; falling back to S3 listing for retrieval",
+ "Failed to register downloaded file as artifact",
file=file,
organization_id=organization_id,
run_id=run_id,
@@ -939,14 +924,10 @@ class S3Storage(BaseStorage):
async def get_downloaded_files(
self, organization_id: str, run_id: str | None, attempt_started_at: datetime | None = None
) -> list[FileInfo]:
- # Artifact-first: when a run has DOWNLOAD artifact rows, return them as
- # the source of truth — the row carries enough to build a short signed
- # /v1/artifacts/{id}/content URL plus the SHA-256 we persisted at save
- # time, so we skip the S3 LIST and per-file HEAD entirely (SKY-8861).
- #
- # If HMAC signing isn't configured (self-hosted OSS default), the signed
- # endpoint requires an API key webhook consumers don't have, so we stay
- # on the legacy S3-list+presign path even when rows exist.
+ # With the keyring set, the run's DOWNLOAD rows are the source of truth: each row carries the SHA-256 and
+ # what a signed /v1/artifacts/{id}/content URL needs, so there is no S3 LIST or per-file HEAD, and a run with
+ # no rows has no downloads. Without a keyring (OSS default) the signed endpoint needs an API key that webhook
+ # consumers lack, so this lists and presigns even when rows exist, as it also does when the row lookup fails.
# ``download_row_count`` stays None when the rows were never queried (no keyring, no run id,
# or the lookup failed), so an unqueried read is never reported as a read that found nothing.
@@ -959,38 +940,22 @@ class S3Storage(BaseStorage):
)
if not rows_lookup_failed:
download_row_count = len(download_artifacts)
- download_artifacts = dedupe_run_scoped_download_artifacts(
- download_artifacts, attempt_started_at=attempt_started_at
- )
- if download_artifacts:
+ download_artifacts = dedupe_run_scoped_download_artifacts(
+ download_artifacts, attempt_started_at=attempt_started_at
+ )
file_infos = await _file_infos_from_download_artifacts(download_artifacts)
if not file_infos:
self._log_empty_downloads_read(
organization_id=organization_id,
run_id=run_id,
download_row_count=download_row_count,
- rows_lookup_failed=rows_lookup_failed,
- skip_fired=False,
- rows_present_but_unresolvable=True,
+ rows_lookup_failed=False,
+ skip_fired=not download_artifacts,
+ rows_present_but_unresolvable=bool(download_artifacts),
listed=False,
)
return file_infos
- if not rows_lookup_failed and await self._skip_empty_downloads_listing(
- organization_id=organization_id, run_id=run_id
- ):
- self._log_empty_downloads_read(
- organization_id=organization_id,
- run_id=run_id,
- download_row_count=download_row_count,
- rows_lookup_failed=rows_lookup_failed,
- skip_fired=True,
- rows_present_but_unresolvable=False,
- listed=False,
- )
- return []
- # Legacy fallback — runs predating SKY-8861 (no artifact rows) and
- # OSS-default deployments without HMAC signing both arrive here.
file_infos = await self._get_downloaded_files_via_s3_listing(
organization_id=organization_id,
run_id=run_id,
@@ -1034,36 +999,6 @@ class S3Storage(BaseStorage):
**decision,
)
- async def _skip_empty_downloads_listing(self, *, organization_id: str, run_id: str) -> bool:
- """True when a run with zero DOWNLOAD rows may skip the legacy S3 LIST.
-
- Only runs created at/after DOWNLOADS_EMPTY_S3_LISTING_CUTOVER qualify: they
- register every download as an artifact row at save time, so an empty row set
- means an empty S3 prefix. Anything unresolvable (cutover unset or unparseable,
- run row missing, DB error) keeps the LIST fallback.
- """
- cutover_raw = settings.DOWNLOADS_EMPTY_S3_LISTING_CUTOVER
- if not cutover_raw:
- return False
- try:
- cutover = datetime.fromisoformat(cutover_raw)
- run = await app.DATABASE.tasks.get_run(run_id=run_id, organization_id=organization_id)
- except Exception:
- LOG.warning(
- "Failed to resolve run for empty-downloads listing skip; using S3 LIST",
- run_id=run_id,
- exc_info=True,
- )
- return False
- if run is None:
- return False
- created_at = run.created_at
- if created_at.tzinfo is None:
- created_at = created_at.replace(tzinfo=timezone.utc)
- if cutover.tzinfo is None:
- cutover = cutover.replace(tzinfo=timezone.utc)
- return created_at >= cutover
-
async def _list_download_artifacts_safe(self, *, organization_id: str, run_id: str) -> tuple[list[Artifact], bool]:
"""The run's DOWNLOAD rows, plus whether the lookup itself failed.
@@ -1318,8 +1253,8 @@ class S3Storage(BaseStorage):
For ``downloads``, also drop the matching DOWNLOAD artifact row so a
subsequent ``GET /v1/browser_sessions/{id}`` doesn't hand out a signed
URL that 404s. The DB delete runs before the S3 delete: if S3 fails
- we'd rather have an artifact row missing (the listing fallback covers
- it) than a row pointing at a deleted object.
+ we'd rather have an artifact row missing (the file simply stops being
+ listed) than a row pointing at a deleted object.
"""
uri = self._build_browser_session_uri(organization_id, browser_session_id, artifact_type, remote_path, date)
if artifact_type == "downloads":
diff --git a/tests/unit/test_browser_session_download_artifacts.py b/tests/unit/test_browser_session_download_artifacts.py
index 4e6a0f2c8..6057d6b9b 100644
--- a/tests/unit/test_browser_session_download_artifacts.py
+++ b/tests/unit/test_browser_session_download_artifacts.py
@@ -389,41 +389,6 @@ async def test_get_shared_downloaded_files_in_browser_session_uses_artifact_urls
storage.async_client.create_presigned_urls.assert_not_awaited()
-async def test_get_shared_downloaded_files_in_browser_session_falls_back_to_presigned_for_legacy(keyring_configured):
- """Pre-cutover sessions have no artifact rows. Files must still surface as presigned URLs."""
- storage = S3Storage()
- storage.async_client = MagicMock()
- object_uri = "s3://skyvern-artifacts/v1/local/o_1/browser_sessions/pbs_old/downloads/legacy.pdf"
- storage.async_client.list_files = AsyncMock(return_value=[object_uri.split("/", 3)[-1]])
- storage.async_client.get_object_info = AsyncMock(
- return_value={
- "Metadata": {"sha256_checksum": "sha-old", "original_filename": "legacy.pdf"},
- "LastModified": None,
- "ContentLength": 1024,
- }
- )
- storage.async_client.create_presigned_urls = AsyncMock(
- return_value=["https://skyvern-artifacts.s3.amazonaws.com/...?sig=old"]
- )
-
- mock_list = AsyncMock(return_value=[])
- resolve_url = AsyncMock() # must NOT be called
-
- with patch("skyvern.forge.sdk.artifact.storage.base.app") as base_app:
- with patch("skyvern.forge.sdk.artifact.storage.s3.app") as s3_app:
- s3_app.DATABASE.artifacts.list_artifacts_for_browser_session_by_type = mock_list
- base_app.ARTIFACT_MANAGER.resolve_share_url = resolve_url
- result = await storage.get_shared_downloaded_files_in_browser_session(
- organization_id="o_1", browser_session_id="pbs_old"
- )
-
- assert len(result) == 1
- assert _is_amazonaws_s3_url(result[0].url)
- assert result[0].file_size == 1024
- resolve_url.assert_not_awaited()
-
-
@pytest.mark.asyncio
async def test_get_shared_downloaded_files_in_browser_session_filters_partial_artifacts(keyring_configured):
"""User-facing listing must hide ``*.crdownload`` rows even when DB returns them.
diff --git a/tests/unit/test_browser_session_recording_artifacts.py b/tests/unit/test_browser_session_recording_artifacts.py
index 48e812343..da4d4f6bf 100644
--- a/tests/unit/test_browser_session_recording_artifacts.py
+++ b/tests/unit/test_browser_session_recording_artifacts.py
@@ -433,45 +433,6 @@ async def test_get_shared_recordings_sorts_newest_first(keyring_configured):
assert [fi.artifact_id for fi in result] == ["a_new", "a_old"]
-async def test_get_shared_recordings_falls_back_to_presigned_for_legacy_session(keyring_configured):
- """Legacy session: no RECORDING rows. Files in S3 still surface as presigned
- URLs via the listing fallback so existing recordings remain reachable."""
- storage = S3Storage()
- storage.async_client = MagicMock()
- s3_key = "v1/local/o_1/browser_sessions/pbs_old/videos/2026-04-26/legacy.webm"
- storage.async_client.list_files = AsyncMock(return_value=[s3_key])
- storage.async_client.get_object_info = AsyncMock(
- return_value={
- "Metadata": {"sha256_checksum": "sha-old"},
- "LastModified": None,
- "ContentLength": 1024,
- }
- )
- storage.async_client.create_presigned_urls = AsyncMock(
- return_value=["https://skyvern-artifacts.s3.amazonaws.com/...?sig=old"]
- )
-
- mock_list = AsyncMock(return_value=[]) # no rows
- resolve_url = AsyncMock() # must NOT be called
-
- with (
- patch("skyvern.forge.sdk.artifact.storage.base.app") as base_app,
- patch("skyvern.forge.sdk.artifact.storage.s3.app") as s3_app,
- ):
- s3_app.DATABASE.artifacts.list_artifacts_for_browser_session_by_type = mock_list
- base_app.ARTIFACT_MANAGER.resolve_share_url = resolve_url
- base_app.ARTIFACT_MANAGER.resolve_artifact_url_expiry_seconds = AsyncMock(return_value=12 * 60 * 60)
- result = await storage.get_shared_recordings_in_browser_session(
- organization_id="o_1", browser_session_id="pbs_old"
- )
-
- assert len(result) == 1
- assert _is_amazonaws_s3_url(result[0].url)
- assert result[0].file_size == 1024
- resolve_url.assert_not_awaited()
-
-
@pytest.mark.asyncio
async def test_get_shared_recordings_keyring_unset_skips_artifact_lookup():
"""OSS default (no keyring) skips the artifact path — webhook consumers
diff --git a/tests/unit/test_code_block_downloads.py b/tests/unit/test_code_block_downloads.py
index 0c2a043ce..c4a42077b 100644
--- a/tests/unit/test_code_block_downloads.py
+++ b/tests/unit/test_code_block_downloads.py
@@ -3379,7 +3379,6 @@ async def test_downloads_empty_read_reports_unresolvable_rows(monkeypatch: pytes
async def test_downloads_empty_read_reports_listing_skip(monkeypatch: pytest.MonkeyPatch) -> None:
storage = _artifact_row_storage(monkeypatch, keyring="k1:secret", file_infos=[])
monkeypatch.setattr(storage, "_list_download_artifacts_safe", AsyncMock(return_value=([], False)))
- monkeypatch.setattr(storage, "_skip_empty_downloads_listing", AsyncMock(return_value=True))
listing = AsyncMock(return_value=[])
monkeypatch.setattr(storage, "_get_downloaded_files_via_s3_listing", listing)
@@ -3403,7 +3402,6 @@ async def test_downloads_empty_read_reports_failed_row_lookup_as_unknown_count(
"list_artifacts_for_run_by_type",
AsyncMock(side_effect=RuntimeError("database unavailable")),
)
- monkeypatch.setattr(storage, "_skip_empty_downloads_listing", AsyncMock(return_value=False))
monkeypatch.setattr(storage, "_get_downloaded_files_via_s3_listing", AsyncMock(return_value=[]))
with _capture_empty_read_logs() as logs:
@@ -3570,18 +3568,15 @@ async def test_failed_row_lookup_still_lists_instead_of_reporting_no_downloads(
) -> None:
"""A DB blip must not be answered with an empty download list.
- The cutover skip exists to avoid listing when a run provably has no rows; a lookup that
- failed proves nothing, so the legitimate case has to keep its route through the listing.
+ Rows are trusted only when the lookup succeeds; a lookup that failed proves nothing, so the
+ read keeps its route through the listing.
"""
listed = [FileInfo(url="https://example.test/real")]
storage = _artifact_row_storage(monkeypatch, keyring="k1:secret", file_infos=[])
monkeypatch.setattr(storage, "_list_download_artifacts_safe", AsyncMock(return_value=([], True)))
- skip = AsyncMock(return_value=True)
- monkeypatch.setattr(storage, "_skip_empty_downloads_listing", skip)
monkeypatch.setattr(storage, "_get_downloaded_files_via_s3_listing", AsyncMock(return_value=listed))
assert await storage.get_downloaded_files("o_1", "wr_blip") == listed
- skip.assert_not_awaited()
@pytest.mark.asyncio
diff --git a/tests/unit/test_download_artifact_claim_dedupe.py b/tests/unit/test_download_artifact_claim_dedupe.py
index afb1a015b..fbe0226e2 100644
--- a/tests/unit/test_download_artifact_claim_dedupe.py
+++ b/tests/unit/test_download_artifact_claim_dedupe.py
@@ -243,13 +243,10 @@ async def test_current_attempt_downloads_pair_only_current_artifacts(
)
storage = _install_storage(sqlite_db, monkeypatch)
monkeypatch.setattr(base_module, "resolve_download_attempt", AsyncMock(return_value=(run_id, 2, cutoff)))
- skip_empty = AsyncMock(wraps=storage._skip_empty_downloads_listing)
- monkeypatch.setattr(storage, "_skip_empty_downloads_listing", skip_empty)
files = await storage.get_current_attempt_downloaded_files(organization_id=org_id, run_id=run_id)
assert [file.artifact_id for file in files] == expected_ids
- skip_empty.assert_not_called()
storage.async_client.list_files.assert_not_called()
if "r2" in row_names:
whole_run_files = await storage.get_downloaded_files(organization_id=org_id, run_id=run_id)
diff --git a/tests/unit/test_downloaded_files_artifact_urls.py b/tests/unit/test_downloaded_files_artifact_urls.py
index 7b77d2561..7393e39f5 100644
--- a/tests/unit/test_downloaded_files_artifact_urls.py
+++ b/tests/unit/test_downloaded_files_artifact_urls.py
@@ -11,6 +11,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
from urllib.parse import urlparse
import pytest
+from sqlalchemy.ext.asyncio import AsyncEngine
import skyvern.forge.sdk.artifact.manager as manager_module
import skyvern.forge.sdk.artifact.storage.azure as azure_module
@@ -25,6 +26,7 @@ from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType
from skyvern.forge.sdk.artifact.storage.local import LocalStorage
from skyvern.forge.sdk.artifact.storage.s3 import S3Storage
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
+from skyvern.forge.sdk.db.agent_db import AgentDB
from skyvern.forge.sdk.schemas.files import FileInfo
from skyvern.forge.sdk.workflow.context_manager import WorkflowContextManager
from skyvern.forge.sdk.workflow.loop_download_filter import (
@@ -349,41 +351,26 @@ async def test_get_downloaded_files_preserves_artifact_row_order(keyring_configu
@pytest.mark.asyncio
-async def test_get_downloaded_files_falls_back_to_presigned_for_legacy_runs(keyring_configured):
- """Production-cloud legacy run: keyring IS configured, but the run pre-dates SKY-8861
- so no artifact rows exist. Files in S3 must still surface as presigned URLs — the
- whole point of keeping the fallback path."""
+async def test_get_downloaded_files_returns_nothing_without_listing_when_the_run_has_no_rows(
+ keyring_configured, sqlite_engine: AsyncEngine, monkeypatch: pytest.MonkeyPatch
+):
+ """With the keyring set, DOWNLOAD rows are the source of truth: a run with none has no
+ downloads, even when S3 still holds files under its prefix."""
+ db = AgentDB("sqlite+aiosqlite:///:memory:", db_engine=sqlite_engine)
+ await db.artifacts.create_artifact(
+ artifact_id="a_other",
+ artifact_type=ArtifactType.DOWNLOAD,
+ uri="s3://skyvern-uploads/downloads/local/o_1/wr_other/other.pdf",
+ organization_id="o_1",
+ run_id="wr_other",
+ )
+ monkeypatch.setattr(s3_module.app, "DATABASE", db)
storage = S3Storage()
storage.async_client = MagicMock()
- s3_key = "downloads/local/o_1/wr_old/legacy.pdf"
- storage.async_client.list_files = AsyncMock(return_value=[s3_key])
- storage.async_client.get_object_info = AsyncMock(
- return_value={
- "Metadata": {"sha256_checksum": "sha-old", "original_filename": "legacy.pdf"},
- "ContentLength": 2048,
- }
- )
- storage.async_client.create_presigned_urls = AsyncMock(
- return_value=["https://skyvern-uploads.s3.amazonaws.com/...?sig=old"]
- )
-
- mock_list = AsyncMock(return_value=[]) # no artifact rows for this legacy run
- build_url = MagicMock() # must NOT be called
-
- with patch("skyvern.forge.sdk.artifact.storage.base.app") as base_app:
- with patch("skyvern.forge.sdk.artifact.storage.s3.app") as s3_app:
- s3_app.DATABASE.artifacts.list_artifacts_for_run_by_type = mock_list
- base_app.ARTIFACT_MANAGER.build_signed_content_url = build_url
- result = await storage.get_downloaded_files(organization_id="o_1", run_id="wr_old")
+ storage.async_client.list_files = AsyncMock(return_value=["downloads/local/o_1/wr_old/legacy.pdf"])
- assert len(result) == 1
- assert result[0].filename == "legacy.pdf"
- assert result[0].checksum == "sha-old"
- assert result[0].file_size == 2048
- assert _is_amazonaws_s3_url(result[0].url)
- build_url.assert_not_called()
- storage.async_client.list_files.assert_awaited_once()
- storage.async_client.create_presigned_urls.assert_awaited_once()
+ assert await storage.get_downloaded_files(organization_id="o_1", run_id="wr_old") == []
+ storage.async_client.list_files.assert_not_awaited()
@pytest.mark.asyncio
@@ -395,11 +382,11 @@ async def test_get_downloaded_files_falls_back_to_presigned_when_keyring_unset(t
storage = S3Storage()
storage.async_client = MagicMock()
- s3_key = "downloads/local/o_1/wr_1/invoice.pdf"
+ s3_key = "downloads/local/o_1/wr_1/stored-8f3a.pdf"
storage.async_client.list_files = AsyncMock(return_value=[s3_key])
storage.async_client.get_object_info = AsyncMock(
return_value={
- "Metadata": {"sha256_checksum": "sha-abc", "original_filename": "invoice.pdf"},
+ "Metadata": {"sha256_checksum": "sha-abc", "original_filename": "Invoice March.pdf"},
"ContentLength": 1024,
}
)
@@ -422,6 +409,8 @@ async def test_get_downloaded_files_falls_back_to_presigned_when_keyring_unset(t
assert len(result) == 1
assert _is_amazonaws_s3_url(result[0].url)
assert result[0].file_size == 1024
+ assert result[0].checksum == "sha-abc"
+ assert result[0].filename == "Invoice March.pdf"
build_url.assert_not_called()
@@ -652,95 +641,6 @@ def test_content_endpoint_download_filename_strips_header_injection():
assert disposition.count('"') == 2 # only the pair around filename
-def _run_with_created_at(created_at):
- run = MagicMock()
- run.created_at = created_at
- return run
-
-
-async def test_get_downloaded_files_skips_listing_for_empty_post_cutover_run(keyring_configured):
- """A post-cutover run with zero DOWNLOAD rows returns [] without the legacy S3 LIST:
- every download registers a row at save time, so the LIST could only confirm emptiness."""
- from datetime import datetime
-
- from skyvern.config import settings
-
- storage = S3Storage()
- storage.async_client = MagicMock()
- storage.async_client.list_files = AsyncMock() # must NOT be called
-
- mock_list = AsyncMock(return_value=[])
- mock_get_run = AsyncMock(return_value=_run_with_created_at(datetime(2026, 8, 2, 12, 0, 0)))
-
- with (
- patch.object(settings, "DOWNLOADS_EMPTY_S3_LISTING_CUTOVER", "2026-08-01T00:00:00"),
- patch("skyvern.forge.sdk.artifact.storage.s3.app") as s3_app,
- ):
- s3_app.DATABASE.artifacts.list_artifacts_for_run_by_type = mock_list
- s3_app.DATABASE.tasks.get_run = mock_get_run
- result = await storage.get_downloaded_files(organization_id="o_1", run_id="wr_new")
-
- assert result == []
- storage.async_client.list_files.assert_not_awaited()
- mock_get_run.assert_awaited_once_with(run_id="wr_new", organization_id="o_1")
-
-
-async def test_get_downloaded_files_lists_for_empty_pre_cutover_run(keyring_configured):
- """A run created before the cutover keeps the legacy S3 LIST — its downloads may
- predate row registration."""
- from datetime import datetime
-
- from skyvern.config import settings
-
- storage = S3Storage()
- storage.async_client = MagicMock()
- storage.async_client.list_files = AsyncMock(return_value=[])
-
- mock_list = AsyncMock(return_value=[])
- mock_get_run = AsyncMock(return_value=_run_with_created_at(datetime(2026, 7, 1, 0, 0, 0)))
-
- with (
- patch.object(settings, "DOWNLOADS_EMPTY_S3_LISTING_CUTOVER", "2026-08-01T00:00:00"),
- patch("skyvern.forge.sdk.artifact.storage.s3.app") as s3_app,
- ):
- s3_app.DATABASE.artifacts.list_artifacts_for_run_by_type = mock_list
- s3_app.DATABASE.tasks.get_run = mock_get_run
- result = await storage.get_downloaded_files(organization_id="o_1", run_id="wr_old")
-
- assert result == []
- storage.async_client.list_files.assert_awaited_once()
-
-
[email protected]("get_run_behavior", ["raises", "returns_none"])
-async def test_get_downloaded_files_lists_when_run_unresolvable(keyring_configured, get_run_behavior):
- """DB errors or a missing run row fail open to the legacy S3 LIST."""
- from skyvern.config import settings
-
- storage = S3Storage()
- storage.async_client = MagicMock()
- storage.async_client.list_files = AsyncMock(return_value=[])
-
- mock_list = AsyncMock(return_value=[])
- if get_run_behavior == "raises":
- mock_get_run = AsyncMock(side_effect=RuntimeError("db down"))
- else:
- mock_get_run = AsyncMock(return_value=None)
-
- with (
- patch.object(settings, "DOWNLOADS_EMPTY_S3_LISTING_CUTOVER", "2026-08-01T00:00:00"),
- patch("skyvern.forge.sdk.artifact.storage.s3.app") as s3_app,
- ):
- s3_app.DATABASE.artifacts.list_artifacts_for_run_by_type = mock_list
- s3_app.DATABASE.tasks.get_run = mock_get_run
- result = await storage.get_downloaded_files(organization_id="o_1", run_id="wr_x")
-
- assert result == []
- storage.async_client.list_files.assert_awaited_once()
-
-
@pytest.mark.asyncio
async def test_create_download_artifact_refreshes_checksum_for_changed_bytes():
"""A re-save of changed bytes under the same uri moves the row's checksum, so the loop
diff --git a/tests/unit/webeye/test_browser_session_response.py b/tests/unit/webeye/test_browser_session_response.py
index ccf813291..30843f0f6 100644
--- a/tests/unit/webeye/test_browser_session_response.py
+++ b/tests/unit/webeye/test_browser_session_response.py
@@ -4,9 +4,15 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import HTTPException
+from sqlalchemy.ext.asyncio import AsyncEngine
+from skyvern.config import settings
from skyvern.forge import app
from skyvern.forge.agent_functions import AgentFunction
+from skyvern.forge.sdk.artifact.manager import ArtifactManager
+from skyvern.forge.sdk.artifact.models import ArtifactType
+from skyvern.forge.sdk.artifact.storage.s3 import S3Storage
+from skyvern.forge.sdk.db.agent_db import AgentDB
from skyvern.forge.sdk.schemas.files import FileInfo
from skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSession
from skyvern.webeye import schemas as browser_session_schemas
@@ -377,6 +383,75 @@ async def test_browser_session_response_lists_files_newest_first_with_undated_fi
assert response.recordings == [newer, older, undated]
+_KEYRING = '{"current_kid": "k1", "keys": {"k1": {"secret": "00"}}}'
+
+
+def s3_holding_one_file_per_prefix() -> MagicMock:
+ async def list_files(uri: str) -> list[str]:
+ name = "s3_session.webm" if uri.endswith("/videos") else "s3_report.pdf"
+ return [f"{uri.split('/', 3)[3]}/{name}"]
+
+ client = MagicMock()
+ client.list_files = AsyncMock(side_effect=list_files)
+ client.get_object_info = AsyncMock(return_value={"Metadata": {}, "LastModified": None, "ContentLength": 10})
+ client.create_presigned_urls = AsyncMock(side_effect=lambda keys: [f"https://b.s3.amazonaws.com/{k}" for k in keys])
+ return client
+
+
[email protected]("base_agent_function")
+ ("keyring", "rows", "expected"),
+ [
+ pytest.param(_KEYRING, "none", ([], []), id="keyring-no-rows-skips-s3"),
+ pytest.param(_KEYRING, "present", (["row_report.pdf"], ["row_session.webm"]), id="keyring-serves-rows"),
+ pytest.param(_KEYRING, "lookup-raises", (["s3_report.pdf"], ["s3_session.webm"]), id="failed-lookup-lists"),
+ pytest.param(None, "none", (["s3_report.pdf"], ["s3_session.webm"]), id="no-keyring-lists"),
+ ],
+)
+async def test_browser_session_files_come_from_artifact_rows_and_list_s3_only_as_a_fallback(
+ sqlite_engine: AsyncEngine,
+ monkeypatch: pytest.MonkeyPatch,
+ keyring: str | None,
+ rows: str,
+ expected: tuple[list[str], list[str]],
+) -> None:
+ db = AgentDB("sqlite+aiosqlite:///:memory:", db_engine=sqlite_engine)
+ monkeypatch.setattr(app, "DATABASE", db)
+ monkeypatch.setattr(app, "ARTIFACT_MANAGER", ArtifactManager())
+ monkeypatch.setattr(settings, "ARTIFACT_CONTENT_HMAC_KEYRING", keyring)
+ session = completed_session()
+ prefix = (
+ f"s3://{settings.AWS_S3_BUCKET_ARTIFACTS}/v1/{settings.ENV}/{session.organization_id}"
+ f"/browser_sessions/{session.persistent_browser_session_id}"
+ )
+ if rows == "present":
+ for artifact_type, path in (
+ (ArtifactType.DOWNLOAD, "downloads/row_report.pdf"),
+ (ArtifactType.RECORDING, "videos/row_session.webm"),
+ ):
+ await db.artifacts.create_artifact(
+ artifact_id=f"a_{artifact_type}",
+ artifact_type=artifact_type,
+ uri=f"{prefix}/{path}",
+ organization_id=session.organization_id,
+ browser_session_id=session.persistent_browser_session_id,
+ )
+ elif rows == "lookup-raises":
+ monkeypatch.setattr(
+ db.artifacts, "list_artifacts_for_browser_session_by_type", AsyncMock(side_effect=RuntimeError("db down"))
+ )
+ storage = S3Storage()
+ storage.async_client = s3_holding_one_file_per_prefix()
+
+ response = await BrowserSessionResponse.from_browser_session(session, storage, concurrent_listings=True)
+
+ downloads = [f.filename for f in response.downloaded_files or []]
+ recordings = [f.filename for f in response.recordings or []]
+ assert (downloads, recordings) == expected
+ assert storage.async_client.list_files.await_count == (2 if expected[0] == ["s3_report.pdf"] else 0)
+
+
def test_no_server_side_row_field_becomes_a_response_field() -> None:
leaked = server_side_row_fields() & set(BrowserSessionResponse.model_fields)
assert leaked == set()