Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-12153): address codex review on fallback credentials (follow-up to #13599) (#7528)
Aaron Perez844cc3b74b16
diff --git a/skyvern-frontend/src/routes/workflows/RunWorkflowForm.tsx b/skyvern-frontend/src/routes/workflows/RunWorkflowForm.tsxindex cd8a321d8..012cc414b 100644--- a/skyvern-frontend/src/routes/workflows/RunWorkflowForm.tsx+++ b/skyvern-frontend/src/routes/workflows/RunWorkflowForm.tsx@@ -51,6 +51,8 @@ import { useWorkflowStudioEnabled } from "@/hooks/useWorkflowStudioEnabled";import { workflowEditorPath } from "./studioNavigation";import { CredentialSetupPrompt } from "@/components/onboarding/CredentialSetupPrompt";import { useFeatureFlagVariantKey } from "posthog-js/react";+import { useFeatureFlag } from "@/hooks/useFeatureFlag";+import { CREDENTIAL_FALLBACK_RETRY_FLAG } from "@/util/featureFlags";import { EXPERIMENT } from "@/util/onboarding/experimentConfig";import { isActivationRun } from "@/util/onboarding/rolloutGating";import { useOnboardingStateOptional } from "@/store/onboarding/useOnboardingState";@@ -461,6 +463,8 @@ function RunWorkflowForm({);const hasLoginBlockValidationError = loginBlocksWithoutCredentials.length > 0;const onboarding = useOnboardingStateOptional();+ const credentialFallbackRetryEnabled =+ useFeatureFlag(CREDENTIAL_FALLBACK_RETRY_FLAG) ?? false;const onboardingFlagVariant = useFeatureFlagVariantKey(EXPERIMENT.flagKey);const onboardingLoading = onboarding != null && onboarding.isLoading;// Gate on the rollout arm so a 0% rollout / rollback restores the@@ -821,7 +825,14 @@ function RunWorkflowForm({parameter,loginBlockLabels,);- const hasFallbacks = fallbackCredentialIds.length > 0;+ // Only surface fallbacks (and the "retries automatically" promise) for orgs in the+ // rollout; the backend retry gate is keyed on the same flag.+ const hasFallbacks =+ credentialFallbackRetryEnabled &&+ fallbackCredentialIds.length > 0;+ const displayedFallbackCredentialIds = hasFallbacks+ ? fallbackCredentialIds+ : [];if (parameter.parameter_type === WorkflowParameterTypes.Workflow@@ -914,7 +925,7 @@ function RunWorkflowForm({)}</div><FallbackCredentialList- fallbackCredentialIds={fallbackCredentialIds}+ fallbackCredentialIds={displayedFallbackCredentialIds}fallbackTrigger={fallbackTrigger}credentialNamesById={credentialNamesById}/>@@ -942,7 +953,7 @@ function RunWorkflowForm({showPrimaryBadge={hasFallbacks}fallbackContent={<FallbackCredentialList- fallbackCredentialIds={fallbackCredentialIds}+ fallbackCredentialIds={displayedFallbackCredentialIds}fallbackTrigger={fallbackTrigger}credentialNamesById={credentialNamesById}/>diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginBlockCredentialSelector.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginBlockCredentialSelector.test.tsxindex 054e04eab..cd4e8c705 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginBlockCredentialSelector.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginBlockCredentialSelector.test.tsx@@ -12,6 +12,8 @@ import {import type { CredentialApiResponse } from "@/api/types";import CloudContext from "@/store/CloudContext";+import { FeatureFlagContext } from "@/hooks/useFeatureFlag";+import { CREDENTIAL_FALLBACK_RETRY_FLAG } from "@/util/featureFlags";import { useWorkflowParametersStore } from "@/store/WorkflowParametersStore";import { LoginBlockCredentialSelector } from "./LoginBlockCredentialSelector";@@ -102,9 +104,19 @@ function credential(} as CredentialApiResponse;}-function renderInCloud(children: ReactNode) {+function renderInCloud(children: ReactNode, fallbackRetryEnabled = true) {return render(- <CloudContext.Provider value={true}>{children}</CloudContext.Provider>,+ <CloudContext.Provider value={true}>+ <FeatureFlagContext.Provider+ value={(flag) =>+ flag === CREDENTIAL_FALLBACK_RETRY_FLAG+ ? fallbackRetryEnabled+ : undefined+ }+ >+ {children}+ </FeatureFlagContext.Provider>+ </CloudContext.Provider>,);}@@ -285,6 +297,19 @@ describe("LoginBlockCredentialSelector fallback picker", () => {await screen.findByPlaceholderText("Search credentials...");}+ it("hides the fallback editor when CREDENTIAL_FALLBACK_RETRY is disabled", () => {+ renderInCloud(+ <LoginBlockCredentialSelector+ nodeId="node-1"+ value="portal_credential"+ />,+ false,+ );++ // Orgs outside the retry rollout must not be able to configure a fallback that never runs.+ expect(screen.queryByText("Add fallback credentials")).toBeNull();+ });+it("hides fallback controls when credential rotation is configured", () => {useWorkflowParametersStore.setState({parameters: [diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginBlockCredentialSelector.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginBlockCredentialSelector.tsxindex e2de6b242..7f286eff1 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginBlockCredentialSelector.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginBlockCredentialSelector.tsx@@ -23,6 +23,8 @@ import { Skeleton } from "@/components/ui/skeleton";import { Switch } from "@/components/ui/switch";import { useCredentialsQuery } from "@/routes/workflows/hooks/useCredentialsQuery";import { useSkyvernCredentialSourceAvailable } from "@/routes/workflows/hooks/useSkyvernCredentialSourceAvailable";+import { useFeatureFlag } from "@/hooks/useFeatureFlag";+import { CREDENTIAL_FALLBACK_RETRY_FLAG } from "@/util/featureFlags";import { useEffect, useMemo, useState } from "react";import { useWorkflowHasChangesStore } from "@/store/WorkflowHasChangesStore";import { useWorkflowParametersStore } from "@/store/WorkflowParametersStore";@@ -184,6 +186,8 @@ function LoginBlockCredentialSelector({const [rotationQuery, setRotationQuery] = useState("");const [debouncedRotationQuery] = useDebounce(rotationQuery, 300);const [fallbackDraft, setFallbackDraft] = useState(false);+ const credentialFallbackRetryEnabled =+ useFeatureFlag(CREDENTIAL_FALLBACK_RETRY_FLAG) ?? false;const {parameters: workflowParameters,setParameters: setWorkflowParameters,@@ -723,7 +727,11 @@ function LoginBlockCredentialSelector({selectedSkyvernCredentialParameter?.fallbackTrigger ??DEFAULT_FALLBACK_TRIGGER;- const fallbackSection = selectedSkyvernCredentialParameter ? (+ const fallbackConfigVisible =+ credentialFallbackRetryEnabled &&+ Boolean(selectedSkyvernCredentialParameter);++ const fallbackSection = fallbackConfigVisible ? (fallbackMode ? (<div className="mt-3 space-y-2 border-t border-border pt-3"><div className="space-y-1">diff --git a/skyvern-frontend/src/util/featureFlags.ts b/skyvern-frontend/src/util/featureFlags.tsindex 90c399b42..88ac03476 100644--- a/skyvern-frontend/src/util/featureFlags.ts+++ b/skyvern-frontend/src/util/featureFlags.ts@@ -33,3 +33,9 @@ export const COPILOT_UX_V1_FLAG = "copilot_ux_v1";// (run metadata / workflow tag). Off ⇒ the dashboard renders as today with no// group-by control. See cloud_docs/analytics/GROUP_BY_LENS_DESIGN.md.export const ANALYTICS_GROUP_BY_LENS_FLAG = "ANALYTICS_GROUP_BY_LENS";++// Gates the login-block fallback-credential editor. Off ⇒ the fallback config is hidden, because+// automatic retries only run for orgs in the CREDENTIAL_FALLBACK_RETRY rollout (backend gate), so+// showing the editor to other orgs would promise a retry that never fires. Server-evaluated via+// /customer (see FeatureFlagProvider), keyed on organization_id like the backend gate.+export const CREDENTIAL_FALLBACK_RETRY_FLAG = "CREDENTIAL_FALLBACK_RETRY";diff --git a/skyvern/forge/sdk/workflow/credential_fallback.py b/skyvern/forge/sdk/workflow/credential_fallback.pyindex c7d5b8f5d..41103c407 100644--- a/skyvern/forge/sdk/workflow/credential_fallback.py+++ b/skyvern/forge/sdk/workflow/credential_fallback.py@@ -9,6 +9,7 @@ from skyvern.forge.failure_classifier import classify_from_failure_reasonfrom skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.forge.sdk.workflow.models.parameter import CredentialParameter+from skyvern.forge.sdk.workflow.models.validators import is_reserved_tag_keyfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRun, WorkflowRunStatusLOG = structlog.get_logger()@@ -18,6 +19,9 @@ ANY_FAILURE = "any_failure"VALID_FALLBACK_TRIGGERS = frozenset({CREDENTIAL_FAILURES, ANY_FAILURE})CREDENTIAL_FAILURE_CATEGORIES = frozenset({"AUTH_FAILURE", "CREDENTIAL_ERROR"})CREDENTIAL_FALLBACK_RETRY_FLAG = "CREDENTIAL_FALLBACK_RETRY"+# Terminal statuses that any fallback trigger may retry from. timed_out counts because it is a+# failure elsewhere; credential_failures narrows further to failed/terminated in _trigger_matches.+RETRYABLE_STATUSES = frozenset({WorkflowRunStatus.failed, WorkflowRunStatus.terminated, WorkflowRunStatus.timed_out})async def _retry_enabled_for_organization(organization_id: str, workflow_run: WorkflowRun) -> bool:@@ -64,16 +68,37 @@ def _failure_category_names(workflow_run: WorkflowRun) -> set[str]:def _trigger_matches(workflow_run: WorkflowRun, trigger: str | None) -> bool:- if workflow_run.status not in {WorkflowRunStatus.failed, WorkflowRunStatus.terminated}:- return Falseeffective_trigger = trigger or CREDENTIAL_FAILURESif effective_trigger == ANY_FAILURE:- return True+ return workflow_run.status in RETRYABLE_STATUSESif effective_trigger != CREDENTIAL_FAILURES:return False+ # A timeout is not a credential failure, so credential_failures keeps rejecting timed_out.+ if workflow_run.status not in {WorkflowRunStatus.failed, WorkflowRunStatus.terminated}:+ return Falsereturn bool(_failure_category_names(workflow_run) & CREDENTIAL_FAILURE_CATEGORIES)+async def _reload_user_run_metadata(workflow_run: WorkflowRun, organization_id: str) -> dict[str, str] | None:+ """Reload the failed run's user-writable tags so the retry keeps them (matches the manual+ retry path in agent_protocol). Reserved keys are dropped — they are re-derived per run."""+ try:+ grouped = await app.DATABASE.tags.get_active_grouped_tags_for_run(+ workflow_run_id=workflow_run.workflow_run_id,+ organization_id=organization_id,+ )+ except Exception:+ LOG.warning(+ "Failed to reload run metadata for fallback retry; continuing without it",+ workflow_run_id=workflow_run.workflow_run_id,+ exc_info=True,+ )+ return None+ if not grouped:+ return None+ return {key: value for key, value in grouped.items() if not is_reserved_tag_key(key)} or None++async def maybe_start_credential_fallback_retry(workflow_run: WorkflowRun, organization_id: str) -> str | None:try:return await _maybe_start_credential_fallback_retry(workflow_run, organization_id)@@ -88,7 +113,16 @@ async def maybe_start_credential_fallback_retry(workflow_run: WorkflowRun, organasync def _maybe_start_credential_fallback_retry(workflow_run: WorkflowRun, organization_id: str) -> str | None:- if workflow_run.parent_workflow_run_id or workflow_run.debug_session_id:+ # Scheduled from clean_up_workflow, which runs for every terminal status. Bail on non-failure+ # runs before the flag check and DB reads so the success path stays cheap. _trigger_matches+ # below still applies the finer per-parameter trigger (credential_failures vs any_failure).+ if workflow_run.status not in RETRYABLE_STATUSES:+ return None++ # copilot_session_id marks a Copilot-scoped test run: it supplies block_labels directly without+ # the debug block-run marker checked below, so guard on it too or a Copilot test would spawn a+ # detached full-workflow run (real credits, real side effects) outside the test.+ if workflow_run.parent_workflow_run_id or workflow_run.debug_session_id or workflow_run.copilot_session_id:return Noneif not await _retry_enabled_for_organization(organization_id, workflow_run):@@ -205,12 +239,18 @@ async def _maybe_start_credential_fallback_retry(workflow_run: WorkflowRun, orgafrom skyvern.services.workflow_service import run_workflow, workflow_request_body_from_existing_run+ run_metadata = await _reload_user_run_metadata(workflow_run, organization_id)workflow_request = workflow_request_body_from_existing_run(workflow_run=workflow_run,parameters=retry_parameters,+ run_metadata=run_metadata,)+ # Shed every handle to the failed run's browser so the fallback credential gets a clean session+ # instead of reconnecting to the old account's cookies/authenticated state.workflow_request.browser_session_id = Noneworkflow_request.browser_profile_id = None+ workflow_request.browser_address = None+ workflow_request.cdp_connect_headers = Noneworkflow_request.extra_http_headers = app.AGENT_FUNCTION.strip_proxy_session_extra_http_headers(workflow_request.extra_http_headers)diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 92a34b7b8..d2eb87c1e 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -1344,6 +1344,7 @@ class WorkflowService:workflow_run: WorkflowRun,organization_id: str,credential_parameter_overrides: dict[str, str] | None = None,+ parameter_values: dict[str, Any] | None = None,) -> dict[str, str]:selections = dict(credential_parameter_overrides or {})try:@@ -1361,6 +1362,23 @@ class WorkflowService:credential_ids=credential_ids,selection_strategy=parameter.selection_strategy,)+ for parameter in self._get_credential_parameters_with_configured_selection(workflow):+ # Fallback-only parameters have no rotation pool, so the loop above skips them, but a+ # browser_profile_key referencing this login parameter still needs a render value.+ # The initial run pins the primary credential; a fallback retry overrides it above.+ if parameter.key in selections or parameter.credential_ids:+ continue+ primary = parameter.credential_id+ if not primary:+ continue+ # credential_id may indirectly reference another workflow parameter that carries the+ # real credential value (mirrors WorkflowRunContext.resolve_credential_parameter_id).+ # Render the resolved value so distinct accounts get distinct browser profiles.+ if parameter_values:+ referenced = parameter_values.get(primary)+ if isinstance(referenced, str) and referenced:+ primary = referenced+ selections[parameter.key] = primaryreturn selectionsexcept Exception:LOG.warning(@@ -1491,14 +1509,19 @@ class WorkflowService:workflow_request.webhook_callback_url = workflow.webhook_callback_urlif workflow_request.extra_http_headers is None and workflow.extra_http_headers is not None:workflow_request.extra_http_headers = workflow.extra_http_headers+ # A credential-fallback retry clears the browser handles so the replacement credential+ # gets a clean session; re-inheriting the workflow's profile/cdp headers here would+ # reconnect the retry to the failed account's persistent-browser-session profile.+ is_fallback_retry = retried_from_workflow_run_id is not Noneif (- workflow_request.browser_profile_id is None+ not is_fallback_retry+ and workflow_request.browser_profile_id is Noneand workflow_request.browser_session_id is Noneand workflow.browser_profile_id is not None):workflow_request.browser_profile_id = workflow.browser_profile_idif workflow_request.cdp_connect_headers is None:- if workflow.cdp_connect_headers is not None:+ if not is_fallback_retry and workflow.cdp_connect_headers is not None:workflow_request.cdp_connect_headers = workflow.cdp_connect_headerselse:workflow_request.cdp_connect_headers = merge_masked_headers(@@ -1715,6 +1738,7 @@ class WorkflowService:workflow_run=workflow_run,organization_id=organization.organization_id,credential_parameter_overrides=run_credential_parameter_overrides,+ parameter_values=parameter_values,)parameter_values.update(rotating_credential_selections)workflow_run = await self._prepare_persisted_workflow_browser_profile(@@ -1944,6 +1968,18 @@ class WorkflowService:if should_pin:raise+ @staticmethod+ def _profile_key_render_values(workflow: Workflow, workflow_request: WorkflowRequestBody) -> dict[str, Any]:+ """Workflow-parameter values used to render browser_profile_key at run-request time:+ workflow defaults overlaid with the request's provided values."""+ values: dict[str, Any] = {}+ for parameter in workflow.workflow_definition.parameters:+ if isinstance(parameter, WorkflowParameter) and parameter.default_value is not None:+ values[parameter.key] = parameter.default_value+ if workflow_request.data:+ values.update({key: value for key, value in workflow_request.data.items() if value is not None})+ return values+async def _resolve_managed_browser_profile_for_run_request(self,*,@@ -1959,14 +1995,7 @@ class WorkflowService:rendered_key = Noneif workflow.browser_profile_key:- parameter_values: dict[str, Any] = {}- for parameter in workflow.workflow_definition.parameters:- if isinstance(parameter, WorkflowParameter) and parameter.default_value is not None:- parameter_values[parameter.key] = parameter.default_value- if workflow_request.data:- parameter_values.update(- {key: value for key, value in workflow_request.data.items() if value is not None}- )+ parameter_values = self._profile_key_render_values(workflow, workflow_request)if extra_parameter_values:parameter_values.update(extra_parameter_values)rendered_key = render_browser_profile_key(workflow.browser_profile_key, parameter_values)@@ -6085,6 +6114,7 @@ class WorkflowService:workflow_run=workflow_run,organization_id=organization_id,credential_parameter_overrides=run_credential_parameter_overrides,+ parameter_values=self._profile_key_render_values(workflow, workflow_request),)forced_browser_profile_id = await self._resolve_managed_browser_profile_for_run_request(workflow=workflow,@@ -6399,7 +6429,6 @@ class WorkflowService:run_with=run_with,failure_category=failure_category,)- self._schedule_credential_fallback_retry(workflow_run)return workflow_runasync def mark_workflow_run_as_running(self, workflow_run_id: str, run_with: str | None = None) -> WorkflowRun:@@ -6487,7 +6516,6 @@ class WorkflowService:run_with=run_with,failure_category=failure_category,)- self._schedule_credential_fallback_retry(workflow_run)return workflow_runasync def mark_workflow_run_as_canceled(self, workflow_run_id: str) -> WorkflowRun:@@ -7365,69 +7393,69 @@ class WorkflowService:all_workflow_task_ids = browser_cleanup_result.all_workflow_task_idschild_workflow_run_ids = browser_cleanup_result.child_workflow_run_idsclose_browser_on_completion = browser_cleanup_result.close_browser_on_completion- if browser_state:- await self.persist_video_data(- browser_state, workflow, workflow_run, close_browser_on_completion=close_browser_on_completion- )- if tasks:- await self.persist_debug_artifacts(browser_state, tasks[-1], workflow, workflow_run)- if not browser_cleanup_result.browser_session_write_back_attempted:- await self._persist_workflow_browser_session_if_needed(- workflow=workflow,- workflow_run=workflow_run,- browser_state=browser_state,- close_browser_on_completion=close_browser_on_completion,+ try:+ if browser_state:+ await self.persist_video_data(+ browser_state, workflow, workflow_run, close_browser_on_completion=close_browser_on_completion)+ if tasks:+ await self.persist_debug_artifacts(browser_state, tasks[-1], workflow, workflow_run)+ if not browser_cleanup_result.browser_session_write_back_attempted:+ await self._persist_workflow_browser_session_if_needed(+ workflow=workflow,+ workflow_run=workflow_run,+ browser_state=browser_state,+ close_browser_on_completion=close_browser_on_completion,+ )- await app.ARTIFACT_MANAGER.wait_for_upload_aiotasks(all_workflow_task_ids)+ await app.ARTIFACT_MANAGER.wait_for_upload_aiotasks(all_workflow_task_ids)- try:- async with asyncio.timeout(SAVE_DOWNLOADED_FILES_TIMEOUT):- context = skyvern_context.current()- finalization_run_id = context.run_id if context and context.run_id else workflow_run.workflow_run_id- await app.STORAGE.save_downloaded_files(- organization_id=workflow_run.organization_id,- run_id=finalization_run_id,- )- # Tag any session-scoped DOWNLOAD artifacts created during this- # workflow run with run_id (see- # cloud_docs/BROWSER_SESSION_DOWNLOAD_ARTIFACTS.md).- browser_session_id = context.browser_session_id if context else None- if browser_session_id and finalization_run_id:- try:- claimed = await app.DATABASE.artifacts.claim_session_download_artifacts_for_run(- run_id=finalization_run_id,- browser_session_id=browser_session_id,- organization_id=workflow_run.organization_id,- run_started_at=workflow_run.created_at,- )- if claimed:- LOG.debug(- "Claimed session-scoped download artifacts for workflow run",+ try:+ async with asyncio.timeout(SAVE_DOWNLOADED_FILES_TIMEOUT):+ context = skyvern_context.current()+ finalization_run_id = context.run_id if context and context.run_id else workflow_run.workflow_run_id+ await app.STORAGE.save_downloaded_files(+ organization_id=workflow_run.organization_id,+ run_id=finalization_run_id,+ )+ # Tag any session-scoped DOWNLOAD artifacts created during this+ # workflow run with run_id (see+ # cloud_docs/BROWSER_SESSION_DOWNLOAD_ARTIFACTS.md).+ browser_session_id = context.browser_session_id if context else None+ if browser_session_id and finalization_run_id:+ try:+ claimed = await app.DATABASE.artifacts.claim_session_download_artifacts_for_run(+ run_id=finalization_run_id,+ browser_session_id=browser_session_id,+ organization_id=workflow_run.organization_id,+ run_started_at=workflow_run.created_at,+ )+ if claimed:+ LOG.debug(+ "Claimed session-scoped download artifacts for workflow run",+ workflow_run_id=workflow_run.workflow_run_id,+ browser_session_id=browser_session_id,+ claimed=claimed,+ )+ except Exception:+ LOG.warning(+ "Failed to claim session-scoped download artifacts for workflow run",workflow_run_id=workflow_run.workflow_run_id,browser_session_id=browser_session_id,- claimed=claimed,+ exc_info=True,)- except Exception:- LOG.warning(- "Failed to claim session-scoped download artifacts for workflow run",- workflow_run_id=workflow_run.workflow_run_id,- browser_session_id=browser_session_id,- exc_info=True,- )- except asyncio.TimeoutError:- LOG.warning(- "Timeout to save downloaded files",- workflow_run_id=workflow_run.workflow_run_id,- )- except Exception:- LOG.warning(- "Failed to save downloaded files",- exc_info=True,- workflow_run_id=workflow_run.workflow_run_id,- )+ except asyncio.TimeoutError:+ LOG.warning(+ "Timeout to save downloaded files",+ workflow_run_id=workflow_run.workflow_run_id,+ )+ except Exception:+ LOG.warning(+ "Failed to save downloaded files",+ exc_info=True,+ workflow_run_id=workflow_run.workflow_run_id,+ )- try:if need_call_webhook:await self.execute_workflow_webhook(workflow_run, api_key)finally:@@ -7437,6 +7465,14 @@ class WorkflowService:for child_workflow_run_id in child_workflow_run_ids:app.WORKFLOW_CONTEXT_MANAGER.remove_workflow_run_context(child_workflow_run_id)+ # Schedule the credential fallback retry only after this run's cleanup (artifact/video+ # persistence, browser/session write-back, webhook) has run, so the replacement run+ # cannot overlap it and race browser-profile/session writes. In the finally wrapping the+ # whole cleanup sequence — not after it — so an exception in any cleanup step can't skip+ # it; scheduling was removed from the status markers, which fired before cleanup and for+ # cascade/reaper failures that never reach cleanup. A no-op for non-eligible runs.+ self._schedule_credential_fallback_retry(workflow_run)+async def prepare_workflow_webhook(self,workflow_run: WorkflowRun,diff --git a/tests/unit/test_credential_fallback.py b/tests/unit/test_credential_fallback.pyindex 0cc180389..8d19986b8 100644--- a/tests/unit/test_credential_fallback.py+++ b/tests/unit/test_credential_fallback.py@@ -59,8 +59,11 @@ def _workflow_run(retried_from_workflow_run_id: str | None = None,browser_session_id: str | None = None,browser_profile_id: str | None = None,+ browser_address: str | None = None,+ cdp_connect_headers: dict[str, str] | None = None,extra_http_headers: dict[str, str] | None = None,workflow_schedule_id: str | None = None,+ copilot_session_id: str | None = None,) -> WorkflowRun:now = datetime.now(timezone.utc)return WorkflowRun(@@ -77,8 +80,11 @@ def _workflow_run(retried_from_workflow_run_id=retried_from_workflow_run_id,browser_session_id=browser_session_id,browser_profile_id=browser_profile_id,+ browser_address=browser_address,+ cdp_connect_headers=cdp_connect_headers,extra_http_headers=extra_http_headers,workflow_schedule_id=workflow_schedule_id,+ copilot_session_id=copilot_session_id,trigger_type=WorkflowRunTriggerType.api,created_at=now,modified_at=now,@@ -222,20 +228,31 @@ def test_credential_failure_trigger_falls_back_to_failure_reason_classification(assert _trigger_matches(workflow_run, CREDENTIAL_FAILURES)[email protected]("status", [WorkflowRunStatus.failed, WorkflowRunStatus.terminated])-def test_any_failure_trigger_matches_failed_and_terminated_runs(status: WorkflowRunStatus) -> None:+ "status",+ [WorkflowRunStatus.failed, WorkflowRunStatus.terminated, WorkflowRunStatus.timed_out],+)+def test_any_failure_trigger_matches_failed_terminated_and_timed_out_runs(status: WorkflowRunStatus) -> None:workflow_run = _workflow_run(status=status, failure_category=[{"category": "ELEMENT_NOT_FOUND"}])assert _trigger_matches(workflow_run, ANY_FAILURE)+def test_credential_failures_trigger_ignores_timed_out_runs() -> None:+ workflow_run = _workflow_run(status=WorkflowRunStatus.timed_out, failure_category=[{"category": "AUTH_FAILURE"}])++ assert not _trigger_matches(workflow_run, CREDENTIAL_FAILURES)++PROXY_SESSION_MARKER_HEADER = "x-proxy-session-marker"def _strip_marker_header(extra_http_headers: dict[str, str] | None) -> dict[str, str] | None:if not extra_http_headers:return extra_http_headers- return {key: value for key, value in extra_http_headers.items() if key != PROXY_SESSION_MARKER_HEADER} or None+ # Mirror the cloud strip contract: return the (possibly empty) mapping, never None, so+ # setup_workflow_run does not re-inherit the workflow's proxy headers.+ return {key: value for key, value in extra_http_headers.items() if key != PROXY_SESSION_MARKER_HEADER}async def _run_fallback_retry(@@ -250,6 +267,7 @@ async def _run_fallback_retry(run_workflow_error: Exception | None = None,flag_enabled: bool = True,flag_error: Exception | None = None,+ run_tags: dict[str, str] | None = None,) -> tuple[str | None, AsyncMock, MagicMock]:captured: dict[str, object] = {}@@ -306,6 +324,7 @@ async def _run_fallback_retry(mock_app.DATABASE.organizations.get_organization = AsyncMock(return_value=SimpleNamespace(organization_id="org_test"))+ mock_app.DATABASE.tags.get_active_grouped_tags_for_run = AsyncMock(return_value=run_tags)result = await maybe_start_credential_fallback_retry(workflow_run, "org_test")return result, run_workflow_mock, mock_app@@ -509,6 +528,107 @@ async def test_retry_request_strips_credential_proxy_session_headers() -> None:assert run_workflow_mock.await_args.kwargs["workflow_request"].extra_http_headers == {"x-custom": "keep"}+async def test_retry_request_strips_headers_leaving_empty_mapping_not_none() -> None:+ # When the failed run's only header was the proxy-session marker, the strip must yield an empty+ # mapping (not None): setup_workflow_run treats None as "unset" and would re-inherit the+ # workflow's configured proxy header, defeating the strip.+ workflow_run = _workflow_run(+ failure_category=[{"category": "AUTH_FAILURE"}],+ extra_http_headers={PROXY_SESSION_MARKER_HEADER: "proxy_sess_1"},+ )+ login = _credential_parameter(fallback_credential_ids=["cred_fb1"])++ result, run_workflow_mock, _ = await _run_fallback_retry(workflow_run=workflow_run, parameters=[login])++ assert result == "wr_retry"+ assert run_workflow_mock.await_args.kwargs["workflow_request"].extra_http_headers == {}+++async def test_retry_clears_browser_address_and_cdp_headers() -> None:+ workflow_run = _workflow_run(+ failure_category=[{"category": "AUTH_FAILURE"}],+ browser_address="http://remote-cdp:9222",+ cdp_connect_headers={"authorization": "Bearer stale"},+ )+ login = _credential_parameter(fallback_credential_ids=["cred_fb1"])++ result, run_workflow_mock, _ = await _run_fallback_retry(workflow_run=workflow_run, parameters=[login])++ assert result == "wr_retry"+ request = run_workflow_mock.await_args.kwargs["workflow_request"]+ assert request.browser_address is None+ assert request.cdp_connect_headers is None+++async def test_retry_preserves_user_run_metadata() -> None:+ workflow_run = _workflow_run(failure_category=[{"category": "AUTH_FAILURE"}])+ login = _credential_parameter(fallback_credential_ids=["cred_fb1"])++ result, run_workflow_mock, _ = await _run_fallback_retry(+ workflow_run=workflow_run,+ parameters=[login],+ run_tags={"team": "growth", "env": "prod"},+ )++ assert result == "wr_retry"+ assert run_workflow_mock.await_args.kwargs["workflow_request"].run_metadata == {"team": "growth", "env": "prod"}+++async def test_completed_run_bails_before_flag_check_and_db_reads() -> None:+ # clean_up_workflow calls the hook for every run; a non-failure run must exit before touching+ # the flag provider or the database.+ workflow_run = _workflow_run(status=WorkflowRunStatus.completed, failure_category=None, failure_reason=None)+ login = _credential_parameter(fallback_credential_ids=["cred_fb1"])++ result, run_workflow_mock, mock_app = await _run_fallback_retry(workflow_run=workflow_run, parameters=[login])++ assert result is None+ run_workflow_mock.assert_not_awaited()+ mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached.assert_not_awaited()+ mock_app.WORKFLOW_SERVICE.get_workflow.assert_not_awaited()+++async def test_copilot_scoped_run_does_not_retry() -> None:+ workflow_run = _workflow_run(+ failure_category=[{"category": "AUTH_FAILURE"}],+ copilot_session_id="cs_1",+ )+ login = _credential_parameter(fallback_credential_ids=["cred_fb1"])++ result, run_workflow_mock, _ = await _run_fallback_retry(workflow_run=workflow_run, parameters=[login])++ assert result is None+ run_workflow_mock.assert_not_awaited()+++async def test_timed_out_run_with_any_failure_trigger_starts_retry() -> None:+ workflow_run = _workflow_run(status=WorkflowRunStatus.timed_out, failure_category=None)+ login = _credential_parameter(fallback_credential_ids=["cred_fb1"], fallback_trigger=ANY_FAILURE)++ result, run_workflow_mock, _ = await _run_fallback_retry(workflow_run=workflow_run, parameters=[login])++ assert result == "wr_retry"+ assert run_workflow_mock.await_args.kwargs["workflow_request"].data["login_cred"] == "cred_fb1"+++async def test_timed_out_run_with_credential_failures_trigger_does_not_retry() -> None:+ # A timeout is not a credential failure, so the default trigger must not advance the credential.+ workflow_run = _workflow_run(status=WorkflowRunStatus.timed_out, failure_category=None)+ login = _credential_parameter(fallback_credential_ids=["cred_fb1"], fallback_trigger=CREDENTIAL_FAILURES)++ result, run_workflow_mock, _ = await _run_fallback_retry(workflow_run=workflow_run, parameters=[login])++ assert result is None+ run_workflow_mock.assert_not_awaited()++@pytest.mark.asyncioasync def test_retry_run_creation_does_not_inherit_ambient_skyvern_context() -> None:workflow_run = _workflow_run(failure_category=[{"category": "AUTH_FAILURE"}])@@ -720,7 +840,9 @@ def test_yaml_to_credential_parameter_round_trip_preserves_fallback_fields() ->@pytest.mark.asyncio-async def test_mark_workflow_run_as_failed_invokes_fallback_hook() -> None:+async def test_mark_workflow_run_as_failed_does_not_schedule_before_cleanup() -> None:+ # The retry must be scheduled from clean_up_workflow (after finally/cleanup), never from the+ # status marker — scheduling here would let the replacement run overlap the failed run's cleanup.service = WorkflowService()workflow_run = _workflow_run(failure_category=[{"category": "AUTH_FAILURE"}])service._update_workflow_run_status = AsyncMock(return_value=workflow_run) # type: ignore[method-assign]@@ -733,11 +855,11 @@ async def test_mark_workflow_run_as_failed_invokes_fallback_hook() -> None:)assert result == workflow_run- service._schedule_credential_fallback_retry.assert_called_once_with(workflow_run)+ service._schedule_credential_fallback_retry.assert_not_called()@pytest.mark.asyncio-async def test_mark_workflow_run_as_terminated_invokes_fallback_hook() -> None:+async def test_mark_workflow_run_as_terminated_does_not_schedule_before_cleanup() -> None:service = WorkflowService()workflow_run = _workflow_run(status=WorkflowRunStatus.terminated,@@ -753,6 +875,115 @@ async def test_mark_workflow_run_as_terminated_invokes_fallback_hook() -> None:)assert result == workflow_run+ service._schedule_credential_fallback_retry.assert_not_called()+++async def test_clean_up_workflow_schedules_credential_fallback_retry() -> None:+ service = WorkflowService()+ workflow_run = _workflow_run(failure_category=[{"category": "AUTH_FAILURE"}])+ workflow = _workflow([])+ service._schedule_credential_fallback_retry = MagicMock() # type: ignore[method-assign]+ browser_cleanup_result = SimpleNamespace(+ browser_state=None,+ tasks=[],+ all_workflow_task_ids=[],+ child_workflow_run_ids=[],+ close_browser_on_completion=True,+ browser_session_write_back_attempted=True,+ )++ with (+ patch("skyvern.forge.sdk.workflow.service.app") as mock_app,+ patch("skyvern.forge.sdk.workflow.service.analytics") as mock_analytics,+ ):+ mock_analytics.capture = MagicMock()+ mock_app.ARTIFACT_MANAGER.wait_for_upload_aiotasks = AsyncMock()+ mock_app.STORAGE.save_downloaded_files = AsyncMock()+ mock_app.WORKFLOW_CONTEXT_MANAGER.remove_workflow_run_context = MagicMock()++ await service.clean_up_workflow(+ workflow=workflow,+ workflow_run=workflow_run,+ need_call_webhook=False,+ browser_cleanup_result=browser_cleanup_result, # type: ignore[arg-type]+ )++ service._schedule_credential_fallback_retry.assert_called_once_with(workflow_run)+++async def test_clean_up_workflow_schedules_retry_even_when_webhook_raises() -> None:+ # The schedule lives in the finally block: a webhook-preparation failure must not swallow the+ # fallback retry (scheduling was removed from the status markers).+ service = WorkflowService()+ workflow_run = _workflow_run(failure_category=[{"category": "AUTH_FAILURE"}])+ workflow = _workflow([])+ service._schedule_credential_fallback_retry = MagicMock() # type: ignore[method-assign]+ service.execute_workflow_webhook = AsyncMock(side_effect=RuntimeError("webhook prep failed")) # type: ignore[method-assign]+ browser_cleanup_result = SimpleNamespace(+ browser_state=None,+ tasks=[],+ all_workflow_task_ids=[],+ child_workflow_run_ids=[],+ close_browser_on_completion=True,+ browser_session_write_back_attempted=True,+ )++ with (+ patch("skyvern.forge.sdk.workflow.service.app") as mock_app,+ patch("skyvern.forge.sdk.workflow.service.analytics") as mock_analytics,+ ):+ mock_analytics.capture = MagicMock()+ mock_app.ARTIFACT_MANAGER.wait_for_upload_aiotasks = AsyncMock()+ mock_app.STORAGE.save_downloaded_files = AsyncMock()+ mock_app.WORKFLOW_CONTEXT_MANAGER.remove_workflow_run_context = MagicMock()++ with pytest.raises(RuntimeError):+ await service.clean_up_workflow(+ workflow=workflow,+ workflow_run=workflow_run,+ need_call_webhook=True,+ browser_cleanup_result=browser_cleanup_result, # type: ignore[arg-type]+ )++ service._schedule_credential_fallback_retry.assert_called_once_with(workflow_run)+++async def test_clean_up_workflow_schedules_retry_when_earlier_cleanup_step_raises() -> None:+ # The schedule finally wraps the whole cleanup sequence, not just the webhook: a failure in an+ # earlier step (here wait_for_upload_aiotasks) must still schedule the eligible run's retry.+ service = WorkflowService()+ workflow_run = _workflow_run(failure_category=[{"category": "AUTH_FAILURE"}])+ workflow = _workflow([])+ service._schedule_credential_fallback_retry = MagicMock() # type: ignore[method-assign]+ browser_cleanup_result = SimpleNamespace(+ browser_state=None,+ tasks=[],+ all_workflow_task_ids=["t_1"],+ child_workflow_run_ids=[],+ close_browser_on_completion=True,+ browser_session_write_back_attempted=True,+ )++ with (+ patch("skyvern.forge.sdk.workflow.service.app") as mock_app,+ patch("skyvern.forge.sdk.workflow.service.analytics") as mock_analytics,+ ):+ mock_analytics.capture = MagicMock()+ mock_app.ARTIFACT_MANAGER.wait_for_upload_aiotasks = AsyncMock(side_effect=RuntimeError("upload drain failed"))+ mock_app.STORAGE.save_downloaded_files = AsyncMock()+ mock_app.WORKFLOW_CONTEXT_MANAGER.remove_workflow_run_context = MagicMock()++ with pytest.raises(RuntimeError):+ await service.clean_up_workflow(+ workflow=workflow,+ workflow_run=workflow_run,+ need_call_webhook=False,+ browser_cleanup_result=browser_cleanup_result, # type: ignore[arg-type]+ )+service._schedule_credential_fallback_retry.assert_called_once_with(workflow_run)diff --git a/tests/unit/test_credential_rotation.py b/tests/unit/test_credential_rotation.pyindex 4a03af6f5..b8d55fe60 100644--- a/tests/unit/test_credential_rotation.py+++ b/tests/unit/test_credential_rotation.py@@ -291,6 +291,96 @@ async def test_select_rotating_credentials_keeps_override_and_selects_remaining()+def _fallback_only_credential_parameter() -> CredentialParameter:+ now = datetime.now(timezone.utc)+ return CredentialParameter(+ key="login_cred",+ credential_parameter_id="cp_login",+ workflow_id="wf_test",+ credential_id="cred_primary",+ credential_ids=None,+ fallback_credential_ids=["cred_fb1", "cred_fb2"],+ created_at=now,+ modified_at=now,+ )+++async def test_select_render_includes_fallback_only_primary_credential() -> None:+ # A login credential with fallbacks but no rotation pool serializes as a block-scoped+ # CredentialParameter (credential_ids empty). Its primary must still reach the profile-key render+ # values, or a browser_profile_key referencing this parameter fails setup on the initial run.+ service = WorkflowService()+ workflow = _setup_workflow_with_rotating_credential(browser_profile_key="{{ login_cred }}")+ workflow.workflow_definition.parameters = [_fallback_only_credential_parameter()]+ select_mock = AsyncMock()++ with patch("skyvern.forge.sdk.workflow.service.select_credential_for_run", select_mock):+ selections = await service._select_rotating_credential_parameters_for_render(+ workflow=workflow,+ workflow_run=_setup_workflow_run(),+ organization_id="org_test",+ )++ assert selections == {"login_cred": "cred_primary"}+ select_mock.assert_not_awaited()+++async def test_select_render_resolves_indirect_fallback_primary_from_parameter_values() -> None:+ # A fallback-only credential_id can indirectly reference another workflow parameter carrying the+ # real credential value (mirrors WorkflowRunContext.resolve_credential_parameter_id). The render+ # must resolve it, or a browser_profile_key would collapse distinct accounts onto one profile.+ now = datetime.now(timezone.utc)+ service = WorkflowService()+ workflow = _setup_workflow_with_rotating_credential(browser_profile_key="{{ login_cred }}")+ workflow.workflow_definition.parameters = [+ CredentialParameter(+ key="login_cred",+ credential_parameter_id="cp_login",+ workflow_id="wf_test",+ credential_id="account_param",+ credential_ids=None,+ fallback_credential_ids=["cred_fb1"],+ created_at=now,+ modified_at=now,+ )+ ]+ select_mock = AsyncMock()++ with patch("skyvern.forge.sdk.workflow.service.select_credential_for_run", select_mock):+ selections = await service._select_rotating_credential_parameters_for_render(+ workflow=workflow,+ workflow_run=_setup_workflow_run(),+ organization_id="org_test",+ parameter_values={"account_param": "cred_runtime"},+ )++ assert selections == {"login_cred": "cred_runtime"}+ select_mock.assert_not_awaited()+++async def test_select_render_fallback_override_takes_precedence_over_primary() -> None:+ # On a fallback retry the chosen fallback arrives as a credential_parameter_override and must win+ # over the primary.+ service = WorkflowService()+ workflow = _setup_workflow_with_rotating_credential(browser_profile_key="{{ login_cred }}")+ workflow.workflow_definition.parameters = [_fallback_only_credential_parameter()]+ select_mock = AsyncMock()++ with patch("skyvern.forge.sdk.workflow.service.select_credential_for_run", select_mock):+ selections = await service._select_rotating_credential_parameters_for_render(+ workflow=workflow,+ workflow_run=_setup_workflow_run(),+ organization_id="org_test",+ credential_parameter_overrides={"login_cred": "cred_fb1"},+ )++ assert selections == {"login_cred": "cred_fb1"}+ select_mock.assert_not_awaited()++@pytest.mark.asyncioasync def test_random_selection_returns_member(monkeypatch: pytest.MonkeyPatch) -> None:repo = _SelectionRepo()diff --git a/tests/unit/test_workflow_run_parameter_batching.py b/tests/unit/test_workflow_run_parameter_batching.pyindex 7e07bc3d2..8d29db2cc 100644--- a/tests/unit/test_workflow_run_parameter_batching.py+++ b/tests/unit/test_workflow_run_parameter_batching.py@@ -49,6 +49,8 @@ def _make_service_with_mocks(batch_side_effect: Exception | None = None,single_side_effect: Exception | None = None,persist_browser_session: bool = False,+ browser_profile_id: str | None = None,+ cdp_connect_headers: dict[str, str] | None = None,) -> tuple[WorkflowService, SimpleNamespace, SimpleNamespace]:"""Helper to build a WorkflowService with mocked internals for setup_workflow_run tests."""service = WorkflowService()@@ -59,8 +61,8 @@ def _make_service_with_mocks(proxy_location=None,webhook_callback_url=None,extra_http_headers=None,- cdp_connect_headers=None,- browser_profile_id=None,+ cdp_connect_headers=cdp_connect_headers,+ browser_profile_id=browser_profile_id,persist_browser_session=persist_browser_session,browser_profile_key=None,title="Workflow",@@ -834,3 +836,57 @@ async def test_setup_workflow_run_rolls_back_outer_session_on_batch_failure() ->assert rollback_index[0] < fallback_call_index[0], (f"rollback must precede fallback insert; got rollback at {rollback_index} fallback at {fallback_call_index}")+++async def test_setup_workflow_run_skips_browser_inheritance_for_fallback_retry() -> None:+ # A credential-fallback retry (retried_from_workflow_run_id set) clears the browser handles; it+ # must NOT re-inherit the workflow's configured profile/cdp headers, or the retry reconnects to+ # the failed account's persistent-browser-session profile.+ service, organization, _ = _make_service_with_mocks(+ workflow_parameters=[],+ browser_profile_id="bp_workflow",+ cdp_connect_headers={"authorization": "Bearer workflow"},+ )+ request = WorkflowRequestBody(data={}, browser_profile_id=None, browser_session_id=None, cdp_connect_headers=None)++ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:+ mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)+ mock_app.AGENT_FUNCTION.should_use_flex_llm_routing = AsyncMock(return_value=False)++ await service.setup_workflow_run(+ request_id="req_test",+ workflow_request=request,+ workflow_permanent_id="wpid_test",+ organization=organization,+ retried_from_workflow_run_id="wr_original",+ )++ assert request.browser_profile_id is None+ assert request.cdp_connect_headers is None+++async def test_setup_workflow_run_inherits_browser_profile_for_normal_run() -> None:+ # The fallback-retry gate is conditional: a normal run (no retried_from) still inherits the+ # workflow's configured browser profile / cdp headers.+ service, organization, _ = _make_service_with_mocks(+ workflow_parameters=[],+ browser_profile_id="bp_workflow",+ cdp_connect_headers={"authorization": "Bearer workflow"},+ )+ request = WorkflowRequestBody(data={}, browser_profile_id=None, browser_session_id=None, cdp_connect_headers=None)++ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:+ mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)+ mock_app.AGENT_FUNCTION.should_use_flex_llm_routing = AsyncMock(return_value=False)++ await service.setup_workflow_run(+ request_id="req_test",+ workflow_request=request,+ workflow_permanent_id="wpid_test",+ organization=organization,+ )++ assert request.browser_profile_id == "bp_workflow"+ assert request.cdp_connect_headers == {"authorization": "Bearer workflow"}