Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Grant the Estuary CDC role SELECT on three app tables missing from the warehouse mirror (SKY-15607) (#8449)
Marc Kelechava6c15069e8d81
diff --git a/alembic/versions/2026_09_04_0608-456c370b0f7d_grant_the_estuary_cdc_role_select_on_three_app_tables_missing_from_the_warehouse_mirror.py b/alembic/versions/2026_09_04_0608-456c370b0f7d_grant_the_estuary_cdc_role_select_on_three_app_tables_missing_from_the_warehouse_mirror.pynew file mode 100644index 000000000..abc796a7b--- /dev/null+++ b/alembic/versions/2026_09_04_0608-456c370b0f7d_grant_the_estuary_cdc_role_select_on_three_app_tables_missing_from_the_warehouse_mirror.py@@ -0,0 +1,62 @@+"""grant the Estuary CDC role SELECT on three app tables missing from the warehouse mirror++Revision ID: 456c370b0f7d+Revises: ac35398557c1+Create Date: 2026-09-04T06:08:50.733883+00:00++"""++from collections.abc import Sequence++from alembic import op++# revision identifiers, used by Alembic.+revision: str = "456c370b0f7d"+down_revision: str | None = "ac35398557c1"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++_CDC_ROLE = "flow_capture"+_PUBLICATION = "flow_publication"+_MIRRORED_TABLES = (+ "user_onboarding",+ "recovery_guidance_experiment_assignments",+ "workflow_tag_events",+)+++def upgrade() -> None:+ for table in _MIRRORED_TABLES:+ op.execute(f"""+ DO $$+ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '{_CDC_ROLE}') THEN+ RAISE NOTICE '{_CDC_ROLE} role not found, skipping grant on {table} (expected on local/OSS)';+ RETURN;+ END IF;+ IF to_regclass('public.{table}') IS NULL THEN+ RAISE NOTICE 'public.{table} not found, skipping grant';+ RETURN;+ END IF;++ GRANT SELECT ON public.{table} TO {_CDC_ROLE};++ IF EXISTS (SELECT 1 FROM pg_publication WHERE pubname = '{_PUBLICATION}' AND NOT puballtables) THEN+ IF NOT EXISTS (+ SELECT 1 FROM pg_publication_tables+ WHERE pubname = '{_PUBLICATION}' AND schemaname = 'public' AND tablename = '{table}'+ ) THEN+ BEGIN+ ALTER PUBLICATION {_PUBLICATION} ADD TABLE public.{table};+ EXCEPTION WHEN insufficient_privilege THEN+ RAISE WARNING 'cannot alter {_PUBLICATION} as %; run manually as its owner: '+ 'ALTER PUBLICATION {_PUBLICATION} ADD TABLE public.{table};', current_user;+ END;+ END IF;+ END IF;+ END $$;+ """)+++def downgrade() -> None:+ passdiff --git a/skyvern/config.py b/skyvern/config.pyindex ea45c6725..d9110ce2a 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -110,6 +110,10 @@ class Settings(BaseSettings):MAX_SCRAPING_RETRIES: int = 0VIDEO_PATH: str | None = "./video"VIDEO_COMPRESSION_ENABLED: bool = True+ # SKY-15288: when enabled, in-progress recording snapshots copy the already-uploaded prefix+ # server-side (UploadPartCopy against the prior ETag) and upload only the new tail; any unsupported+ # condition or failure falls back to the Phase 1 full-prefix stream. Off by default.+ RECORDING_INCREMENTAL_COMPOSE_ENABLED: bool = FalseVIDEO_COMPRESSION_CRF: int = 28VIDEO_COMPRESSION_PRESET: str = "veryfast"VIDEO_COMPRESSION_TIMEOUT_SECONDS: float = 300.0diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex f4501b7a0..dbdae2f4a 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -27,6 +27,7 @@ from skyvern.config import settingsfrom skyvern.constants import (BROWSER_DOWNLOAD_TIMEOUT,BROWSER_DOWNLOADING_SUFFIX,+ BROWSER_PAGE_CLOSE_TIMEOUT,DEFAULT_MAX_SCREENSHOT_SCROLLS,GET_DOWNLOADED_FILES_TIMEOUT,SAVE_DOWNLOADED_FILES_TIMEOUT,@@ -1103,6 +1104,57 @@ class ForgeAgent:return files_to_rename+ async def _close_claimed_download_popups(+ self, task: Task, browser_state: BrowserState | None, claims: list[Page]+ ) -> None:+ """Bounded best-effort close of exactly the given recorded download-popup claims.++ A file-download click that opens a new page is expected to have that page closed once the+ download finishes, regardless of its URL. On dynamic/remote-CDP runs the download is carried by+ the CDP monitor and credited by the file-scan task lifecycle after the action seam has returned,+ so no Playwright popup download event fires and the in-seam cleanup never sees it — the popup+ lingers and the next task can select it as the working page, wedging on screenshot/scrape/reload.+ Called only once a download is durably credited, this closes exactly the recorded popup Pages+ that are still open and still live in this run; an absent/closed page or a listing/close failure+ never closes an unrelated page, and the opener (never recorded as a claim) is never touched.+ """+ if browser_state is None or not claims:+ return+ try:+ valid_pages = await browser_state.list_valid_pages()+ except Exception:+ LOG.warning(+ "Failed to list valid pages while closing credited download popups",+ task_id=task.task_id,+ exc_info=True,+ )+ return+ for popup in claims:+ try:+ if popup.is_closed():+ continue+ if not any(candidate is popup for candidate in valid_pages):+ continue+ # Bound the close so a hung popup cannot block the completed-task handoff.+ async with asyncio.timeout(BROWSER_PAGE_CLOSE_TIMEOUT):+ await popup.close()+ LOG.info("Closed credited download popup", task_id=task.task_id)+ except Exception:+ LOG.warning(+ "Failed to close credited download popup",+ task_id=task.task_id,+ exc_info=True,+ )++ async def _close_credited_download_popups(self, task: Task, browser_state: BrowserState | None) -> None:+ """complete_on_download credit seam: take this task's recorded download-popup claims and close+ the popups the download action opened."""+ context = skyvern_context.current()+ if context is None:+ return+ claims = context.take_download_popup_claims(task.task_id)+ await self._close_claimed_download_popups(task, browser_state, claims)+async def _wait_for_in_flight_downloads(self,task: Task,@@ -2765,6 +2817,9 @@ class ForgeAgent:num_files_after=len(list_files_before) + len(files_to_rename),new_files=files_to_rename,)+ # The download is durably credited now; close the popup(s) the download action+ # opened so the next task does not select one as its working page.+ await self._close_credited_download_popups(task, browser_state)last_step = await self.update_step(step, is_last=True)completed_task = await self.update_task(task,@@ -5172,14 +5227,46 @@ class ForgeAgent:if not browser_state:returntry:- video_artifacts = await app.BROWSER_MANAGER.get_video_artifacts(- task_id=task.task_id, browser_state=browser_state, finalize=False- )- for video_artifact in video_artifacts:- await app.ARTIFACT_MANAGER.update_artifact_data(- artifact_id=video_artifact.video_artifact_id,+ snapshots = app.BROWSER_MANAGER.snapshot_recording_prefixes(+ browser_state=browser_state, task_id=task.task_id+ )+ if snapshots is None:+ # An artifact needs the remux/finalize (or first-registration) semantics owned by the+ # byte-based path; preserve it exactly rather than stream a partial prefix.+ video_artifacts = await app.BROWSER_MANAGER.get_video_artifacts(+ task_id=task.task_id, browser_state=browser_state, finalize=False+ )+ for video_artifact in video_artifacts:+ registered_video_path = video_artifact.video_path+ if (+ video_artifact.video_artifact_id+ and registered_video_path+ and not os.path.exists(registered_video_path)+ ):+ # Local file raced teardown: get_video_artifacts returned stale cached bytes.+ # Writing them would clobber the newer streamed prefix (see cleanup_and_persist_task).+ LOG.info(+ "Registered recording path missing; preserving latest stored prefix",+ task_id=task.task_id,+ organization_id=task.organization_id,+ video_artifact_id=video_artifact.video_artifact_id,+ video_path=registered_video_path,+ )+ continue+ # Mid-step fallback, not a terminal finalize: must not seal/supersede a queued prefix.+ await app.ARTIFACT_MANAGER.update_artifact_data(+ artifact_id=video_artifact.video_artifact_id,+ organization_id=task.organization_id,+ data=video_artifact.video_data,+ supersede_queued_prefixes=False,+ )+ return+ for snapshot in snapshots:+ await app.ARTIFACT_MANAGER.stream_artifact_prefix_from_path(+ artifact_id=snapshot.video_artifact_id,organization_id=task.organization_id,- data=video_artifact.video_data,+ path=snapshot.path,+ length=snapshot.prefix_len,)except Exception:LOG.warning(@@ -5411,19 +5498,28 @@ class ForgeAgent:# The recording file is still open here, so skip the ffmpeg remux — matches the# per-step sync path; the finalized upload happens in cleanup_and_persist_task.if browser_state and browser_state.browser_artifacts:- video_artifacts = await app.BROWSER_MANAGER.get_video_artifacts(- task_id=task.task_id, browser_state=browser_state, finalize=False- )- for idx, video_artifact in enumerate(video_artifacts):- if video_artifact.video_artifact_id:- continue- video_artifact_id = await app.ARTIFACT_MANAGER.create_artifact(- step=step,- artifact_type=ArtifactType.RECORDING,- data=video_artifact.video_data,+ # Only read recording bytes to register a not-yet-tracked recording: the empty/initial+ # list (first registration, incl. vendor/CDP browsers whose recordings attach later) or a+ # later popup/new-page recording that still lacks an id. Once every tracked recording is+ # registered, the per-step streaming sync path grows it without re-reading the whole+ # (growing) file here every step.+ tracked_video_artifacts = browser_state.browser_artifacts.video_artifacts+ if not tracked_video_artifacts or any(+ not video_artifact.video_artifact_id for video_artifact in tracked_video_artifacts+ ):+ video_artifacts = await app.BROWSER_MANAGER.get_video_artifacts(+ task_id=task.task_id, browser_state=browser_state, finalize=False)- video_artifacts[idx].video_artifact_id = video_artifact_id- app.BROWSER_MANAGER.set_video_artifact_for_task(task, video_artifacts)+ for idx, video_artifact in enumerate(video_artifacts):+ if video_artifact.video_artifact_id:+ continue+ video_artifact_id = await app.ARTIFACT_MANAGER.create_artifact(+ step=step,+ artifact_type=ArtifactType.RECORDING,+ data=video_artifact.video_data,+ )+ video_artifacts[idx].video_artifact_id = video_artifact_id+ app.BROWSER_MANAGER.set_video_artifact_for_task(task, video_artifacts)detailed_output = DetailedAgentStepOutput(scraped_page=None,@@ -6683,6 +6779,17 @@ class ForgeAgent:"""send the task response to the webhook callback url"""+ # Task-terminal expiry for download-popup claims: clean_up_task runs exactly when a task+ # reaches a terminal state (and not on retries, where the same task's next step may still+ # credit the download). Take (and drop) the claims into a local now, so terminal expiry holds+ # even if the DB refresh or later cleanup raises; if cleanup's own download finalization proves+ # a durable credit below, these held claims get the same bounded popup close as the+ # complete_on_download seam, otherwise they simply expire. (That seam already popped its own+ # claims, so this is empty on the completed-download path.)+ _claim_context = skyvern_context.current()+ cleanup_download_popup_claims = (+ _claim_context.take_download_popup_claims(task.task_id) if _claim_context is not None else []+ )_cleanup_span = otel_trace.get_current_span()# task_id, workflow_run_id auto-attached by @traced from SkyvernContext._cleanup_span.set_attribute("close_browser_on_completion", bool(close_browser_on_completion))@@ -6756,13 +6863,20 @@ class ForgeAgent:async with settle_browser_downloads_for_context(browser_context):passif download_suffix and list_files_before is not None:- await self._finalize_downloaded_files_for_task(+ cleanup_finalized_files = await self._finalize_downloaded_files_for_task(task,organization_id=task.organization_id,download_suffix=download_suffix,list_files_before=list_files_before,randomize_if_missing=False,)+ # Cleanup finalization is the second durable-credit seam: only when it+ # proves a new file did the download land, so only then close the popups the+ # download action opened (using the claims taken at cleanup entry).+ if cleanup_finalized_files:+ await self._close_claimed_download_popups(+ task, browser_state, cleanup_download_popup_claims+ )try:await app.STORAGE.save_downloaded_files(organization_id=task.organization_id,@@ -7167,19 +7281,37 @@ class ForgeAgent:LOG.debug("Uploading video artifacts", number_of_video_artifacts=len(video_artifacts))for video_artifact in video_artifacts:if video_artifact.video_artifact_id:+ registered_video_path = video_artifact.video_path+ if registered_video_path and not os.path.exists(registered_video_path):+ # The local file is gone (path raced teardown) so get_video_artifacts could not+ # refresh the cached bytes; writing them would clobber the newer streamed prefix.+ LOG.info(+ "Registered recording path missing; preserving latest stored prefix",+ task_id=task.task_id,+ organization_id=task.organization_id,+ video_artifact_id=video_artifact.video_artifact_id,+ video_path=registered_video_path,+ )+ continuetry:+ # Only a true terminal finalize (browser closed -> recording complete) may+ # supersede queued prefixes. On an intermediate cleanup the recording is still+ # growing and its prefixes are still legitimately being streamed, so sealing the+ # live key would kill per-step visibility (see manager.update_artifact_data).if video_artifact.video_file_extension:await app.ARTIFACT_MANAGER.update_artifact_data(artifact_id=video_artifact.video_artifact_id,organization_id=task.organization_id,data=video_artifact.video_data,file_extension=video_artifact.video_file_extension,+ supersede_queued_prefixes=close_browser_on_completion,)else:await app.ARTIFACT_MANAGER.update_artifact_data(artifact_id=video_artifact.video_artifact_id,organization_id=task.organization_id,data=video_artifact.video_data,+ supersede_queued_prefixes=close_browser_on_completion,)except Exception:LOG.warning(diff --git a/skyvern/forge/sdk/api/aws.py b/skyvern/forge/sdk/api/aws.pyindex b78eff42a..0282b3fc3 100644--- a/skyvern/forge/sdk/api/aws.py+++ b/skyvern/forge/sdk/api/aws.py@@ -5,16 +5,19 @@ import ioimport osimport socketimport time+import uuid+from collections import OrderedDictfrom collections.abc import Awaitable, Callablefrom enum import StrEnumfrom mimetypes import add_type, guess_type-from typing import IO, TYPE_CHECKING, Any+from typing import IO, TYPE_CHECKING, Any, castfrom urllib.parse import urlparseimport aioboto3import structlogfrom aiobotocore.config import AioConfigfrom aiohttp.abc import AbstractResolver, ResolveResult+from boto3.s3.transfer import TransferConfigfrom botocore.exceptions import ClientError, ProfileNotFoundfrom skyvern.config import settings@@ -34,11 +37,24 @@ add_type("application/zstd", ".zst")_S3_OPERATION_RETRIES = 2# get_object on a missing key raises NoSuchKey; head-style paths use 404/NotFound.S3_NOT_FOUND_ERROR_CODES = frozenset({"NoSuchKey", "NotFound", "404"})+# Expired AWS credentials surface under either exact code depending on the service/path.+_EXPIRED_TOKEN_ERROR_CODES = frozenset({"ExpiredTokenException", "ExpiredToken"})+# Aborting an upload id that no longer exists (e.g. an ambiguous Complete actually landed) returns this; it+# means the cleanup goal is already met, so it counts as a successful abort rather than a leaked orphan.+_ABORT_ALREADY_GONE_ERROR_CODES = frozenset({"NoSuchUpload", "404"})# Long-lived holders (e.g. the storage singleton on persistent-sessions workers) must not reuse a# session past the 1-hour projected web-identity token expiry (SKY-8743, SKY-13210)._SESSION_TTL_SECONDS: float = 45 * 60LOG = structlog.get_logger()+# Bound the resident memory of a streamed prefix upload. aioboto3's upload_fileobj reads parts into an+# asyncio queue of maxsize=max_io_queue_size (s3transfer default 1000) with multipart_chunksize=8MB, so a+# slow uploader lets resident bytes track the prefix size (a 400MB prefix queues >100MB). Capping the+# queue makes the resident buffer ~(queue depth x chunk size) regardless of prefix size. TransferConfig's+# max_io_queue aliases s3transfer's max_io_queue_size, so aioboto3 reads it correctly.+_STREAM_UPLOAD_IO_QUEUE_DEPTH = 8+_STREAM_UPLOAD_TRANSFER_CONFIG = TransferConfig(max_io_queue=_STREAM_UPLOAD_IO_QUEUE_DEPTH)+# We only include the storage classes that we want to use in our application.class S3StorageClass(StrEnum):@@ -106,6 +122,170 @@ class _PinnedIPResolver(AbstractResolver):return None+# S3 requires every non-final multipart part to be >= 5 MiB. A confirmed prefix below this cannot be+# copied as the (non-final) first part of an incremental compose, so such steps fall back to Phase 1.+_MIN_COMPOSE_BASE_BYTES = 5 * 1024 * 1024+# A single UploadPartCopy source range (and a single UploadPart body) may cover at most 5 GiB. A base+# prefix or a per-step tail beyond this would need multi-part splitting; we instead fall back to Phase 1.+_MAX_COMPOSE_PART_BYTES = 5 * 1024 * 1024 * 1024+# Unique per-generation token stored as object user metadata so an ambiguous Complete is reconciled by+# exact generation identity (length + token), never by length alone (a foreign write can share a length).+_COMPOSE_GEN_META_KEY = "skyvern-compose-gen"+# Bound the per-key compose-state cache: a recording's snapshots finish well within the TTL, and the cap+# stops leaked/extension-changed keys from accumulating. A miss just forces a safe full reseed next step.+_COMPOSE_STATE_MAX_ENTRIES = 512+_COMPOSE_STATE_TTL_SECONDS = 30 * 60+++class ComposeUnsupportedError(Exception):+ """Signal that an incremental same-key compose cannot proceed because the remote object is UNCHANGED+ (no/too-small/not-growing base, provider limit, or a failure before Complete). The caller may safely+ perform the Phase 1 full-prefix replacement in the same serialized slot; the base reseeds next step."""+++class _ComposeConflict(Exception):+ """The remote object moved under us (stale ETag, or a foreign generation surfaced during ambiguous-+ Complete reconciliation). The caller must PRESERVE the remote object — never overwrite it — and skip+ this step's write, reseeding the base from authoritative S3 state on the next step."""+++class _ComposeState:+ """The last compose-confirmed object generation for a key: its exact length and current ETag. Used+ as the ``CopySourceIfMatch`` fence for the next step's UploadPartCopy. Advanced only after a+ Complete is reconciled as durable."""++ __slots__ = ("etag", "length")++ def __init__(self, length: int, etag: str) -> None:+ self.length = length+ self.etag = etag+++class _RangedFileReader(io.RawIOBase):+ """A 0-based, seekable, read-only ``io.RawIOBase`` view over exactly ``[start, start+size)`` of an+ ALREADY-OPEN binary file handle. Being a real ``io.RawIOBase`` lets aiohttp/aiobotocore stream it as a+ request body (a plain duck-typed reader is rejected), so the tail/prefix upload never buffers the whole+ range. The handle is opened by the caller before any detach so a post-cancel unlink/replace of the path+ cannot strand the transfer; reads are hard-capped to ``size`` (the frozen snapshot length) so the view+ never follows a still-growing file, and ``seek(0)`` rewinds to ``start`` for a retry."""++ def __init__(self, fh: IO[bytes], start: int, size: int, owns_fh: bool = False) -> None:+ super().__init__()+ self._fh = fh+ # By default the reader is a NON-OWNING view: several readers share one fd within a single+ # store_recording_prefix call, so a reader closing on GC (its RawIOBase.__del__ -> close) must NOT+ # close the shared fd — otherwise a later same-slot fallback reads a closed file. The single caller+ # that outlives the outer call (the parked terminal fallback) passes owns_fh=True.+ self._owns_fh = owns_fh+ self._start = max(0, int(start))+ self._size = max(0, int(size))+ self._pos = 0+ self._fh.seek(self._start)++ def readinto(self, b: Any) -> int:+ remaining = self._size - self._pos+ if remaining <= 0:+ return 0+ data = self._fh.read(min(len(b), remaining))+ n = len(data)+ b[:n] = data+ self._pos += n+ return n++ def seek(self, offset: int, whence: int = os.SEEK_SET) -> int:+ if whence == os.SEEK_SET:+ target = offset+ elif whence == os.SEEK_CUR:+ target = self._pos + offset+ elif whence == os.SEEK_END:+ target = self._size + offset+ else:+ raise ValueError(f"invalid whence: {whence}")+ target = max(0, min(target, self._size))+ self._fh.seek(self._start + target)+ self._pos = target+ return self._pos++ def tell(self) -> int:+ return self._pos++ def seekable(self) -> bool:+ return True++ def readable(self) -> bool:+ return True++ def close(self) -> None:+ try:+ if self._owns_fh:+ self._fh.close()+ finally:+ super().close()+++class _ComposeStateCache:+ """Bounded TTL + LRU cache of per-key compose generations.++ Unbounded retention would leak a ``_ComposeState`` per recording forever (a terminal that remuxes the+ ``.webm`` object to a different ``.mp4`` uri never clears the old key). Entries expire after ``ttl_seconds``+ and the map is capped at ``max_size`` (oldest evicted first), so a missing/stale entry simply forces a safe+ full reseed on the next step. ``clock`` is injectable for deterministic tests."""++ def __init__(self, max_size: int, ttl_seconds: float, clock: Callable[[], float]) -> None:+ self._max_size = max_size+ self._ttl = ttl_seconds+ self._clock = clock+ self._entries: OrderedDict[str, tuple[_ComposeState, float]] = OrderedDict()++ def _evict(self) -> None:+ now = self._clock()+ for key in [k for k, (_, ts) in self._entries.items() if now - ts > self._ttl]:+ self._entries.pop(key, None)+ while len(self._entries) > self._max_size:+ self._entries.popitem(last=False)++ def get(self, key: str) -> _ComposeState | None:+ entry = self._entries.get(key)+ if entry is None:+ return None+ state, ts = entry+ if self._clock() - ts > self._ttl:+ self._entries.pop(key, None)+ return None+ self._entries.move_to_end(key)+ return state++ def set(self, key: str, state: _ComposeState) -> None:+ self._entries[key] = (state, self._clock())+ self._entries.move_to_end(key)+ self._evict()++ def pop(self, key: str) -> None:+ self._entries.pop(key, None)++ def __len__(self) -> int:+ return len(self._entries)++ def __contains__(self, key: str) -> bool:+ return self.get(key) is not None+++class _ParkedFallback:+ """The newest pre-terminal queued recording prefix, held so the terminal write can upload it iff the+ terminal write fails (otherwise it is discarded unread). ``upload`` streams the retained reader."""++ def __init__(self, reader: IO[bytes], upload: Callable[[], Awaitable[Any]]) -> None:+ self.reader = reader+ self.upload = upload+ self.consumed = False++ def close_reader(self) -> None:+ try:+ self.reader.close()+ except Exception:+ LOG.warning("Failed to close parked fallback reader", exc_info=True)++class AsyncAWSClient:def __init__(self,@@ -132,6 +312,27 @@ class AsyncAWSClient:)self._session: aioboto3.Session | None = Noneself._session_created_at: float = 0.0+ # Per-object-key write chain: serializes writes to one key in issue order so a later terminal+ # write is never overwritten by an earlier write that is still in flight (including one detached+ # by _detach_on_cancel). Holds at most one (tail) future per key with an in-flight write; each+ # entry is dropped when its key goes idle, so the map cannot grow unbounded.+ self._object_write_chains: dict[str, asyncio.Future[None]] = {}+ # Keys whose terminal (finalize) write has been reserved: queued-but-not-yet-active prefixes to+ # such a key are superseded and skipped, so the terminal waits only for the active transfer.+ # Dropped alongside the chain entry when the key goes idle.+ self._object_write_sealed: set[str] = set()+ # For a sealed key, the done future of the newest pre-terminal queued snapshot (the terminal's+ # `prev`). That one prefix parks itself as the terminal's fallback instead of being skipped.+ self._object_write_fallback_target: dict[str, asyncio.Future[None] | None] = {}+ # At most one parked fallback per key: the retained reader + a callable that uploads it. The+ # terminal discards it on success or uploads it on failure, and closes the reader either way.+ self._object_write_fallback: dict[str, _ParkedFallback] = {}+ # Phase 2: last compose-confirmed generation per serialize_key (recording uri), authored+verified by+ # this process. Read/written only inside that key's serialized write section, so steps observe a+ # consistent base. Bounded (TTL + LRU) so it cannot leak across many recordings.+ self._compose_state = _ComposeStateCache(+ max_size=_COMPOSE_STATE_MAX_ENTRIES, ttl_seconds=_COMPOSE_STATE_TTL_SECONDS, clock=time.monotonic+ )@propertydef session(self) -> aioboto3.Session:@@ -172,8 +373,11 @@ class AsyncAWSClient:self._create_session()def _is_expired_token_error(self, error: Exception) -> bool:- """Check if an exception is an AWS ExpiredTokenException."""- return isinstance(error, ClientError) and error.response.get("Error", {}).get("Code") == "ExpiredTokenException"+ """Check if an exception is an AWS expired-credentials error. S3/STS report this under either exact+ code: ``ExpiredTokenException`` (the long form) or ``ExpiredToken`` (the bare S3 form)."""+ return (+ isinstance(error, ClientError) and error.response.get("Error", {}).get("Code") in _EXPIRED_TOKEN_ERROR_CODES+ )def _is_not_found_error(self, error: Exception) -> bool:"""Check if an exception is a missing-object (terminal not-found) error."""@@ -234,6 +438,65 @@ class AsyncAWSClient:task.add_done_callback(lambda done: self._log_detached_transfer(op_name, done, **log_kwargs))raise+ def _begin_serialized_write(+ self, key: str, seal: bool = False, arm_fallback: bool = True+ ) -> tuple[asyncio.Future[None] | None, asyncio.Future[None]]:+ """Reserve this write's slot in ``key``'s issue-ordered write chain. Call synchronously before+ the first await so slot order matches call order. Returns ``(prev, done)``: await ``prev`` before+ writing, and complete ``done`` (via ``_finish_serialized_write``) once the real write finishes —+ for a detached transfer this must happen in the detached task, not on the cancelled awaiter.++ ``seal=True`` marks the key as being finalized: a queued prefix that has not yet begun its real+ transfer is superseded when its turn comes, so the terminal recording write waits only for the+ currently active transfer, not the whole queued backlog.++ ``arm_fallback`` (only meaningful with ``seal``) remembers the newest pre-terminal queued snapshot+ (``prev`` at seal time) as the terminal's fallback target: instead of being skipped it parks its+ reader (``_prefix_is_fallback_target``) so the terminal can upload it iff the terminal write fails.+ A fallback is only meaningful when the terminal writes the same object the prefixes queued to; when+ the finalize renames the object (``.webm`` prefixes, ``.mp4`` terminal) the parked prefix could+ never be served under the finalized uri, so the caller passes ``arm_fallback=False`` and the newest+ queued prefix is superseded like the rest."""+ prev = self._object_write_chains.get(key)+ done: asyncio.Future[None] = asyncio.get_running_loop().create_future()+ self._object_write_chains[key] = done+ if seal:+ self._object_write_sealed.add(key)+ if arm_fallback:+ self._object_write_fallback_target[key] = prev+ return prev, done++ def _prefix_superseded(self, key: str) -> bool:+ return key in self._object_write_sealed++ def _prefix_is_fallback_target(self, key: str, done: asyncio.Future[None]) -> bool:+ return self._object_write_fallback_target.get(key) is done++ def _finish_serialized_write(self, key: str, done: asyncio.Future[None]) -> None:+ if not done.done():+ done.set_result(None)+ if self._object_write_chains.get(key) is done:+ del self._object_write_chains[key]+ self._object_write_sealed.discard(key)+ self._object_write_fallback_target.pop(key, None)+ # Defensive: if a fallback was parked but its terminal never consumed it (e.g. no terminal+ # ever ran), close the retained reader when the key drains so it cannot leak.+ orphan = self._object_write_fallback.pop(key, None)+ if orphan is not None:+ orphan.close_reader()++ @staticmethod+ async def _await_prev_write(prev: asyncio.Future[None]) -> None:+ # Order this write after the previous one to the same key. The chain future only ever resolves+ # with a result, so the only exception here is this task's own cancellation, which must propagate+ # (never swallow it); a prior write's own outcome must not block us, hence the defensive guard.+ try:+ await prev+ except asyncio.CancelledError:+ raise+ except Exception:+ pass+@staticmethoddef _log_detached_transfer(op_name: str, task: asyncio.Task[Any], **log_kwargs: Any) -> None:if task.cancelled():@@ -318,6 +581,8 @@ class AsyncAWSClient:data: bytes,storage_class: S3StorageClass = S3StorageClass.STANDARD,tags: dict[str, str] | None = None,+ serialize_key: str | None = None,+ supersede_queued: bool = False,) -> str | None:# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3/client/put_object.htmlif storage_class not in S3StorageClass:@@ -336,6 +601,51 @@ class AsyncAWSClient:)return uri+ if serialize_key is not None:+ # A serialized write (a recording's terminal put) must both wait for older prefixes and+ # survive the wait_for_upload_aiotasks barrier that can cancel this queued task while it is+ # draining them — detach so put_object still lands last instead of being lost.+ # supersede_queued marks this the finalize: queued-not-active prefixes are then skipped so+ # this write waits only for the currently active transfer. A fallback is only armed when the+ # finalize writes the same object the prefixes queued to; when it renames the object+ # (serialize_key is the old prefix key, uri is the new object) a parked prefix could never be+ # served under the finalized uri, so we skip the fallback and let the newest prefix supersede.+ arm_fallback = serialize_key == uri+ prev, done = self._begin_serialized_write(serialize_key, seal=supersede_queued, arm_fallback=arm_fallback)++ async def _run() -> str | None:+ # The terminal owns any parked fallback (the newest pre-terminal queued prefix): discard it+ # unread on success, upload it on failure so the recording does not regress to the older+ # active prefix. The retained reader is closed on every path in the finally.+ try:+ if prev is not None:+ await self._await_prev_write(prev)+ return await self._s3_with_retry("upload", _op, uri=uri)+ except Exception:+ LOG.exception("S3 upload failed.", uri=uri)+ fallback = self._object_write_fallback.get(serialize_key)+ if fallback is not None and not fallback.consumed:+ fallback.consumed = True+ try:+ await fallback.upload()+ except Exception:+ LOG.exception("S3 fallback prefix upload failed.", uri=uri)+ return None+ finally:+ fb = self._object_write_fallback.pop(serialize_key, None)+ if fb is not None:+ fb.close_reader()+ # Any serialized upload_file is a full put_object that replaces the whole object (and its+ # metadata), so a compose base cached from a prior streamed snapshot is now stale — its+ # ETag no longer matches, and the next snapshot's conditional copy would 412 and be+ # skipped. Clear it INSIDE the serialized slot AFTER draining prior writes and writing,+ # on EVERY exit path (not only the terminal finalize; conservative even when the write+ # outcome is ambiguous — safety beats cache-hit rate). The next snapshot reseeds.+ self._compose_state.pop(serialize_key)+ self._finish_serialized_write(serialize_key, done)++ return await self._detach_on_cancel("upload", _run, uri=uri)+try:return await self._s3_with_retry("upload", _op, uri=uri)except Exception:@@ -348,6 +658,8 @@ class AsyncAWSClient:file_obj: IO[bytes],storage_class: S3StorageClass = S3StorageClass.STANDARD,tags: dict[str, str] | None = None,+ close_file_obj: bool = False,+ serialize_key: str | None = None,) -> str | None:# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3/client/upload_fileobj.html#upload-fileobjif storage_class not in S3StorageClass:@@ -364,6 +676,7 @@ class AsyncAWSClient:parsed_uri.bucket,parsed_uri.key,ExtraArgs=extra_args,+ Config=_STREAM_UPLOAD_TRANSFER_CONFIG,)LOG.debug("Upload file stream success", uri=uri)return uri@@ -376,16 +689,476 @@ class AsyncAWSClient:return Falsereturn None+ # Reserve the write-chain slot synchronously (before detaching) so slot order matches call order.+ prev, done = self._begin_serialized_write(serialize_key) if serialize_key else (None, None)+ parked = False++ async def _run() -> str:+ nonlocal parked+ try:+ # Held inside the detached task: a later same-key write (e.g. the terminal upload) awaits+ # `done`, so even a cancelled-then-detached prefix keeps its slot until it truly finishes.+ if prev is not None:+ await self._await_prev_write(prev)+ if serialize_key is not None and self._prefix_superseded(serialize_key):+ if done is not None and self._prefix_is_fallback_target(serialize_key, done):+ # Newest pre-terminal queued snapshot: park (don't upload) so the terminal can+ # fall back to it if its own write fails. Ownership of file_obj passes to the+ # parked fallback, which the terminal closes (on success) or uploads then closes.+ async def _fallback_upload() -> Any:+ return await self._s3_with_retry(+ "stream upload (fallback)", _op, before_retry=_rewind_stream, uri=uri+ )++ self._object_write_fallback[serialize_key] = _ParkedFallback(file_obj, _fallback_upload)+ parked = True+ return uri+ # Superseded and not the fallback: skip the obsolete upload so the terminal waits only+ # for the active transfer, not the whole queued backlog.+ LOG.debug("Superseded by terminal recording write; skipping queued prefix", uri=uri)+ return uri+ return await self._s3_with_retry("stream upload", _op, before_retry=_rewind_stream, uri=uri)+ finally:+ # The transfer can be detached and outlive this call's awaiter (see _detach_on_cancel), so+ # an owned file_obj is closed only after the real transfer finishes — never on the caller's+ # cancel path. A parked fallback keeps its reader open; the terminal owns and closes it.+ if close_file_obj and not parked:+ file_obj.close()+ if done is not None and serialize_key is not None:+ self._finish_serialized_write(serialize_key, done)+try:- return await self._detach_on_cancel(- "stream upload",- lambda: self._s3_with_retry("stream upload", _op, before_retry=_rewind_stream, uri=uri),- uri=uri,- )+ return await self._detach_on_cancel("stream upload", _run, uri=uri)except Exception:LOG.exception("S3 upload stream failed.", uri=uri)return None+ def forget_compose_state(self, serialize_key: str) -> None:+ """Drop any cached compose base for a key (e.g. after a terminal full replacement rewrites bytes,+ so the next run's first step reseeds from S3 rather than trusting a stale generation)."""+ self._compose_state.pop(serialize_key)++ async def store_recording_prefix(+ self,+ uri: str,+ path: str,+ length: int,+ *,+ storage_class: S3StorageClass = S3StorageClass.STANDARD,+ serialize_key: str,+ ) -> str | None:+ """Advance the recording object at ``uri`` to exactly ``[0, length)``.++ Preferred path: copy the already-uploaded prefix server-side (UploadPartCopy against the confirmed+ ETag) and upload only the new tail, so per-step client bytes are the delta, not the whole prefix.+ If that is unsupported (no/too-small/not-growing base, provider limit, or a failure that left the+ remote object UNCHANGED) the Phase 1 full-prefix replacement runs IN THE SAME serialized slot, so a+ later step can never interleave between the failed compose and its fallback. If the remote object+ moved under us (stale ETag / foreign generation) the step is skipped and the remote is preserved.++ The file handle is opened before the transfer is detached so a post-cancel unlink cannot strand it;+ reads are hard-capped to the frozen ``length``. Readers only ever observe a complete old or complete+ new object. Returns ``uri`` on success, ``None`` on a swallowed transfer failure; ``OSError`` from+ opening a vanished file propagates so the caller can treat it like the Phase 1 stream did."""+ parsed_uri = S3Uri(uri)+ # Own the fd before reserving the slot / detaching (blocker: cancel-then-unlink must not strand it).+ fh = open(path, "rb") # noqa: SIM115 — lifetime spans the detached transfer; closed in _run's finally+ prev, done = self._begin_serialized_write(serialize_key)+ parked = False++ async def _run() -> str | None:+ nonlocal parked+ try:+ if prev is not None:+ await self._await_prev_write(prev)+ if self._prefix_superseded(serialize_key):+ if done is not None and self._prefix_is_fallback_target(serialize_key, done):+ # Newest pre-terminal snapshot: park an owned full-prefix reader so the terminal can+ # upload it iff the terminal write fails (mirrors the Phase 1 stream fallback). This+ # reader OUTLIVES the outer call, so it owns the fd; the terminal closes it on success+ # or uploads-then-closes on failure.+ reader = _RangedFileReader(fh, 0, length, owns_fh=True)++ def _rewind() -> bool | None:+ try:+ reader.seek(0)+ except (OSError, io.UnsupportedOperation):+ return False+ return None++ async def _fallback_upload() -> Any:+ async def _op() -> None:+ async with self._s3_client() as client:+ await client.upload_fileobj(+ reader,+ parsed_uri.bucket,+ parsed_uri.key,+ ExtraArgs={"StorageClass": str(storage_class)},+ Config=_STREAM_UPLOAD_TRANSFER_CONFIG,+ )++ return await self._s3_with_retry(+ "recording prefix (fallback)", _op, before_retry=_rewind, uri=uri+ )++ self._object_write_fallback[serialize_key] = _ParkedFallback(+ cast("IO[bytes]", reader), _fallback_upload+ )+ parked = True+ return uri+ # Superseded and not the fallback target: skip the obsolete write.+ LOG.debug("Superseded by terminal recording write; skipping queued prefix", uri=uri)+ return uri+ return await self._compose_or_replace(parsed_uri, uri, fh, length, serialize_key, storage_class)+ finally:+ # A parked fallback keeps its reader (and fd) open; the terminal owns and closes it.+ if not parked:+ fh.close()+ self._finish_serialized_write(serialize_key, done)++ try:+ return await self._detach_on_cancel("recording prefix", _run, uri=uri)+ except Exception:+ LOG.exception("S3 recording prefix write failed.", uri=uri)+ return None++ async def _compose_or_replace(+ self, parsed_uri: S3Uri, uri: str, fh: IO[bytes], length: int, serialize_key: str, sc: S3StorageClass+ ) -> str:+ # Wrap the WHOLE compose-or-replace transaction in the shared expired-token refresh+retry (parity+ # with the Phase 1 stream): an ExpiredToken on head/create/copy/upload/complete refreshes the session+ # and retries the whole transaction once on a fresh client, instead of silently degrading to a+ # fallback on the same expired client and failing every snapshot until the TTL.+ # An expired-token attempt that had already created an MPU cannot abort it on its now-invalid client+ # (one dead session token invalidates the whole client, so that abort just raises); the orphan upload+ # id is carried here and aborted on the refreshed client before a replacement MPU is created, so a+ # credential expiry mid-compose does not leak an incomplete multipart upload.+ orphan_upload_ids: list[str] = []++ async def _op() -> str:+ async with self._s3_client() as client:+ unabortable: list[str] = []+ while orphan_upload_ids:+ uid = orphan_upload_ids.pop()+ if not await self._abort_compose(client, parsed_uri, uid):+ unabortable.append(uid)+ if unabortable:+ # Fail closed: the refreshed client still could not abort a carried orphan MPU. Do NOT+ # create a replacement compose MPU on top of an un-aborted orphan. Preserve the existing+ # remote object (never overwrite), drop stale local compose state so the next step authors+ # a fresh verified generation, log the lifecycle-policy backstop, and skip this step. The+ # bucket AbortIncompleteMultipartUpload lifecycle rule (the documented rollout+ # prerequisite) reclaims the leaked upload.+ self._compose_state.pop(serialize_key)+ LOG.warning(+ "Orphaned compose MPU could not be aborted on the refreshed client; skipping this "+ "step and preserving the remote (bucket AbortIncompleteMultipartUpload lifecycle rule "+ "is the backstop)",+ uri=uri,+ upload_ids=unabortable,+ )+ return uri+ try:+ result = await self._compose_once(+ client, parsed_uri, uri, fh, length, serialize_key, sc, orphan_upload_ids+ )+ except _ComposeConflict:+ # The remote object moved under us: never overwrite it. Drop our (now wrong) state and+ # let the next step author a fresh verified generation; skip this write.+ self._compose_state.pop(serialize_key)+ LOG.warning("Compose conflict; preserving remote generation and skipping step", uri=uri)+ return uri+ except ComposeUnsupportedError:+ # Remote unchanged or no owned base: author a verified full replacement in this same slot+ # (also reseeds compose state), so ordering with later steps is preserved.+ return await self._full_replace_and_seed(client, parsed_uri, uri, fh, length, serialize_key, sc)+ if isinstance(result, str):+ # A fresh-client fallback already replaced-or-skipped on a healthy client and managed+ # compose state itself (a failed inline abort was cleaned up before continuing).+ return result+ self._compose_state.set(serialize_key, result)+ return uri++ return await self._s3_with_retry("recording prefix compose", _op, uri=uri)++ async def _full_replace_and_seed(+ self,+ client: Any,+ parsed_uri: S3Uri,+ uri: str,+ fh: IO[bytes],+ length: int,+ serialize_key: str,+ sc: S3StorageClass,+ ) -> str:+ """Full-prefix replacement that AUTHORS a verified generation: write ``[0, length)`` with a unique+ token in object metadata, then HeadObject and seed local compose state ONLY if the object carries our+ exact token and length. This is the sole way compose state is seeded, so a later step can only ever+ copy a prefix this process authored and verified — a foreign/zombie writer's object is never spliced+ into. If a foreign writer raced our PUT (token/length mismatch) we do not seed and the next step+ full-replaces again."""+ token = uuid.uuid4().hex+ reader = _RangedFileReader(fh, 0, length) # non-owning: the outer store_recording_prefix owns fh+ await client.upload_fileobj(+ reader,+ parsed_uri.bucket,+ parsed_uri.key,+ ExtraArgs={"StorageClass": str(sc), "Metadata": {_COMPOSE_GEN_META_KEY: token}},+ Config=_STREAM_UPLOAD_TRANSFER_CONFIG,+ )+ head = await client.head_object(Bucket=parsed_uri.bucket, Key=parsed_uri.key)+ hmeta = head.get("Metadata") or {}+ head_len = head.get("ContentLength")+ head_etag = head.get("ETag")+ seeded = (+ head_len is not None+ and head_etag is not None+ and int(head_len) == length+ and hmeta.get(_COMPOSE_GEN_META_KEY) == token+ )+ if seeded:+ self._compose_state.set(serialize_key, _ComposeState(length, str(head_etag).strip('"')))+ else:+ self._compose_state.pop(serialize_key)+ return uri++ async def _compose_once(+ self,+ client: Any,+ parsed_uri: S3Uri,+ uri: str,+ fh: IO[bytes],+ length: int,+ serialize_key: str,+ sc: S3StorageClass,+ orphan_upload_ids: list[str],+ ) -> _ComposeState | str:+ if self._endpoint_url is not None:+ # The compose anti-corruption fence relies on conditional CompleteMultipartUpload (IfMatch) and+ # CopySourceIfMatch, which are AWS-S3-specific. A customer-pointed S3-compatible endpoint may ignore+ # an unsupported IfMatch and silently degrade the fence to an unconditional overwrite, so refuse+ # compose entirely and fall back to the verified full-prefix replacement (fail closed).+ raise ComposeUnsupportedError()+ base = self._compose_state.get(serialize_key)+ if base is None:+ # No generation THIS process authored+verified. Never head-and-trust an unowned remote object: a+ # duplicate/zombie producer could have full-PUT a foreign >=5 MiB generation, and copying its+ # prefix + our tail would splice a mixed/unplayable object. Force a verified full reseed instead.+ raise ComposeUnsupportedError()+ if base.length < _MIN_COMPOSE_BASE_BYTES:+ # Confirmed base below the 5-MiB copy floor: fall back to a full replacement (which reseeds).+ raise ComposeUnsupportedError()+ if length < base.length:+ # The confirmed generation is LONGER than this snapshot: never truncate it back to an older,+ # shorter prefix — preserve the remote and skip.+ raise _ComposeConflict()+ if length == base.length:+ # Already at the target length: nothing to append. No-op (do not full-PUT), keep the base.+ return base+ tail_size = length - base.length+ if base.length > _MAX_COMPOSE_PART_BYTES or tail_size > _MAX_COMPOSE_PART_BYTES:+ # A single copy part / tail part cannot exceed 5 GiB; fall back rather than split.+ raise ComposeUnsupportedError()+ token = uuid.uuid4().hex+ try:+ create = await client.create_multipart_upload(+ Bucket=parsed_uri.bucket,+ Key=parsed_uri.key,+ StorageClass=str(sc),+ Metadata={_COMPOSE_GEN_META_KEY: token},+ )+ except Exception as e:+ if self._is_expired_token_error(e):+ raise # let _s3_with_retry refresh + retry the whole transaction+ # No MPU to abort; the remote object is unchanged -> safe full-prefix fallback.+ raise ComposeUnsupportedError()+ upload_id = create["UploadId"]+ try:+ try:+ copy = await client.upload_part_copy(+ Bucket=parsed_uri.bucket,+ Key=parsed_uri.key,+ UploadId=upload_id,+ PartNumber=1,+ CopySource={"Bucket": parsed_uri.bucket, "Key": parsed_uri.key},+ CopySourceIfMatch=base.etag,+ CopySourceRange=f"bytes=0-{base.length - 1}",+ )+ except ClientError as e:+ if self._error_code(e) in ("PreconditionFailed", "412"):+ # The confirmed base moved under us: preserve the remote, do not full-PUT over it.+ if await self._abort_compose(client, parsed_uri, upload_id):+ raise _ComposeConflict()+ return await self._cleanup_after_failed_abort(parsed_uri, uri, upload_id, serialize_key, None)+ raise+ part1_etag = copy["CopyPartResult"]["ETag"]+ tail_reader = _RangedFileReader(fh, base.length, tail_size) # non-owning+ part2 = await client.upload_part(+ Bucket=parsed_uri.bucket, Key=parsed_uri.key, UploadId=upload_id, PartNumber=2, Body=tail_reader+ )+ parts = {"Parts": [{"PartNumber": 1, "ETag": part1_etag}, {"PartNumber": 2, "ETag": part2["ETag"]}]}+ try:+ # Fence the Complete on the verified base ETag (If-Match header on CompleteMultipartUpload in+ # the pinned botocore model). UploadPartCopy fences only the COPY SOURCE; a foreign producer+ # can still replace the destination object between the copy and the Complete. Without this+ # fence an unconditional Complete would overwrite that newer generation. base.etag is the+ # stripped ETag, matching the CopySourceIfMatch convention above (S3 accepts the unquoted+ # strong validator; validated in the real-S3 compose probe).+ complete = await client.complete_multipart_upload(+ Bucket=parsed_uri.bucket,+ Key=parsed_uri.key,+ UploadId=upload_id,+ MultipartUpload=parts,+ IfMatch=base.etag,+ )+ except Exception as e:+ if self._is_expired_token_error(e):+ # The client is dead — reconciling/aborting here is futile. Re-raise; the outer handler+ # records the orphan MPU (once) and _s3_with_retry refreshes + retries on a fresh client.+ raise+ if isinstance(e, ClientError) and self._error_code(e) in (+ "PreconditionFailed",+ "412",+ "ConditionalRequestConflict",+ "409",+ ):+ # The IfMatch fence rejected the Complete: the destination changed under us (a foreign+ # generation replaced it after our copy). Preserve that generation — never overwrite it.+ if await self._abort_compose(client, parsed_uri, upload_id):+ raise _ComposeConflict()+ return await self._cleanup_after_failed_abort(parsed_uri, uri, upload_id, serialize_key, None)+ # Ambiguous Complete (lost response / transport blip): reconcile by HEAD, which preserves a+ # foreign generation and only advances on a proven-durable one; never a blind full replacement.+ outcome = await self._reconcile_complete(client, parsed_uri, length, base, token)+ if isinstance(outcome, _ComposeState):+ return outcome # Complete actually landed (verified by length + generation token).+ if await self._abort_compose(client, parsed_uri, upload_id):+ if outcome == "conflict":+ raise _ComposeConflict()+ raise ComposeUnsupportedError()+ fallback = None if outcome == "conflict" else (fh, length, sc)+ return await self._cleanup_after_failed_abort(parsed_uri, uri, upload_id, serialize_key, fallback)+ new_etag = complete.get("ETag")+ if not new_etag:+ # Complete succeeded but omitted ETag. Reconcile by HEAD and advance state ONLY if the object+ # is provably OUR generation (exact length + our token). A foreign generation that raced in+ # between Complete and HEAD must not be cached (its ETag would let the next snapshot's+ # conditional copy splice a foreign prefix onto our tail) nor overwritten (the MPU already+ # completed): preserve it and skip this step.+ outcome = await self._reconcile_complete(client, parsed_uri, length, base, token)+ if isinstance(outcome, _ComposeState):+ return outcome+ raise _ComposeConflict()+ return _ComposeState(length, new_etag.strip('"'))+ except (_ComposeConflict, ComposeUnsupportedError):+ raise+ except Exception as e:+ if self._is_expired_token_error(e):+ # Carry the orphan MPU to the refreshed-client retry (aborting on this expired client fails);+ # do NOT abort here on the dead client.+ orphan_upload_ids.append(upload_id)+ raise+ # A non-expired failure before/around Complete that left the remote object unchanged: abort now on+ # this still-valid client, then let the caller do the safe full-prefix replacement. If this inline+ # abort fails (a transient transport blip), retry the cleanup on a freshly-created client and author+ # the replacement there — never leave the incomplete MPU to lifecycle when a fresh client can still+ # reclaim it, and never full-replace on top of an un-aborted orphan.+ if await self._abort_compose(client, parsed_uri, upload_id):+ raise ComposeUnsupportedError()+ return await self._cleanup_after_failed_abort(parsed_uri, uri, upload_id, serialize_key, (fh, length, sc))++ async def _reconcile_complete(+ self, client: Any, parsed_uri: S3Uri, length: int, base: _ComposeState, token: str+ ) -> _ComposeState | str:+ """Resolve an ambiguous Complete by HeadObject. Returns a ``_ComposeState`` only when the object is+ provably OUR generation (exact length AND our generation token); ``"unsupported"`` when the old base+ is still intact (safe to full-replace); ``"conflict"`` when a foreign/other generation is present or+ the head cannot be read (must preserve, never overwrite)."""+ try:+ head = await client.head_object(Bucket=parsed_uri.bucket, Key=parsed_uri.key)+ hlen = int(head["ContentLength"])+ hetag = str(head["ETag"]).strip('"')+ hmeta = head.get("Metadata") or {}+ except asyncio.CancelledError:+ raise+ except Exception as e:+ if self._is_expired_token_error(e):+ # An expired token on the reconciliation HEAD is recoverable, not a conflict: re-raise so the+ # outer handler carries the orphan MPU and _s3_with_retry refreshes the session and retries the+ # whole transaction on a fresh client (preserving expired-token handling).+ raise+ # ANY OTHER unreadable HEAD after an ambiguous Complete — a non-token ClientError, a botocore+ # transport/read/endpoint failure (EndpointConnectionError, ReadTimeoutError, ...), OR a 200 whose+ # body omits ContentLength/ETag — leaves the Complete outcome unknown. A foreign generation may+ # have landed during the same blip, so preserve the remote and resolve conflict; never fall+ # through to a full replacement that could clobber it.+ return "conflict"+ if hlen == length and hmeta.get(_COMPOSE_GEN_META_KEY) == token:+ LOG.info("Ambiguous compose Complete reconciled as durable (length + token)", uri=parsed_uri.uri)+ return _ComposeState(length, hetag)+ if hlen == base.length and hetag == base.etag:+ return "unsupported"+ return "conflict"++ async def _abort_compose(self, client: Any, parsed_uri: S3Uri, upload_id: str) -> bool:+ """Best-effort abort of a compose MPU. Returns True iff the incomplete upload is gone afterward, so a+ caller cleaning up an orphan on the refreshed client can tell it is actually cleaned up. A+ ``NoSuchUpload`` (the upload was already completed/aborted — e.g. an ambiguous Complete actually+ landed) counts as success: the cleanup goal is met, so it must not be reported as an unabortable+ orphan (which would trigger a false lifecycle-leak warning / fail-closed skip). A genuine failure+ (AccessDenied, transport, expired token, ...) still returns False so it is not masked."""+ try:+ await client.abort_multipart_upload(Bucket=parsed_uri.bucket, Key=parsed_uri.key, UploadId=upload_id)+ return True+ except ClientError as e:+ if self._error_code(e) in _ABORT_ALREADY_GONE_ERROR_CODES:+ return True+ LOG.warning("Failed to abort compose multipart upload", uri=parsed_uri.uri, upload_id=upload_id)+ return False+ except Exception:+ LOG.warning("Failed to abort compose multipart upload", uri=parsed_uri.uri, upload_id=upload_id)+ return False++ async def _cleanup_after_failed_abort(+ self,+ parsed_uri: S3Uri,+ uri: str,+ upload_id: str,+ serialize_key: str,+ fallback_replace: tuple[IO[bytes], int, S3StorageClass] | None,+ ) -> str:+ """An in-line abort of our compose MPU failed on a still-valid (non-expired) client. Retry the cleanup+ exactly once on a freshly-created client BEFORE disposing of this snapshot, so a transient abort blip+ does not strand the incomplete MPU until the bucket lifecycle rule reclaims it. On cleanup success a+ safe fallback path (``fallback_replace`` given, remote unchanged) authors its full replacement on that+ same healthy fresh client; a conflict path (``fallback_replace`` None) just preserves the remote. On+ cleanup failure, fail closed: preserve the remote, clear stale compose state, author no replacement /+ new MPU, and leave the bucket AbortIncompleteMultipartUpload lifecycle rule as the only backstop. This+ never loops."""+ # Disposing of this snapshot: drop our (now-suspect) compose state up front so even a fresh-client+ # construction failure cannot strand it. A successful fallback replacement below re-seeds a verified+ # generation via _full_replace_and_seed; every other outcome intentionally leaves it cleared.+ self._compose_state.pop(serialize_key)+ # The in-line abort may have failed because the token expired between the primary op and the abort.+ # _s3_client reuses the cached session (recreated only on the 45-min TTL), so refresh it here to give+ # the fresh client refreshed credentials; otherwise a token-expired abort fails identically and, since+ # this returns normally, _s3_with_retry never sees the token error and never refreshes.+ self.refresh_session()+ async with self._s3_client() as fresh:+ cleaned = await self._abort_compose(fresh, parsed_uri, upload_id)+ if cleaned and fallback_replace is not None:+ fh, length, sc = fallback_replace+ return await self._full_replace_and_seed(fresh, parsed_uri, uri, fh, length, serialize_key, sc)+ if not cleaned:+ LOG.warning(+ "Failed to abort compose MPU on both the in-line and a freshly-created client; preserving the "+ "remote and skipping this step (bucket AbortIncompleteMultipartUpload lifecycle rule is the "+ "backstop)",+ uri=uri,+ upload_id=upload_id,+ )+ return uri+async def upload_file_from_path(self,uri: str,diff --git a/skyvern/forge/sdk/artifact/manager.py b/skyvern/forge/sdk/artifact/manager.pyindex ec93b7036..53e107e24 100644--- a/skyvern/forge/sdk/artifact/manager.py+++ b/skyvern/forge/sdk/artifact/manager.py@@ -1277,6 +1277,7 @@ class ArtifactManager:data: bytes,primary_key: str = "task_id",file_extension: str | None = None,+ supersede_queued_prefixes: bool = False,) -> str | None:if not artifact_id or not organization_id:return None@@ -1292,10 +1293,12 @@ class ArtifactManager:data,workflow_run_id=artifact.workflow_run_id,)+ prefix_uri: str | None = Noneif file_extension and artifact.artifact_type == ArtifactType.RECORDING:- next_uri = replace_file_extension(artifact.uri, file_extension)+ old_uri = artifact.uri+ next_uri = replace_file_extension(old_uri, file_extension)file_size = len(data)- if next_uri != artifact.uri or artifact.file_size != file_size:+ if next_uri != old_uri or artifact.file_size != file_size:updated_artifact = await app.DATABASE.artifacts.update_artifact_uri(artifact_id=artifact.artifact_id,organization_id=organization_id,@@ -1309,9 +1312,20 @@ class ArtifactManager:f"Failed to update recording artifact metadata before upload: {artifact.artifact_id}")artifact = updated_artifact-- # Fire and forget- aio_task = asyncio.create_task(app.STORAGE.store_artifact(artifact, data))+ if next_uri != old_uri:+ # The finalize renamed the object (e.g. .webm -> .mp4); the per-step prefixes queued to the+ # pre-rename key, so pass it as prefix_uri to seal/supersede THAT key rather than the new one+ # nothing queued to.+ prefix_uri = old_uri++ # Fire and forget. Only a terminal recording finalize (supersede_queued_prefixes=True, passed by+ # the terminal persistence sites) supersedes queued prefixes; the generic path — including the+ # mid-step byte fallback in _sync_video_artifact_after_step — must not seal.+ aio_task = asyncio.create_task(+ app.STORAGE.store_artifact(+ artifact, data, supersede_queued_prefixes=supersede_queued_prefixes, prefix_uri=prefix_uri+ )+ )# A code-block recording artifact is workflow-run-block-scoped rather than task-scoped, so# key the upload tracking on the first available scope id instead of failing on a null task_id.@@ -1321,6 +1335,49 @@ class ArtifactManager:self._track_upload_aiotask(aio_task_key, aio_task, artifact=artifact)return aio_task_key+ async def stream_artifact_prefix_from_path(+ self,+ artifact_id: str | None,+ organization_id: str | None,+ path: str,+ length: int,+ primary_key: str = "task_id",+ ) -> str | None:+ """Per-step recording sync: upload exactly ``[0, length)`` of ``path`` by streaming it, without+ buffering the whole growing prefix as ``bytes``. RECORDING is not redactable, so (unlike+ ``update_artifact_data``) no redaction pass is needed."""+ if not artifact_id or not organization_id:+ return None+ artifact = await app.DATABASE.artifacts.get_artifact_by_id(artifact_id, organization_id)+ if not artifact:+ return None+ if artifact.artifact_type == ArtifactType.UNKNOWN:+ LOG.warning("Refusing to stream data for an artifact of unknown type", artifact_id=artifact_id)+ return None++ async def _store_prefix() -> None:+ # The recording file can be removed concurrently; the read now happens in this fire-and-forget+ # task (not the caller's try/except), so swallow a vanished/unreadable file the way the old+ # synchronous per-step read did, rather than let it surface unhandled in wait_for_upload_aiotasks.+ try:+ await app.STORAGE.store_artifact_prefix_from_path(artifact, path, length)+ except OSError:+ LOG.warning(+ "Skipping recording prefix upload; file unavailable",+ artifact_id=artifact_id,+ path=path,+ exc_info=True,+ )++ # Fire and forget+ aio_task = asyncio.create_task(_store_prefix())++ aio_task_key = artifact[primary_key] or artifact["workflow_run_block_id"] or artifact["run_id"]+ if not aio_task_key:+ raise ValueError("artifact must have a task_id, workflow_run_block_id, or run_id to track its upload.")+ self._track_upload_aiotask(aio_task_key, aio_task, artifact=artifact)+ return aio_task_key+async def retrieve_artifact(self, artifact: Artifact) -> bytes | None:return await app.STORAGE.retrieve_artifact(artifact)diff --git a/skyvern/forge/sdk/artifact/storage/azure.py b/skyvern/forge/sdk/artifact/storage/azure.pyindex 0833bb35e..ec34798a0 100644--- a/skyvern/forge/sdk/artifact/storage/azure.py+++ b/skyvern/forge/sdk/artifact/storage/azure.py@@ -133,7 +133,13 @@ class AzureStorage(BaseStorage):file_path=file_path,)- async def store_artifact(self, artifact: Artifact, data: bytes) -> None:+ async def store_artifact(+ self,+ artifact: Artifact,+ data: bytes,+ supersede_queued_prefixes: bool = False,+ prefix_uri: str | None = None,+ ) -> None:tier = await self._get_storage_tier_for_org(artifact.organization_id)tags = await self._get_tags_for_org(artifact.organization_id)LOG.debug(diff --git a/skyvern/forge/sdk/artifact/storage/base.py b/skyvern/forge/sdk/artifact/storage/base.pyindex 8da4efe1e..8003f60ca 100644--- a/skyvern/forge/sdk/artifact/storage/base.py+++ b/skyvern/forge/sdk/artifact/storage/base.py@@ -226,7 +226,18 @@ class BaseStorage(ABC):pass@abstractmethod- async def store_artifact(self, artifact: Artifact, data: bytes) -> None:+ async def store_artifact(+ self,+ artifact: Artifact,+ data: bytes,+ supersede_queued_prefixes: bool = False,+ prefix_uri: str | None = None,+ ) -> None:+ # supersede_queued_prefixes marks a recording's finalize write and prefix_uri names the pre-finalize+ # key its per-step prefixes queued to (when the finalize renames the object, e.g. .webm -> .mp4).+ # Only the S3 backend serializes prefix vs finalize writes and acts on these; other backends ignore+ # them and just overwrite, so the stale-prefix-cannot-overwrite-the-finalized-object ordering+ # guarantee holds on S3 only (see store_artifact_prefix_from_path).pass@abstractmethod@@ -253,6 +264,18 @@ class BaseStorage(ABC):async def store_artifact_from_path(self, artifact: Artifact, path: str) -> None:pass+ async def store_artifact_prefix_from_path(self, artifact: Artifact, path: str, length: int) -> None:+ """Upload exactly the first ``length`` bytes of ``path`` (a snapshot of a still-growing file).++ The default reads that bounded prefix and delegates to ``store_artifact``; backends that can+ stream override this to avoid materializing the prefix in memory. The default buffers, so on+ local/GCS/Azure a per-step prefix is not serialized against the finalize write — only S3 orders+ them so a stale prefix cannot overwrite the finalized object.+ """+ with open(path, "rb") as f:+ data = f.read(length)+ await self.store_artifact(artifact, data)+@abstractmethodasync def save_streaming_file(self, organization_id: str, file_name: str) -> bool | None:"""None/True means the frame was uploaded; False means a gate intentionally skipped it,diff --git a/skyvern/forge/sdk/artifact/storage/bounded_file.py b/skyvern/forge/sdk/artifact/storage/bounded_file.pynew file mode 100644index 000000000..6f567571a--- /dev/null+++ b/skyvern/forge/sdk/artifact/storage/bounded_file.py@@ -0,0 +1,69 @@+from __future__ import annotations++import os+from typing import Self+++class BoundedFileReader:+ """A seekable, read-only file-like view over exactly ``[0, length)`` of ``path``.++ ``length`` is captured by the caller before the read (a snapshot of the recording's current+ size), so the view never follows the file's still-growing EOF. It exposes the ``read``/``seek``/+ ``tell`` surface ``upload_fileobj`` needs: a size probe (``seek(0, 2)`` returns ``length``) and a+ retry rewind (``seek(0)``).+ """++ def __init__(self, path: str, length: int) -> None:+ self._length = max(0, int(length))+ # The reader owns this handle for the whole streamed upload (including retry rewinds), so it+ # is deliberately not a with-block; close() / the context manager release it.+ self._fh = open(path, "rb") # noqa: SIM115+ self._pos = 0++ def read(self, size: int = -1) -> bytes:+ remaining = self._length - self._pos+ if remaining <= 0:+ return b""+ want = remaining if size is None or size < 0 else min(size, remaining)+ data = self._fh.read(want)+ self._pos += len(data)+ return data++ def seek(self, offset: int, whence: int = os.SEEK_SET) -> int:+ if whence == os.SEEK_SET:+ target = offset+ elif whence == os.SEEK_CUR:+ target = self._pos + offset+ elif whence == os.SEEK_END:+ target = self._length + offset+ else:+ raise ValueError(f"invalid whence: {whence}")+ target = max(0, min(target, self._length))+ self._fh.seek(target)+ self._pos = target+ return self._pos++ def tell(self) -> int:+ return self._pos++ def seekable(self) -> bool:+ return True++ def readable(self) -> bool:+ return True++ def writable(self) -> bool:+ return False++ @property+ def closed(self) -> bool:+ return self._fh.closed++ def close(self) -> None:+ self._fh.close()++ def __enter__(self) -> Self:+ return self++ def __exit__(self, *exc: object) -> None:+ self.close()diff --git a/skyvern/forge/sdk/artifact/storage/gcs.py b/skyvern/forge/sdk/artifact/storage/gcs.pyindex e7ac8c52e..31747949c 100644--- a/skyvern/forge/sdk/artifact/storage/gcs.py+++ b/skyvern/forge/sdk/artifact/storage/gcs.py@@ -137,7 +137,13 @@ class GcsStorage(BaseStorage):file_path=file_path,)- async def store_artifact(self, artifact: Artifact, data: bytes) -> None:+ async def store_artifact(+ self,+ artifact: Artifact,+ data: bytes,+ supersede_queued_prefixes: bool = False,+ prefix_uri: str | None = None,+ ) -> None:storage_class = await self._get_storage_class_for_org(artifact.organization_id)tags = await self._get_tags_for_org(artifact.organization_id)LOG.debug(diff --git a/skyvern/forge/sdk/artifact/storage/local.py b/skyvern/forge/sdk/artifact/storage/local.pyindex 498a447c6..24ef8a4f9 100644--- a/skyvern/forge/sdk/artifact/storage/local.py+++ b/skyvern/forge/sdk/artifact/storage/local.py@@ -130,7 +130,13 @@ class LocalStorage(BaseStorage):file_path=file_path,)- async def store_artifact(self, artifact: Artifact, data: bytes) -> None:+ async def store_artifact(+ self,+ artifact: Artifact,+ data: bytes,+ supersede_queued_prefixes: bool = False,+ prefix_uri: str | None = None,+ ) -> None:file_path = Nonetry:file_path = Path(parse_uri_to_path(artifact.uri))diff --git a/skyvern/forge/sdk/artifact/storage/s3.py b/skyvern/forge/sdk/artifact/storage/s3.pyindex ce67e6387..1aa417d8d 100644--- a/skyvern/forge/sdk/artifact/storage/s3.py+++ b/skyvern/forge/sdk/artifact/storage/s3.py@@ -5,7 +5,7 @@ import shutilimport uuidimport zipfilefrom datetime import datetime, timezone-from typing import BinaryIO+from typing import BinaryIO, castimport structlogimport zstandard as zstd@@ -37,6 +37,7 @@ from skyvern.forge.sdk.artifact.storage.base import (key_is_org_scoped,presign_with_sensitive_cap,)+from skyvern.forge.sdk.artifact.storage.bounded_file import BoundedFileReaderfrom skyvern.forge.sdk.artifact.storage.run_recording_clips import (RUN_RECORDING_CLIPS_SYNC_TIMEOUT_SECONDS,RUN_RECORDING_PATH_SEGMENT,@@ -185,7 +186,13 @@ class S3Storage(BaseStorage):file_path=file_path,)- async def store_artifact(self, artifact: Artifact, data: bytes) -> None:+ async def store_artifact(+ self,+ artifact: Artifact,+ data: bytes,+ supersede_queued_prefixes: bool = False,+ prefix_uri: str | None = None,+ ) -> None:# We compress HAR files with zstd level 3 to reduce storage size.# HARs are easily compressible because they are mostly JSON.# Other artifacts are not compressed because they are not easily compressible.@@ -202,7 +209,20 @@ class S3Storage(BaseStorage):uri=uri,storage_class=sc,)- await self.async_client.upload_file(uri, data, storage_class=sc)+ # A recording's per-step prefixes stream to the key they were registered under, and its terminal+ # finalize must serialize against them so a stale detached prefix can never overwrite the finalized+ # object. The finalize can rename the object (.webm prefixes -> .mp4 terminal), so serialize on the+ # key the prefixes actually queued to (prefix_uri when the finalize renamed, else this uri); the+ # terminal still writes `uri`. supersede_queued_prefixes (the finalize) additionally skips prefixes+ # still queued behind the active transfer.+ serialize_key = (prefix_uri or uri) if artifact.artifact_type == ArtifactType.RECORDING else None+ if supersede_queued_prefixes and serialize_key is not None:+ # Terminal finalize does a full replacement that can rewrite earlier bytes, so any Phase 2+ # compose base cached for this key is now stale and must not seed a later copy.+ self.async_client.forget_compose_state(serialize_key)+ await self.async_client.upload_file(+ uri, data, storage_class=sc, serialize_key=serialize_key, supersede_queued=supersede_queued_prefixes+ )async def _get_storage_class_for_org(self,@@ -278,6 +298,45 @@ class S3Storage(BaseStorage):)await self.async_client.upload_file_from_path(artifact.uri, path, storage_class=sc)+ async def store_artifact_prefix_from_path(self, artifact: Artifact, path: str, length: int) -> None:+ # A compressed-suffix URI must be compressed in full (HAR only); recordings never use it, so+ # fall back to the buffered default rather than stream a raw prefix under a .zst key.+ if artifact.uri.endswith(S3_ZSTD_COMPRESSED_SUFFIX):+ await super().store_artifact_prefix_from_path(artifact, path, length)+ return+ sc = await self._get_storage_class_for_org(artifact.organization_id, self.bucket, length)+ LOG.debug(+ "Streaming artifact prefix from path",+ artifact_id=artifact.artifact_id,+ organization_id=artifact.organization_id,+ uri=artifact.uri,+ storage_class=sc,+ path=path,+ length=length,+ )+ # Phase 2 (SKY-15288): when enabled, advance the recording object in place by copying the already+ # uploaded prefix server-side and uploading only the new tail. The compose method owns the whole+ # step — including the Phase 1 full-prefix fallback for unsupported steps — inside ONE serialized+ # write slot, so a later step can never interleave between a failed compose and its fallback.+ if settings.RECORDING_INCREMENTAL_COMPOSE_ENABLED and artifact.artifact_type == ArtifactType.RECORDING:+ await self.async_client.store_recording_prefix(+ artifact.uri, path, length, storage_class=sc, serialize_key=artifact.uri+ )+ return++ # Feature off (or non-recording): the exact Phase 1 path — hand the reader's lifetime to+ # upload_file_stream: the transfer can be detached on caller cancel and keep reading, so it must+ # close the reader only after the real transfer finishes.+ reader = BoundedFileReader(path, length)+ # serialize_key fences this prefix ahead of the terminal write to the same uri (see store_artifact).+ await self.async_client.upload_file_stream(+ artifact.uri,+ cast(BinaryIO, reader),+ storage_class=sc,+ close_file_obj=True,+ serialize_key=artifact.uri,+ )+async def save_streaming_file(self, organization_id: str, file_name: str) -> bool | None:from_path = f"{get_skyvern_temp_dir()}/{organization_id}/{file_name}"to_path = f"s3://{settings.AWS_S3_BUCKET_SCREENSHOTS}/{settings.ENV}/{organization_id}/{file_name}"diff --git a/skyvern/forge/sdk/core/skyvern_context.py b/skyvern/forge/sdk/core/skyvern_context.pyindex 5feea57f1..7adc7f45b 100644--- a/skyvern/forge/sdk/core/skyvern_context.py+++ b/skyvern/forge/sdk/core/skyvern_context.py@@ -394,6 +394,13 @@ class SkyvernContext:# next blocks won't consider the page as a magic link pagemagic_link_pages: dict[str, Page] = field(default_factory=dict)+ # Exact popup Page objects opened by a download click, keyed by the task that opened them. A+ # download credited after the action seam returns (the CDP monitor / file-scan task lifecycle,+ # which never fires a Playwright popup download event) can then close the never-committed marker+ # popup it stranded. Task-keyed and dropped on task teardown so a claim never leaks into a later+ # task/run/persistent-session scope.+ download_popup_claims: dict[str, list[Page]] = field(default_factory=dict)+# parallel verification optimization# stores pre-scraped data for next step to avoid re-scrapingnext_step_pre_scraped_data: dict[str, Any] | None = None@@ -590,6 +597,17 @@ class SkyvernContext:return Falsereturn True+ def record_download_popup_claim(self, task_id: str, page: Page) -> None:+ claims = self.download_popup_claims.setdefault(task_id, [])+ if all(existing is not page for existing in claims):+ claims.append(page)++ def take_download_popup_claims(self, task_id: str) -> list[Page]:+ return self.download_popup_claims.pop(task_id, [])++ def clear_download_popup_claims(self, task_id: str) -> None:+ self.download_popup_claims.pop(task_id, None)+def flush_feature_flags(self) -> None:if not self.feature_flag_entries:returndiff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 8b255d449..aff8cece1 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -11769,19 +11769,38 @@ class WorkflowService:last_step_resolved = Falsefor video_artifact in video_artifacts:if video_artifact.video_artifact_id:+ registered_video_path = video_artifact.video_path+ if registered_video_path and not os.path.exists(registered_video_path):+ # The local file is gone (path raced teardown) so get_video_artifacts could not+ # refresh the cached bytes; writing them would clobber the newer streamed prefix.+ LOG.info(+ "Registered recording path missing; preserving latest stored prefix",+ workflow_id=workflow.workflow_id,+ workflow_run_id=workflow_run.workflow_run_id,+ organization_id=workflow_run.organization_id,+ video_artifact_id=video_artifact.video_artifact_id,+ video_path=registered_video_path,+ )+ continuetry:+ # Only a true terminal finalize (workflow / task-v2 / code-block, browser closed ->+ # recording complete) may supersede queued prefixes. On an intermediate persist the+ # recording is still growing and its prefixes are still legitimately streaming, so+ # sealing the live key would kill per-step visibility (see manager.update_artifact_data).if video_artifact.video_file_extension:upload_key = await app.ARTIFACT_MANAGER.update_artifact_data(artifact_id=video_artifact.video_artifact_id,organization_id=workflow_run.organization_id,data=video_artifact.video_data,file_extension=video_artifact.video_file_extension,+ supersede_queued_prefixes=close_browser_on_completion,)else:upload_key = await app.ARTIFACT_MANAGER.update_artifact_data(artifact_id=video_artifact.video_artifact_id,organization_id=workflow_run.organization_id,data=video_artifact.video_data,+ supersede_queued_prefixes=close_browser_on_completion,)except Exception:LOG.warning(diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex d6af09174..2ab2786c6 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -4040,6 +4040,13 @@ class ActionHandler:download_page.on("download", capture_download)download_callbacks.append((download_page, capture_download))+ # Record identity for the task-scoped late cleanup too: if the download is+ # credited only after this seam returns, the credit path can still close the+ # marker popup. In-seam cleanup below stays the primary close; the claim is a+ # superset backstop, deduped by exact Page identity.+ _claim_context = skyvern_context.current()+ if _claim_context is not None:+ _claim_context.record_download_popup_claim(task.task_id, download_page)page.on("popup", on_popup)@@ -4192,6 +4199,16 @@ class ActionHandler:popup_page.on("download", _capture_download_event)download_popup_callbacks.append((popup_page, _capture_download_event))+ def _record_download_popup_claim(popup_page: Page) -> None:+ # Record popup identity only (no download-listener wiring, so managed-session download+ # behavior is unchanged). Ungated by browser_session_id: a dynamic/remote-CDP run mints the+ # download through the CDP monitor + file-scan task credit, which fires no Playwright popup+ # download event and lands after this seam returns, so the never-committed marker popup must+ # be recorded here for the task's credit seam to close it later.+ _claim_context = skyvern_context.current()+ if _claim_context is not None:+ _claim_context.record_download_popup_claim(task.task_id, popup_page)+def _download_signal_identity(file: str) -> str:return file.removesuffix(BROWSER_DOWNLOADING_SUFFIX)@@ -4314,6 +4331,8 @@ class ActionHandler:workflow_run_id=task.workflow_run_id,)page.on("download", _capture_download_event)+ # Identity-only recorder for the task-scoped late cleanup, armed for every download click.+ page.on("popup", _record_download_popup_claim)# Popup-owned blob downloads only matter for adopted/persistent sessions; managed sessions# keep their existing single-page download behavior with no popup-download wiring.if task.browser_session_id:@@ -4865,6 +4884,11 @@ class ActionHandler:_remove_download_listener(observed_popup, popup_callback)except Exception:LOG.warning("Failed to remove download popup listener", exc_info=True)+ try:+ _remove_popup_listener(page, _record_download_popup_claim)+ except Exception:+ with contained_effect("remove download popup claim recorder"):+ LOG.warning("Failed to remove download popup claim recorder", exc_info=True)if task.browser_session_id:try:_remove_popup_listener(page, _register_download_popup)diff --git a/skyvern/webeye/browser_artifacts.py b/skyvern/webeye/browser_artifacts.pyindex 4914f2f4e..6ce957ad1 100644--- a/skyvern/webeye/browser_artifacts.py+++ b/skyvern/webeye/browser_artifacts.py@@ -56,6 +56,15 @@ class VideoArtifact(BaseModel):video_data: bytes = b""+class RecordingPrefixSnapshot(BaseModel):+ """A per-step upload plan for one growing recording: upload exactly ``prefix_len`` bytes of ``path``+ (captured once) to the existing ``video_artifact_id``, streamed rather than buffered."""++ video_artifact_id: str+ path: str+ prefix_len: int++class BrowserArtifacts(BaseModel):video_artifacts: list[VideoArtifact] = []har_path: str | None = Nonediff --git a/skyvern/webeye/browser_manager.py b/skyvern/webeye/browser_manager.pyindex ba5deecdb..f5e29b230 100644--- a/skyvern/webeye/browser_manager.py+++ b/skyvern/webeye/browser_manager.py@@ -8,7 +8,7 @@ import structlogfrom skyvern.forge.sdk.schemas.tasks import Taskfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRun-from skyvern.webeye.browser_artifacts import VideoArtifact+from skyvern.webeye.browser_artifacts import RecordingPrefixSnapshot, VideoArtifactfrom skyvern.webeye.browser_state import BrowserStateLOG = structlog.get_logger()@@ -99,6 +99,12 @@ class BrowserManager(Protocol):finalize: bool = True,) -> list[VideoArtifact]: ...+ def snapshot_recording_prefixes(+ self,+ browser_state: BrowserState,+ task_id: str = "",+ ) -> list[RecordingPrefixSnapshot] | None: ...+async def get_har_data(self,browser_state: BrowserState,diff --git a/skyvern/webeye/real_browser_manager.py b/skyvern/webeye/real_browser_manager.pyindex 1c8e96a2b..41a246ba7 100644--- a/skyvern/webeye/real_browser_manager.py+++ b/skyvern/webeye/real_browser_manager.py@@ -31,7 +31,7 @@ from skyvern.forge.sdk.streaming.registries import ()from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunfrom skyvern.schemas.runs import ProxyLocation, ProxyLocationInput-from skyvern.webeye.browser_artifacts import DownloadBinding, VideoArtifact+from skyvern.webeye.browser_artifacts import DownloadBinding, RecordingPrefixSnapshot, VideoArtifactfrom skyvern.webeye.browser_engine import (BrowserEngineBootstrapError,BrowserEngineContext,@@ -1241,6 +1241,39 @@ class RealBrowserManager(BrowserManager):return browser_state.browser_artifacts.video_artifacts+ def snapshot_recording_prefixes(+ self,+ browser_state: BrowserState,+ task_id: str = "",+ ) -> list[RecordingPrefixSnapshot] | None:+ """Plan a per-step recording sync without reading any bytes.++ Mirrors the per-step branch of ``get_video_artifacts(finalize=False)`` for the shipped Playwright+ per-page recording: returns ``[]`` when there is nothing to sync, a per-artifact prefix plan (a+ size snapshot of each ordinary growing WebM recording) for the fast streaming path, or ``None`` to+ fall back to the byte-based path whenever an artifact is non-WebM, not yet registered, or missing on+ disk.+ """+ video_artifacts = browser_state.browser_artifacts.video_artifacts+ if len(video_artifacts) == 0:+ return []++ snapshots: list[RecordingPrefixSnapshot] = []+ for video_artifact in video_artifacts:+ path = video_artifact.video_path+ if not video_artifact.video_artifact_id or not path or not os.path.exists(path=path):+ return None+ if not path.lower().endswith(".webm"):+ return None+ snapshots.append(+ RecordingPrefixSnapshot(+ video_artifact_id=video_artifact.video_artifact_id,+ path=path,+ prefix_len=os.path.getsize(path),+ )+ )+ return snapshots+async def get_har_data(self,browser_state: BrowserState,diff --git a/tests/unit/forge/sdk/artifact/storage/test_s3_storage.py b/tests/unit/forge/sdk/artifact/storage/test_s3_storage.pyindex 1fe5eab09..b67cd596f 100644--- a/tests/unit/forge/sdk/artifact/storage/test_s3_storage.py+++ b/tests/unit/forge/sdk/artifact/storage/test_s3_storage.py@@ -17,7 +17,7 @@ from freezegun import freeze_timefrom skyvern.config import settingsfrom skyvern.exceptions import DownloadSaveIncompleteError-from skyvern.forge.sdk.api.aws import S3StorageClass, S3Uri+from skyvern.forge.sdk.api.aws import _STREAM_UPLOAD_IO_QUEUE_DEPTH, S3StorageClass, S3Urifrom skyvern.forge.sdk.artifact.manager import ArtifactManagerfrom skyvern.forge.sdk.artifact.models import Artifact, ArtifactType, LogEntityTypefrom skyvern.forge.sdk.artifact.signing import SENSITIVE_ARTIFACT_URL_EXPIRY_SECONDS@@ -1454,3 +1454,699 @@ class TestS3SaveDownloadedFiles:assert sorted(uploaded) == ["b.pdf", "c.pdf"]assert len(rows) == 3+++async def _settle(iterations: int = 100) -> None:+ """Drain the event loop's ready queue deterministically so create_task'd writes reach their+ chain-reservation/await points before the next reservation. Timing-independent (no wall-clock sleep+ that can flake under load), and it needs no production test-only hook — every write reserves its chain+ slot synchronously at task start, so a bounded set of no-op yields settles the intended interleaving.+ A task parked on an unresolved predecessor future stays parked, preserving the queued-behind ordering.+ """+ for _ in range(iterations):+ await asyncio.sleep(0)+++def _recording_artifact(uri: str) -> Artifact:+ now = datetime.now(UTC)+ return Artifact(+ artifact_id="a_rec",+ artifact_type=ArtifactType.RECORDING,+ uri=uri,+ organization_id=TEST_ORGANIZATION_ID,+ task_id=TEST_TASK_ID,+ created_at=now,+ modified_at=now,+ )+++async def test_store_artifact_prefix_from_path_streams_bounded_reader(s3_storage: S3Storage, tmp_path: Path) -> None:+ src = tmp_path / "rec.webm"+ src.write_bytes(b"R" * 500)+ artifact = _recording_artifact(f"s3://{TEST_BUCKET}/k/rec.webm")++ captured: dict = {}++ async def _capture(+ uri: str,+ file_obj: object,+ storage_class: object = None,+ close_file_obj: bool = False,+ serialize_key: str | None = None,+ ) -> str:+ captured["uri"] = uri+ captured["close_file_obj"] = close_file_obj+ captured["serialize_key"] = serialize_key+ captured["data"] = file_obj.read() # read inside the call; ownership/close is handed to the client+ return uri++ s3_storage.async_client = MagicMock()+ s3_storage.async_client.upload_file_stream = AsyncMock(side_effect=_capture)++ await s3_storage.store_artifact_prefix_from_path(artifact, str(src), 300)++ assert captured["uri"] == artifact.uri+ assert captured["data"] == b"R" * 300 # exactly the snapshot prefix, streamed+ assert captured["close_file_obj"] is True # reader lifetime handed to the client, not the with-block+ assert captured["serialize_key"] == artifact.uri # fenced against the terminal write to the same uri+++async def test_store_artifact_prefix_from_path_zst_falls_back_to_buffered(+ s3_storage: S3Storage, tmp_path: Path+) -> None:+ src = tmp_path / "data.zst"+ src.write_bytes(b"D" * 100)+ artifact = _recording_artifact(f"s3://{TEST_BUCKET}/k/data.zst")++ s3_storage.async_client = MagicMock()+ s3_storage.async_client.upload_file = AsyncMock(return_value=artifact.uri)+ s3_storage.async_client.upload_file_stream = AsyncMock()++ await s3_storage.store_artifact_prefix_from_path(artifact, str(src), 50)++ s3_storage.async_client.upload_file_stream.assert_not_awaited()+ s3_storage.async_client.upload_file.assert_awaited_once() # buffered store_artifact (compressed) path+++async def test_store_artifact_prefix_reader_survives_caller_cancel_until_transfer_done(+ s3_storage: S3Storage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """AsyncAWSClient shields/detaches the transfer, so a cancelled caller must NOT close the reader+ out from under the still-running transfer. The reader must stay open until the real transfer+ finishes, then close, and the detached transfer must still read the full snapshot."""+ src = tmp_path / "rec.webm"+ src.write_bytes(b"Z" * 400)+ artifact = _recording_artifact(f"s3://{TEST_BUCKET}/k/rec.webm")++ started = asyncio.Event()+ release = asyncio.Event()+ captured: dict = {}++ class _FakeClient:+ async def upload_fileobj(+ self, fileobj: object, bucket: str, key: str, ExtraArgs: dict | None = None, Config: object = None+ ) -> None:+ captured["fileobj"] = fileobj+ started.set()+ await release.wait() # model an in-flight transfer that outlives the caller's cancel+ captured["read_after_cancel"] = fileobj.read()++ class _FakeCtx:+ async def __aenter__(self) -> _FakeClient:+ return _FakeClient()++ async def __aexit__(self, *exc: object) -> bool:+ return False++ monkeypatch.setattr(s3_storage.async_client, "_s3_client", lambda: _FakeCtx())++ task = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(artifact, str(src), 400))+ await asyncio.wait_for(started.wait(), timeout=5)+ assert captured["fileobj"].closed is False # open while the transfer is active++ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ # Caller has cancelled, but the shielded transfer is still active — the reader MUST remain open.+ assert captured["fileobj"].closed is False++ release.set()+ for _ in range(1000):+ if captured["fileobj"].closed:+ break+ await asyncio.sleep(0.005)++ assert captured["read_after_cancel"] == b"Z" * 400 # detached transfer streamed the full snapshot+ assert captured["fileobj"].closed is True # closed only after the real transfer finished+++async def test_stale_prefix_cannot_overwrite_terminal_full_upload(+ s3_storage: S3Storage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Data-integrity race: a per-step prefix transfer that is cancelled (30s barrier timeout) detaches+ and keeps running. The terminal full-recording upload then writes the SAME uri. The stale detached+ prefix must NOT land afterward and overwrite the finalized object with truncated bytes."""+ src = tmp_path / "rec.webm"+ src.write_bytes(b"P" * 200) # truncated per-step prefix+ rec = _recording_artifact(f"s3://{TEST_BUCKET}/k/rec.webm")+ full = b"F" * 5000 # finalized full recording++ store: dict[str, bytes] = {}+ prefix_started = asyncio.Event()+ prefix_release = asyncio.Event()++ class _FakeClient:+ async def upload_fileobj(+ self, fileobj: object, bucket: str, key: str, ExtraArgs: dict | None = None, Config: object = None+ ) -> None:+ prefix_started.set()+ await prefix_release.wait() # in-flight; still reading after the caller cancelled/detached+ store[key] = fileobj.read()++ async def put_object(+ self, Body: bytes = b"", Bucket: str = "", Key: str = "", StorageClass: str = "", **kw: object+ ) -> None:+ store[Key] = Body++ class _FakeCtx:+ async def __aenter__(self) -> _FakeClient:+ return _FakeClient()++ async def __aexit__(self, *exc: object) -> bool:+ return False++ monkeypatch.setattr(s3_storage.async_client, "_s3_client", lambda: _FakeCtx())+ key = S3Uri(rec.uri).key++ prefix_task = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(rec, str(src), 200))+ await asyncio.wait_for(prefix_started.wait(), timeout=5)+ prefix_task.cancel() # models wait_for_upload_aiotasks' 30s timeout cancelling the tracked task+ with pytest.raises(asyncio.CancelledError):+ await prefix_task++ terminal_task = asyncio.create_task(s3_storage.store_artifact(rec, full))+ await asyncio.sleep(0) # give the terminal write a turn to attempt/queue+ prefix_release.set() # let the detached stale prefix finish+ await asyncio.wait_for(terminal_task, timeout=5)+ for _ in range(200): # let any detached prefix transfer settle+ await asyncio.sleep(0.005)+ if store.get(key) == b"P" * 200:+ break++ assert store[key] == full, "finalized full upload must win; a stale prefix must not overwrite it"+ # No unbounded chain/task registry: the per-key entry is dropped once the key goes idle.+ assert s3_storage.async_client._object_write_chains == {}+++async def test_store_artifact_serializes_only_recording_writes(+ s3_storage: S3Storage, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The terminal write path fences recordings by uri (so any terminal call site is covered) and+ leaves every other artifact type unserialized."""+ seen: dict = {}++ async def _capture(+ uri: str,+ data: bytes,+ storage_class: object = None,+ serialize_key: str | None = None,+ supersede_queued: bool = False,+ ) -> str:+ seen[uri] = (serialize_key, supersede_queued)+ return uri++ s3_storage.async_client = MagicMock()+ s3_storage.async_client.upload_file = AsyncMock(side_effect=_capture)++ rec = _recording_artifact(f"s3://{TEST_BUCKET}/k/rec.webm")+ other = rec.model_copy(update={"uri": f"s3://{TEST_BUCKET}/k/page.html", "artifact_type": ArtifactType.HTML})+ await s3_storage.store_artifact(rec, b"data", supersede_queued_prefixes=True)+ await s3_storage.store_artifact(other, b"data", supersede_queued_prefixes=True)++ # recording terminal write is fenced by uri and (as a finalize) seals queued prefixes;+ # a non-recording write is never fenced (serialize_key=None), so the seal flag is inert.+ assert seen[rec.uri] == (rec.uri, True)+ assert seen[other.uri][0] is None+++async def test_terminal_recording_write_survives_barrier_cancel_and_lands_last(+ s3_storage: S3Storage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The 30s barrier cancels the QUEUED terminal task too, not just the prefix. The terminal recording+ write must still complete after the older prefix drains — otherwise the persisted recording is left+ truncated (the prefix) because the terminal put_object never ran."""+ src = tmp_path / "rec.webm"+ src.write_bytes(b"P" * 200)+ rec = _recording_artifact(f"s3://{TEST_BUCKET}/k/rec.webm")+ full = b"F" * 5000++ store: dict[str, bytes] = {}+ prefix_started = asyncio.Event()+ prefix_release = asyncio.Event()++ class _FakeClient:+ async def upload_fileobj(+ self, fileobj: object, bucket: str, key: str, ExtraArgs: dict | None = None, Config: object = None+ ) -> None:+ prefix_started.set()+ await prefix_release.wait()+ store[key] = fileobj.read()++ async def put_object(+ self, Body: bytes = b"", Bucket: str = "", Key: str = "", StorageClass: str = "", **kw: object+ ) -> None:+ store[Key] = Body++ class _FakeCtx:+ async def __aenter__(self) -> _FakeClient:+ return _FakeClient()++ async def __aexit__(self, *exc: object) -> bool:+ return False++ monkeypatch.setattr(s3_storage.async_client, "_s3_client", lambda: _FakeCtx())+ key = S3Uri(rec.uri).key++ prefix_task = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(rec, str(src), 200))+ await asyncio.wait_for(prefix_started.wait(), timeout=5)+ prefix_task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await prefix_task++ terminal_task = asyncio.create_task(s3_storage.store_artifact(rec, full))+ await asyncio.sleep(0) # terminal reaches the chain await, blocked behind the detached prefix+ terminal_task.cancel() # the barrier cancels the queued terminal task as well+ with pytest.raises(asyncio.CancelledError):+ await terminal_task++ prefix_release.set()+ for _ in range(400):+ await asyncio.sleep(0.005)+ if store.get(key) == full:+ break++ assert store.get(key) == full, "terminal recording write must survive the barrier cancel and land last"+ assert s3_storage.async_client._object_write_chains == {}+++async def test_live_run_prefixes_all_upload_in_issue_order(+ s3_storage: S3Storage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """No terminal write: every per-step prefix must upload, in issue order (no coalescing)."""+ uploaded: list[bytes] = []++ class _FakeClient:+ async def upload_fileobj(+ self, fileobj: object, bucket: str, key: str, ExtraArgs: dict | None = None, Config: object = None+ ) -> None:+ uploaded.append(fileobj.read())++ class _FakeCtx:+ async def __aenter__(self) -> _FakeClient:+ return _FakeClient()++ async def __aexit__(self, *exc: object) -> bool:+ return False++ monkeypatch.setattr(s3_storage.async_client, "_s3_client", lambda: _FakeCtx())+ rec = _recording_artifact(f"s3://{TEST_BUCKET}/k/rec.webm")++ for content in (b"A" * 10, b"B" * 20, b"C" * 30):+ p = tmp_path / f"{len(content)}.webm"+ p.write_bytes(content)+ await s3_storage.store_artifact_prefix_from_path(rec, str(p), len(content))++ assert uploaded == [b"A" * 10, b"B" * 20, b"C" * 30]+ assert _clean_write_state(s3_storage.async_client)+++def _recording_fake_ctx(monkeypatch, s3_storage, client): # type: ignore[no-untyped-def]+ class _FakeCtx:+ async def __aenter__(self): # type: ignore[no-untyped-def]+ return client++ async def __aexit__(self, *exc: object) -> bool:+ return False++ monkeypatch.setattr(s3_storage.async_client, "_s3_client", lambda: _FakeCtx())+++async def test_terminal_finalize_suppresses_queued_prefixes_and_waits_only_for_active(+ s3_storage: S3Storage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """prefix1 active, prefix2/prefix3 queued: the terminal finalize waits only for the active prefix1,+ suppresses the queued prefix2/prefix3, then lands last."""+ store: dict[str, bytes] = {}+ calls = {"fileobj": 0, "put": 0}+ p1_started = asyncio.Event()+ p1_release = asyncio.Event()++ class _FakeClient:+ async def upload_fileobj(+ self, fileobj: object, bucket: str, key: str, ExtraArgs: dict | None = None, Config: object = None+ ) -> None:+ calls["fileobj"] += 1+ p1_started.set()+ await p1_release.wait()+ store[key] = fileobj.read()++ async def put_object(+ self, Body: bytes = b"", Bucket: str = "", Key: str = "", StorageClass: str = "", **kw: object+ ) -> None:+ calls["put"] += 1+ store[Key] = Body++ _recording_fake_ctx(monkeypatch, s3_storage, _FakeClient())+ rec = _recording_artifact(f"s3://{TEST_BUCKET}/k/rec.webm")+ key = S3Uri(rec.uri).key+ for i in (1, 2, 3):+ (tmp_path / f"p{i}.webm").write_bytes(b"P" * (10 * i))++ p1 = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(rec, str(tmp_path / "p1.webm"), 10))+ await asyncio.wait_for(p1_started.wait(), timeout=5) # prefix1 is the active transfer+ p2 = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(rec, str(tmp_path / "p2.webm"), 20))+ p3 = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(rec, str(tmp_path / "p3.webm"), 30))+ await _settle() # let prefix2/prefix3 queue behind prefix1+ term = asyncio.create_task(s3_storage.store_artifact(rec, b"F" * 5000, supersede_queued_prefixes=True))+ await _settle() # terminal reserved + sealed+ p1_release.set()+ await asyncio.gather(p1, p2, p3, term)++ assert calls["fileobj"] == 1 # only the active prefix uploaded; queued prefix2/prefix3 were suppressed+ assert calls["put"] == 1+ assert store[key] == b"F" * 5000 # terminal landed last+ assert _clean_write_state(s3_storage.async_client)+++async def test_prefix_reserved_after_terminal_reserved_cannot_overwrite(+ s3_storage: S3Storage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A prefix reserved while the terminal finalize is still in flight is superseded and never writes."""+ store: dict[str, bytes] = {}+ calls = {"fileobj": 0, "put": 0}+ term_started = asyncio.Event()+ term_release = asyncio.Event()++ class _FakeClient:+ async def upload_fileobj(+ self, fileobj: object, bucket: str, key: str, ExtraArgs: dict | None = None, Config: object = None+ ) -> None:+ calls["fileobj"] += 1+ store[key] = fileobj.read()++ async def put_object(+ self, Body: bytes = b"", Bucket: str = "", Key: str = "", StorageClass: str = "", **kw: object+ ) -> None:+ calls["put"] += 1+ term_started.set()+ await term_release.wait()+ store[Key] = Body++ _recording_fake_ctx(monkeypatch, s3_storage, _FakeClient())+ rec = _recording_artifact(f"s3://{TEST_BUCKET}/k/rec.webm")+ key = S3Uri(rec.uri).key+ (tmp_path / "late.webm").write_bytes(b"P" * 200)++ term = asyncio.create_task(s3_storage.store_artifact(rec, b"F" * 5000, supersede_queued_prefixes=True))+ await asyncio.wait_for(term_started.wait(), timeout=5) # terminal in flight, key sealed+ late = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(rec, str(tmp_path / "late.webm"), 200))+ await _settle()+ term_release.set()+ await asyncio.gather(term, late)++ assert calls["fileobj"] == 0 # the late prefix was superseded and never uploaded+ assert store[key] == b"F" * 5000+ assert _clean_write_state(s3_storage.async_client)+++async def test_active_prefix_failure_still_unblocks_terminal(+ s3_storage: S3Storage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """If the active prefix transfer fails, it must still release the write chain so the terminal lands."""+ store: dict[str, bytes] = {}+ p1_started = asyncio.Event()+ p1_release = asyncio.Event()++ class _FakeClient:+ async def upload_fileobj(+ self, fileobj: object, bucket: str, key: str, ExtraArgs: dict | None = None, Config: object = None+ ) -> None:+ p1_started.set()+ await p1_release.wait()+ raise RuntimeError("prefix transfer boom")++ async def put_object(+ self, Body: bytes = b"", Bucket: str = "", Key: str = "", StorageClass: str = "", **kw: object+ ) -> None:+ store[Key] = Body++ _recording_fake_ctx(monkeypatch, s3_storage, _FakeClient())+ rec = _recording_artifact(f"s3://{TEST_BUCKET}/k/rec.webm")+ key = S3Uri(rec.uri).key+ (tmp_path / "p.webm").write_bytes(b"P" * 200)++ p1 = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(rec, str(tmp_path / "p.webm"), 200))+ await asyncio.wait_for(p1_started.wait(), timeout=5)+ term = asyncio.create_task(s3_storage.store_artifact(rec, b"F" * 5000, supersede_queued_prefixes=True))+ await _settle()+ p1_release.set() # active prefix now fails+ await asyncio.gather(p1, term)++ assert store[key] == b"F" * 5000 # terminal unblocked and landed despite the prefix failure+ assert _clean_write_state(s3_storage.async_client)+++def _clean_write_state(client: object) -> bool:+ return (+ client._object_write_chains == {}+ and client._object_write_sealed == set()+ and client._object_write_fallback == {}+ and client._object_write_fallback_target == {}+ )+++async def test_terminal_failure_uploads_newest_queued_prefix_as_fallback(+ s3_storage: S3Storage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """active P1 + queued P2/P3 + terminal failure => the newest queued snapshot (P3) lands as a+ fallback, P2 never uploads, and all per-key state drains."""+ store: dict[str, bytes] = {}+ uploaded: list[bytes] = []+ p1_started = asyncio.Event()+ p1_release = asyncio.Event()+ first = {"seen": False}++ class _FakeClient:+ async def upload_fileobj(+ self, fileobj: object, bucket: str, key: str, ExtraArgs: dict | None = None, Config: object = None+ ) -> None:+ if not first["seen"]: # the active prefix P1+ first["seen"] = True+ p1_started.set()+ await p1_release.wait()+ data = fileobj.read()+ uploaded.append(data)+ store[key] = data++ async def put_object(+ self, Body: bytes = b"", Bucket: str = "", Key: str = "", StorageClass: str = "", **kw: object+ ) -> None:+ raise RuntimeError("terminal put_object failed") # non-token failure, not retried++ _recording_fake_ctx(monkeypatch, s3_storage, _FakeClient())+ rec = _recording_artifact(f"s3://{TEST_BUCKET}/k/rec.webm")+ key = S3Uri(rec.uri).key+ (tmp_path / "p1.webm").write_bytes(b"1" * 10)+ (tmp_path / "p2.webm").write_bytes(b"2" * 20)+ (tmp_path / "p3.webm").write_bytes(b"3" * 30)++ p1 = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(rec, str(tmp_path / "p1.webm"), 10))+ await asyncio.wait_for(p1_started.wait(), timeout=5)+ p2 = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(rec, str(tmp_path / "p2.webm"), 20))+ p3 = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(rec, str(tmp_path / "p3.webm"), 30))+ await _settle() # P2 then P3 queue; P3 is the newest pre-terminal snapshot+ term = asyncio.create_task(s3_storage.store_artifact(rec, b"F" * 5000, supersede_queued_prefixes=True))+ await _settle() # terminal reserved: seals, designates P3 the fallback+ p1_release.set()+ await asyncio.gather(p1, p2, p3, term)++ assert store[key] == b"3" * 30 # newest queued snapshot preserved after the terminal write failed+ assert uploaded == [b"1" * 10, b"3" * 30] # active P1, then P3 fallback; P2 never uploaded+ assert _clean_write_state(s3_storage.async_client)+++async def test_fallback_upload_failure_still_drains_and_closes(+ s3_storage: S3Storage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """If both the terminal write and the fallback upload fail, all per-key state still drains and the+ retained reader is closed (no leak, no unhandled exception)."""+ p1_started = asyncio.Event()+ p1_release = asyncio.Event()+ first = {"seen": False}+ readers: list[object] = []++ class _FakeClient:+ async def upload_fileobj(+ self, fileobj: object, bucket: str, key: str, ExtraArgs: dict | None = None, Config: object = None+ ) -> None:+ readers.append(fileobj)+ if not first["seen"]:+ first["seen"] = True+ p1_started.set()+ await p1_release.wait()+ fileobj.read()+ return+ raise RuntimeError("fallback upload failed")++ async def put_object(+ self, Body: bytes = b"", Bucket: str = "", Key: str = "", StorageClass: str = "", **kw: object+ ) -> None:+ raise RuntimeError("terminal put_object failed")++ _recording_fake_ctx(monkeypatch, s3_storage, _FakeClient())+ rec = _recording_artifact(f"s3://{TEST_BUCKET}/k/rec.webm")+ for name, n in (("p1", 10), ("p3", 30)):+ (tmp_path / f"{name}.webm").write_bytes(b"x" * n)++ p1 = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(rec, str(tmp_path / "p1.webm"), 10))+ await asyncio.wait_for(p1_started.wait(), timeout=5)+ p3 = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(rec, str(tmp_path / "p3.webm"), 30))+ await _settle()+ term = asyncio.create_task(s3_storage.store_artifact(rec, b"F" * 5000, supersede_queued_prefixes=True))+ await _settle()+ p1_release.set()+ await asyncio.gather(p1, p3, term) # no exception escapes++ assert _clean_write_state(s3_storage.async_client)+ # the parked fallback reader (P3) was the second reader handed to the client and must be closed+ assert readers[-1].closed is True+++async def test_renamed_finalize_seals_prefix_key_and_supersedes_queued(+ s3_storage: S3Storage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The dominant finalize compresses the .webm prefixes into a renamed .mp4 object. The terminal write+ must seal the OLD .webm key the prefixes queued to (so queued prefixes are superseded), while writing+ the new .mp4 object — not seal the .mp4 key that nothing queued to (SKY-15288, thread r3917658240)."""+ store: dict[str, bytes] = {}+ calls = {"fileobj": 0, "put": 0}+ p1_started = asyncio.Event()+ p1_release = asyncio.Event()++ class _FakeClient:+ async def upload_fileobj(+ self, fileobj: object, bucket: str, key: str, ExtraArgs: dict | None = None, Config: object = None+ ) -> None:+ calls["fileobj"] += 1+ p1_started.set()+ await p1_release.wait()+ store[key] = fileobj.read()++ async def put_object(+ self, Body: bytes = b"", Bucket: str = "", Key: str = "", StorageClass: str = "", **kw: object+ ) -> None:+ calls["put"] += 1+ store[Key] = Body++ _recording_fake_ctx(monkeypatch, s3_storage, _FakeClient())+ webm = _recording_artifact(f"s3://{TEST_BUCKET}/k/rec.webm")+ mp4 = webm.model_copy(update={"uri": f"s3://{TEST_BUCKET}/k/rec.mp4"})+ webm_key = S3Uri(webm.uri).key+ mp4_key = S3Uri(mp4.uri).key+ for i in (1, 2, 3):+ (tmp_path / f"p{i}.webm").write_bytes(b"P" * (10 * i))++ p1 = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(webm, str(tmp_path / "p1.webm"), 10))+ await asyncio.wait_for(p1_started.wait(), timeout=5) # prefix1 active on the .webm key+ p2 = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(webm, str(tmp_path / "p2.webm"), 20))+ p3 = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(webm, str(tmp_path / "p3.webm"), 30))+ await _settle()+ # Terminal finalize: writes the renamed .mp4 object, seals the .webm prefix key.+ term = asyncio.create_task(+ s3_storage.store_artifact(mp4, b"F" * 5000, supersede_queued_prefixes=True, prefix_uri=webm.uri)+ )+ await _settle()+ p1_release.set()+ await asyncio.gather(p1, p2, p3, term)++ assert calls["fileobj"] == 1 # only the active .webm prefix uploaded; queued p2/p3 superseded on the old key+ assert store[mp4_key] == b"F" * 5000 # finalized recording landed under the renamed .mp4 key+ assert store.get(webm_key) == b"P" * 10 # the one active prefix; no queued prefix drained afterward+ assert _clean_write_state(s3_storage.async_client)+++async def test_renamed_finalize_failure_arms_no_fallback(+ s3_storage: S3Storage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """When the finalize renames the object, a parked .webm prefix could never be served under the .mp4+ row, so the terminal must NOT arm a fallback. On terminal failure the newest queued prefix is+ superseded like the rest (contrast test_terminal_failure_uploads_newest_queued_prefix_as_fallback,+ the same-key case where it IS the fallback)."""+ store: dict[str, bytes] = {}+ uploaded: list[bytes] = []+ p1_started = asyncio.Event()+ p1_release = asyncio.Event()+ first = {"seen": False}++ class _FakeClient:+ async def upload_fileobj(+ self, fileobj: object, bucket: str, key: str, ExtraArgs: dict | None = None, Config: object = None+ ) -> None:+ if not first["seen"]:+ first["seen"] = True+ p1_started.set()+ await p1_release.wait()+ data = fileobj.read()+ uploaded.append(data)+ store[key] = data++ async def put_object(+ self, Body: bytes = b"", Bucket: str = "", Key: str = "", StorageClass: str = "", **kw: object+ ) -> None:+ raise RuntimeError("terminal put_object failed")++ _recording_fake_ctx(monkeypatch, s3_storage, _FakeClient())+ webm = _recording_artifact(f"s3://{TEST_BUCKET}/k/rec.webm")+ mp4 = webm.model_copy(update={"uri": f"s3://{TEST_BUCKET}/k/rec.mp4"})+ (tmp_path / "p1.webm").write_bytes(b"1" * 10)+ (tmp_path / "p3.webm").write_bytes(b"3" * 30)++ p1 = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(webm, str(tmp_path / "p1.webm"), 10))+ await asyncio.wait_for(p1_started.wait(), timeout=5)+ p3 = asyncio.create_task(s3_storage.store_artifact_prefix_from_path(webm, str(tmp_path / "p3.webm"), 30))+ await _settle()+ term = asyncio.create_task(+ s3_storage.store_artifact(mp4, b"F" * 5000, supersede_queued_prefixes=True, prefix_uri=webm.uri)+ )+ await _settle()+ p1_release.set()+ await asyncio.gather(p1, p3, term)++ assert uploaded == [b"1" * 10] # only the active prefix; no meaningless .webm fallback on rename+ assert _clean_write_state(s3_storage.async_client)+++async def test_stream_upload_bounds_resident_memory_with_transfer_config(+ s3_storage: S3Storage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """upload_fileobj must receive a TransferConfig that caps s3transfer's io queue, so a streamed+ prefix's resident memory is a fixed queue-depth x chunk-size regardless of prefix size+ (SKY-15288, thread r3918986929)."""+ seen: list[object] = []++ class _FakeClient:+ async def upload_fileobj(+ self, fileobj: object, bucket: str, key: str, ExtraArgs: dict | None = None, Config: object = None+ ) -> None:+ seen.append(Config)+ fileobj.read()++ _recording_fake_ctx(monkeypatch, s3_storage, _FakeClient())+ rec = _recording_artifact(f"s3://{TEST_BUCKET}/k/rec.webm")++ small = tmp_path / "small.webm"+ small.write_bytes(b"s" * 100)+ large = tmp_path / "large.webm"+ large.write_bytes(b"l" * 100_000)+ await s3_storage.store_artifact_prefix_from_path(rec, str(small), 100)+ await s3_storage.store_artifact_prefix_from_path(rec, str(large), 100_000)++ assert len(seen) == 2+ assert all(cfg is not None for cfg in seen)+ # size-independent: the same bounded queue depth for a 100B and a 100KB prefix+ assert {cfg.max_io_queue_size for cfg in seen} == {_STREAM_UPLOAD_IO_QUEUE_DEPTH}diff --git a/tests/unit/test_agent_cleanup_download_suffix.py b/tests/unit/test_agent_cleanup_download_suffix.pyindex 21948382d..4f7d3ee5d 100644--- a/tests/unit/test_agent_cleanup_download_suffix.py+++ b/tests/unit/test_agent_cleanup_download_suffix.py@@ -9,7 +9,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom structlog.testing import capture_logs-from skyvern.exceptions import DownloadFileMaxWaitingTime+from skyvern.exceptions import DownloadFileMaxWaitingTime, TaskNotFoundfrom skyvern.forge.agent import ForgeAgentfrom skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.schemas.runs import RunEngine@@ -310,7 +310,6 @@ async def test_cleanup_timeout_bounds_browser_download_handler_drain() -> None:browser_state = MagicMock(browser_context=browser_context)finalize = AsyncMock()save = AsyncMock()- started_at = asyncio.get_running_loop().time()with (patch("skyvern.forge.agent.SAVE_DOWNLOADED_FILES_TIMEOUT", 0.01),@@ -333,7 +332,6 @@ async def test_cleanup_timeout_bounds_browser_download_handler_drain() -> None:timeout=0.5,)- assert asyncio.get_running_loop().time() - started_at < 0.2finalize.assert_not_awaited()save.assert_not_awaited()@@ -1017,3 +1015,481 @@ async def test_finalize_materializes_session_download_matching_baseline_before(tf"new session download must be materialized under its suffix, not deduped against the baseline, got {remaining}")assert (download_dir / "req-999.pdf").read_bytes() == shared_bytes+++def _claimed_popup(url: str = ":") -> MagicMock:+ popup = MagicMock(url=url)+ popup.is_closed.return_value = False+ popup.close = AsyncMock()+ return popup+++def test_download_popup_claim_record_dedup_take_clear() -> None:+ """The task-scoped claim registry dedups by exact Page identity and pops/clears by task_id, so a+ claim can never be double-recorded or leak into another task's scope."""+ ctx = SkyvernContext(task_id="t1")+ page = _claimed_popup()+ ctx.record_download_popup_claim("t1", page)+ ctx.record_download_popup_claim("t1", page) # exact-identity dedup+ assert ctx.download_popup_claims["t1"] == [page]++ other = _claimed_popup()+ ctx.record_download_popup_claim("t2", other)+ assert ctx.take_download_popup_claims("t1") == [page]+ assert "t1" not in ctx.download_popup_claims # take pops++ ctx.clear_download_popup_claims("t2")+ assert "t2" not in ctx.download_popup_claims+ # taking/clearing a missing key is safe and non-mutating+ assert ctx.take_download_popup_claims("missing") == []+ ctx.clear_download_popup_claims("missing")+++async def test_close_credited_download_popups_closes_claimed_popup_and_clears_claim() -> None:+ """After a durable download credit, the exact recorded popup that is still open and still a live+ page in this run is closed (so the next task does not select it as its working page), and the task's+ claims are cleared. The opener is never recorded as a claim, so it is untouched."""+ agent = ForgeAgent()+ task = _make_task(task_id="task-credit")+ popup = _claimed_popup(":")+ opener = _claimed_popup("https://example.test/documents")+ browser_state = MagicMock()+ browser_state.list_valid_pages = AsyncMock(return_value=[opener, popup])+ ctx = SkyvernContext(task_id=task.task_id)+ ctx.record_download_popup_claim(task.task_id, popup)++ with patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx):+ await agent._close_credited_download_popups(task, browser_state)++ popup.close.assert_awaited_once()+ opener.close.assert_not_called()+ assert task.task_id not in ctx.download_popup_claims+++async def test_close_credited_download_popups_closes_committed_popup() -> None:+ """Product contract: a download that opens a new page has that page closed after the download+ finishes REGARDLESS of URL. A claimed popup that committed to a real URL is therefore still closed+ by the late cleanup -- this fails on the pre-fix head that filtered to the ``":"`` marker only."""+ agent = ForgeAgent()+ task = _make_task(task_id="task-committed")+ committed = _claimed_popup("https://example.test/report.pdf")+ browser_state = MagicMock()+ browser_state.list_valid_pages = AsyncMock(return_value=[committed])+ ctx = SkyvernContext(task_id=task.task_id)+ ctx.record_download_popup_claim(task.task_id, committed)++ with patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx):+ await agent._close_credited_download_popups(task, browser_state)++ committed.close.assert_awaited_once()+ assert task.task_id not in ctx.download_popup_claims+++async def test_close_credited_download_popups_skips_popup_not_in_run_pages() -> None:+ """A recorded popup no longer among the run's live pages is left untouched (scope guard)."""+ agent = ForgeAgent()+ task = _make_task(task_id="task-stray")+ stray = _claimed_popup(":")+ opener = _claimed_popup("https://example.test/documents")+ browser_state = MagicMock()+ browser_state.list_valid_pages = AsyncMock(return_value=[opener])+ ctx = SkyvernContext(task_id=task.task_id)+ ctx.record_download_popup_claim(task.task_id, stray)++ with patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx):+ await agent._close_credited_download_popups(task, browser_state)++ stray.close.assert_not_called()+++async def test_close_credited_download_popups_idempotent_on_already_closed() -> None:+ """An already-closed recorded popup is a no-op (idempotent double-close guard, req #2)."""+ agent = ForgeAgent()+ task = _make_task(task_id="task-closed")+ already_closed = _claimed_popup(":")+ already_closed.is_closed.return_value = True+ browser_state = MagicMock()+ browser_state.list_valid_pages = AsyncMock(return_value=[already_closed])+ ctx = SkyvernContext(task_id=task.task_id)+ ctx.record_download_popup_claim(task.task_id, already_closed)++ with patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx):+ await agent._close_credited_download_popups(task, browser_state)++ already_closed.close.assert_not_called()+++async def test_close_credited_download_popups_no_claim_is_noop() -> None:+ """With no recorded claim (no credited download popup) nothing is closed (req #5)."""+ agent = ForgeAgent()+ task = _make_task(task_id="task-empty")+ browser_state = MagicMock()+ browser_state.list_valid_pages = AsyncMock(return_value=[_claimed_popup(":")])+ ctx = SkyvernContext(task_id=task.task_id)++ with patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx):+ await agent._close_credited_download_popups(task, browser_state)++ browser_state.list_valid_pages.assert_not_awaited()+++async def test_clean_up_task_clears_download_popup_claims_even_on_early_error() -> None:+ """Task-terminal expiry: clean_up_task drops the task's popup claims at the very top, so a claim+ never survives into a later task/run/persistent-session -- proven here on the early-error path+ (DB refresh fails) which stands in for cancellation/exception exits."""+ agent = ForgeAgent()+ task = _make_task(task_id="task-terminal")+ step = MagicMock()+ ctx = SkyvernContext(task_id=task.task_id)+ ctx.record_download_popup_claim(task.task_id, _claimed_popup(":"))++ mock_app = MagicMock()+ mock_app.DATABASE.tasks.get_task = AsyncMock(return_value=None) # forces TaskNotFound right after the clear++ with (+ patch("skyvern.forge.agent.app", mock_app),+ patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx),+ ):+ with pytest.raises(TaskNotFound):+ await agent.clean_up_task(task=task, last_step=step)++ assert task.task_id not in ctx.download_popup_claims+++async def test_close_credited_download_popups_bounds_a_hung_close() -> None:+ """A hung ``popup.close()`` must not block task completion: the late close is bounded by+ BROWSER_PAGE_CLOSE_TIMEOUT so the consumer always returns and the claim is consumed. Pre-fix the+ close was awaited unbounded and a never-resolving close would hang update_step/update_task."""+ agent = ForgeAgent()+ task = _make_task(task_id="task-hang")+ marker = _claimed_popup(":")++ async def _never_resolves() -> None:+ await asyncio.Event().wait()++ marker.close = AsyncMock(side_effect=_never_resolves)+ browser_state = MagicMock()+ browser_state.list_valid_pages = AsyncMock(return_value=[marker])+ ctx = SkyvernContext(task_id=task.task_id)+ ctx.record_download_popup_claim(task.task_id, marker)++ with (+ patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx),+ patch("skyvern.forge.agent.BROWSER_PAGE_CLOSE_TIMEOUT", 0.01, create=True),+ ):+ # asyncio.wait_for turns the pre-fix unbounded hang into a bounded test failure.+ await asyncio.wait_for(agent._close_credited_download_popups(task, browser_state), timeout=2)++ marker.close.assert_awaited_once()+ assert task.task_id not in ctx.download_popup_claims+++async def test_execute_step_complete_on_download_closes_claimed_popup_before_handoff(tmp_path) -> None:+ """Real outer-path regression: driving the actual v1 execute_step complete_on_download credit+ branch, the exact recorded ``":"`` marker popup is closed before the completed-task handoff+ (update_step/update_task). Removing the single _close_credited_download_popups call makes this+ fail (the marker is never closed)."""+ agent = ForgeAgent()+ download_dir = tmp_path / "downloads"+ download_dir.mkdir()++ task = _make_task(task_id="task-outer")+ task.status = SimpleNamespace(value="running")+ task.navigation_goal = "Download invoice"+ task.data_extraction_goal = None+ task.complete_criterion = None+ task.terminate_criterion = None+ task.browser_address = None+ task.max_steps_per_run = None+ task.url = "https://example.com"+ task.proxy_location = None+ task.llm_key = None+ task.task_type = "general"++ step = MagicMock()+ step.step_id = "step-1"+ step.order = 0+ step.retry_index = 0+ step.status = "created"++ organization = MagicMock()+ organization.organization_id = task.organization_id+ organization.max_steps_per_run = None++ task_block = MagicMock()+ task_block.complete_on_download = True+ task_block.download_timeout = None+ task_block.download_suffix = "req-123"++ order: list[str] = []++ marker = _claimed_popup(":")++ async def _close_marker() -> None:+ order.append("close")++ marker.close = AsyncMock(side_effect=_close_marker)+ opener = _claimed_popup("https://example.com/documents")++ browser_state = MagicMock()+ browser_state.get_working_page = AsyncMock(return_value=None)+ browser_state.list_valid_pages = AsyncMock(return_value=[opener, marker])++ ctx = SkyvernContext(task_id=task.task_id)+ ctx.record_download_popup_claim(task.task_id, marker)++ async def agent_step_side_effect(*args, **kwargs):+ (download_dir / "uuid-file.zip").write_text("dummy")+ return step, DetailedAgentStepOutput(+ scraped_page=None,+ extract_action_prompt=None,+ llm_response=None,+ actions=None,+ action_results=None,+ actions_and_results=None,+ cua_response=None,+ )++ async def update_step_side_effect(step_obj, *args, **kwargs):+ if "is_last" in kwargs:+ step_obj.is_last = kwargs["is_last"]+ return step_obj++ async def update_task_side_effect(task_obj, *args, **kwargs):+ if "status" in kwargs:+ order.append(f"update_task:{kwargs['status']}")+ return task_obj++ with (+ patch("skyvern.forge.agent.analytics.capture"),+ patch("skyvern.forge.agent.skyvern_context.ensure_context", return_value=ctx),+ patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx),+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=download_dir),+ patch("skyvern.forge.agent.list_downloading_files_in_directory", return_value=[]),+ patch("skyvern.forge.agent.app") as mock_app,+ patch.object(agent, "initialize_execution_state", AsyncMock(return_value=(step, browser_state, None))),+ patch.object(agent, "agent_step", AsyncMock(side_effect=agent_step_side_effect)),+ patch.object(agent, "update_step", AsyncMock(side_effect=update_step_side_effect)),+ patch.object(agent, "update_task", AsyncMock(side_effect=update_task_side_effect)),+ patch.object(agent, "update_task_errors_from_detailed_output", AsyncMock(return_value=task)),+ patch.object(agent, "clean_up_task", AsyncMock()),+ ):+ mock_app.DATABASE.workflow_runs.get_workflow_run = AsyncMock(return_value=None)+ mock_app.DATABASE.tasks.get_task = AsyncMock(return_value=task)+ mock_app.DATABASE.tasks.update_task = AsyncMock(return_value=task)+ mock_app.AGENT_FUNCTION.validate_step_execution = AsyncMock()+ mock_app.AGENT_FUNCTION.post_step_execution = AsyncMock()+ mock_app.ARTIFACT_MANAGER.flush_step_archive = AsyncMock()+ mock_app.BROWSER_MANAGER.get_for_task = MagicMock(return_value=None)+ mock_app.STORAGE.save_downloaded_files = AsyncMock()+ mock_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(return_value=[])++ await agent.execute_step(+ organization=organization,+ task=task,+ step=step,+ task_block=task_block,+ close_browser_on_completion=True,+ complete_verification=True,+ engine=RunEngine.skyvern_v1,+ )++ # The credit branch fired (file was finalized) and closed exactly the marker popup, not the opener.+ assert (download_dir / "req-123.zip").exists()+ marker.close.assert_awaited_once()+ opener.close.assert_not_called()+ assert task.task_id not in ctx.download_popup_claims+ # The close happened before the completed-task handoff (update_step/update_task).+ close_i = order.index("close")+ update_task_indices = [i for i, entry in enumerate(order) if entry.startswith("update_task:")]+ assert update_task_indices and all(close_i < i for i in update_task_indices)+++async def test_clean_up_task_closes_claimed_popup_on_cleanup_finalization_credit(tmp_path) -> None:+ """Second durable-credit seam: when the ``download_suffix``/``list_files_before`` finalization inside+ clean_up_task proves a new file, the exact recorded ``":"`` marker popup is closed. Pre-fix the+ top-of-cleanup claim clear preempted this seam, dropping the claim without closing the popup."""+ agent = ForgeAgent()+ task = _make_task(task_id="task-cleanup-credit")+ last_step = MagicMock()+ last_step.step_id = "step-1"+ marker = _claimed_popup(":")+ opener = _claimed_popup("https://example.com/documents")+ browser_state = MagicMock()+ browser_state.get_working_page = AsyncMock(return_value=None)+ browser_state.list_valid_pages = AsyncMock(return_value=[opener, marker])+ ctx = SkyvernContext(task_id=task.task_id)+ ctx.record_download_popup_claim(task.task_id, marker)++ async def finalize_side_effect(*args, **kwargs):+ return ["req-123.zip"] # cleanup finalization proves a newly landed file++ with (+ patch("skyvern.forge.agent.analytics.capture"),+ patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx),+ patch.object(agent, "_finalize_downloaded_files_for_task", AsyncMock(side_effect=finalize_side_effect)),+ patch("skyvern.forge.agent.app") as mock_app,+ ):+ mock_app.DATABASE.tasks.get_task = AsyncMock(return_value=task)+ mock_app.BROWSER_MANAGER.get_for_task = MagicMock(return_value=browser_state)+ mock_app.STORAGE.save_downloaded_files = AsyncMock()++ await agent.clean_up_task(+ task,+ last_step=last_step,+ need_final_screenshot=False,+ download_suffix="req-123",+ list_files_before=[],+ )++ marker.close.assert_awaited_once()+ opener.close.assert_not_called()+ assert task.task_id not in ctx.download_popup_claims+++async def test_clean_up_task_no_cleanup_credit_expires_claims_without_close(tmp_path) -> None:+ """When cleanup finalization proves no new file, the marker popup is NOT closed, but the claims+ still expire (taken and dropped at cleanup entry)."""+ agent = ForgeAgent()+ task = _make_task(task_id="task-cleanup-nocredit")+ last_step = MagicMock()+ last_step.step_id = "step-1"+ marker = _claimed_popup(":")+ browser_state = MagicMock()+ browser_state.get_working_page = AsyncMock(return_value=None)+ browser_state.list_valid_pages = AsyncMock(return_value=[marker])+ ctx = SkyvernContext(task_id=task.task_id)+ ctx.record_download_popup_claim(task.task_id, marker)++ async def finalize_side_effect(*args, **kwargs):+ return [] # nothing finalized -> no durable credit++ with (+ patch("skyvern.forge.agent.analytics.capture"),+ patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx),+ patch.object(agent, "_finalize_downloaded_files_for_task", AsyncMock(side_effect=finalize_side_effect)),+ patch("skyvern.forge.agent.app") as mock_app,+ ):+ mock_app.DATABASE.tasks.get_task = AsyncMock(return_value=task)+ mock_app.BROWSER_MANAGER.get_for_task = MagicMock(return_value=browser_state)+ mock_app.STORAGE.save_downloaded_files = AsyncMock()++ await agent.clean_up_task(+ task,+ last_step=last_step,+ need_final_screenshot=False,+ download_suffix="req-123",+ list_files_before=[],+ )++ marker.close.assert_not_called()+ assert task.task_id not in ctx.download_popup_claims+++async def test_close_credited_download_popups_closes_multiple_distinct_claims_each_once() -> None:+ """One durable credit closes every distinct popup the task recorded, each exactly once and+ regardless of URL, matching the legacy multi-extra-page cleanup that closed all pages the download+ opened. The opener (never a claim) is untouched."""+ agent = ForgeAgent()+ task = _make_task(task_id="task-multi")+ popup_blank = _claimed_popup(":")+ popup_committed = _claimed_popup("https://example.test/report.pdf")+ popup_about = _claimed_popup("about:blank")+ opener = _claimed_popup("https://example.test/documents")+ browser_state = MagicMock()+ browser_state.list_valid_pages = AsyncMock(return_value=[opener, popup_blank, popup_committed, popup_about])+ ctx = SkyvernContext(task_id=task.task_id)+ for popup in (popup_blank, popup_committed, popup_about):+ ctx.record_download_popup_claim(task.task_id, popup)++ with patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx):+ await agent._close_credited_download_popups(task, browser_state)++ popup_blank.close.assert_awaited_once()+ popup_committed.close.assert_awaited_once()+ popup_about.close.assert_awaited_once()+ opener.close.assert_not_called()+ assert task.task_id not in ctx.download_popup_claims+++async def test_close_credited_download_popups_dedups_exact_duplicate_claim() -> None:+ """Recording the same Page twice yields a single claim, so an exact duplicate closes at most once."""+ agent = ForgeAgent()+ task = _make_task(task_id="task-dup")+ popup = _claimed_popup("https://example.test/report.pdf")+ browser_state = MagicMock()+ browser_state.list_valid_pages = AsyncMock(return_value=[popup])+ ctx = SkyvernContext(task_id=task.task_id)+ ctx.record_download_popup_claim(task.task_id, popup)+ ctx.record_download_popup_claim(task.task_id, popup) # exact duplicate++ with patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx):+ await agent._close_credited_download_popups(task, browser_state)++ popup.close.assert_awaited_once()+++async def test_two_credit_seams_cannot_both_close_the_same_claimed_popup() -> None:+ """pop-once/take semantics: the complete_on_download seam pops the claims, so the later+ cleanup-finalization seam (which takes from the same registry) finds none and cannot re-close the+ same Page."""+ agent = ForgeAgent()+ task = _make_task(task_id="task-two-seams")+ popup = _claimed_popup("https://example.test/report.pdf")+ browser_state = MagicMock()+ browser_state.list_valid_pages = AsyncMock(return_value=[popup])+ ctx = SkyvernContext(task_id=task.task_id)+ ctx.record_download_popup_claim(task.task_id, popup)++ with patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx):+ # complete_on_download seam consumes the claim and closes the popup.+ await agent._close_credited_download_popups(task, browser_state)+ # cleanup-finalization seam takes from the same registry -> already empty.+ cleanup_claims = ctx.take_download_popup_claims(task.task_id)+ await agent._close_claimed_download_popups(task, browser_state, cleanup_claims)++ popup.close.assert_awaited_once()+ assert cleanup_claims == []+++async def test_late_cleanup_skips_popup_already_closed_by_in_seam_cleanup() -> None:+ """Sequential topology: after the legacy action-level / #16476 in-seam cleanup actually closes the+ popup (is_closed flips true and the run drops it from valid pages), the late credit cleanup does not+ close it a second time."""+ agent = ForgeAgent()+ task = _make_task(task_id="task-seq")+ popup = _claimed_popup(":")+ closed_state = {"value": False}+ popup.is_closed.side_effect = lambda: closed_state["value"]++ async def _mark_closed() -> None:+ closed_state["value"] = True++ popup.close = AsyncMock(side_effect=_mark_closed)+ browser_state = MagicMock()+ ctx = SkyvernContext(task_id=task.task_id)+ ctx.record_download_popup_claim(task.task_id, popup)++ # In-seam cleanup closes the popup first; the run then drops the closed page from its valid pages.+ await popup.close()+ browser_state.list_valid_pages = AsyncMock(return_value=[])++ with patch("skyvern.forge.agent.skyvern_context.current", return_value=ctx):+ await agent._close_credited_download_popups(task, browser_state)++ popup.close.assert_awaited_once() # only the in-seam close; late cleanup did not re-close+ assert task.task_id not in ctx.download_popup_claimsdiff --git a/tests/unit/test_bounded_file.py b/tests/unit/test_bounded_file.pynew file mode 100644index 000000000..28daff0cb--- /dev/null+++ b/tests/unit/test_bounded_file.py@@ -0,0 +1,75 @@+import hashlib++from skyvern.forge.sdk.artifact.storage.bounded_file import BoundedFileReader+++def _write(path, data: bytes) -> None:+ with open(path, "wb") as f:+ f.write(data)+++def test_reads_exactly_length_and_ignores_later_growth(tmp_path) -> None:+ """Snapshot semantics: the reader yields exactly [0, length) even if the file grows afterward,+ so a per-step upload never follows the still-growing recording's EOF."""+ p = tmp_path / "rec.webm"+ _write(p, b"A" * 100)+ reader = BoundedFileReader(str(p), 100)++ # File keeps growing after the snapshot was taken.+ with open(p, "ab") as f:+ f.write(b"B" * 900)++ out = reader.read()+ assert out == b"A" * 100+ assert reader.read() == b"" # nothing past the bound+ reader.close()+++def test_chunked_reads_are_byte_identical_to_prefix(tmp_path) -> None:+ p = tmp_path / "rec.webm"+ full = bytes((i * 37 + 11) % 256 for i in range(5000))+ _write(p, full)+ length = 4096+ reader = BoundedFileReader(str(p), length)++ chunks = []+ while True:+ c = reader.read(512)+ if not c:+ break+ assert len(c) <= 512+ chunks.append(c)+ reader.close()++ joined = b"".join(chunks)+ assert len(joined) == length+ assert joined == full[:length]+ assert hashlib.sha256(joined).hexdigest() == hashlib.sha256(full[:length]).hexdigest()+++def test_seek_and_tell_support_size_probe_and_retry_rewind(tmp_path) -> None:+ """upload_fileobj probes size via seek(0, 2)/tell and rewinds via seek(0) on retry."""+ p = tmp_path / "rec.webm"+ _write(p, b"Z" * 800)+ length = 500+ reader = BoundedFileReader(str(p), length)++ assert reader.seek(0, 2) == length # size probe returns the bound, not the file size+ assert reader.tell() == length+ reader.seek(0) # rewind for retry+ assert reader.tell() == 0++ first = reader.read(length)+ assert first == b"Z" * length+ reader.seek(0)+ assert reader.read(length) == first # replay after rewind is identical+ reader.close()+++def test_read_never_exceeds_bound_even_with_large_request(tmp_path) -> None:+ p = tmp_path / "rec.webm"+ _write(p, b"Q" * 10_000)+ reader = BoundedFileReader(str(p), 1234)+ out = reader.read(1_000_000)+ assert out == b"Q" * 1234+ reader.close()diff --git a/tests/unit/test_browser_effect_sink_enumeration.py b/tests/unit/test_browser_effect_sink_enumeration.pyindex 541082e32..e51240ba0 100644--- a/tests/unit/test_browser_effect_sink_enumeration.py+++ b/tests/unit/test_browser_effect_sink_enumeration.py@@ -15,7 +15,7 @@ _CANDIDATE_METHODS = frozenset()_DISCOVERED_BROWSER_API_CALLS = {- "skyvern/forge/agent.py": Counter({"evaluate": 2, "new_page": 1}),+ "skyvern/forge/agent.py": Counter({"close": 1, "evaluate": 2, "new_page": 1}),"skyvern/forge/agent_functions.py": Counter({"close": 1, "scroll_into_view_if_needed": 1}),"skyvern/webeye/actions/handler.py": Counter({@@ -217,14 +217,14 @@ def test_discovered_browser_api_lower_bound_is_stable() -> None:}assert observed == _DISCOVERED_BROWSER_API_CALLS- assert sum(sum(methods.values()) for methods in observed.values()) == 162+ assert sum(sum(methods.values()) for methods in observed.values()) == 163handler_candidates = _candidate_signatures("skyvern/webeye/actions/handler.py", _CANDIDATE_METHODS)classified_non_browser = Counter({signature: count for signature, count in handler_candidates.items() if signature in _NON_BROWSER_CANDIDATES})assert classified_non_browser == _NON_BROWSER_CANDIDATESassert sum(_NON_BROWSER_CANDIDATES.values()) == 5- assert sum(sum(methods.values()) for methods in observed.values()) - sum(_NON_BROWSER_CANDIDATES.values()) == 157+ assert sum(sum(methods.values()) for methods in observed.values()) - sum(_NON_BROWSER_CANDIDATES.values()) == 158def test_every_raw_evaluate_call_is_classified() -> None:diff --git a/tests/unit/test_cleanup_browser_video_path_fallback.py b/tests/unit/test_cleanup_browser_video_path_fallback.pyindex 1a6fec1bd..f87f45e02 100644--- a/tests/unit/test_cleanup_browser_video_path_fallback.py+++ b/tests/unit/test_cleanup_browser_video_path_fallback.py@@ -263,9 +263,11 @@ async def test_cleanup_path_fallback_skips_when_path_missing(tmp_path: Path) ->async def test_cleanup_preserves_update_path_for_pre_registered_artifact(tmp_path: Path) -> None:# A standard Playwright recording arrives pre-registered (``initialize_execution_state``); the# existing data-update path stays in charge and the new path-upload helper stays idle.+ webm = tmp_path / "playwright.webm"+ webm.write_bytes(b"video")video_artifacts = [VideoArtifact(- video_path=str(tmp_path / "playwright.webm"),+ video_path=str(webm),video_artifact_id="a_existing",video_data=b"video",)@@ -290,10 +292,12 @@ async def test_cleanup_preserves_update_path_for_pre_registered_artifact(tmp_pattask=task,)+ # Terminal finalize (no-extension branch) must supersede queued prefixes.mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_awaited_once_with(artifact_id="a_existing",organization_id="o_1",data=b"video",+ supersede_queued_prefixes=True,)recording_calls = [c@@ -304,6 +308,293 @@ async def test_cleanup_preserves_update_path_for_pre_registered_artifact(tmp_patassert video_artifacts[0].video_artifact_id == "a_existing"+async def test_cleanup_terminal_extension_branch_supersedes_queued_prefixes(tmp_path: Path) -> None:+ """Task terminal finalize, extension branch: passes file_extension AND supersede_queued_prefixes=True."""+ webm = tmp_path / "playwright.webm"+ webm.write_bytes(b"video")+ video_artifacts = [+ VideoArtifact(+ video_path=str(webm),+ video_artifact_id="a_existing",+ video_data=b"video",+ video_file_extension="mp4",+ )+ ]+ agent = ForgeAgent()+ task = _make_task()+ last_step = _make_step()+ browser_state = _browser_state()++ with patch("skyvern.forge.agent.app") as mock_app:+ mock_app.BROWSER_MANAGER.cleanup_for_task = AsyncMock(return_value=browser_state)+ mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock(return_value=video_artifacts)+ mock_app.BROWSER_MANAGER.get_har_data = AsyncMock(return_value=b"")+ mock_app.BROWSER_MANAGER.get_browser_console_log = AsyncMock(return_value=b"")+ mock_app.ARTIFACT_MANAGER.update_artifact_data = AsyncMock()+ mock_app.ARTIFACT_MANAGER.create_artifact = AsyncMock()++ await agent.cleanup_browser_and_create_artifacts(+ close_browser_on_completion=True,+ last_step=last_step,+ task=task,+ )++ mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_awaited_once_with(+ artifact_id="a_existing",+ organization_id="o_1",+ data=b"video",+ file_extension="mp4",+ supersede_queued_prefixes=True,+ )++[email protected]("extension", [None, "mp4"])+async def test_workflow_persist_terminal_supersedes_queued_prefixes(tmp_path: Path, extension: str | None) -> None:+ """Workflow/task-v2/code-block terminal finalize supersedes queued prefixes on both branches."""+ webm = tmp_path / "session.webm"+ webm.write_bytes(b"video")+ video_artifacts = [+ VideoArtifact(+ video_path=str(webm),+ video_artifact_id="a_existing",+ video_data=b"video",+ video_file_extension=extension,+ )+ ]+ workflow = SimpleNamespace(workflow_id="wf_1")+ workflow_run = SimpleNamespace(workflow_run_id="wfr_1", organization_id="o_1")++ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:+ mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock(return_value=video_artifacts)+ mock_app.ARTIFACT_MANAGER.update_artifact_data = AsyncMock(return_value="task_1")+ mock_app.ARTIFACT_MANAGER.create_artifact = AsyncMock()+ mock_app.ARTIFACT_MANAGER.wait_for_upload_aiotasks = AsyncMock()++ await WorkflowService().persist_video_data(_browser_state(), workflow, workflow_run)++ expected: dict = {+ "artifact_id": "a_existing",+ "organization_id": "o_1",+ "data": b"video",+ "supersede_queued_prefixes": True,+ }+ if extension is not None:+ expected["file_extension"] = extension+ mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_awaited_once_with(**expected)+++async def test_cleanup_intermediate_does_not_supersede_queued_prefixes(tmp_path: Path) -> None:+ """Intermediate task cleanup (browser NOT closed): the recording is still growing and its per-step+ prefixes are still legitimately streaming, so it must NOT seal/supersede the live key even though the+ non-finalized snapshot carries a truthy .webm extension (SKY-15288, thread r3918986927)."""+ webm = tmp_path / "playwright.webm"+ webm.write_bytes(b"partial")+ video_artifacts = [+ VideoArtifact(+ video_path=str(webm),+ video_artifact_id="a_existing",+ video_data=b"partial",+ video_file_extension="webm", # non-finalize snapshots still set a truthy extension+ )+ ]+ agent = ForgeAgent()+ task = _make_task()+ last_step = _make_step()+ browser_state = _browser_state()++ with patch("skyvern.forge.agent.app") as mock_app:+ mock_app.BROWSER_MANAGER.cleanup_for_task = AsyncMock(return_value=browser_state)+ mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock(return_value=video_artifacts)+ mock_app.BROWSER_MANAGER.get_har_data = AsyncMock(return_value=b"")+ mock_app.BROWSER_MANAGER.get_browser_console_log = AsyncMock(return_value=b"")+ mock_app.ARTIFACT_MANAGER.update_artifact_data = AsyncMock()+ mock_app.ARTIFACT_MANAGER.create_artifact = AsyncMock()++ await agent.cleanup_browser_and_create_artifacts(+ close_browser_on_completion=False,+ last_step=last_step,+ task=task,+ )++ mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_awaited_once_with(+ artifact_id="a_existing",+ organization_id="o_1",+ data=b"partial",+ file_extension="webm",+ supersede_queued_prefixes=False,+ )+++async def test_workflow_persist_intermediate_does_not_supersede_queued_prefixes(tmp_path: Path) -> None:+ """Intermediate workflow persist (browser NOT closed, persistent/shared session): must not seal the+ live recording key while prefixes are still streaming (SKY-15288, thread r3918986927)."""+ webm = tmp_path / "session.webm"+ webm.write_bytes(b"partial")+ video_artifacts = [+ VideoArtifact(+ video_path=str(webm),+ video_artifact_id="a_existing",+ video_data=b"partial",+ video_file_extension="webm",+ )+ ]+ workflow = SimpleNamespace(workflow_id="wf_1")+ workflow_run = SimpleNamespace(workflow_run_id="wfr_1", organization_id="o_1")++ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:+ mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock(return_value=video_artifacts)+ mock_app.ARTIFACT_MANAGER.update_artifact_data = AsyncMock(return_value="task_1")+ mock_app.ARTIFACT_MANAGER.create_artifact = AsyncMock()+ mock_app.ARTIFACT_MANAGER.wait_for_upload_aiotasks = AsyncMock()++ await WorkflowService().persist_video_data(+ _browser_state(), workflow, workflow_run, close_browser_on_completion=False+ )++ mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_awaited_once_with(+ artifact_id="a_existing",+ organization_id="o_1",+ data=b"partial",+ file_extension="webm",+ supersede_queued_prefixes=False,+ )+++async def test_cleanup_skips_stale_update_when_registered_path_missing(tmp_path: Path) -> None:+ """Task terminal finalize: a registered recording whose local file has vanished must NOT overwrite the+ newer streamed prefix with the stale cached bytes get_video_artifacts could no longer refresh+ (SKY-15288)."""+ missing = tmp_path / "gone.webm"+ assert not missing.exists()+ video_artifacts = [+ VideoArtifact(+ video_path=str(missing),+ video_artifact_id="a_existing",+ video_data=b"stale-cached-bytes",+ video_file_extension="webm",+ )+ ]+ agent = ForgeAgent()+ task = _make_task()+ last_step = _make_step()+ browser_state = _browser_state()++ with patch("skyvern.forge.agent.app") as mock_app:+ mock_app.BROWSER_MANAGER.cleanup_for_task = AsyncMock(return_value=browser_state)+ mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock(return_value=video_artifacts)+ mock_app.BROWSER_MANAGER.get_har_data = AsyncMock(return_value=b"")+ mock_app.BROWSER_MANAGER.get_browser_console_log = AsyncMock(return_value=b"")+ mock_app.ARTIFACT_MANAGER.update_artifact_data = AsyncMock()+ mock_app.ARTIFACT_MANAGER.create_artifact = AsyncMock()++ await agent.cleanup_browser_and_create_artifacts(+ close_browser_on_completion=True,+ last_step=last_step,+ task=task,+ )++ mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_not_awaited()+ recording_calls = [+ c+ for c in mock_app.ARTIFACT_MANAGER.create_artifact.await_args_list+ if c.kwargs.get("artifact_type") == ArtifactType.RECORDING+ ]+ assert recording_calls == []+ assert video_artifacts[0].video_artifact_id == "a_existing"+++async def test_workflow_persist_skips_stale_update_when_registered_path_missing(tmp_path: Path) -> None:+ """Workflow terminal finalize: same missing-path preservation guard as the task path (SKY-15288)."""+ missing = tmp_path / "gone.webm"+ assert not missing.exists()+ video_artifacts = [+ VideoArtifact(+ video_path=str(missing),+ video_artifact_id="a_existing",+ video_data=b"stale-cached-bytes",+ video_file_extension="webm",+ )+ ]+ workflow = SimpleNamespace(workflow_id="wf_1")+ workflow_run = SimpleNamespace(workflow_run_id="wfr_1", organization_id="o_1")++ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:+ mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock(return_value=video_artifacts)+ mock_app.ARTIFACT_MANAGER.update_artifact_data = AsyncMock(return_value="task_1")+ mock_app.ARTIFACT_MANAGER.create_artifact = AsyncMock()+ mock_app.ARTIFACT_MANAGER.wait_for_upload_aiotasks = AsyncMock()++ await WorkflowService().persist_video_data(_browser_state(), workflow, workflow_run)++ mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_not_awaited()+ mock_app.ARTIFACT_MANAGER.create_artifact.assert_not_awaited()+ mock_app.ARTIFACT_MANAGER.wait_for_upload_aiotasks.assert_not_awaited()+ assert video_artifacts[0].video_artifact_id == "a_existing"+++async def test_cleanup_uploads_registered_vendor_bytes_when_path_is_none() -> None:+ """Vendor/CDP recordings register with no local path and supply bytes out of band; the missing-path+ guard keys on a truthy-but-absent path, so it must NOT swallow a pathless upload (SKY-15288)."""+ video_artifacts = [VideoArtifact(video_path=None, video_artifact_id="a_existing", video_data=b"vendor-bytes")]+ agent = ForgeAgent()+ task = _make_task()+ last_step = _make_step()+ browser_state = _browser_state()++ with patch("skyvern.forge.agent.app") as mock_app:+ mock_app.BROWSER_MANAGER.cleanup_for_task = AsyncMock(return_value=browser_state)+ mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock(return_value=video_artifacts)+ mock_app.BROWSER_MANAGER.get_har_data = AsyncMock(return_value=b"")+ mock_app.BROWSER_MANAGER.get_browser_console_log = AsyncMock(return_value=b"")+ mock_app.ARTIFACT_MANAGER.update_artifact_data = AsyncMock()+ mock_app.ARTIFACT_MANAGER.create_artifact = AsyncMock()++ await agent.cleanup_browser_and_create_artifacts(+ close_browser_on_completion=True,+ last_step=last_step,+ task=task,+ )++ mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_awaited_once_with(+ artifact_id="a_existing",+ organization_id="o_1",+ data=b"vendor-bytes",+ supersede_queued_prefixes=True,+ )+++async def test_workflow_persist_uploads_registered_vendor_bytes_when_path_is_none() -> None:+ """Workflow path mirror of the vendor/CDP pathless-bytes guard (SKY-15288)."""+ video_artifacts = [VideoArtifact(video_path=None, video_artifact_id="a_existing", video_data=b"vendor-bytes")]+ workflow = SimpleNamespace(workflow_id="wf_1")+ workflow_run = SimpleNamespace(workflow_run_id="wfr_1", organization_id="o_1")++ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:+ mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock(return_value=video_artifacts)+ mock_app.ARTIFACT_MANAGER.update_artifact_data = AsyncMock(return_value="task_1")+ mock_app.ARTIFACT_MANAGER.create_artifact = AsyncMock()+ mock_app.ARTIFACT_MANAGER.wait_for_upload_aiotasks = AsyncMock()++ await WorkflowService().persist_video_data(_browser_state(), workflow, workflow_run)++ mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_awaited_once_with(+ artifact_id="a_existing",+ organization_id="o_1",+ data=b"vendor-bytes",+ supersede_queued_prefixes=True,+ )+ mock_app.ARTIFACT_MANAGER.create_artifact.assert_not_awaited()+ mock_app.ARTIFACT_MANAGER.wait_for_upload_aiotasks.assert_awaited_once_with(["task_1"])++@pytest.mark.asyncio@pytest.mark.parametrize("redaction_enabled", [False, True])async def test_cleanup_gates_har_and_console_redaction_on_run_gate(diff --git a/tests/unit/test_code_block_recording_artifact.py b/tests/unit/test_code_block_recording_artifact.pyindex 186fa1d00..c4848c8bf 100644--- a/tests/unit/test_code_block_recording_artifact.py+++ b/tests/unit/test_code_block_recording_artifact.py@@ -376,10 +376,10 @@ class TestPersistVideoDataFlushesUploads:clean_up_workflow's task-id drain never awaits — persist_video_data must flush those keys itself."""@pytest.mark.asyncio- async def test_flushes_the_keys_it_enqueued(self) -> None:- video_artifacts = [- VideoArtifact(video_path="/tmp/recording.webm", video_artifact_id="a_recording", video_data=b"video")- ]+ async def test_flushes_the_keys_it_enqueued(self, tmp_path: Path) -> None:+ webm = tmp_path / "recording.webm"+ webm.write_bytes(b"video")+ video_artifacts = [VideoArtifact(video_path=str(webm), video_artifact_id="a_recording", video_data=b"video")]get_video = AsyncMock(return_value=video_artifacts)update_data = AsyncMock(return_value="wrb_1")wait_for_uploads = AsyncMock()@@ -529,9 +529,11 @@ class TestPersistVideoDataPathFallback:async def test_preserves_update_path_for_pre_registered_artifact(self, tmp_path: Path) -> None:# A code-block recording arrives pre-registered (``_ensure_run_recording_artifact``); the# existing data-update path stays in charge and the new path-upload helper stays idle.+ webm = tmp_path / "code-block.webm"+ webm.write_bytes(b"video")video_artifacts = [VideoArtifact(- video_path=str(tmp_path / "code-block.webm"),+ video_path=str(webm),video_artifact_id="a_existing",video_data=b"video",)diff --git a/tests/unit/test_download_file_action_handler.py b/tests/unit/test_download_file_action_handler.pyindex 60a6798bc..1ad635d72 100644--- a/tests/unit/test_download_file_action_handler.py+++ b/tests/unit/test_download_file_action_handler.py@@ -20,6 +20,7 @@ from skyvern.config import settingsfrom skyvern.constants import BROWSER_DOWNLOAD_TIMEOUTfrom skyvern.errors.errors import UserDefinedErrorfrom skyvern.exceptions import BlockedHost+from skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.forge.sdk.models import StepStatusfrom skyvern.webeye.actions.actions import (ActionStatus,@@ -2676,10 +2677,14 @@ async def test_handle_action_download_no_signal_fails_fast(span_exporter: InMemoassert results[-1].followup_message == DOWNLOAD_NOT_TRIGGERED_FOLLOWUP_MESSAGEassert wait_for_downloads.await_count == 0page.off.assert_any_call("download", download_listeners["download"])- # Managed (non-adopted) sessions must not gain popup-download-event wiring.- assert "popup" not in download_listeners- assert not any(c.args and c.args[0] == "popup" for c in page.on.call_args_list)- assert not any(c.args and c.args[0] == "popup" for c in page.off.call_args_list)+ # Managed (non-adopted) sessions now gain the identity-only download-popup claim recorder, but+ # must not gain popup-download-EVENT wiring: firing the recorded popup listener attaches no+ # download listener to the popup (SKY-12621 invariant preserved).+ popup_cb = download_listeners.get("popup")+ assert popup_cb is not None+ sentinel_popup = MagicMock()+ popup_cb(sentinel_popup)+ sentinel_popup.on.assert_not_called()span_attrs = _download_wait_span_attrs(span_exporter)assert span_attrs["download_signal_observed"] is Falseassert span_attrs["download_wait_extended_for_in_flight_request"] is False@@ -6145,8 +6150,13 @@ async def test_handle_action_managed_session_disables_eager_and_popup_wiring() -)assert captured_kwargs.get("enabled") is False- assert "popup" not in page_listeners- assert not any(c.args and c.args[0] == "popup" for c in page.on.call_args_list)+ # Managed sessions now gain the identity-only download-popup claim recorder, but no popup-download+ # -event wiring: firing the recorded popup listener attaches no download listener to the popup.+ popup_cb = page_listeners.get("popup")+ assert popup_cb is not None+ sentinel_popup = MagicMock()+ popup_cb(sentinel_popup)+ sentinel_popup.on.assert_not_called()def _blob_download(url: str, suggested_filename: str) -> MagicMock:@@ -7130,3 +7140,83 @@ async def test_local_artifact_skips_provider_at_finalization_without_duplicate()assert results[-1].download_triggered is Trueassert results[-1].downloaded_files == action.downloaded_files == ["report.pdf"]assert observation.poll_deadlines == []+++async def test_explicit_download_marker_popup_recorded_as_claim(tmp_path: Path) -> None:+ """SKY-15371 follow-up, deployed-#16476 reproduction: an explicit ``action.download=True`` click on+ a run with no ``browser_session_id`` opens a never-committed ``":"`` popup and mints no Playwright+ download event, so the action returns ``download_triggered=False`` and the popup is left open. The+ exact popup Page must be recorded as a task-scoped claim so a download credited later (via the CDP+ monitor / file-scan task lifecycle, which never fires a Playwright popup download event) can close+ it. Pre-fix the only popup recorder was gated behind ``browser_session_id``, so nothing was recorded+ for these dynamic-CDP runs and the marker popup leaked into the next task's working-page selection."""+ now = datetime.now(UTC)+ organization = make_organization(now)+ task, step, page, browser_state, scraped_page, action = _make_download_click_context(+ now=now,+ organization=organization,+ page_url="https://example.test/documents",+ )+ page.expose_binding = AsyncMock()+ page.evaluate = AsyncMock(return_value=[])+ page.context._skyvern_cdp_download_active = False++ popup_callbacks: list[Callable] = []++ def _capture_on(event: str, callback: Callable) -> None:+ if event == "popup":+ popup_callbacks.append(callback)++ page.on.side_effect = _capture_on++ marker_popup = MagicMock(url=":")+ marker_popup.is_closed.return_value = False+ marker_popup.close = AsyncMock()++ async def click_opens_marker_popup(*args: object, **kwargs: object) -> list[ActionSuccess]:+ # The click opens the download popup; no Playwright download event ever fires on it.+ for callback in popup_callbacks:+ callback(marker_popup)+ return [ActionSuccess()]++ ctx = SkyvernContext(+ task_id=task.task_id,+ workflow_run_id=task.workflow_run_id,+ organization_id=organization.organization_id,+ )+ xhr_capture = MagicMock(has_in_flight_requests=False)+ xhr_capture.drain = AsyncMock(return_value=False)+ mock_app = MagicMock()+ mock_app.BROWSER_MANAGER.get_for_task.return_value = browser_state+ mock_app.DATABASE.workflow_params.create_action = AsyncMock(return_value=action)+ mock_app.STORAGE = MagicMock()++ with (+ patch.object(ActionHandler, "_handle_action", side_effect=click_opens_marker_popup),+ patch("skyvern.webeye.actions.handler.BROWSER_DOWNLOAD_NO_SIGNAL_GRACE_TIME", 0),+ patch("skyvern.webeye.actions.handler.get_download_dir", return_value=str(tmp_path)),+ patch("skyvern.webeye.actions.handler.list_files_in_directory", return_value=[]),+ patch("skyvern.webeye.actions.handler.ScopedXhrDownloadCapture", return_value=xhr_capture),+ patch(+ "skyvern.webeye.actions.handler._recover_blocked_inline_pdf_download",+ new=AsyncMock(return_value=None),+ ),+ patch("skyvern.webeye.actions.handler.skyvern_context.current", return_value=ctx),+ patch("skyvern.webeye.actions.handler.app", mock_app),+ ):+ results = await ActionHandler.handle_action(+ scraped_page=scraped_page,+ task=task,+ step=step,+ page=page,+ action=action,+ )++ assert results[-1].download_triggered is False+ # handle_action itself must not close the popup; closing is deferred to the durable credit seam.+ marker_popup.close.assert_not_called()+ claims = ctx.download_popup_claims.get(task.task_id, [])+ assert any(candidate is marker_popup for candidate in claims), (+ "explicit-download marker popup must be recorded as a task-scoped claim"+ )diff --git a/tests/unit/test_real_browser_manager.py b/tests/unit/test_real_browser_manager.pyindex c1ce421be..f8e1774ad 100644--- a/tests/unit/test_real_browser_manager.py+++ b/tests/unit/test_real_browser_manager.py@@ -21,7 +21,12 @@ from skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.forge.sdk.streaming import registriesfrom skyvern.webeye import real_browser_manager-from skyvern.webeye.browser_artifacts import BrowserArtifacts, DownloadBinding, VideoArtifact+from skyvern.webeye.browser_artifacts import (+ BrowserArtifacts,+ DownloadBinding,+ RecordingPrefixSnapshot,+ VideoArtifact,+)from skyvern.webeye.browser_engine import (BrowserEngineBootstrapError,BrowserEngineMetadata,@@ -2665,3 +2670,57 @@ def test_the_browser_manager_never_drags_in_the_http_route_layer() -> None:)result = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, timeout=180)assert result.returncode == 0, f"route layer leaked into the browser manager import graph\n{result.stderr[-800:]}"+++def _browser_state_for_snapshot(artifacts: list[VideoArtifact]) -> MagicMock:+ browser_state = MagicMock()+ browser_state.browser_artifacts.video_artifacts = artifacts+ return browser_state+++def test_snapshot_recording_prefixes_empty_when_no_artifacts() -> None:+ manager = RealBrowserManager()+ browser_state = _browser_state_for_snapshot([])+ assert manager.snapshot_recording_prefixes(browser_state=browser_state, task_id="t") == []+++def test_snapshot_recording_prefixes_plans_growing_webm(tmp_path) -> None:+ """The plan captures the current on-disk length as the snapshot bound, not the live EOF."""+ manager = RealBrowserManager()+ src = tmp_path / "rec.webm"+ src.write_bytes(b"x" * 321)+ artifact = VideoArtifact(video_path=str(src), video_artifact_id="vid-0")+ browser_state = _browser_state_for_snapshot([artifact])++ plan = manager.snapshot_recording_prefixes(browser_state=browser_state, task_id="t")++ src.write_bytes(b"x" * 10_000) # a snapshot taken now must not be enlarged by later growth+ assert plan == [RecordingPrefixSnapshot(video_artifact_id="vid-0", path=str(src), prefix_len=321)]+++def test_snapshot_recording_prefixes_none_when_non_webm(tmp_path) -> None:+ manager = RealBrowserManager()+ src = tmp_path / "rec.mp4"+ src.write_bytes(b"mp4")+ artifact = VideoArtifact(video_path=str(src), video_artifact_id="vid-0")+ browser_state = _browser_state_for_snapshot([artifact])++ assert manager.snapshot_recording_prefixes(browser_state=browser_state, task_id="t") is None+++def test_snapshot_recording_prefixes_none_when_missing_artifact_id(tmp_path) -> None:+ manager = RealBrowserManager()+ src = tmp_path / "rec.webm"+ src.write_bytes(b"x")+ artifact = VideoArtifact(video_path=str(src), video_artifact_id=None)+ browser_state = _browser_state_for_snapshot([artifact])++ assert manager.snapshot_recording_prefixes(browser_state=browser_state, task_id="t") is None+++def test_snapshot_recording_prefixes_none_when_path_absent(tmp_path) -> None:+ manager = RealBrowserManager()+ artifact = VideoArtifact(video_path=str(tmp_path / "missing.webm"), video_artifact_id="vid-0")+ browser_state = _browser_state_for_snapshot([artifact])++ assert manager.snapshot_recording_prefixes(browser_state=browser_state, task_id="t") is Nonediff --git a/tests/unit/test_recording_artifact_update.py b/tests/unit/test_recording_artifact_update.pyindex ee4ba5249..b75435977 100644--- a/tests/unit/test_recording_artifact_update.py+++ b/tests/unit/test_recording_artifact_update.py@@ -37,6 +37,7 @@ async def test_update_recording_artifact_data_rewrites_uri_for_prepared_extensioorganization_id=original.organization_id,data=b"mp4-bytes",file_extension="mp4",+ supersede_queued_prefixes=True,)await asyncio.gather(*manager.upload_aiotasks_map["task_1"])@@ -46,7 +47,37 @@ async def test_update_recording_artifact_data_rewrites_uri_for_prepared_extensiouri="s3://bucket/path/recording.mp4",file_size=9,)- mock_app.STORAGE.store_artifact.assert_awaited_once_with(updated, b"mp4-bytes")+ # The finalize renamed .webm -> .mp4, so the terminal write must seal the OLD .webm key its per-step+ # prefixes queued to (prefix_uri), not the new .mp4 key nothing queued to (SKY-15288, thread r3917658240).+ mock_app.STORAGE.store_artifact.assert_awaited_once_with(+ updated, b"mp4-bytes", supersede_queued_prefixes=True, prefix_uri=original.uri+ )+++async def test_update_recording_artifact_data_defaults_to_not_superseding() -> None:+ """update_artifact_data is generic (also the mid-step byte fallback), so it must default to NOT+ sealing/superseding queued prefixes — only explicit terminal callers pass the flag."""+ manager = ArtifactManager()+ artifact = _make_recording_artifact("s3://bucket/path/recording.webm").model_copy(update={"file_size": 10})++ with patch("skyvern.forge.sdk.artifact.manager.app") as mock_app:+ mock_app.DATABASE.artifacts.get_artifact_by_id = AsyncMock(return_value=artifact)+ mock_app.DATABASE.artifacts.update_artifact_uri = AsyncMock()+ mock_app.STORAGE.store_artifact = AsyncMock()++ await manager.update_artifact_data(+ artifact_id=artifact.artifact_id,+ organization_id=artifact.organization_id,+ data=b"webm-bytes",+ file_extension="webm",+ )+ await asyncio.gather(*manager.upload_aiotasks_map["task_1"])++ # No rename (.webm -> .webm), so there is no distinct prefix key to seal: prefix_uri stays None.+ mock_app.STORAGE.store_artifact.assert_awaited_once_with(+ artifact, b"webm-bytes", supersede_queued_prefixes=False, prefix_uri=None+ )@pytest.mark.asyncio@@ -65,6 +96,7 @@ async def test_update_recording_artifact_data_same_extension_updates_file_size()organization_id=artifact.organization_id,data=b"webm-bytes",file_extension="webm",+ supersede_queued_prefixes=True,)await asyncio.gather(*manager.upload_aiotasks_map["task_1"])@@ -74,7 +106,11 @@ async def test_update_recording_artifact_data_same_extension_updates_file_size()uri=artifact.uri,file_size=10,)- mock_app.STORAGE.store_artifact.assert_awaited_once_with(updated, b"webm-bytes")+ # Same-extension finalize (.webm -> .webm): the write object and the prefix key coincide, so+ # prefix_uri stays None and store_artifact serializes on its own uri.+ mock_app.STORAGE.store_artifact.assert_awaited_once_with(+ updated, b"webm-bytes", supersede_queued_prefixes=True, prefix_uri=None+ )@pytest.mark.asyncio@@ -92,11 +128,15 @@ async def test_update_recording_artifact_data_skips_db_update_when_uri_and_size_organization_id=artifact.organization_id,data=b"webm-bytes",file_extension="webm",+ supersede_queued_prefixes=True,)await asyncio.gather(*manager.upload_aiotasks_map["task_1"])mock_app.DATABASE.artifacts.update_artifact_uri.assert_not_awaited()- mock_app.STORAGE.store_artifact.assert_awaited_once_with(artifact, b"webm-bytes")+ # No rename happened, so no distinct prefix key to seal: prefix_uri stays None.+ mock_app.STORAGE.store_artifact.assert_awaited_once_with(+ artifact, b"webm-bytes", supersede_queued_prefixes=True, prefix_uri=None+ )@pytest.mark.asyncio@@ -148,3 +188,86 @@ async def test_update_recording_artifact_data_logs_store_task_failure() -> None:and call.kwargs["uri"] == updated.urifor call in mock_log.warning.call_args_list)+++async def test_stream_artifact_prefix_from_path_streams_bounded_length() -> None:+ manager = ArtifactManager()+ artifact = _make_recording_artifact("s3://bucket/path/recording.webm")++ with patch("skyvern.forge.sdk.artifact.manager.app") as mock_app:+ mock_app.DATABASE.artifacts.get_artifact_by_id = AsyncMock(return_value=artifact)+ mock_app.STORAGE.store_artifact_prefix_from_path = AsyncMock()++ key = await manager.stream_artifact_prefix_from_path(+ artifact_id=artifact.artifact_id,+ organization_id=artifact.organization_id,+ path="/tmp/recording.webm",+ length=4096,+ )+ await asyncio.gather(*manager.upload_aiotasks_map["task_1"])++ assert key == "task_1"+ mock_app.STORAGE.store_artifact_prefix_from_path.assert_awaited_once_with(artifact, "/tmp/recording.webm", 4096)+++async def test_stream_artifact_prefix_from_path_noop_without_ids() -> None:+ manager = ArtifactManager()++ with patch("skyvern.forge.sdk.artifact.manager.app") as mock_app:+ mock_app.STORAGE.store_artifact_prefix_from_path = AsyncMock()++ assert await manager.stream_artifact_prefix_from_path(None, "org_1", "/tmp/x.webm", 10) is None+ assert await manager.stream_artifact_prefix_from_path("a_recording", None, "/tmp/x.webm", 10) is None++ mock_app.STORAGE.store_artifact_prefix_from_path.assert_not_awaited()+++async def test_stream_artifact_prefix_from_path_noop_when_artifact_missing() -> None:+ manager = ArtifactManager()++ with patch("skyvern.forge.sdk.artifact.manager.app") as mock_app:+ mock_app.DATABASE.artifacts.get_artifact_by_id = AsyncMock(return_value=None)+ mock_app.STORAGE.store_artifact_prefix_from_path = AsyncMock()++ assert await manager.stream_artifact_prefix_from_path("a_missing", "org_1", "/tmp/x.webm", 10) is None++ mock_app.STORAGE.store_artifact_prefix_from_path.assert_not_awaited()+++async def test_stream_artifact_prefix_swallows_missing_file() -> None:+ """The read now happens in the fire-and-forget task; a concurrently removed recording file must be+ logged and swallowed, not surface unhandled through wait_for_upload_aiotasks' gather."""+ manager = ArtifactManager()+ artifact = _make_recording_artifact("s3://bucket/path/recording.webm")++ with patch("skyvern.forge.sdk.artifact.manager.app") as mock_app:+ mock_app.DATABASE.artifacts.get_artifact_by_id = AsyncMock(return_value=artifact)+ mock_app.STORAGE.store_artifact_prefix_from_path = AsyncMock(side_effect=FileNotFoundError("gone"))++ key = await manager.stream_artifact_prefix_from_path(+ artifact.artifact_id, artifact.organization_id, "/tmp/missing.webm", 10+ )+ # The tracked task must finish cleanly (no exception escaping into the barrier's gather).+ await asyncio.gather(*manager.upload_aiotasks_map["task_1"])++ assert key == "task_1"+++async def test_stream_artifact_prefix_from_path_refuses_unknown_type() -> None:+ manager = ArtifactManager()+ artifact = _make_recording_artifact("s3://bucket/path/recording.webm").model_copy(+ update={"artifact_type": ArtifactType.UNKNOWN}+ )++ with patch("skyvern.forge.sdk.artifact.manager.app") as mock_app:+ mock_app.DATABASE.artifacts.get_artifact_by_id = AsyncMock(return_value=artifact)+ mock_app.STORAGE.store_artifact_prefix_from_path = AsyncMock()++ assert await manager.stream_artifact_prefix_from_path("a_recording", "org_1", "/tmp/x.webm", 10) is None++ mock_app.STORAGE.store_artifact_prefix_from_path.assert_not_awaited()diff --git a/tests/unit/test_recording_incremental_compose.py b/tests/unit/test_recording_incremental_compose.pynew file mode 100644index 000000000..a45d0e248--- /dev/null+++ b/tests/unit/test_recording_incremental_compose.py@@ -0,0 +1,1243 @@+"""Phase 2 (SKY-15288) incremental same-key S3 compose — protocol & lifecycle tests.++A fake async S3 client models the exact MPU surface the compose path drives (create with Metadata /+upload_part_copy with CopySourceIfMatch fencing / upload_part / complete / abort / head with Metadata /+put / upload_fileobj), so these assert the product lifecycle logic — atomic same-key visibility, stale-ETag+conflict preservation, generation-token reconciliation, single-slot fallback ordering, and fd ownership —+without real S3. The real-S3 protocol probe (temp bucket) validates the wire protocol separately.+"""++from __future__ import annotations++import asyncio+import contextlib+import gc+import os+import tempfile+from datetime import UTC, datetime+from typing import Any+from unittest.mock import AsyncMock, MagicMock++import pytest+from botocore.exceptions import ClientError++from skyvern.config import settings+from skyvern.forge.sdk.api.aws import (+ _MAX_COMPOSE_PART_BYTES,+ AsyncAWSClient,+ _ComposeState,+ _ComposeStateCache,+)+from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType+from skyvern.forge.sdk.artifact.storage.s3 import S3Storage++MIB = 1024 * 1024+KEY = "v1/prod/org/task/rec.webm"+URI = f"s3://bucket/{KEY}"+GEN = "skyvern-compose-gen"+++def _client_error(code: str, status: int = 400) -> ClientError:+ return ClientError({"Error": {"Code": code}, "ResponseMetadata": {"HTTPStatusCode": status}}, "op")+++class FakeS3:+ def __init__(self) -> None:+ # key -> (bytes, etag, metadata)+ self.objects: dict[str, tuple[bytes, str, dict[str, str]]] = {}+ self.mpus: dict[str, dict[str, Any]] = {}+ self.aborted: list[str] = []+ self.abort_attempts: list[str] = [] # every abort attempt (incl. failed), in order+ self.abort_transient_failures = 0 # first N abort calls raise a transient (non-expired) error, then work+ self.ops: list[str] = [] # ordered op log (cleanup-before-replacement ordering assertions)+ self.completed: list[str] = []+ self._n = 0+ self.fail: dict[str, Exception] = {} # op -> exception to raise once (ClientError OR transport error)+ self.on_complete: Any = None # optional hook(key, uploadid) to simulate ambiguity/foreign writes+ self.on_before_complete: Any = None # hook(key, uploadid) firing AFTER copy, BEFORE the IfMatch check+ self.complete_omit_etag = False # model a successful Complete whose response omits ETag+ self.head_malformed = False # model a HEAD 200 whose body omits ContentLength/ETag++ def _fail(self, op: str) -> None:+ err = self.fail.pop(op, None)+ if err is not None:+ raise err++ async def put_object(self, *, Bucket: str, Key: str, Body: Any, **kw: Any) -> dict[str, Any]:+ self.ops.append("put_object")+ self._fail("put_object")+ data = Body if isinstance(Body, bytes) else Body.read()+ self._n += 1+ etag = f'"put-{self._n}"'+ self.objects[Key] = (data, etag, {})+ return {"ETag": etag}++ async def upload_fileobj(+ self, Fileobj: Any, Bucket: str, Key: str, ExtraArgs: dict | None = None, Config: Any = None+ ) -> None:+ self.ops.append("upload_fileobj")+ self._fail("upload_fileobj")+ chunks = []+ while True:+ c = Fileobj.read(1 << 20)+ if not c:+ break+ chunks.append(c)+ self._n += 1+ meta = dict((ExtraArgs or {}).get("Metadata") or {}) # real S3 preserves user metadata on put/multipart+ self.objects[Key] = (b"".join(chunks), f'"stream-{self._n}"', meta)++ async def create_multipart_upload(+ self, *, Bucket: str, Key: str, Metadata: dict | None = None, **kw: Any+ ) -> dict[str, Any]:+ self.ops.append("create")+ self._fail("create")+ self._n += 1+ uid = f"mpu-{self._n}"+ self.mpus[uid] = {"key": Key, "parts": {}, "meta": dict(Metadata or {})}+ return {"UploadId": uid}++ async def upload_part_copy(+ self,+ *,+ Bucket: str,+ Key: str,+ UploadId: str,+ PartNumber: int,+ CopySource: dict[str, str],+ CopySourceIfMatch: str,+ CopySourceRange: str,+ ) -> dict[str, Any]:+ self.ops.append("copy")+ self._fail("copy")+ src = self.objects.get(CopySource["Key"])+ if src is None:+ raise _client_error("NoSuchKey", 404)+ data, etag, _ = src+ if CopySourceIfMatch.strip('"') != etag.strip('"'):+ raise _client_error("PreconditionFailed", 412)+ a, b = CopySourceRange.split("=", 1)[1].split("-")+ self.mpus[UploadId]["parts"][PartNumber] = data[int(a) : int(b) + 1]+ return {"CopyPartResult": {"ETag": f'"copy-{PartNumber}"'}}++ async def upload_part(self, *, Bucket: str, Key: str, UploadId: str, PartNumber: int, Body: Any) -> dict[str, Any]:+ self.ops.append("uploadpart")+ self._fail("uploadpart")+ body = Body if isinstance(Body, bytes) else Body.read()+ assert len(body) > 0, "final tail part must never be empty"+ self.mpus[UploadId]["parts"][PartNumber] = body+ return {"ETag": f'"part-{PartNumber}"'}++ async def complete_multipart_upload(+ self, *, Bucket: str, Key: str, UploadId: str, MultipartUpload: dict[str, Any], IfMatch: str | None = None+ ) -> dict[str, Any]:+ if self.on_before_complete is not None:+ # A foreign generation lands AFTER our UploadPartCopy but BEFORE Complete.+ self.on_before_complete(Key, UploadId)+ if IfMatch is not None:+ cur = self.objects.get(Key)+ cur_etag = cur[1] if cur is not None else None+ if cur_etag is None or cur_etag.strip('"') != IfMatch.strip('"'):+ # The destination changed under us: the conditional Complete is rejected (never overwrites).+ raise _client_error("PreconditionFailed", 412)+ m = self.mpus[UploadId]+ data = b"".join(+ m["parts"][p["PartNumber"]] for p in sorted(MultipartUpload["Parts"], key=lambda x: x["PartNumber"])+ )+ etag = f'"complete-{UploadId}"'+ self.objects[Key] = (data, etag, dict(m["meta"]))+ self.completed.append(UploadId)+ if self.on_complete is not None:+ self.on_complete(Key, UploadId) # may mutate to simulate ambiguity/foreign writes+ self._fail("complete")+ return {} if self.complete_omit_etag else {"ETag": etag}++ async def abort_multipart_upload(self, *, Bucket: str, Key: str, UploadId: str) -> dict[str, Any]:+ self.ops.append("abort")+ self.abort_attempts.append(UploadId)+ if self.abort_transient_failures > 0:+ self.abort_transient_failures -= 1+ raise _client_error("RequestTimeout", 400) # transient (non-expired) abort failure+ self.aborted.append(UploadId)+ self.mpus.pop(UploadId, None)+ return {}++ async def head_object(self, *, Bucket: str, Key: str) -> dict[str, Any]:+ self._fail("head")+ obj = self.objects.get(Key)+ if obj is None:+ raise _client_error("NotFound", 404)+ data, etag, meta = obj+ if self.head_malformed:+ return {"Metadata": dict(meta)} # a HEAD success that omits ContentLength/ETag+ return {"ETag": etag, "ContentLength": len(data), "Metadata": dict(meta)}+++def _make_client(fake: FakeS3) -> AsyncAWSClient:+ c = AsyncAWSClient()++ @contextlib.asynccontextmanager+ async def _cm() -> Any:+ yield fake++ c._s3_client = _cm # type: ignore[method-assign]+ return c+++def _write(path: str, n: int, fill: bytes = b"\xab") -> None:+ with open(path, "wb") as f:+ f.write(fill * n)+++def tmpfile() -> Any:+ fd, path = tempfile.mkstemp(suffix=".webm")+ os.close(fd)+ yield path+ with contextlib.suppress(FileNotFoundError):+ os.unlink(path)+++async def _seed(fake: FakeS3, n: int, fill: bytes = b"\xab") -> None:+ fake.objects[KEY] = (fill * n, f'"seed-{n}"', {})+++def _seed_base(c: AsyncAWSClient, fake: FakeS3, n: int, fill: bytes = b"\xab") -> None:+ """Seed a process-AUTHORED base: the remote object AND the local compose state that a prior verified+ full replacement would have recorded. Compose only ever runs off such an owned base."""+ etag = f'"seed-{n}"' # S3 etags are quoted on the wire+ fake.objects[KEY] = (fill * n, etag, {GEN: "prior-token"})+ c._compose_state.set(URI, _ComposeState(n, etag.strip('"'))) # _ComposeState holds the stripped etag+++def _obj(fake: FakeS3) -> bytes:+ return fake.objects[KEY][0]+++# --- unsupported / fallback (remote unchanged) -------------------------------------------------+++async def test_initial_step_full_replacement_when_no_object(tmpfile: str) -> None:+ fake = FakeS3()+ c = _make_client(fake)+ _write(tmpfile, 10 * MIB)+ assert await c.store_recording_prefix(URI, tmpfile, 10 * MIB, serialize_key=URI) == URI+ assert _obj(fake) == b"\xab" * (10 * MIB) # full-prefix fallback seeded the object+ assert not fake.mpus and not fake.completed # no compose attempted+++async def test_small_base_falls_back_to_full_replacement(tmpfile: str) -> None:+ fake = FakeS3()+ await _seed(fake, 2 * MIB) # < 5 MiB copy floor+ c = _make_client(fake)+ _write(tmpfile, 4 * MIB)+ await c.store_recording_prefix(URI, tmpfile, 4 * MIB, serialize_key=URI)+ assert _obj(fake) == b"\xab" * (4 * MIB)+ assert not fake.completed+++async def test_over_5gib_base_guard_falls_back_without_mpu(tmpfile: str) -> None:+ fake = FakeS3()+ c = _make_client(fake)+ await _seed(fake, 8 * MIB)+ base_len = _MAX_COMPOSE_PART_BYTES + 1 # confirmed base over the single-copy-part limit+ c._compose_state.set(URI, _ComposeState(base_len, '"e"'))+ _write(tmpfile, 8 * MIB)+ # length MUST exceed base_len (a growing snapshot) so the truncate/no-op guards do NOT fire first and the+ # >5GiB base guard is actually reached. The file itself stays 8 MiB — the guard rejects before any tail+ # read, and the same-slot full replacement then uploads whatever the file holds.+ length = base_len + 2+ await c.store_recording_prefix(URI, tmpfile, length, serialize_key=URI)+ assert not fake.mpus # >5GiB base guard fired before any create_multipart_upload+ assert not fake.completed+ assert _obj(fake) == b"\xab" * (8 * MIB) # full-prefix fallback wrote the file bytes, no server-side copy+++async def test_custom_endpoint_refuses_compose_and_full_replaces(tmpfile: str, monkeypatch: Any) -> None:+ """A customer-supplied S3-compatible endpoint may ignore the AWS-specific IfMatch / CopySourceIfMatch+ fence and silently degrade compose to an unconditional overwrite. Compose must refuse when a custom+ endpoint is configured and fall back to the verified full-prefix replacement — even with an owned base+ that would otherwise compose, and even when the feature flag is enabled."""+ monkeypatch.setattr(settings, "RECORDING_INCREMENTAL_COMPOSE_ENABLED", True)+ fake = FakeS3()+ c = AsyncAWSClient(endpoint_url="https://minio.example.internal")++ @contextlib.asynccontextmanager+ async def _cm() -> Any:+ yield fake++ c._s3_client = _cm # type: ignore[method-assign]+ _seed_base(c, fake, 8 * MIB) # an owned base that WOULD compose against real AWS S3+ _write(tmpfile, 11 * MIB)+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert not fake.mpus and not fake.completed # no create_multipart_upload / upload_part_copy+ assert _obj(fake) == b"\xab" * (11 * MIB) # full-prefix replacement wrote the file bytes+++# --- successful compose ------------------------------------------------------------------------+++async def test_compose_success_copy_tail_complete(tmpfile: str) -> None:+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert _obj(fake) == b"\xab" * (11 * MIB)+ assert fake.completed and not fake.aborted+ assert c._compose_state.get(URI).length == 11 * MIB+++async def test_compose_chains_and_uses_cached_state(tmpfile: str) -> None:+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ fake.fail["head"] = _client_error("ServiceUnavailable", 503) # cached state means no head needed+ _write(tmpfile, 13 * MIB)+ await c.store_recording_prefix(URI, tmpfile, 13 * MIB, serialize_key=URI)+ assert len(_obj(fake)) == 13 * MIB+++# --- conflict preservation (blocker 2) ---------------------------------------------------------+++async def test_stale_etag_conflict_preserves_remote(tmpfile: str) -> None:+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ # A foreign writer replaces the object with a NEWER, longer generation.+ foreign = b"\x01" * (20 * MIB)+ fake.objects[KEY] = (foreign, '"foreign"', {})+ _write(tmpfile, 13 * MIB)+ await c.store_recording_prefix(URI, tmpfile, 13 * MIB, serialize_key=URI)+ # 412 on copy => conflict => remote preserved, NOT overwritten with our 13 MiB prefix.+ assert _obj(fake) == foreign+ assert fake.aborted # our MPU aborted+ assert URI not in c._compose_state # base reseeds next step+++# --- review 3920309801: fence Complete against a destination change after copy -----------------+++async def test_foreign_generation_after_copy_before_complete_is_fenced_out(tmpfile: str) -> None:+ """A foreign producer can replace the destination AFTER our UploadPartCopy but BEFORE our Complete.+ The Complete is fenced with IfMatch on the verified base ETag, so it is rejected (412) instead of+ unconditionally overwriting the newer generation: preserve the foreign bytes, abort our MPU, clear+ state, never full-replace."""+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)+ foreign = b"\x0a" * (14 * MIB)++ def foreign_lands_before_complete(key: str, uid: str) -> None:+ fake.objects[key] = (foreign, '"foreign-newgen"', {GEN: "not-our-token"})++ fake.on_before_complete = foreign_lands_before_complete+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert _obj(fake) == foreign # newer foreign generation preserved, NOT clobbered by our Complete+ assert fake.aborted and not fake.completed # our MPU aborted; our Complete never wrote+ assert URI not in c._compose_state # conflict path cleared local state+++async def test_fenced_complete_succeeds_when_destination_unchanged(tmpfile: str) -> None:+ """Normal fenced Complete: the destination still holds the verified base at Complete time, so the+ IfMatch fence passes and the compose lands."""+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert _obj(fake) == b"\xab" * (11 * MIB) # compose landed under the fence+ assert fake.completed and not fake.aborted+ assert c._compose_state.get(URI).length == 11 * MIB+++# --- ambiguous complete (blocker 3) ------------------------------------------------------------+++async def test_ambiguous_complete_reconciled_by_token(tmpfile: str) -> None:+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)+ # Complete writes the object (with our token) then the response is "lost".+ fake.fail["complete"] = _client_error("RequestTimeout", 400)+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert len(_obj(fake)) == 11 * MIB+ assert not fake.aborted # reconciled as durable via length + token; never abort a completed object+++async def test_ambiguous_complete_same_length_foreign_gen_not_accepted(tmpfile: str) -> None:+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)++ def foreign_same_length(key: str, uid: str) -> None:+ # Simulate a DIFFERENT generation of the SAME length (foreign token) landing at the key.+ fake.objects[key] = (b"\x09" * (11 * MIB), '"foreign-same-len"', {GEN: "not-our-token"})++ fake.on_complete = foreign_same_length+ fake.fail["complete"] = _client_error("RequestTimeout", 400)+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ # Same length but foreign token => conflict => preserve foreign bytes, do NOT overwrite.+ assert _obj(fake) == b"\x09" * (11 * MIB)+ assert fake.aborted+ assert URI not in c._compose_state+++async def test_ambiguous_complete_old_base_intact_falls_back(tmpfile: str) -> None:+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)++ def revert_to_old_base(key: str, uid: str) -> None:+ fake.objects[key] = (b"\xab" * (8 * MIB), '"seed-8388608"', {}) # complete "didn't land"++ fake.on_complete = revert_to_old_base+ fake.fail["complete"] = _client_error("RequestTimeout", 400)+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ # Old base intact => unsupported => safe full replacement to our 11 MiB prefix.+ assert _obj(fake) == b"\xab" * (11 * MIB)+ assert fake.aborted+++# --- review 3917237493: unreadable HEAD after ambiguous complete must PRESERVE, never clobber ---+++async def test_ambiguous_complete_head_transport_failure_preserves_remote(tmpfile: str) -> None:+ """A NON-ClientError HEAD failure (endpoint/read timeout) during ambiguous-complete reconciliation must+ resolve to conflict and preserve the remote — never fall through to an unconditional full replacement+ that could clobber a foreign generation written during the same network blip."""+ from botocore.exceptions import EndpointConnectionError++ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)++ def foreign_lands(key: str, uid: str) -> None:+ fake.objects[key] = (b"\x07" * (11 * MIB), '"foreign"', {GEN: "not-our-token"})++ fake.on_complete = foreign_lands+ fake.fail["complete"] = _client_error("RequestTimeout", 400) # ambiguous complete+ fake.fail["head"] = EndpointConnectionError(endpoint_url="https://s3") # transport failure, NOT a ClientError+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert _obj(fake) == b"\x07" * (11 * MIB) # foreign generation preserved, NOT overwritten with our prefix+ assert fake.aborted # our MPU aborted+ assert URI not in c._compose_state # base reseeds next step+++async def test_reconcile_complete_reraises_expired_token_for_retry() -> None:+ """An expired token on the reconciliation HEAD is recoverable, NOT a conflict: it must be re-raised so+ _s3_with_retry refreshes the session and retries the transaction, rather than being swallowed as+ "conflict" (which would skip the step on a recoverable expiry)."""+ from skyvern.forge.sdk.api.aws import S3Uri++ fake = FakeS3()+ c = _make_client(fake)+ fake.objects[KEY] = (b"\xab" * (8 * MIB), '"seed-8"', {GEN: "prior"})+ base = _ComposeState(8 * MIB, "seed-8")+ fake.fail["head"] = _client_error("ExpiredTokenException", 400)+ with pytest.raises(ClientError) as ei:+ await c._reconcile_complete(fake, S3Uri(URI), 11 * MIB, base, "token")+ assert ei.value.response["Error"]["Code"] == "ExpiredTokenException"+++async def test_ambiguous_complete_malformed_head_preserves_remote(tmpfile: str) -> None:+ """A HEAD that returns 200 but omits ContentLength/ETag is just as unreadable as a failed HEAD: the parse+ must not escape reconciliation and trigger a clobbering full replacement. Resolve to conflict, preserve."""+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)++ def foreign_lands(key: str, uid: str) -> None:+ fake.objects[key] = (b"\x06" * (11 * MIB), '"foreign"', {GEN: "not-our-token"})++ fake.on_complete = foreign_lands+ fake.fail["complete"] = _client_error("RequestTimeout", 400)+ fake.head_malformed = True # HEAD 200 without ContentLength/ETag+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert _obj(fake) == b"\x06" * (11 * MIB) # preserved, not clobbered by a full replacement+ assert fake.aborted+ assert URI not in c._compose_state+++async def test_full_replace_malformed_head_pops_stale_compose_state(tmpfile: str) -> None:+ """A malformed HEAD (200 without ContentLength/ETag) after the full-replacement PUT must guard its read+ and pop the previous compose state rather than raise; a raise would strand the stale base cached and cost+ a snapshot self-healing as a 412 next step."""+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 2 * MIB) # base below the 5-MiB copy floor -> ComposeUnsupportedError -> full replace+ _write(tmpfile, 4 * MIB)+ fake.head_malformed = True # the seed-and-verify HEAD omits ContentLength/ETag+ assert await c.store_recording_prefix(URI, tmpfile, 4 * MIB, serialize_key=URI) == URI+ assert URI not in c._compose_state # stale base popped, not left cached+ assert _obj(fake) == b"\xab" * (4 * MIB) # replacement still wrote the file+ assert not fake.mpus and not fake.completed # full-replace path, no compose MPU+++# --- review 3917237500: Complete without ETag must validate length + token before caching -------+++async def test_complete_without_etag_foreign_gen_not_cached(tmpfile: str) -> None:+ """A successful Complete whose response omits ETag must reconcile by HEAD and validate our exact+ length + generation token; a foreign same-length generation that raced in must NOT be cached (else the+ next snapshot's conditional copy splices the foreign prefix with our tail)."""+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)+ fake.complete_omit_etag = True++ def foreign_same_len(key: str, uid: str) -> None:+ fake.objects[key] = (b"\x05" * (11 * MIB), '"foreign-noetag"', {GEN: "not-our-token"})++ fake.on_complete = foreign_same_len+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert URI not in c._compose_state # foreign generation NOT cached as our base+ assert _obj(fake) == b"\x05" * (11 * MIB) # foreign preserved, not clobbered+++async def test_complete_without_etag_own_gen_cached(tmpfile: str) -> None:+ """Regression guard: a successful Complete omitting ETag, with OUR generation at the key, still caches+ the base (validated by exact length + token) so the compose chain continues."""+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)+ fake.complete_omit_etag = True+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert len(_obj(fake)) == 11 * MIB+ assert c._compose_state.get(URI) is not None and c._compose_state.get(URI).length == 11 * MIB+++# --- pre-complete failure aborts + preserves old object (remote unchanged => fallback) ----------++[email protected]("failop", ["create", "copy", "uploadpart"])+async def test_precomplete_failure_aborts_then_full_replacement(tmpfile: str, failop: str) -> None:+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)+ fake.fail[failop] = _client_error("InternalError", 500)+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ # Remote was unchanged by the failed compose, so the same-slot full replacement lands our prefix.+ assert _obj(fake) == b"\xab" * (11 * MIB)+ if failop != "create":+ assert fake.aborted+++# --- single-slot ordering (blocker 1) ----------------------------------------------------------+++async def test_failed_compose_fallback_and_next_step_stay_ordered() -> None:+ """Step A's compose fails and must complete its full-prefix fallback before step B (queued) writes."""+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ order: list[str] = []+ gate = asyncio.Event()+ orig_fileobj = fake.upload_fileobj++ async def gated_fileobj(+ Fileobj: Any, Bucket: str, Key: str, ExtraArgs: dict | None = None, Config: Any = None+ ) -> None:+ await gate.wait() # hold A inside its fallback+ await orig_fileobj(Fileobj, Bucket, Key, ExtraArgs, Config)+ order.append("A_fallback")++ fake.upload_fileobj = gated_fileobj # type: ignore[method-assign]+ fake.fail["copy"] = _client_error("InternalError", 500) # force A to fall back++ fa = tempfile.mkstemp(suffix=".webm")[1]+ fb = tempfile.mkstemp(suffix=".webm")[1]+ _write(fa, 11 * MIB)+ _write(fb, 13 * MIB)+ try:+ a = asyncio.create_task(c.store_recording_prefix(URI, fa, 11 * MIB, serialize_key=URI))+ await asyncio.sleep(0.05) # let A reserve its slot and enter the gated fallback+ orig_complete = fake.complete_multipart_upload++ async def b_complete(**kw: Any) -> dict[str, Any]:+ order.append("B_complete")+ return await orig_complete(**kw)++ fake.complete_multipart_upload = b_complete # type: ignore[method-assign]+ b = asyncio.create_task(c.store_recording_prefix(URI, fb, 13 * MIB, serialize_key=URI))+ await asyncio.sleep(0.05)+ assert "B_complete" not in order # B must not overtake A's unfinished fallback+ gate.set()+ await asyncio.gather(a, b)+ assert order == ["A_fallback", "B_complete"] # strict ordering held across compose+fallback+ assert len(_obj(fake)) == 13 * MIB+ finally:+ for f in (fa, fb):+ with contextlib.suppress(FileNotFoundError):+ os.unlink(f)+++# --- fd ownership before detach (blocker 4) ----------------------------------------------------+++async def test_fd_owned_before_detach_survives_unlink(tmpfile: str) -> None:+ fake = FakeS3()+ await _seed(fake, 8 * MIB)+ c = _make_client(fake)+ _write(tmpfile, 11 * MIB)+ # Block the step at its queued wait, unlink the path, then release: the pre-opened fd must survive.+ _prev, prev_done = c._begin_serialized_write(URI)+ task = asyncio.create_task(c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI))+ await asyncio.sleep(0.05)+ os.unlink(tmpfile) # caller removes the file after the transfer was queued+ prev_done.set_result(None)+ assert await task == URI+ assert len(_obj(fake)) == 11 * MIB # tail read from the owned fd despite the unlink+++# --- storage gating / feature-off exact Phase 1 ------------------------------------------------+++def _recording_artifact(uri: str, atype: ArtifactType = ArtifactType.RECORDING) -> Artifact:+ return Artifact(+ artifact_id="art_1",+ artifact_type=atype,+ uri=uri,+ bundle_key=None,+ organization_id="o_1",+ created_at=datetime.now(UTC),+ modified_at=datetime.now(UTC),+ )+++def _mock_storage() -> S3Storage:+ s = S3Storage()+ s.async_client = AsyncMock()+ s.async_client.forget_compose_state = MagicMock()+ return s+++async def test_storage_gating_off_uses_exact_phase1_stream(tmpfile: str, monkeypatch: Any) -> None:+ monkeypatch.setattr(settings, "RECORDING_INCREMENTAL_COMPOSE_ENABLED", False)+ s = _mock_storage()+ _write(tmpfile, 10 * MIB)+ await s.store_artifact_prefix_from_path(_recording_artifact(URI), tmpfile, 10 * MIB)+ s.async_client.store_recording_prefix.assert_not_called()+ s.async_client.upload_file_stream.assert_awaited_once()+++async def test_storage_gating_on_recording_uses_compose_path(tmpfile: str, monkeypatch: Any) -> None:+ monkeypatch.setattr(settings, "RECORDING_INCREMENTAL_COMPOSE_ENABLED", True)+ s = _mock_storage()+ _write(tmpfile, 10 * MIB)+ await s.store_artifact_prefix_from_path(_recording_artifact(URI), tmpfile, 10 * MIB)+ s.async_client.store_recording_prefix.assert_awaited_once()+ s.async_client.upload_file_stream.assert_not_called()+++async def test_storage_non_recording_uses_phase1_even_when_enabled(tmpfile: str, monkeypatch: Any) -> None:+ monkeypatch.setattr(settings, "RECORDING_INCREMENTAL_COMPOSE_ENABLED", True)+ s = _mock_storage()+ _write(tmpfile, 10 * MIB)+ await s.store_artifact_prefix_from_path(_recording_artifact(URI, ArtifactType.SKYVERN_LOG), tmpfile, 10 * MIB)+ s.async_client.store_recording_prefix.assert_not_called()+ s.async_client.upload_file_stream.assert_awaited_once()+++async def test_terminal_forgets_compose_state(monkeypatch: Any) -> None:+ monkeypatch.setattr(settings, "RECORDING_INCREMENTAL_COMPOSE_ENABLED", True)+ s = _mock_storage()+ art = _recording_artifact(URI)+ await s.store_artifact(art, b"final-bytes", supersede_queued_prefixes=True)+ s.async_client.forget_compose_state.assert_called_once_with(art.uri)+ s.async_client.upload_file.assert_awaited_once()+++# --- never regress/truncate a newer remote generation (addendum 1) -----------------------------+++async def test_larger_remote_generation_preserved_not_truncated(tmpfile: str) -> None:+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 20 * MIB) # process-authored base LONGER than this step's snapshot+ _write(tmpfile, 13 * MIB)+ await c.store_recording_prefix(URI, tmpfile, 13 * MIB, serialize_key=URI)+ assert len(_obj(fake)) == 20 * MIB # preserved; never overwritten with the shorter 13 MiB prefix+ assert not fake.completed # no compose, and crucially no full-PUT truncation+ assert URI not in c._compose_state+++async def test_same_length_remote_is_noop(tmpfile: str) -> None:+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 8 * MIB)+ before = _obj(fake)+ await c.store_recording_prefix(URI, tmpfile, 8 * MIB, serialize_key=URI)+ assert _obj(fake) == before # no-op: no MPU, no full-PUT+ assert not fake.completed and not fake.mpus+++# --- newest pre-terminal fallback contract (addendum 2) ----------------------------------------+++async def _park_newest(c: AsyncAWSClient, fake: FakeS3, path: str, length: int) -> asyncio.Task:+ """Reserve a queued prefix, seal a terminal behind it so the queued prefix is the fallback target,+ and drive the queued prefix so it parks. Returns the terminal task (already reserved, awaiting)."""+ blk_prev, blk_done = c._begin_serialized_write(URI) # blocker so the queued prefix waits+ q = asyncio.create_task(c.store_recording_prefix(URI, path, length, serialize_key=URI))+ await asyncio.sleep(0.03) # queued prefix reserves its slot, then awaits blk_done+ return blk_done, q+++async def test_superseded_newest_parks_and_terminal_failure_uploads_it(tmpfile: str) -> None:+ fake = FakeS3()+ await _seed(fake, 8 * MIB)+ c = _make_client(fake)+ _write(tmpfile, 11 * MIB)+ blk_done, q = await _park_newest(c, fake, tmpfile, 11 * MIB)+ fake.fail["put_object"] = _client_error("InternalError", 500) # terminal finalize fails -> use fallback+ t = asyncio.create_task(c.upload_file(URI, b"terminal-final", serialize_key=URI, supersede_queued=True))+ await asyncio.sleep(0.03) # terminal reserves the seal (its prev = the queued prefix's done)+ blk_done.set_result(None) # release: queued prefix parks; terminal runs, put fails, uploads fallback+ await asyncio.gather(q, t)+ assert _obj(fake) == b"\xab" * (11 * MIB) # newest pre-terminal snapshot uploaded on terminal failure+ assert URI not in c._object_write_fallback # consumed + cleaned up+++async def test_superseded_newest_parked_then_terminal_success_discards_it(tmpfile: str) -> None:+ fake = FakeS3()+ await _seed(fake, 8 * MIB)+ c = _make_client(fake)+ _write(tmpfile, 11 * MIB)+ blk_done, q = await _park_newest(c, fake, tmpfile, 11 * MIB)+ t = asyncio.create_task(c.upload_file(URI, b"terminal-final", serialize_key=URI, supersede_queued=True))+ await asyncio.sleep(0.03)+ blk_done.set_result(None) # queued prefix parks; terminal put succeeds -> fallback discarded, not uploaded+ await asyncio.gather(q, t)+ assert _obj(fake) == b"terminal-final" # terminal full replacement wins+ assert URI not in c._object_write_fallback+++async def test_superseded_older_prefix_skips_without_parking(tmpfile: str) -> None:+ fake = FakeS3()+ await _seed(fake, 8 * MIB)+ c = _make_client(fake)+ _write(tmpfile, 11 * MIB)+ # Seal the key with a DIFFERENT (sentinel) fallback target so this queued prefix is NOT the newest.+ sentinel: asyncio.Future = asyncio.get_running_loop().create_future()+ c._object_write_sealed.add(URI)+ c._object_write_fallback_target[URI] = sentinel+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert URI not in c._object_write_fallback # older superseded prefix skips, does not park+ assert not fake.completed+++# --- MUST_FIX 1: a GC'd abandoned reader must NOT close the fd the same-slot fallback still reads ------+++async def test_gc_during_fallback_does_not_close_shared_fd(tmpfile: str) -> None:+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)+ # Compose creates a tail reader over the shared fd, then fails; the compose falls back to a full+ # replacement in the same slot. A gc.collect() before the fallback reads would, if any reader owned the+ # shared fd, run its __del__ -> close() and the fallback would die with "read of closed file".+ fake.fail["uploadpart"] = _client_error("InternalError", 500)+ orig_fileobj = fake.upload_fileobj++ async def gc_then_upload(+ Fileobj: Any, Bucket: str, Key: str, ExtraArgs: dict | None = None, Config: Any = None+ ) -> None:+ gc.collect()+ await orig_fileobj(Fileobj, Bucket, Key, ExtraArgs, Config)++ fake.upload_fileobj = gc_then_upload # type: ignore[method-assign]+ assert await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI) == URI+ assert _obj(fake) == b"\xab" * (11 * MIB) # fallback read the shared fd successfully after GC+++# --- MUST_FIX 2: expired-token refresh+retry parity for compose AND the inline full-replace -----------+++async def test_compose_refreshes_and_retries_on_expired_token(tmpfile: str) -> None:+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)+ refreshed: list[bool] = []+ c.refresh_session = lambda: refreshed.append(True) # type: ignore[method-assign]+ fake.fail["copy"] = _client_error("ExpiredTokenException", 400) # first copy expires; popped -> retry ok+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert refreshed # session was refreshed instead of silently degrading+ assert len(_obj(fake)) == 11 * MIB and fake.completed # compose landed on the retry+ assert c._compose_state.get(URI).length == 11 * MIB+++async def test_full_replace_refreshes_and_retries_on_expired_token(tmpfile: str) -> None:+ fake = FakeS3()+ c = _make_client(fake) # no owned base -> full-replace path+ _write(tmpfile, 10 * MIB)+ refreshed: list[bool] = []+ c.refresh_session = lambda: refreshed.append(True) # type: ignore[method-assign]+ fake.fail["upload_fileobj"] = _client_error("ExpiredTokenException", 400)+ await c.store_recording_prefix(URI, tmpfile, 10 * MIB, serialize_key=URI)+ assert refreshed+ assert _obj(fake) == b"\xab" * (10 * MIB)+ assert c._compose_state.get(URI) is not None # verified generation seeded after the retry+++# --- Aron review finding 2: expired-token orphan MPU must be aborted on the REFRESHED client ----+++class _GenBackend:+ """Shared S3 state across client 'generations'. Generation 1 is a stale/expired client: its complete+ AND abort both raise ExpiredTokenException (one expired session token invalidates the whole client, so+ aborting the orphaned MPU on that same client is futile). Generation 2 (post-refresh) works. Records+ which upload ids were aborted by which generation so a test can assert the refreshed client aborts the+ exact orphan before creating a replacement MPU."""++ def __init__(self) -> None:+ self.objects: dict[str, tuple[bytes, str, dict[str, str]]] = {}+ self.mpus: dict[str, dict[str, Any]] = {}+ self.completed: list[str] = []+ self.completed_ids: set[str] = set() # upload ids whose Complete actually landed+ self.aborted_by_gen: dict[int, list[str]] = {} # successful aborts, per generation+ self.abort_attempts_by_gen: dict[int, list[str]] = {} # every abort attempt (incl. failed), per gen+ self.fail_abort_gens: set[int] = set() # generations whose abort raises (e.g. a transient failure)+ self.expired_code = "ExpiredTokenException" # exact S3 error code to raise (S3 also uses "ExpiredToken")+ self.complete_fail_gens: set[int] = {1} # generations whose Complete raises expired-token (orphan MPU)+ self.complete_omit_etag = False # Complete succeeds but omits ETag+ self.head_expired_gens: set[int] = set() # generations whose head_object raises expired-token+ self.nosuchupload_on_completed_abort = True # abort of an already-completed id raises NoSuchUpload+ self._n = 0+ self.gen = 0++ def next_client(self) -> _GenClient:+ self.gen += 1+ return _GenClient(self, self.gen)+++class _GenClient:+ def __init__(self, be: _GenBackend, gen: int) -> None:+ self.be = be+ self.gen = gen++ async def create_multipart_upload(self, *, Bucket: str, Key: str, Metadata: dict | None = None, **kw: Any) -> Any:+ self.be._n += 1+ uid = f"mpu-{self.be._n}"+ self.be.mpus[uid] = {"key": Key, "parts": {}, "meta": dict(Metadata or {})}+ return {"UploadId": uid}++ async def upload_part_copy(+ self,+ *,+ Bucket: str,+ Key: str,+ UploadId: str,+ PartNumber: int,+ CopySource: dict,+ CopySourceIfMatch: str,+ CopySourceRange: str,+ ) -> Any:+ data, etag, _ = self.be.objects[CopySource["Key"]]+ if CopySourceIfMatch.strip('"') != etag.strip('"'):+ raise _client_error("PreconditionFailed", 412)+ a, b = CopySourceRange.split("=", 1)[1].split("-")+ self.be.mpus[UploadId]["parts"][PartNumber] = data[int(a) : int(b) + 1]+ return {"CopyPartResult": {"ETag": f'"copy-{PartNumber}"'}}++ async def upload_part(self, *, Bucket: str, Key: str, UploadId: str, PartNumber: int, Body: Any) -> Any:+ body = Body if isinstance(Body, bytes) else Body.read()+ self.be.mpus[UploadId]["parts"][PartNumber] = body+ return {"ETag": f'"part-{PartNumber}"'}++ async def complete_multipart_upload(+ self, *, Bucket: str, Key: str, UploadId: str, MultipartUpload: dict, IfMatch: str | None = None+ ) -> Any:+ if self.gen in self.be.complete_fail_gens:+ raise _client_error(self.be.expired_code, 400) # token expires at complete -> MPU orphaned+ if IfMatch is not None:+ cur = self.be.objects.get(Key)+ if cur is None or cur[1].strip('"') != IfMatch.strip('"'):+ raise _client_error("PreconditionFailed", 412)+ m = self.be.mpus[UploadId]+ data = b"".join(+ m["parts"][p["PartNumber"]] for p in sorted(MultipartUpload["Parts"], key=lambda x: x["PartNumber"])+ )+ etag = f'"complete-{UploadId}"'+ self.be.objects[Key] = (data, etag, dict(m["meta"]))+ self.be.completed.append(UploadId)+ self.be.completed_ids.add(UploadId)+ return {} if self.be.complete_omit_etag else {"ETag": etag}++ async def abort_multipart_upload(self, *, Bucket: str, Key: str, UploadId: str) -> Any:+ self.be.abort_attempts_by_gen.setdefault(self.gen, []).append(UploadId) # record EVERY attempt+ if UploadId in self.be.completed_ids and self.be.nosuchupload_on_completed_abort:+ # An already-completed upload can no longer be aborted: real S3 returns NoSuchUpload.+ raise _client_error("NoSuchUpload", 404)+ if self.gen in self.be.complete_fail_gens or self.gen in self.be.fail_abort_gens:+ raise _client_error(self.be.expired_code, 400) # stale client or injected transient abort failure+ self.be.aborted_by_gen.setdefault(self.gen, []).append(UploadId)+ self.be.mpus.pop(UploadId, None)+ return {}++ async def head_object(self, *, Bucket: str, Key: str) -> Any:+ if self.gen in self.be.head_expired_gens:+ raise _client_error(self.be.expired_code, 400)+ obj = self.be.objects.get(Key)+ if obj is None:+ raise _client_error("NotFound", 404)+ data, etag, meta = obj+ return {"ETag": etag, "ContentLength": len(data), "Metadata": dict(meta)}+++def _make_client_gen(be: _GenBackend) -> AsyncAWSClient:+ c = AsyncAWSClient()++ @contextlib.asynccontextmanager+ async def _cm() -> Any:+ yield be.next_client()++ c._s3_client = _cm # type: ignore[method-assign]+ return c+++# S3 reports an expired STS/web-identity token under EITHER exact code; both must drive the same refresh+retry+# path (the compose retry, not just the helper). "ExpiredToken" is the bare S3 code the review flagged.[email protected]("expired_code", ["ExpiredTokenException", "ExpiredToken"])+async def test_expired_token_orphan_mpu_aborted_on_refreshed_client(tmpfile: str, expired_code: str) -> None:+ be = _GenBackend()+ be.expired_code = expired_code+ be.objects[KEY] = (b"\xab" * (8 * MIB), '"seed-8"', {GEN: "prior"}) # process-owned base+ c = _make_client_gen(be)+ c._compose_state.set(URI, _ComposeState(8 * MIB, "seed-8"))+ c.refresh_session = lambda: None # type: ignore[method-assign] # no real STS session in the test+ _write(tmpfile, 11 * MIB)+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ # gen1 created mpu-1, then expired at complete; aborting mpu-1 on that stale gen1 client also failed.+ # The refreshed gen2 client MUST abort the exact orphaned mpu-1 before completing the replacement mpu-2.+ assert be.aborted_by_gen.get(2) == ["mpu-1"] # refreshed client aborted the exact old upload id+ assert 1 not in be.aborted_by_gen # the stale client did NOT successfully abort it+ assert be.completed == ["mpu-2"] # the replacement compose completed on the retry+ assert "mpu-1" not in be.mpus # the orphan MPU is gone (no lingering incomplete upload)+ assert len(be.objects[KEY][0]) == 11 * MIB # composed recording landed+ assert c._compose_state.get(URI).length == 11 * MIB+++async def test_expired_token_orphan_abort_failure_fails_closed_no_replacement(tmpfile: str) -> None:+ """If the REFRESHED client's abort of the carried orphan ALSO fails, fail closed: do NOT create a+ replacement compose MPU on top of an un-aborted orphan. Preserve the existing remote object, drop stale+ compose state (so the next step authors a fresh verified generation), and skip — the bucket+ AbortIncompleteMultipartUpload lifecycle rule is the documented backstop for the leaked MPU."""+ be = _GenBackend()+ base_bytes = b"\xab" * (8 * MIB)+ be.objects[KEY] = (base_bytes, '"seed-8"', {GEN: "prior"})+ be.fail_abort_gens = {2} # the refreshed (gen2) client's abort of the orphan ALSO fails+ c = _make_client_gen(be)+ c._compose_state.set(URI, _ComposeState(8 * MIB, "seed-8"))+ c.refresh_session = lambda: None # type: ignore[method-assign]+ _write(tmpfile, 11 * MIB)+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert be.abort_attempts_by_gen.get(2) == ["mpu-1"] # the orphan abort WAS attempted on the refreshed client+ assert be.aborted_by_gen.get(2) is None # ...and it failed+ assert "mpu-2" not in be.mpus and be.completed == [] # fail-closed: NO replacement MPU created/completed+ assert be.objects[KEY][0] == base_bytes # existing remote object preserved, not overwritten+ assert URI not in c._compose_state # stale compose state dropped -> next step authors a fresh generation+++async def test_abort_compose_treats_nosuchupload_as_success() -> None:+ """A NoSuchUpload from abort means the upload no longer exists (e.g. an ambiguous Complete actually+ landed) — that IS the cleanup goal, so _abort_compose reports success (True), not an unabortable orphan.+ A genuine failure (AccessDenied) or any other error still reports False so it is not masked."""+ from skyvern.forge.sdk.api.aws import S3Uri++ c = _make_client(FakeS3())+ u = S3Uri(URI)++ async def _abort_raises(code: str) -> bool:+ client = MagicMock()+ client.abort_multipart_upload = AsyncMock(+ side_effect=_client_error(code, 404 if code == "NoSuchUpload" else 403)+ )+ return await c._abort_compose(client, u, "mpu-x")++ assert await _abort_raises("NoSuchUpload") is True # already gone -> cleanup success+ assert await _abort_raises("AccessDenied") is False # genuine failure not masked+ assert await _abort_raises("InternalError") is False # any other error still reported as failure+++async def test_generic_failure_inline_abort_transient_then_fresh_cleanup_before_full_replace(tmpfile: str) -> None:+ """A non-expired pre-Complete failure leaves the remote unchanged (safe to full-replace), but the inline+ abort of our MPU fails transiently. The transaction MUST clean up on a freshly-created client BEFORE the+ full replacement — so no incomplete MPU leaks — and then land exactly one safe replacement, in that order+ (cleanup precedes replacement)."""+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)+ fake.fail["uploadpart"] = _client_error("InternalError", 500) # non-expired pre-Complete failure+ fake.abort_transient_failures = 1 # inline abort fails once; the fresh-client abort then succeeds+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert fake.abort_attempts == ["mpu-1", "mpu-1"] # inline attempt, then the fresh-client retry (same id)+ assert fake.aborted == ["mpu-1"] and "mpu-1" not in fake.mpus # orphan cleaned up on the fresh client+ assert not fake.completed # no compose Complete+ assert _obj(fake) == b"\xab" * (11 * MIB) # the safe full replacement landed our prefix+ assert fake.ops.count("upload_fileobj") == 1 # exactly one replacement, no duplicate PUT+ last_abort = max(i for i, o in enumerate(fake.ops) if o == "abort")+ assert fake.ops.index("upload_fileobj") > last_abort # cleanup precedes the replacement+ assert c._compose_state.get(URI) is not None and c._compose_state.get(URI).length == 11 * MIB+++async def test_fresh_cleanup_refreshes_session_before_building_client(tmpfile: str) -> None:+ """The fresh-client cleanup may be reached because the token expired between the primary op and the inline+ abort. _s3_client reuses the cached session (recreated only on the 45-min TTL), so the cleanup must refresh+ the session BEFORE constructing the fresh client — otherwise it carries the same expired credentials and+ fails identically, and since this path returns normally _s3_with_retry never sees the token error."""+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)+ fake.fail["uploadpart"] = _client_error("InternalError", 500) # non-expired pre-Complete failure+ fake.abort_transient_failures = 1 # inline abort fails once -> the fresh-client cleanup path is taken+ calls: list[str] = []+ real_refresh = c.refresh_session++ def _spy() -> None:+ calls.append("refresh")+ real_refresh()++ c.refresh_session = _spy # type: ignore[method-assign]+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert calls == ["refresh"] # session refreshed once, on the fresh-cleanup path+ assert fake.aborted == ["mpu-1"] # cleanup then succeeded on the refreshed fresh client+++async def test_conflict_inline_abort_transient_then_fresh_cleanup_preserves_remote(tmpfile: str) -> None:+ """A copy 412 conflict against a moved remote, where the inline abort fails transiently: the MPU must be+ cleaned up on a fresh client, the remote generation preserved (never overwritten), and NO replacement+ written."""+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)+ foreign = b"\x01" * (20 * MIB)+ fake.objects[KEY] = (foreign, '"foreign"', {}) # base moved under us -> copy 412 conflict+ fake.abort_transient_failures = 1 # inline abort fails; fresh-client abort succeeds+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert fake.abort_attempts == ["mpu-1", "mpu-1"] # inline attempt + fresh-client retry+ assert fake.aborted == ["mpu-1"] and "mpu-1" not in fake.mpus # orphan cleaned up on the fresh client+ assert _obj(fake) == foreign # remote preserved, never overwritten+ assert not fake.completed and fake.ops.count("upload_fileobj") == 0 # conflict path never full-replaces+ assert URI not in c._compose_state # stale compose state cleared+++async def test_fenced_complete_conflict_inline_abort_transient_then_fresh_cleanup_preserves_remote(+ tmpfile: str,+) -> None:+ """A foreign generation lands AFTER our copy but BEFORE our fenced Complete (IfMatch 412), and the inline+ abort of our MPU then fails transiently. The fenced-Complete conflict site must converge exactly like the+ copy conflict site: clean up the MPU on a fresh client, preserve the foreign remote, and write NO+ replacement."""+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ _write(tmpfile, 11 * MIB)+ foreign = b"\x0a" * (14 * MIB)++ def foreign_lands_before_complete(key: str, uid: str) -> None:+ fake.objects[key] = (foreign, '"foreign-newgen"', {GEN: "not-our-token"})++ fake.on_before_complete = foreign_lands_before_complete+ fake.abort_transient_failures = 1 # inline abort fails; the fresh-client abort then succeeds+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert fake.abort_attempts == ["mpu-1", "mpu-1"] # inline attempt + fresh-client retry (same id)+ assert fake.aborted == ["mpu-1"] and "mpu-1" not in fake.mpus # orphan cleaned up on the fresh client+ assert _obj(fake) == foreign # newer foreign generation preserved, never overwritten by a Complete/replace+ assert not fake.completed and fake.ops.count("upload_fileobj") == 0 # fenced-conflict path never full-replaces+ assert URI not in c._compose_state # stale compose state cleared+++async def test_generic_failure_fresh_cleanup_also_fails_fails_closed_no_replacement(tmpfile: str) -> None:+ """If the inline abort AND the fresh-client abort both fail, fail closed: preserve the remote, clear stale+ compose state, and create NO replacement MPU / full PUT on top of the un-aborted orphan. The bucket+ AbortIncompleteMultipartUpload lifecycle rule is the only remaining backstop for the leaked MPU."""+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ base = _obj(fake)+ _write(tmpfile, 11 * MIB)+ fake.fail["uploadpart"] = _client_error("InternalError", 500) # non-expired pre-Complete failure+ fake.abort_transient_failures = 99 # both the inline AND the fresh-client abort fail+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert fake.abort_attempts == ["mpu-1", "mpu-1"] # tried inline, then a fresh client+ assert fake.aborted == [] and "mpu-1" in fake.mpus # neither succeeded -> orphan remains (lifecycle backstop)+ assert _obj(fake) == base # remote preserved: NO full replacement over the un-aborted orphan+ assert not fake.completed and fake.ops.count("upload_fileobj") == 0 # no replacement / new PUT authored+ assert URI not in c._compose_state # stale compose state cleared; next step authors a fresh generation+++async def test_completed_no_etag_then_expired_reconcile_then_nosuchupload_abort_is_safe(tmpfile: str) -> None:+ """Full interleaving: Complete succeeds but omits ETag; the reconciliation HEAD then returns an expired+ token, so the transaction refreshes and retries; the refreshed abort of the (already-completed) orphan+ returns NoSuchUpload. That NoSuchUpload must count as cleanup success — no fail-closed skip, no false+ unabortable orphan — leaving a safe remote outcome and no lingering incomplete MPU."""+ be = _GenBackend()+ be.objects[KEY] = (b"\xab" * (8 * MIB), '"seed-8"', {GEN: "prior"})+ be.complete_fail_gens = set() # gen1 Complete SUCCEEDS (does not raise)+ be.complete_omit_etag = True # ...but omits ETag -> reconciliation HEAD is consulted+ be.head_expired_gens = {1} # ...and that HEAD returns an expired token on the stale gen1 client+ c = _make_client_gen(be)+ c._compose_state.set(URI, _ComposeState(8 * MIB, "seed-8"))+ c.refresh_session = lambda: None # type: ignore[method-assign]+ _write(tmpfile, 11 * MIB)+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ # gen1 Complete landed mpu-1 (our 11 MiB generation), returned no ETag; the reconcile HEAD expired ->+ # refresh + retry. gen2 aborts the orphan mpu-1 -> NoSuchUpload (already completed) -> treated as success.+ assert "mpu-1" in be.abort_attempts_by_gen.get(2, []) # the orphan abort was attempted on the refreshed client+ assert be.completed == ["mpu-1"] # the original Complete had actually landed our generation+ assert be.objects[KEY][0] == b"\xab" * (11 * MIB) # safe remote: our completed generation is preserved+ assert be._n == 2 # gen2 was NOT fail-closed: it proceeded to create a replacement (mpu-2)...+ assert "mpu-2" not in be.mpus # ...which then conflicted on the moved destination and was aborted (no leak)+ assert URI not in c._compose_state # conflict path cleared local state; next step reseeds+++# --- MUST_FIX 3: compose-state cache is bounded (LRU + TTL) and cleared after the terminal drain -------+++def test_compose_state_cache_bounds_by_lru_and_ttl() -> None:+ now = [0.0]+ cache = _ComposeStateCache(max_size=2, ttl_seconds=10, clock=lambda: now[0])+ cache.set("a", _ComposeState(1, "a"))+ cache.set("b", _ComposeState(2, "b"))+ assert cache.get("a").length == 1 # touch a -> a is now most-recently-used+ cache.set("c", _ComposeState(3, "c")) # over cap -> evict LRU, which is b (not the touched a)+ assert cache.get("b") is None+ assert cache.get("a").length == 1 and cache.get("c").length == 3+ now[0] = 100 # advance past TTL+ assert cache.get("a") is None and cache.get("c") is None # expired entries are dropped+ assert len(cache) == 0+++async def test_terminal_clears_compose_state_inside_serialized_slot(tmpfile: str) -> None:+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB)+ assert URI in c._compose_state+ # The terminal finalize clears state AFTER draining prior writes (race-safe), not only pre-emptively.+ await c.upload_file(URI, b"final-bytes", serialize_key=URI, supersede_queued=True)+ assert URI not in c._compose_state+++# --- review 3920309806: any serialized full recording write must invalidate compose state ------+++async def test_nonterminal_full_write_invalidates_compose_state_so_next_snapshot_reseeds(tmpfile: str) -> None:+ """A NON-terminal serialized full byte write (supersede_queued=False — e.g. the mid-step byte fallback in+ _sync_video_artifact_after_step) replaces the object/metadata. It must clear the cached compose base too,+ or the next streamed snapshot's conditional copy 412s against the now-stale ETag and is skipped. Prove+ the state is invalidated and the next snapshot full-reseeds and lands."""+ fake = FakeS3()+ c = _make_client(fake)+ _seed_base(c, fake, 8 * MIB) # compose base cached at etag "seed-8388608"+ assert URI in c._compose_state+ # A serialized, NON-terminal full write replaces the object with a new ETag ("put-N").+ await c.upload_file(URI, b"\x03" * (9 * MIB), serialize_key=URI, supersede_queued=False)+ assert URI not in c._compose_state # stale compose base invalidated inside the serialized slot+ # The next streamed snapshot must full-reseed (base is gone) and LAND, not 412-skip on the stale ETag.+ _write(tmpfile, 11 * MIB, fill=b"\xcd")+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ assert _obj(fake) == b"\xcd" * (11 * MIB) # reseeded full replacement landed+ assert not fake.completed # no compose (no owned base) -> no UploadPartCopy against a stale ETag+ assert c._compose_state.get(URI) is not None # fresh verified generation seeded for the next step+++# --- MUST_FIX 4: never splice an unowned/foreign remote generation --------------------------------------+++async def test_foreign_remote_object_is_not_spliced(tmpfile: str) -> None:+ fake = FakeS3()+ c = _make_client(fake)+ # A duplicate/zombie producer full-PUT a foreign >=5 MiB generation; this process has NO owned state.+ foreign = b"\x07" * (8 * MIB)+ fake.objects[KEY] = (foreign, '"foreign-gen"', {GEN: "foreign-token"})+ _write(tmpfile, 11 * MIB, fill=b"\xcd")+ await c.store_recording_prefix(URI, tmpfile, 11 * MIB, serialize_key=URI)+ # Must be a clean full replacement of OUR bytes — never foreign-prefix copy + our-tail splice.+ assert _obj(fake) == b"\xcd" * (11 * MIB)+ assert not fake.mpus and not fake.completed # no UploadPartCopy of the foreign prefix+ # And local state is now seeded from OUR authored+verified generation for the next step to compose off.+ assert c._compose_state.get(URI) is not None+++async def test_full_replace_does_not_seed_when_foreign_writer_wins_the_race(tmpfile: str) -> None:+ fake = FakeS3()+ c = _make_client(fake)+ _write(tmpfile, 10 * MIB)+ orig_head = fake.head_object++ async def head_shows_foreign(*, Bucket: str, Key: str) -> dict[str, Any]:+ # A foreign writer overwrote our object between our PUT and this readback (token mismatch).+ fake.objects[Key] = (b"\x02" * (10 * MIB), '"foreign"', {GEN: "not-ours"})+ return await orig_head(Bucket=Bucket, Key=Key)++ fake.head_object = head_shows_foreign # type: ignore[method-assign]+ await c.store_recording_prefix(URI, tmpfile, 10 * MIB, serialize_key=URI)+ # Readback token/length did not match ours -> do NOT seed; the next step safely full-replaces again.+ assert URI not in c._compose_statediff --git a/tests/unit/test_sync_video_artifact_after_step.py b/tests/unit/test_sync_video_artifact_after_step.pyindex dfa647a01..f133054b4 100644--- a/tests/unit/test_sync_video_artifact_after_step.py+++ b/tests/unit/test_sync_video_artifact_after_step.py@@ -3,6 +3,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom skyvern.forge.agent import ForgeAgent+from skyvern.webeye.browser_artifacts import RecordingPrefixSnapshotdef _make_task(task_id: str = "task-1", organization_id: str = "org-1") -> MagicMock:@@ -12,13 +13,20 @@ def _make_task(task_id: str = "task-1", organization_id: str = "org-1") -> Magicreturn task-def _make_video_artifact(artifact_id: str, video_data: bytes) -> MagicMock:+def _make_video_artifact(artifact_id: str | None, video_data: bytes, video_path: str | None = None) -> MagicMock:artifact = MagicMock()artifact.video_artifact_id = artifact_idartifact.video_data = video_data+ artifact.video_path = video_pathreturn artifact+def _make_browser_state_with_recordings(artifacts: list[MagicMock]) -> MagicMock:+ browser_state = MagicMock()+ browser_state.browser_artifacts.video_artifacts = artifacts+ return browser_state++@pytest.mark.asyncioasync def test_sync_video_noop_when_browser_state_is_none() -> None:"""When browser_state is None the method must return without touching any app singletons."""@@ -28,13 +36,51 @@ async def test_sync_video_noop_when_browser_state_is_none() -> None:with patch("skyvern.forge.agent.app") as mock_app:await agent._sync_video_artifact_after_step(task, browser_state=None)+ mock_app.BROWSER_MANAGER.snapshot_recording_prefixes.assert_not_called()mock_app.BROWSER_MANAGER.get_video_artifacts.assert_not_called()+ mock_app.ARTIFACT_MANAGER.stream_artifact_prefix_from_path.assert_not_called()mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_not_called()@pytest.mark.asyncio-async def test_sync_video_uploads_each_artifact() -> None:- """Each video artifact returned by BROWSER_MANAGER must be uploaded via ARTIFACT_MANAGER."""+async def test_sync_video_streams_each_prefix_snapshot() -> None:+ """The ordinary per-step path streams exactly the snapshot prefix of each recording and never+ buffers the whole file through the byte-based update path."""+ agent = ForgeAgent()+ task = _make_task()+ browser_state = MagicMock()++ snapshots = [+ RecordingPrefixSnapshot(video_artifact_id="vid-a", path="/tmp/a.webm", prefix_len=100),+ RecordingPrefixSnapshot(video_artifact_id="vid-b", path="/tmp/b.webm", prefix_len=250),+ ]++ with patch("skyvern.forge.agent.app") as mock_app:+ mock_app.BROWSER_MANAGER.snapshot_recording_prefixes = MagicMock(return_value=snapshots)+ mock_app.ARTIFACT_MANAGER.stream_artifact_prefix_from_path = AsyncMock()+ mock_app.ARTIFACT_MANAGER.update_artifact_data = AsyncMock()++ await agent._sync_video_artifact_after_step(task, browser_state=browser_state)++ mock_app.BROWSER_MANAGER.snapshot_recording_prefixes.assert_called_once_with(+ browser_state=browser_state, task_id=task.task_id+ )+ # Streaming path only — the whole-file byte path must not run.+ mock_app.BROWSER_MANAGER.get_video_artifacts.assert_not_called()+ mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_not_called()+ assert mock_app.ARTIFACT_MANAGER.stream_artifact_prefix_from_path.await_count == 2+ mock_app.ARTIFACT_MANAGER.stream_artifact_prefix_from_path.assert_any_await(+ artifact_id="vid-a", organization_id=task.organization_id, path="/tmp/a.webm", length=100+ )+ mock_app.ARTIFACT_MANAGER.stream_artifact_prefix_from_path.assert_any_await(+ artifact_id="vid-b", organization_id=task.organization_id, path="/tmp/b.webm", length=250+ )+++async def test_sync_video_falls_back_to_byte_path_when_snapshot_is_none() -> None:+ """When the planner returns None (remux/finalize/first-registration required), the exact legacy+ byte-based upload is preserved."""agent = ForgeAgent()task = _make_task()browser_state = MagicMock()@@ -43,38 +89,84 @@ async def test_sync_video_uploads_each_artifact() -> None:artifact_b = _make_video_artifact("vid-b", b"bytes-b")with patch("skyvern.forge.agent.app") as mock_app:+ mock_app.BROWSER_MANAGER.snapshot_recording_prefixes = MagicMock(return_value=None)mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock(return_value=[artifact_a, artifact_b])mock_app.ARTIFACT_MANAGER.update_artifact_data = AsyncMock()+ mock_app.ARTIFACT_MANAGER.stream_artifact_prefix_from_path = AsyncMock()await agent._sync_video_artifact_after_step(task, browser_state=browser_state)- # Per-step sync runs while the recording file is still open; finalize=False skips the- # ffmpeg remux path so long tasks do not spawn one ffmpeg subprocess per step.mock_app.BROWSER_MANAGER.get_video_artifacts.assert_awaited_once_with(task_id=task.task_id, browser_state=browser_state, finalize=False)+ mock_app.ARTIFACT_MANAGER.stream_artifact_prefix_from_path.assert_not_called()assert mock_app.ARTIFACT_MANAGER.update_artifact_data.await_count == 2+ # Mid-step byte fallback must NOT seal/supersede a queued streamed prefix (supersede_queued_prefixes=False).mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_any_await(- artifact_id="vid-a", organization_id=task.organization_id, data=b"bytes-a"+ artifact_id="vid-a", organization_id=task.organization_id, data=b"bytes-a", supersede_queued_prefixes=False)mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_any_await(- artifact_id="vid-b", organization_id=task.organization_id, data=b"bytes-b"+ artifact_id="vid-b", organization_id=task.organization_id, data=b"bytes-b", supersede_queued_prefixes=False)+async def test_sync_video_byte_fallback_skips_missing_registered_path_but_processes_sibling() -> None:+ """A registered recording whose local file vanished must not have its stale cached bytes written+ over the newer streamed remote prefix; the byte fallback skips it yet still writes a valid sibling+ returned in the same list (SKY-15288)."""+ agent = ForgeAgent()+ task = _make_task()+ browser_state = MagicMock()++ missing = _make_video_artifact("vid-missing", b"stale", video_path="/nonexistent/gone.webm")+ sibling = _make_video_artifact("vid-ok", b"bytes-ok", video_path=None)++ with patch("skyvern.forge.agent.app") as mock_app:+ mock_app.BROWSER_MANAGER.snapshot_recording_prefixes = MagicMock(return_value=None)+ mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock(return_value=[missing, sibling])+ mock_app.ARTIFACT_MANAGER.update_artifact_data = AsyncMock()+ mock_app.ARTIFACT_MANAGER.stream_artifact_prefix_from_path = AsyncMock()++ await agent._sync_video_artifact_after_step(task, browser_state=browser_state)++ mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_awaited_once_with(+ artifact_id="vid-ok", organization_id=task.organization_id, data=b"bytes-ok", supersede_queued_prefixes=False+ )+++async def test_sync_video_noop_when_no_snapshots() -> None:+ """An empty plan uploads nothing and does not fall back to the byte path."""+ agent = ForgeAgent()+ task = _make_task()+ browser_state = MagicMock()++ with patch("skyvern.forge.agent.app") as mock_app:+ mock_app.BROWSER_MANAGER.snapshot_recording_prefixes = MagicMock(return_value=[])+ mock_app.ARTIFACT_MANAGER.stream_artifact_prefix_from_path = AsyncMock()++ await agent._sync_video_artifact_after_step(task, browser_state=browser_state)++ mock_app.BROWSER_MANAGER.get_video_artifacts.assert_not_called()+ mock_app.ARTIFACT_MANAGER.stream_artifact_prefix_from_path.assert_not_called()++@pytest.mark.asyncioasync def test_sync_video_swallows_exception() -> None:- """If get_video_artifacts raises, the method must not propagate the exception,- and the warning log must include task_id and organization_id for traceability."""+ """If planning raises, the method must not propagate; the warning log includes task_id and+ organization_id for traceability."""agent = ForgeAgent()task = _make_task(task_id="task-err", organization_id="org-err")browser_state = MagicMock()with patch("skyvern.forge.agent.app") as mock_app:- mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock(side_effect=RuntimeError("storage unavailable"))+ mock_app.BROWSER_MANAGER.snapshot_recording_prefixes = MagicMock(+ side_effect=RuntimeError("storage unavailable")+ )+ mock_app.ARTIFACT_MANAGER.stream_artifact_prefix_from_path = AsyncMock()with patch("skyvern.forge.agent.LOG") as mock_log:- # Should not raiseawait agent._sync_video_artifact_after_step(task, browser_state=browser_state)mock_log.warning.assert_called_once()@@ -83,4 +175,88 @@ async def test_sync_video_swallows_exception() -> None:assert kwargs.get("organization_id") == "org-err"assert kwargs.get("exc_info") is True+ mock_app.ARTIFACT_MANAGER.stream_artifact_prefix_from_path.assert_not_called()mock_app.ARTIFACT_MANAGER.update_artifact_data.assert_not_called()+++async def test_initialize_execution_state_skips_byte_read_when_all_recordings_registered() -> None:+ """The common step-loop path must not materialize an already-registered recording's whole (growing)+ file: when every tracked recording already has an id, get_video_artifacts is never called and the+ tracked artifact state is retained unchanged (SKY-15288, reviewer P1)."""+ agent = ForgeAgent()+ task = _make_task()+ step = MagicMock()+ registered = [_make_video_artifact("vid-a", b""), _make_video_artifact("vid-b", b"")]+ browser_state = _make_browser_state_with_recordings(registered)++ with (+ patch("skyvern.forge.agent.app") as mock_app,+ patch("skyvern.forge.agent.fail_step_if_browser_already_gone"),+ ):+ mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock()+ mock_app.ARTIFACT_MANAGER.create_artifact = AsyncMock()+ mock_app.BROWSER_MANAGER.set_video_artifact_for_task = MagicMock()++ await agent.initialize_execution_state(task=task, step=step, pre_resolved_browser_state=browser_state)++ mock_app.BROWSER_MANAGER.get_video_artifacts.assert_not_called()+ mock_app.ARTIFACT_MANAGER.create_artifact.assert_not_called()+ mock_app.BROWSER_MANAGER.set_video_artifact_for_task.assert_not_called()+ assert [va.video_artifact_id for va in registered] == ["vid-a", "vid-b"]+++async def test_initialize_execution_state_registers_unregistered_recording() -> None:+ """A not-yet-registered recording (first registration / new page) still reads bytes and registers."""+ agent = ForgeAgent()+ task = _make_task()+ step = MagicMock()+ unregistered = _make_video_artifact(None, b"bytes-a")+ browser_state = _make_browser_state_with_recordings([unregistered])++ with (+ patch("skyvern.forge.agent.app") as mock_app,+ patch("skyvern.forge.agent.fail_step_if_browser_already_gone"),+ ):+ mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock(return_value=[unregistered])+ mock_app.ARTIFACT_MANAGER.create_artifact = AsyncMock(return_value="new-id-a")+ mock_app.BROWSER_MANAGER.set_video_artifact_for_task = MagicMock()++ await agent.initialize_execution_state(task=task, step=step, pre_resolved_browser_state=browser_state)++ mock_app.BROWSER_MANAGER.get_video_artifacts.assert_awaited_once_with(+ task_id=task.task_id, browser_state=browser_state, finalize=False+ )+ mock_app.ARTIFACT_MANAGER.create_artifact.assert_awaited_once()+ assert unregistered.video_artifact_id == "new-id-a"+ mock_app.BROWSER_MANAGER.set_video_artifact_for_task.assert_called_once_with(task, [unregistered])+++async def test_initialize_execution_state_registers_only_new_recording_when_mixed() -> None:+ """A later popup/new-page recording added alongside an already-registered one must not be skipped:+ the byte path runs and registers only the new artifact, leaving the existing id untouched."""+ agent = ForgeAgent()+ task = _make_task()+ step = MagicMock()+ registered = _make_video_artifact("vid-a", b"")+ new = _make_video_artifact(None, b"bytes-b")+ browser_state = _make_browser_state_with_recordings([registered, new])++ with (+ patch("skyvern.forge.agent.app") as mock_app,+ patch("skyvern.forge.agent.fail_step_if_browser_already_gone"),+ ):+ mock_app.BROWSER_MANAGER.get_video_artifacts = AsyncMock(return_value=[registered, new])+ mock_app.ARTIFACT_MANAGER.create_artifact = AsyncMock(return_value="new-id-b")+ mock_app.BROWSER_MANAGER.set_video_artifact_for_task = MagicMock()++ await agent.initialize_execution_state(task=task, step=step, pre_resolved_browser_state=browser_state)++ mock_app.BROWSER_MANAGER.get_video_artifacts.assert_awaited_once_with(+ task_id=task.task_id, browser_state=browser_state, finalize=False+ )+ mock_app.ARTIFACT_MANAGER.create_artifact.assert_awaited_once()+ assert registered.video_artifact_id == "vid-a"+ assert new.video_artifact_id == "new-id-b"