Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Retry a no-policy initializer failure in process before failing the run, and route the sequential-credential rejection through the helper (SKY-16388) (#8567)
Shuchang Zheng63113be5e187
diff --git a/skyvern/forge/sdk/executor/background_task_executor.py b/skyvern/forge/sdk/executor/background_task_executor.pyindex e2fc34c31..0cf59f16f 100644--- a/skyvern/forge/sdk/executor/background_task_executor.py+++ b/skyvern/forge/sdk/executor/background_task_executor.py@@ -46,6 +46,8 @@ from skyvern.utils.files import initialize_skyvern_state_fileLOG = structlog.get_logger()+INITIALIZER_FAILURE_BUDGET = 3+async def _run_with_own_context(func: Callable[..., Coroutine[Any, Any, Any]],@@ -78,6 +80,7 @@ class BackgroundTaskExecutor(AsyncExecutor):self._scheduled_retry_resumes: set[tuple[str, int]] = set()self._retry_resumes_needing_recovery: set[tuple[str, int]] = set()self._retry_dispatches_needing_recovery: dict[tuple[str, int], tuple[Any, dict[str, Any]]] = {}+ self._initializer_failures: dict[tuple[str, int], int] = {}async def recover_pending_retries(self) -> None:# The lifespan only logs a failed initial pass; the periodic sweep must start regardless.@@ -595,9 +598,9 @@ class BackgroundTaskExecutor(AsyncExecutor):if execution_kwargs.get("prepared_attempt_claimed") and not await self._retry_dispatch_claim_is_current(attempt):+ self._initializer_failures.pop(key, None)self._retry_resumes_needing_recovery.discard(key)return- # Attempt rows let the sweep recover initialization failures; attempt-less runs must fail durably.try:await initialize_skyvern_state_file(workflow_run_id=attempt.workflow_run_id, organization_id=attempt.organization_id@@ -606,12 +609,17 @@ class BackgroundTaskExecutor(AsyncExecutor):app.DATABASE, attempt.organization_id, execution_kwargs.get("organization"))except Exception as exc:+ failures = self._initializer_failures.get(key, 0) + 1+ self._initializer_failures[key] = failures+ if failures < INITIALIZER_FAILURE_BUDGET:+ raiseif await fail_run_without_attempt_row(attempt.workflow_run_id,f"Workflow run initialization failed before execution: {type(exc).__name__}: {exc}",api_key=execution_kwargs.get("api_key"),need_call_webhook=execution_kwargs.get("need_call_webhook", True),):+ self._initializer_failures.pop(key, None)self._retry_resumes_needing_recovery.discard(key)LOG.warning("Workflow run initialization failed without an attempt row; run is terminal",@@ -620,6 +628,7 @@ class BackgroundTaskExecutor(AsyncExecutor):)returnraise+ self._initializer_failures.pop(key, None)await app.WORKFLOW_SERVICE.execute_workflow_with_retries(**execution_kwargs, on_execution_start=on_execution_start)@@ -758,6 +767,7 @@ class BackgroundTaskExecutor(AsyncExecutor):)try:attempt_rows = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)+ attempt_rows_known = Trueexcept Exception:# Attempt lookup only selects the retry-aware attempt number. The owner repeats the# lookup, and a dispatch that fails before execution is retried by the recovery sweep.@@ -767,6 +777,7 @@ class BackgroundTaskExecutor(AsyncExecutor):exc_info=True,)attempt_rows = []+ attempt_rows_known = Falseattempt_number = max((row.attempt_number for row in attempt_rows), default=1)if block_labels or block_outputs:# Scoped inputs live only in this process. The marker must be durable before the queued write@@ -795,15 +806,44 @@ class BackgroundTaskExecutor(AsyncExecutor):workflow_run_id=workflow_run_id,browser_session_id=workflow_run.browser_session_id,)- await app.WORKFLOW_SERVICE.mark_workflow_run_as_failed_if_not_final(- workflow_run_id=workflow_run_id,- failure_reason=(- "Sequential credential execution is unavailable in the background executor; "- "the run failed closed before execution."- ),- cascade_children=True,+ failure_reason = (+ "Sequential credential execution is unavailable in the background executor; "+ "the run failed closed before execution.")- if attempt_rows:+ rows_present = bool(attempt_rows)+ if not rows_present:+ try:+ rows_present = not await fail_run_without_attempt_row(+ workflow_run_id, failure_reason, api_key=api_key, cascade_children=True+ )+ except Exception:+ LOG.warning(+ "Failed to fail the rejected run through the attempt-less path; writing the failure directly",+ workflow_run_id=workflow_run_id,+ exc_info=True,+ )+ failed_run = await app.WORKFLOW_SERVICE.mark_workflow_run_as_failed_if_not_final(+ workflow_run_id=workflow_run_id,+ failure_reason=failure_reason,+ cascade_children=True,+ )+ if attempt_rows_known and failed_run is not None:+ try:+ await app.WORKFLOW_SERVICE.execute_workflow_webhook(+ failed_run, api_key=api_key, claim_kind=None+ )+ except Exception:+ LOG.warning(+ "Failed to deliver workflow webhook after rejecting a sequential credential run",+ workflow_run_id=workflow_run_id,+ exc_info=True,+ )+ if rows_present:+ await app.WORKFLOW_SERVICE.mark_workflow_run_as_failed_if_not_final(+ workflow_run_id=workflow_run_id,+ failure_reason=failure_reason,+ cascade_children=True,+ )terminal_run = await app.DATABASE.workflow_runs.get_workflow_run(workflow_run_id=workflow_run_id,organization_id=organization.organization_id,@@ -822,22 +862,6 @@ class BackgroundTaskExecutor(AsyncExecutor):decision,api_key=api_key,)- else:- try:- terminal_run = await app.DATABASE.workflow_runs.get_workflow_run(- workflow_run_id=workflow_run_id,- organization_id=organization.organization_id,- )- if terminal_run is not None:- await app.WORKFLOW_SERVICE.execute_workflow_webhook(- terminal_run, api_key=api_key, claim_kind=None- )- except Exception:- LOG.warning(- "Failed to deliver workflow webhook after rejecting a sequential credential run",- workflow_run_id=workflow_run_id,- exc_info=True,- )raise BackgroundSequentialCredentialUnsupported(workflow_run_id)attempt = next(diff --git a/skyvern/forge/sdk/workflow/retry_policy.py b/skyvern/forge/sdk/workflow/retry_policy.pyindex ccccfd246..d10de8a97 100644--- a/skyvern/forge/sdk/workflow/retry_policy.py+++ b/skyvern/forge/sdk/workflow/retry_policy.py@@ -338,7 +338,12 @@ async def ensure_attempt_row(async def fail_run_without_attempt_row(- workflow_run_id: str, failure_reason: str, *, api_key: str | None = None, need_call_webhook: bool = True+ workflow_run_id: str,+ failure_reason: str,+ *,+ api_key: str | None = None,+ need_call_webhook: bool = True,+ cascade_children: bool = False,) -> bool:"""Fail a queued run that no recovery sweep can see. Returns False when an attempt row exists."""if await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id):@@ -347,6 +352,7 @@ async def fail_run_without_attempt_row(workflow_run = await app.WORKFLOW_SERVICE.mark_workflow_run_as_failed_if_not_final(workflow_run_id=workflow_run_id,failure_reason=failure_reason,+ cascade_children=cascade_children,)except Exception as finalization_error:try:diff --git a/tests/unit/test_background_task_executor.py b/tests/unit/test_background_task_executor.pyindex 111a66883..c37b15ccd 100644--- a/tests/unit/test_background_task_executor.py+++ b/tests/unit/test_background_task_executor.py@@ -2876,7 +2876,8 @@ async def test_execute_workflow_dispatches_from_latest_retry_attempt(monkeypatch@pytest.mark.asyncio@pytest.mark.parametrize("need_call_webhook", [True, False])@pytest.mark.parametrize(- "scenario", ["state_file", "llm_runtime", "lookup_failure", "attempt_row", "webhook_preparation"]+ "scenario",+ ["state_file", "llm_runtime", "lookup_failure", "attempt_row", "webhook_preparation", "transient_recovers"],)async def test_no_policy_initializer_failure_fails_the_run_durably(interim_retry_db: AgentDB, monkeypatch: pytest.MonkeyPatch, scenario: str, need_call_webhook: bool@@ -2906,7 +2907,11 @@ async def test_no_policy_initializer_failure_fails_the_run_durably(monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())initializer = "prepare_org_llm_runtime" if scenario == "llm_runtime" else "initialize_skyvern_state_file"error = RuntimeError(f"{initializer} unavailable")- monkeypatch.setattr(background_task_executor_module, initializer, AsyncMock(side_effect=error))+ monkeypatch.setattr(+ background_task_executor_module,+ initializer,+ AsyncMock(side_effect=[error, None] if scenario == "transient_recovers" else error),+ )execute = AsyncMock()monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)fail_run = AsyncMock(wraps=app.WORKFLOW_SERVICE.mark_workflow_run_as_failed_if_not_final)@@ -2948,8 +2953,41 @@ async def test_no_policy_initializer_failure_fails_the_run_durably(run = await database.workflow_runs.get_workflow_run("wr_retry")assert run is not Noneassert run.started_at is None- attempts = await get_attempts("wr_retry")key = ("wr_retry", 1)+ assert run.status == WorkflowRunStatus.queued+ assert run.failure_reason is None+ fail_run.assert_not_awaited()+ webhook.assert_not_awaited()+ assert key in executor._retry_dispatches_needing_recovery+ assert key in executor._retry_resumes_needing_recovery+ assert executor._initializer_failures[key] == 1++ dispatches = 2 if scenario == "transient_recovers" else background_task_executor_module.INITIALIZER_FAILURE_BUDGET+ for dispatch_number in range(2, dispatches + 1):+ executor._schedule.reset_mock()+ await executor._recover_pending_retries_once(resume_fresh=True)+ executor._schedule.assert_called_once()+ background_tasks, resume, resume_attempt = executor._schedule.call_args.args+ assert background_tasks is None+ assert resume == executor._resume_pending_retry+ assert resume_attempt == attempt+ await resume(resume_attempt)+ if dispatch_number < dispatches:+ run = await database.workflow_runs.get_workflow_run("wr_retry")+ assert run is not None+ assert run.status == WorkflowRunStatus.queued+ assert run.failure_reason is None+ fail_run.assert_not_awaited()+ webhook.assert_not_awaited()+ execute.assert_not_awaited()+ assert key in executor._retry_dispatches_needing_recovery+ assert key in executor._retry_resumes_needing_recovery+ assert executor._initializer_failures[key] == dispatch_number++ run = await database.workflow_runs.get_workflow_run("wr_retry")+ assert run is not None+ assert run.started_at is None+ attempts = await get_attempts("wr_retry")if scenario in {"lookup_failure", "attempt_row"}:assert run.status == WorkflowRunStatus.queuedassert run.failure_reason is None@@ -2957,17 +2995,29 @@ async def test_no_policy_initializer_failure_fails_the_run_durably(webhook.assert_not_awaited()assert key in executor._retry_dispatches_needing_recoveryassert key in executor._retry_resumes_needing_recovery+ assert executor._initializer_failures[key] == background_task_executor_module.INITIALIZER_FAILURE_BUDGET+ execute.assert_not_awaited()if scenario == "attempt_row":assert len(attempts) == 1assert attempts[0].status == "queued"assert attempts[0].started_at is Noneelse:assert not attempts+ elif scenario == "transient_recovers":+ execute.assert_awaited_once()+ assert run.status == WorkflowRunStatus.queued+ assert run.failure_reason is None+ fail_run.assert_not_awaited()+ webhook.assert_not_awaited()+ assert not attempts+ assert not executor._retry_dispatches_needing_recovery+ assert not executor._retry_resumes_needing_recovery+ assert key not in executor._initializer_failureselse:assert run.status == WorkflowRunStatus.failedreason = f"Workflow run initialization failed before execution: RuntimeError: {error}"assert run.failure_reason == reason- fail_run.assert_awaited_once_with(workflow_run_id="wr_retry", failure_reason=reason)+ fail_run.assert_awaited_once_with(workflow_run_id="wr_retry", failure_reason=reason, cascade_children=False)if need_call_webhook:webhook.assert_awaited_once_with(run, api_key="test-dispatch-key", claim_kind=None)else:@@ -2975,6 +3025,7 @@ async def test_no_policy_initializer_failure_fails_the_run_durably(assert not attemptsassert not executor._retry_dispatches_needing_recoveryassert not executor._retry_resumes_needing_recovery+ assert key not in executor._initializer_failuresexecutor._schedule.reset_mock()await executor._recover_pending_retries_once(resume_fresh=True)executor._schedule.assert_not_called()@@ -3048,7 +3099,9 @@ async def test_fail_run_without_attempt_row_finalization_outcomes(else:assert await retry_policy_module.fail_run_without_attempt_row("wr_test", "initialization failed") is Trueget_attempts.assert_awaited_once_with("wr_test")- fail_run.assert_awaited_once_with(workflow_run_id="wr_test", failure_reason="initialization failed")+ fail_run.assert_awaited_once_with(+ workflow_run_id="wr_test", failure_reason="initialization failed", cascade_children=False+ )if scenario in {"duplicate", "delivery_failure"}:reread.assert_not_awaited()else:@@ -3653,9 +3706,21 @@ async def test_scheduled_task_is_retained_until_done() -> None:@pytest.mark.asyncio[email protected]("delivery_case", ["no_attempt_rows", "attempt_rows", "webhook_error"])+ "delivery_case",+ [+ "no_attempt_rows",+ "attempt_rows",+ "webhook_error",+ "lookup_failure",+ "lookup_failure_twice",+ "helper_lookup_failure",+ "helper_lookup_failure_already_final",+ "row_appears",+ ],+)async def test_execute_workflow_fails_closed_for_stamped_sequential_credential(- monkeypatch: pytest.MonkeyPatch, delivery_case: str+ monkeypatch: pytest.MonkeyPatch, delivery_case: str, caplog: pytest.LogCaptureFixture) -> None:workflow_run = SimpleNamespace(sequential_credential_id="cred_sequential", browser_session_id=None)terminal_run = SimpleNamespace(@@ -3672,9 +3737,20 @@ async def test_execute_workflow_fails_closed_for_stamped_sequential_credential(monkeypatch.setattr(app.DATABASE.workflow_run_attempts,"get_attempts",- AsyncMock(return_value=[SimpleNamespace(attempt_number=1)] if delivery_case == "attempt_rows" else []),+ AsyncMock(+ return_value=[SimpleNamespace(attempt_number=1)] if delivery_case == "attempt_rows" else [],+ side_effect={+ "lookup_failure": [RuntimeError("db down"), []],+ "lookup_failure_twice": [RuntimeError("db down"), RuntimeError("db down")],+ "helper_lookup_failure": [[], RuntimeError("db down")],+ "helper_lookup_failure_already_final": [[], RuntimeError("db down")],+ "row_appears": [[], [SimpleNamespace(attempt_number=1)]],+ }.get(delivery_case),+ ),+ )+ mark_failed = AsyncMock(+ return_value=None if delivery_case == "helper_lookup_failure_already_final" else terminal_run)- mark_failed = AsyncMock()monkeypatch.setattr(app.WORKFLOW_SERVICE, "mark_workflow_run_as_failed_if_not_final", mark_failed)decision = RetryDecision(False, 1, 0, True, "sequential_credential_unsupported")finalize = AsyncMock(return_value=decision)@@ -3702,11 +3778,16 @@ async def test_execute_workflow_fails_closed_for_stamped_sequential_credential()executor._schedule.assert_not_called()- mark_failed.assert_awaited_once()- assert mark_failed.await_args.kwargs["workflow_run_id"] == "wr_test"- assert mark_failed.await_args.kwargs["cascade_children"] is True- get_run.assert_awaited_with(workflow_run_id="wr_test", organization_id="org_test")- if delivery_case == "attempt_rows":+ mark_failed.assert_awaited_once_with(+ workflow_run_id="wr_test",+ failure_reason=(+ "Sequential credential execution is unavailable in the background executor; "+ "the run failed closed before execution."+ ),+ cascade_children=True,+ )+ if delivery_case in {"attempt_rows", "row_appears"}:+ get_run.assert_awaited_with(workflow_run_id="wr_test", organization_id="org_test")finalize.assert_awaited_once_with(workflow_run_id="wr_test",organization_id="org_test",@@ -3718,9 +3799,16 @@ async def test_execute_workflow_fails_closed_for_stamped_sequential_credential(release.assert_awaited_once_with(terminal_run, decision, api_key="test-api-key")webhook.assert_not_awaited()else:- webhook.assert_awaited_once_with(terminal_run, api_key="test-api-key", claim_kind=None)+ if delivery_case in {"lookup_failure_twice", "helper_lookup_failure_already_final"}:+ webhook.assert_not_awaited()+ else:+ webhook.assert_awaited_once_with(terminal_run, api_key="test-api-key", claim_kind=None)release.assert_not_awaited()finalize.assert_not_awaited()+ if delivery_case in {"lookup_failure_twice", "helper_lookup_failure", "helper_lookup_failure_already_final"}:+ assert (+ "Failed to fail the rejected run through the attempt-less path; writing the failure directly" in caplog.text+ )@pytest.mark.asynciodiff --git a/tests/unit/test_workflow_schedule_service.py b/tests/unit/test_workflow_schedule_service.pyindex ad3938511..aa1ff5e20 100644--- a/tests/unit/test_workflow_schedule_service.py+++ b/tests/unit/test_workflow_schedule_service.py@@ -211,6 +211,7 @@ async def test_run_schedule_no_policy_initializer_failure_fails_the_run(fail_run.assert_awaited_once_with(workflow_run_id=run_id,failure_reason=f"Workflow run initialization failed before execution: RuntimeError: {error}",+ cascade_children=False,)webhook.assert_awaited_once_with(failed_run, api_key=None, claim_kind=None)get_attempts.assert_awaited_once_with(run_id)