Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Stop video-path future poisoning from killing workflow activities and finalize interrupted runs (SKY-12852) (#7723)
Aaron Perez55315ebd8b53
diff --git a/skyvern/forge/sdk/db/repositories/workflow_runs.py b/skyvern/forge/sdk/db/repositories/workflow_runs.pyindex de89798db..6aeef257d 100644--- a/skyvern/forge/sdk/db/repositories/workflow_runs.py+++ b/skyvern/forge/sdk/db/repositories/workflow_runs.py@@ -401,6 +401,7 @@ class WorkflowRunsRepository(BaseRepository):status: WorkflowRunStatus,failure_reason: str | None = None,run_with: str | None = None,+ failure_category: list[dict[str, Any]] | None = None,) -> WorkflowRun | None:"""Transition a workflow run to ``status`` only if it is not already in aterminal state. Returns the updated row, or ``None`` when the row was@@ -424,6 +425,8 @@ class WorkflowRunsRepository(BaseRepository):values["failure_reason"] = failure_reasonif run_with is not None:values["run_with"] = run_with+ if failure_category is not None:+ values["failure_category"] = failure_categoryasync with self.Session() as session:result = await session.execute(diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 94532574a..ea85f4682 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -4,6 +4,7 @@ import importlib.utilimport jsonimport osimport random+import sysimport textwrapimport timeimport uuid@@ -214,6 +215,13 @@ POST_RUN_TIMEOUT_EXHAUSTED_THRESHOLD_SECONDS = 0.001# Bound pre-finalization write-back so a stuck profile upload cannot leave the run in a non-terminal state.BROWSER_SESSION_WRITE_BACK_TIMEOUT = SAVE_DOWNLOADED_FILES_TIMEOUT+# Failure reason stamped when execute_workflow's body is interrupted before it captures a terminal+# intent (pre_finally_status stays None)+WORKFLOW_RUN_INTERRUPTED_FAILURE_REASON = (+ "Workflow run was interrupted before completion (worker eviction or in-process cancellation); "+ "finalized as failed by execute_workflow's in-band cleanup."+)+# Short lifespan for auto-provisioned CodeBlock sessions; the renewal loop extends it while the# run is active, so this only bounds how long a leaked session lingers if cleanup never runs.CODE_BLOCK_SESSION_TIMEOUT_MINUTES = 20@@ -2753,10 +2761,14 @@ class WorkflowService:)if max_elapsed_timeout_seconds <= 0:+ # Capture the terminal intent so the finally's interrupted-body backstop+ # doesn't treat this deliberate return as an interruption.+ pre_finally_failure_reason = _require_elapsed_timeout_failure_reason(timeout_failure_reason)workflow_run = await self.mark_workflow_run_as_timed_out(workflow_run_id=workflow_run_id,- failure_reason=_require_elapsed_timeout_failure_reason(timeout_failure_reason),+ failure_reason=pre_finally_failure_reason,)+ pre_finally_status = WorkflowRunStatus.timed_outreturn workflow_runelse:timeout_context = asyncio.timeout(max_elapsed_timeout_seconds)@@ -2766,10 +2778,12 @@ class WorkflowService:except TimeoutError:if not timeout_context.expired():raise+ pre_finally_failure_reason = _require_elapsed_timeout_failure_reason(timeout_failure_reason)workflow_run = await self.mark_workflow_run_as_timed_out(workflow_run_id=workflow_run_id,- failure_reason=_require_elapsed_timeout_failure_reason(timeout_failure_reason),+ failure_reason=pre_finally_failure_reason,)+ pre_finally_status = WorkflowRunStatus.timed_outreturn workflow_runpost_run_timeout_seconds = _get_workflow_run_max_elapsed_timeout_seconds(workflow_run)@@ -2983,6 +2997,41 @@ class WorkflowService:workflow_run_id=workflow_run_id,exc_info=True,)+ elif isinstance(sys.exc_info()[1], asyncio.CancelledError):+ # Cancellation ownership is decided at the activity layer: server-driven+ # cancellations (timeout/cancel/pause/reset) have their own finalizers with+ # concrete statuses, and the interrupted-activity backstop covers the rest+ # with cancellation-details discrimination and an INFRASTRUCTURE_ERROR+ # category. Finalizing here would race all of them with a generic failed.+ LOG.info(+ "Skipping interrupted-run finalize for cancellation; owned at the activity layer",+ workflow_run_id=workflow_run_id,+ )+ else:+ try:+ finalize_task = asyncio.ensure_future(+ self.mark_workflow_run_as_failed_if_not_final(+ workflow_run_id=workflow_run_id,+ failure_reason=WORKFLOW_RUN_INTERRUPTED_FAILURE_REASON,+ cascade_children=True,+ )+ )+ while not finalize_task.done():+ try:+ await asyncio.shield(finalize_task)+ except asyncio.CancelledError:+ continue+ finalized = finalize_task.result()+ if finalized is not None:+ workflow_run = finalized+ else:+ workflow_run = await self._current_row_after_lost_finalize(workflow_run_id, workflow_run)+ except BaseException:+ LOG.warning(+ "Failed to finalize interrupted workflow run during cleanup",+ workflow_run_id=workflow_run_id,+ exc_info=True,+ )if renewal_task is not None and not renewal_task.done():renewal_task.cancel()@@ -6282,6 +6331,31 @@ class WorkflowService:ai_fallback=ai_fallback,failure_category=failure_category,)+ await self._after_workflow_run_status_write(workflow_run, status)+ return workflow_run++ async def _update_workflow_run_status_if_not_final(+ self,+ workflow_run_id: str,+ status: WorkflowRunStatus,+ failure_reason: str | None = None,+ failure_category: list[dict] | None = None,+ ) -> WorkflowRun | None:+ """:meth:`_update_workflow_run_status` for writers that must lose a race against the+ run's own finalizer. Returns ``None`` when the row was already terminal."""+ workflow_run = await app.DATABASE.workflow_runs.update_workflow_run_if_not_final(+ workflow_run_id=workflow_run_id,+ status=status,+ failure_reason=failure_reason,+ failure_category=failure_category,+ )+ if workflow_run is None:+ return None+ await self._after_workflow_run_status_write(workflow_run, status)+ return workflow_run++ async def _after_workflow_run_status_write(self, workflow_run: WorkflowRun, status: WorkflowRunStatus) -> None:+ workflow_run_id = workflow_run.workflow_run_idif status.is_final():# Free extraction-cache entries for this run.extraction_cache.clear_workflow_run(workflow_run_id)@@ -6323,8 +6397,6 @@ class WorkflowService:self._background_tasks.add(bg)bg.add_done_callback(self._background_tasks.discard)- return workflow_run-async def _sync_task_run_from_workflow_run(self,workflow_run: WorkflowRun,@@ -6386,6 +6458,11 @@ class WorkflowService:"""Set final workflow run status based on pre-finally state.Called unconditionally to ensure unified flow.++ Terminal writes are conditional: an out-of-band finalizer (the interrupted-activity+ backstop) may have already terminalized the run and cascaded its children, and this+ shielded write can land after the activity's own cancellation — an unconditional+ write here would restore the parent while the children stay failed."""if pre_finally_status not in (WorkflowRunStatus.canceled,@@ -6393,26 +6470,52 @@ class WorkflowService:WorkflowRunStatus.terminated,WorkflowRunStatus.timed_out,):- return await self.mark_workflow_run_as_completed(workflow_run_id)+ updated = await self._update_workflow_run_status_if_not_final(+ workflow_run_id=workflow_run_id,+ status=WorkflowRunStatus.completed,+ )+ if updated is not None:+ otel_trace.get_current_span().set_attribute("task.completion_status", WorkflowRunStatus.completed)+ return updated+ return await self._current_row_after_lost_finalize(workflow_run_id, workflow_run)if workflow_run.status == WorkflowRunStatus.running:- workflow_run = await self._update_workflow_run_status(+ updated = await self._update_workflow_run_status_if_not_final(workflow_run_id=workflow_run_id,status=pre_finally_status,failure_reason=pre_finally_failure_reason,)+ if updated is None:+ return await self._current_row_after_lost_finalize(workflow_run_id, workflow_run)if pre_finally_status == WorkflowRunStatus.timed_out:await self._cascade_child_entities_on_terminal(workflow_run_id, WorkflowRunStatus.timed_out)- return workflow_run+ return updatedreturn workflow_run+ async def _current_row_after_lost_finalize(self, workflow_run_id: str, fallback: WorkflowRun) -> WorkflowRun:+ LOG.info(+ "In-band finalize lost to an out-of-band finalizer; leaving terminal status intact",+ workflow_run_id=workflow_run_id,+ )+ try:+ current = await self.get_workflow_run(workflow_run_id=workflow_run_id)+ except Exception:+ LOG.warning(+ "Failed to re-read workflow run after lost finalize; using in-memory row",+ workflow_run_id=workflow_run_id,+ exc_info=True,+ )+ return fallback+ return current or fallback+async def mark_workflow_run_as_failed(self,workflow_run_id: str,failure_reason: str | None,run_with: str | None = None,failure_category: list[dict] | None = None,+ cascade_children: bool = False,) -> WorkflowRun:LOG.info(f"Marking workflow run {workflow_run_id} as failed",@@ -6445,6 +6548,52 @@ class WorkflowService:run_with=run_with,failure_category=failure_category,)+ if cascade_children:+ # Opt-in: run-level failures normally leave child rows to their own executors,+ # but out-of-band finalization (an interrupted worker) has no executor left to do it.+ try:+ await self._do_cascade_child_entities(workflow_run_id, WorkflowRunStatus.failed)+ except Exception:+ LOG.exception("Failed to cascade child entity status", workflow_run_id=workflow_run_id)+ return workflow_run++ async def mark_workflow_run_as_failed_if_not_final(+ self,+ workflow_run_id: str,+ failure_reason: str | None,+ failure_category: list[dict] | None = None,+ cascade_children: bool = False,+ ) -> WorkflowRun | None:+ """Conditional failure finalize that no-ops when the run has already reached a terminal+ state. Out-of-band finalizers (the interrupted-activity backstop) run concurrently with+ ``execute_workflow``'s shielded ``_finalize_workflow_run_status`` write, so a+ read-then-write would clobber a real ``completed``/``timed_out`` status with ``failed``.+ Children cascade only on the transition this call actually won.+ """+ if failure_category is None:+ failure_category = classify_from_failure_reason(failure_reason, fallback_to_unknown=True)++ workflow_run = await self._update_workflow_run_status_if_not_final(+ workflow_run_id=workflow_run_id,+ status=WorkflowRunStatus.failed,+ failure_reason=failure_reason,+ failure_category=failure_category,+ )+ if workflow_run is None:+ return None++ otel_trace.get_current_span().set_attribute("task.completion_status", WorkflowRunStatus.failed)+ LOG.info(+ f"Marked workflow run {workflow_run_id} as failed (conditional)",+ workflow_run_id=workflow_run_id,+ workflow_status="failed",+ failure_category=failure_category,+ )+ if cascade_children:+ try:+ await self._do_cascade_child_entities(workflow_run_id, WorkflowRunStatus.failed)+ except Exception:+ LOG.exception("Failed to cascade child entity status", workflow_run_id=workflow_run_id)return workflow_runasync def mark_workflow_run_as_running(self, workflow_run_id: str, run_with: str | None = None) -> WorkflowRun:diff --git a/skyvern/forge/sdk/workflow/status_mapping.py b/skyvern/forge/sdk/workflow/status_mapping.pyindex 59f552e0d..f655e3d5f 100644--- a/skyvern/forge/sdk/workflow/status_mapping.py+++ b/skyvern/forge/sdk/workflow/status_mapping.py@@ -7,15 +7,18 @@ from skyvern.schemas.workflows import BlockStatusBLOCK_STATUS_MAP: dict[WorkflowRunStatus, BlockStatus] = {WorkflowRunStatus.timed_out: BlockStatus.timed_out,+ WorkflowRunStatus.failed: BlockStatus.failed,}TASK_STATUS_MAP: dict[WorkflowRunStatus, TaskStatus] = {WorkflowRunStatus.timed_out: TaskStatus.timed_out,+ WorkflowRunStatus.failed: TaskStatus.failed,}# StepStatus has no timed_out; use canceled for timeout cleanup.STEP_STATUS_MAP: dict[WorkflowRunStatus, StepStatus] = {WorkflowRunStatus.timed_out: StepStatus.canceled,+ WorkflowRunStatus.failed: StepStatus.failed,}_TERMINAL_BLOCK_STATUSES = {diff --git a/skyvern/webeye/browser_factory.py b/skyvern/webeye/browser_factory.pyindex 328575b2e..8cbee2b69 100644--- a/skyvern/webeye/browser_factory.py+++ b/skyvern/webeye/browser_factory.py@@ -10,6 +10,7 @@ import socketimport subprocessimport timeimport uuid+from contextlib import suppressfrom dataclasses import dataclassfrom datetime import datetimefrom pathlib import Path@@ -28,6 +29,7 @@ from playwright.async_api import Error as PlaywrightErrorfrom playwright.async_api import (Page,Playwright,+ Video,)from skyvern.config import settings@@ -157,6 +159,34 @@ def set_browser_console_log(browser_context: BrowserContext, browser_artifacts:browser_context.on("console", browser_console_log)+async def resolve_video_path(video: Video, timeout_seconds: float) -> str | None:+ """Wait for video.path() without ever cancelling patchright's shared artifact future"""+ path_task = asyncio.ensure_future(video.path())+ # Consume the task's eventual outcome even when it outlives this wait (timeout / caller+ # cancelled), so a late PlaywrightError on page close doesn't log "Task exception was+ # never retrieved".+ path_task.add_done_callback(_consume_abandoned_task_result)+ try:+ raw_path = await asyncio.wait_for(asyncio.shield(path_task), timeout_seconds)+ except TimeoutError:+ # path_task keeps waiting harmlessly; the shared future stays live for other awaiters.+ return None+ except asyncio.CancelledError:+ # path_task.cancelled() is direct evidence the shared artifact future was+ # cancelled by another awaiter (shield keeps caller cancellation from reaching+ # it); current_task().cancelling() is a counter that can read stale-nonzero+ # after any caught-but-not-uncancelled CancelledError.+ if path_task.cancelled():+ return None+ raise+ return str(raw_path) if raw_path is not None else None+++def _consume_abandoned_task_result(task: asyncio.Task) -> None:+ if not task.cancelled():+ task.exception()++def set_popup_video_listener(browser_context: BrowserContext, browser_artifacts: BrowserArtifacts) -> None:tracked_paths: set[str] = set()@@ -165,15 +195,19 @@ def set_popup_video_listener(browser_context: BrowserContext, browser_artifacts:video = page.videoif not video:return- async with asyncio.timeout(settings.POPUP_VIDEO_PATH_TIMEOUT_SECONDS):- raw_path = await video.path()- if raw_path is None:+ video_path_or_none = await resolve_video_path(video, settings.POPUP_VIDEO_PATH_TIMEOUT_SECONDS)+ if video_path_or_none is None:+ try:+ page_origin = urlparse(page.url).hostname or "unknown"+ except Exception:+ page_origin = "unknown"+ LOG.warning("Popup video path resolution timed out", page_origin=page_origin)return# The await above may have raced a discard (RealBrowserState closing this page# before it ever became the working page) — honor it even though it landed after.if browser_artifacts.is_page_video_discarded(page):return- video_path = str(raw_path)+ video_path = video_path_or_none# After the await, another handler may have already registered this pathif video_path in tracked_paths:return@@ -185,12 +219,6 @@ def set_popup_video_listener(browser_context: BrowserContext, browser_artifacts:browser_artifacts.video_artifacts.append(VideoArtifact(video_path=video_path))except PlaywrightError:LOG.debug("Failed to register popup page video", exc_info=True)- except TimeoutError:- try:- page_origin = urlparse(page.url).hostname or "unknown"- except Exception:- page_origin = "unknown"- LOG.warning("Popup video path resolution timed out", page_origin=page_origin)except Exception:LOG.warning("Failed to register popup page video", exc_info=True)@@ -515,6 +543,7 @@ class BrowserContextFactory:) -> tuple[BrowserContext, BrowserArtifacts, BrowserCleanupFunc]:browser_type = settings.BROWSER_TYPEbrowser_context: BrowserContext | None = None+ cleanup_func: BrowserCleanupFunc = Nonetry:creator = cls._creators.get(browser_type)if not creator:@@ -534,13 +563,17 @@ class BrowserContextFactory:context.tz_info = get_tzinfo_from_proxy(proxy_location)return browser_context, browser_artifacts, cleanup_func- except Exception as e:+ except BaseException as e:if browser_context is not None:# FIXME: sometimes it can't close the browser context?LOG.error("unexpected error happens after created browser context, going to close the context")- await browser_context.close()+ with suppress(Exception):+ await browser_context.close()+ if cleanup_func:+ with suppress(Exception):+ await cleanup_func()- if isinstance(e, UnknownBrowserType):+ if not isinstance(e, Exception) or isinstance(e, UnknownBrowserType):raise eraise UnknownErrorWhileCreatingBrowserContext(browser_type, e) from ediff --git a/skyvern/webeye/real_browser_state.py b/skyvern/webeye/real_browser_state.pyindex 03d365edd..db9f4c5a5 100644--- a/skyvern/webeye/real_browser_state.py+++ b/skyvern/webeye/real_browser_state.py@@ -29,7 +29,7 @@ from skyvern.forge.sdk.trace import tracedfrom skyvern.schemas.runs import ProxyLocationInputfrom skyvern.webeye.browser_artifacts import BrowserArtifactsfrom skyvern.webeye.browser_engine import BrowserEngineSelection-from skyvern.webeye.browser_factory import BrowserCleanupFunc, BrowserContextFactory+from skyvern.webeye.browser_factory import BrowserCleanupFunc, BrowserContextFactory, resolve_video_pathfrom skyvern.webeye.browser_state import BrowserStatefrom skyvern.webeye.cdp_download_interceptor import disable_download_interceptor_for_contextfrom skyvern.webeye.navigation import is_permanent_navigation_error, navigate_with_retry@@ -144,17 +144,20 @@ class RealBrowserState(BrowserState):video = page.videoif not video:return+ page_origin = "unknown"try:- async with asyncio.timeout(settings.POPUP_VIDEO_PATH_TIMEOUT_SECONDS):- path = str(await video.path())+ page_origin = urlparse(page.url).hostname or "unknown"except Exception:+ pass+ try:+ path = await resolve_video_path(video, settings.POPUP_VIDEO_PATH_TIMEOUT_SECONDS)+ except Exception:+ LOG.warning("Could not get video path to discard orphaned artifact", page_origin=page_origin, exc_info=True)+ return+ if path is None:# Best-effort: leave the artifact registered rather than raising — the# near-empty video is uploaded as-is instead of silently disappearing.- try:- page_origin = urlparse(page.url).hostname or "unknown"- except Exception:- page_origin = "unknown"- LOG.warning("Could not get video path to discard orphaned artifact", page_origin=page_origin, exc_info=True)+ LOG.warning("Could not get video path to discard orphaned artifact", page_origin=page_origin)returnvideo_artifacts = self.browser_artifacts.video_artifactsfiltered = [va for va in video_artifacts if va.video_path != path]diff --git a/tests/unit/test_download_file_action_handler.py b/tests/unit/test_download_file_action_handler.pyindex bc9e34128..81f3accf3 100644--- a/tests/unit/test_download_file_action_handler.py+++ b/tests/unit/test_download_file_action_handler.py@@ -1142,12 +1142,14 @@ async def test_handle_action_download_completion_budget_bounds_hanging_settle(page=page,action=action,),- timeout=0.5,+ timeout=5,)elapsed = time.monotonic() - started_at- assert elapsed < 0.2+ # Proves the 0.03s download budget raised, not the 5s wait_for safety net;+ # the bound is loose because loaded CI runners add hundreds of ms of lag.+ assert elapsed < 1.0def test_remove_download_listener_uses_playwright_remove_listener_when_off_unavailable() -> None:diff --git a/tests/unit/test_real_browser_manager.py b/tests/unit/test_real_browser_manager.pyindex 57f870ea2..e81fa0485 100644--- a/tests/unit/test_real_browser_manager.py+++ b/tests/unit/test_real_browser_manager.py@@ -559,8 +559,10 @@ async def test_popup_video_listener_registers_pre_existing_pages() -> None:browser_context.pages = [initial_page]set_popup_video_listener(browser_context=browser_context, browser_artifacts=artifacts)- # Let the ensure_future tasks run- await asyncio.sleep(0)+ # Let the ensure_future tasks run to completion (registration spans multiple loop turns)+ async with asyncio.timeout(1):+ while not artifacts.video_artifacts:+ await asyncio.sleep(0)paths = [va.video_path for va in artifacts.video_artifacts]assert paths == ["/tmp/videos/initial.webm"]diff --git a/tests/unit/test_workflow_elapsed_timeout.py b/tests/unit/test_workflow_elapsed_timeout.pyindex 4b89d14d8..8ba1b82fa 100644--- a/tests/unit/test_workflow_elapsed_timeout.py+++ b/tests/unit/test_workflow_elapsed_timeout.py@@ -217,6 +217,7 @@ async def test_execute_workflow_returns_after_elapsed_timeout_without_finally(mosvc = WorkflowService()mark_workflow_run_as_timed_out = AsyncMock(return_value=timed_out_run)+ mark_failed_if_not_final = AsyncMock(return_value=None)execute_workflow_blocks = AsyncMock()generate_script_if_needed = AsyncMock()execute_finally_block_if_configured = AsyncMock()@@ -231,6 +232,7 @@ async def test_execute_workflow_returns_after_elapsed_timeout_without_finally(momonkeypatch.setattr(svc, "auto_create_browser_session_if_needed", AsyncMock(return_value=None))monkeypatch.setattr(svc, "_browser_profile_is_managed", AsyncMock(return_value=False))monkeypatch.setattr(svc, "mark_workflow_run_as_timed_out", mark_workflow_run_as_timed_out)+ monkeypatch.setattr(svc, "mark_workflow_run_as_failed_if_not_final", mark_failed_if_not_final)monkeypatch.setattr(svc, "_execute_workflow_blocks", execute_workflow_blocks)monkeypatch.setattr(svc, "generate_script_if_needed", generate_script_if_needed)monkeypatch.setattr(svc, "_execute_finally_block_if_configured", execute_finally_block_if_configured)@@ -252,6 +254,7 @@ async def test_execute_workflow_returns_after_elapsed_timeout_without_finally(moexecute_workflow_blocks.assert_not_awaited()generate_script_if_needed.assert_not_awaited()execute_finally_block_if_configured.assert_not_awaited()+ mark_failed_if_not_final.assert_not_awaited()clean_up_workflow.assert_awaited_once()@@ -299,6 +302,7 @@ async def test_execute_workflow_times_out_slow_pre_block_script_lookup(monkeypatsvc = WorkflowService()mark_workflow_run_as_timed_out = AsyncMock(return_value=timed_out_run)+ mark_failed_if_not_final = AsyncMock(return_value=None)execute_workflow_blocks = AsyncMock()clean_up_workflow = AsyncMock()@@ -311,6 +315,7 @@ async def test_execute_workflow_times_out_slow_pre_block_script_lookup(monkeypatmonkeypatch.setattr(svc, "auto_create_browser_session_if_needed", AsyncMock(return_value=None))monkeypatch.setattr(svc, "_browser_profile_is_managed", AsyncMock(return_value=False))monkeypatch.setattr(svc, "mark_workflow_run_as_timed_out", mark_workflow_run_as_timed_out)+ monkeypatch.setattr(svc, "mark_workflow_run_as_failed_if_not_final", mark_failed_if_not_final)monkeypatch.setattr(svc, "_execute_workflow_blocks", execute_workflow_blocks)monkeypatch.setattr(svc, "clean_up_workflow", clean_up_workflow)@@ -323,6 +328,7 @@ async def test_execute_workflow_times_out_slow_pre_block_script_lookup(monkeypatassert result is timed_out_runmark_workflow_run_as_timed_out.assert_awaited_once()execute_workflow_blocks.assert_not_awaited()+ mark_failed_if_not_final.assert_not_awaited()clean_up_workflow.assert_awaited_once()@@ -964,3 +970,228 @@ async def test_execute_workflow_runs_finally_for_existing_timed_out_status(execute_finally_block_if_configured.assert_awaited_once()finalize_workflow_run_status.assert_awaited_once()clean_up_workflow.assert_awaited_once()+++async def test_execute_workflow_finalizes_failed_when_body_interrupted_before_terminal(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # SKY-12860: block execution is interrupted before it captures a terminal intent+ # (pre_finally_status stays None). The run must be finalized as failed, not left+ # orphaned in `running`, and clean_up_workflow must still run.+ started_at = datetime.now(timezone.utc)+ created_run = _workflow_run(WorkflowRunStatus.created, started_at=started_at)+ running_run = _workflow_run(WorkflowRunStatus.running, started_at=started_at)+ failed_run = _workflow_run(WorkflowRunStatus.failed, started_at=started_at)++ workflow = SimpleNamespace(+ workflow_id="wf_1",+ persist_browser_session=False,+ workflow_permanent_id="wp_1",+ title="Interrupted workflow",+ organization_id="org_1",+ generate_script_on_terminal=False,+ model=None,+ workflow_definition=SimpleNamespace(+ parameters=[],+ finally_block_label=None,+ blocks=[],+ ),+ )+ organization = SimpleNamespace(organization_id="org_1")++ workflow_context_manager = SimpleNamespace(+ initialize_workflow_run_context=AsyncMock(),+ get_workflow_run_context=lambda _workflow_run_id: SimpleNamespace(browser_session_id=None),+ )+ monkeypatch.setattr(service_module.app, "WORKFLOW_CONTEXT_MANAGER", workflow_context_manager)+ monkeypatch.setattr(service_module.workflow_script_service, "workflow_has_conditionals", lambda _workflow: False)+ monkeypatch.setattr(+ service_module.workflow_script_service,+ "get_workflow_script",+ AsyncMock(return_value=(None, None, False)),+ )+ monkeypatch.setattr(service_module.skyvern_context, "current", lambda: None)++ svc = WorkflowService()+ interrupted_blocks = AsyncMock(side_effect=RuntimeError("blocks interrupted"))+ mark_failed_if_not_final = AsyncMock(return_value=failed_run)+ clean_up_workflow = AsyncMock()++ monkeypatch.setattr(svc, "get_workflow_run", AsyncMock(return_value=created_run))+ monkeypatch.setattr(svc, "get_workflow", AsyncMock(return_value=workflow))+ monkeypatch.setattr(svc, "mark_workflow_run_as_running", AsyncMock(return_value=running_run))+ monkeypatch.setattr(svc, "get_workflow_run_parameter_tuples", AsyncMock(return_value=[]))+ monkeypatch.setattr(svc, "get_workflow_output_parameters", AsyncMock(return_value=[]))+ monkeypatch.setattr(svc, "_collect_inherited_workflow_system_prompt", AsyncMock(return_value=None))+ monkeypatch.setattr(svc, "auto_create_browser_session_if_needed", AsyncMock(return_value=None))+ monkeypatch.setattr(svc, "_browser_profile_is_managed", AsyncMock(return_value=False))+ monkeypatch.setattr(svc, "_execute_workflow_blocks", interrupted_blocks)+ monkeypatch.setattr(svc, "mark_workflow_run_as_failed_if_not_final", mark_failed_if_not_final)+ monkeypatch.setattr(svc, "clean_up_workflow", clean_up_workflow)++ with pytest.raises(RuntimeError, match="blocks interrupted"):+ await svc.execute_workflow(+ workflow_run_id="wr_1",+ api_key=None,+ organization=organization,+ )++ mark_failed_if_not_final.assert_awaited_once()+ assert mark_failed_if_not_final.await_args is not None+ assert mark_failed_if_not_final.await_args.kwargs["workflow_run_id"] == "wr_1"+ assert (+ mark_failed_if_not_final.await_args.kwargs["failure_reason"]+ == service_module.WORKFLOW_RUN_INTERRUPTED_FAILURE_REASON+ )+ # The interrupted case has no executor left to terminalize children — the in-flight+ # block/task/step rows must be cascaded alongside the run.+ assert mark_failed_if_not_final.await_args.kwargs["cascade_children"] is True+ clean_up_workflow.assert_awaited_once()+++async def test_finalize_completed_noops_when_backstop_already_failed_run(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Backstop-wins-first ordering: the interrupted-activity backstop already finalized the+ # run as failed (children cascaded). The in-band finalize with a completed intent must+ # lose the conditional write and leave the terminal status (and children) untouched.+ started_at = datetime.now(timezone.utc)+ running_run = _workflow_run(WorkflowRunStatus.running, started_at=started_at)+ failed_run = _workflow_run(WorkflowRunStatus.failed, started_at=started_at)++ svc = WorkflowService()+ conditional = AsyncMock(return_value=None) # lost the race: row already terminal+ unconditional = AsyncMock(side_effect=AssertionError("unconditional terminal write must not run"))+ cascade = AsyncMock()+ monkeypatch.setattr(svc, "_update_workflow_run_status_if_not_final", conditional)+ monkeypatch.setattr(svc, "_update_workflow_run_status", unconditional)+ monkeypatch.setattr(svc, "_cascade_child_entities_on_terminal", cascade)+ monkeypatch.setattr(svc, "get_workflow_run", AsyncMock(return_value=failed_run))++ result = await svc._finalize_workflow_run_status(+ workflow_run_id="wr_1",+ workflow_run=running_run,+ pre_finally_status=WorkflowRunStatus.completed,+ pre_finally_failure_reason=None,+ )++ assert result.status == WorkflowRunStatus.failed+ conditional.assert_awaited_once()+ assert conditional.await_args.kwargs["status"] == WorkflowRunStatus.completed+ cascade.assert_not_awaited()+++async def test_finalize_timed_out_loss_skips_cascade(monkeypatch: pytest.MonkeyPatch) -> None:+ # Terminal-intent arm: a timed_out intent that loses the conditional write must not+ # cascade children on top of the winner's cascade.+ started_at = datetime.now(timezone.utc)+ running_run = _workflow_run(WorkflowRunStatus.running, started_at=started_at)+ failed_run = _workflow_run(WorkflowRunStatus.failed, started_at=started_at)++ svc = WorkflowService()+ monkeypatch.setattr(svc, "_update_workflow_run_status_if_not_final", AsyncMock(return_value=None))+ monkeypatch.setattr(+ svc, "_update_workflow_run_status", AsyncMock(side_effect=AssertionError("must stay conditional"))+ )+ cascade = AsyncMock()+ monkeypatch.setattr(svc, "_cascade_child_entities_on_terminal", cascade)+ monkeypatch.setattr(svc, "get_workflow_run", AsyncMock(return_value=failed_run))++ result = await svc._finalize_workflow_run_status(+ workflow_run_id="wr_1",+ workflow_run=running_run,+ pre_finally_status=WorkflowRunStatus.timed_out,+ pre_finally_failure_reason="elapsed",+ )++ assert result.status == WorkflowRunStatus.failed+ cascade.assert_not_awaited()+++async def test_finalize_completed_wins_when_row_still_running(monkeypatch: pytest.MonkeyPatch) -> None:+ # Win path unchanged: row still running -> conditional write lands completed.+ started_at = datetime.now(timezone.utc)+ running_run = _workflow_run(WorkflowRunStatus.running, started_at=started_at)+ completed_run = _workflow_run(WorkflowRunStatus.completed, started_at=started_at)++ svc = WorkflowService()+ conditional = AsyncMock(return_value=completed_run)+ monkeypatch.setattr(svc, "_update_workflow_run_status_if_not_final", conditional)+ monkeypatch.setattr(+ svc, "_update_workflow_run_status", AsyncMock(side_effect=AssertionError("must stay conditional"))+ )++ result = await svc._finalize_workflow_run_status(+ workflow_run_id="wr_1",+ workflow_run=running_run,+ pre_finally_status=WorkflowRunStatus.completed,+ pre_finally_failure_reason=None,+ )++ assert result.status == WorkflowRunStatus.completed+++async def test_execute_workflow_skips_interrupted_finalize_for_cancellation(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Cancellation ownership lives at the activity layer (server timeout/cancel finalizers,+ # interrupted-activity backstop with cancellation-details discrimination). The in-band+ # pre_finally-None finalize must not race them with a generic failed.+ started_at = datetime.now(timezone.utc)+ created_run = _workflow_run(WorkflowRunStatus.created, started_at=started_at)+ running_run = _workflow_run(WorkflowRunStatus.running, started_at=started_at)++ workflow = SimpleNamespace(+ workflow_id="wf_1",+ persist_browser_session=False,+ workflow_permanent_id="wp_1",+ title="Cancelled workflow",+ organization_id="org_1",+ generate_script_on_terminal=False,+ model=None,+ workflow_definition=SimpleNamespace(parameters=[], finally_block_label=None, blocks=[]),+ )+ organization = SimpleNamespace(organization_id="org_1")++ workflow_context_manager = SimpleNamespace(+ initialize_workflow_run_context=AsyncMock(),+ get_workflow_run_context=lambda _workflow_run_id: SimpleNamespace(browser_session_id=None),+ )+ monkeypatch.setattr(service_module.app, "WORKFLOW_CONTEXT_MANAGER", workflow_context_manager)+ monkeypatch.setattr(service_module.workflow_script_service, "workflow_has_conditionals", lambda _workflow: False)+ monkeypatch.setattr(+ service_module.workflow_script_service,+ "get_workflow_script",+ AsyncMock(return_value=(None, None, False)),+ )+ monkeypatch.setattr(service_module.skyvern_context, "current", lambda: None)++ svc = WorkflowService()+ mark_failed_if_not_final = AsyncMock()+ clean_up_workflow = AsyncMock()++ monkeypatch.setattr(svc, "get_workflow_run", AsyncMock(return_value=created_run))+ monkeypatch.setattr(svc, "get_workflow", AsyncMock(return_value=workflow))+ monkeypatch.setattr(svc, "mark_workflow_run_as_running", AsyncMock(return_value=running_run))+ monkeypatch.setattr(svc, "get_workflow_run_parameter_tuples", AsyncMock(return_value=[]))+ monkeypatch.setattr(svc, "get_workflow_output_parameters", AsyncMock(return_value=[]))+ monkeypatch.setattr(svc, "_collect_inherited_workflow_system_prompt", AsyncMock(return_value=None))+ monkeypatch.setattr(svc, "auto_create_browser_session_if_needed", AsyncMock(return_value=None))+ monkeypatch.setattr(svc, "_browser_profile_is_managed", AsyncMock(return_value=False))+ monkeypatch.setattr(svc, "_execute_workflow_blocks", AsyncMock(side_effect=asyncio.CancelledError()))+ monkeypatch.setattr(svc, "mark_workflow_run_as_failed_if_not_final", mark_failed_if_not_final)+ monkeypatch.setattr(svc, "clean_up_workflow", clean_up_workflow)++ with pytest.raises(asyncio.CancelledError):+ await svc.execute_workflow(+ workflow_run_id="wr_1",+ api_key=None,+ organization=organization,+ )++ mark_failed_if_not_final.assert_not_awaited()diff --git a/tests/unit/webeye/test_browser_factory_video_path.py b/tests/unit/webeye/test_browser_factory_video_path.pynew file mode 100644index 000000000..4ff0e158f--- /dev/null+++ b/tests/unit/webeye/test_browser_factory_video_path.py@@ -0,0 +1,102 @@+import asyncio++import pytest++from skyvern.webeye.browser_factory import resolve_video_path+++class _FakeVideo:+ """Mirrors patchright's Video: path() awaits a single shared artifact future."""++ def __init__(self, artifact_future: asyncio.Future) -> None:+ self._artifact_future = artifact_future++ async def path(self) -> str:+ return await self._artifact_future+++async def test_returns_path_when_future_resolves_in_time() -> None:+ fut: asyncio.Future = asyncio.get_running_loop().create_future()+ fut.set_result("/videos/a.webm")++ assert await resolve_video_path(_FakeVideo(fut), timeout_seconds=1) == "/videos/a.webm"+++async def test_timeout_returns_none_without_cancelling_shared_future() -> None:+ fut: asyncio.Future = asyncio.get_running_loop().create_future()++ result = await resolve_video_path(_FakeVideo(fut), timeout_seconds=0.05)++ assert result is None+ assert not fut.cancelled()+ # A later awaiter must still be able to get the value.+ fut.set_result("/videos/b.webm")+ assert await _FakeVideo(fut).path() == "/videos/b.webm"+++async def test_poisoned_future_returns_none_instead_of_cancelling_caller() -> None:+ fut: asyncio.Future = asyncio.get_running_loop().create_future()+ fut.cancel()++ caller = asyncio.ensure_future(resolve_video_path(_FakeVideo(fut), timeout_seconds=1))+ result = await asyncio.wait_for(caller, timeout=1)++ assert result is None+ assert not caller.cancelled()+++async def test_concurrent_waiter_timeout_does_not_cancel_other_caller() -> None:+ """The SKY-12852 scenario: the popup-video listener times out on the shared future+ while the activity's discard path is awaiting the same future."""+ fut: asyncio.Future = asyncio.get_running_loop().create_future()+ video = _FakeVideo(fut)++ listener = asyncio.ensure_future(resolve_video_path(video, timeout_seconds=0.05))+ caller = asyncio.ensure_future(resolve_video_path(video, timeout_seconds=5))++ assert await listener is None+ await asyncio.sleep(0) # let any stray cancellation propagate+ fut.set_result("/videos/c.webm")++ assert await asyncio.wait_for(caller, timeout=1) == "/videos/c.webm"+ assert not caller.cancelled()+++async def test_poisoned_future_returns_none_with_stale_cancel_count() -> None:+ """A caught-but-not-uncancelled CancelledError leaves current_task().cancelling()+ nonzero; a poisoned-future miss must still degrade to None, not re-raise."""+ fut: asyncio.Future = asyncio.get_running_loop().create_future()+ fut.cancel()++ async def caller_with_stale_cancel_count() -> str | None:+ current = asyncio.current_task()+ assert current is not None+ current.cancel()+ try:+ await asyncio.sleep(0)+ except asyncio.CancelledError:+ pass+ assert current.cancelling() > 0+ return await resolve_video_path(_FakeVideo(fut), timeout_seconds=1)++ caller = asyncio.ensure_future(caller_with_stale_cancel_count())+ assert await asyncio.wait_for(caller, timeout=1) is None+ assert not caller.cancelled()+++async def test_real_task_cancellation_still_propagates() -> None:+ fut: asyncio.Future = asyncio.get_running_loop().create_future()++ caller = asyncio.ensure_future(resolve_video_path(_FakeVideo(fut), timeout_seconds=5))+ await asyncio.sleep(0.01)+ caller.cancel()++ with pytest.raises(asyncio.CancelledError):+ await caller+ assert caller.cancelled()