Skip to content

Automate browser based workflows with AI

Retry a workflow run under the same run id when it ends in a chosen status or error code (SKY-15802) (#8557)

Shuchang Zheng5fe4810b1c56
diff --git a/alembic/versions/2026_09_15_1919-2670d5a61131_add_workflow_run_attempts_and_attempt_attribution_columns.py b/alembic/versions/2026_09_15_1919-2670d5a61131_add_workflow_run_attempts_and_attempt_attribution_columns.py
new file mode 100644
index 000000000..f9ae29cb7
--- /dev/null
+++ b/alembic/versions/2026_09_15_1919-2670d5a61131_add_workflow_run_attempts_and_attempt_attribution_columns.py
@@ -0,0 +1,87 @@
+"""add workflow run attempts and attempt attribution columns
+
+Revision ID: 2670d5a61131
+Revises: de8067e9e60c
+Create Date: 2026-09-15T19:19:18.481168+00:00
+
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "2670d5a61131"
+down_revision: Union[str, None] = "de8067e9e60c"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "workflow_run_attempts",
+ sa.Column("workflow_run_id", sa.String(), nullable=False),
+ sa.Column("attempt_number", sa.Integer(), nullable=False),
+ sa.Column("organization_id", sa.String(), nullable=False),
+ sa.Column("status", sa.String(), nullable=False),
+ sa.Column("failure_reason", sa.Text(), nullable=True),
+ sa.Column("failure_category", sa.JSON(), nullable=True),
+ sa.Column("error_codes", sa.JSON(), nullable=True),
+ sa.Column("retry_decision", sa.String(), nullable=True),
+ sa.Column("decision_reason", sa.String(), nullable=True),
+ sa.Column("next_attempt_at", sa.DateTime(), nullable=True),
+ sa.Column("next_attempt_prepared_at", sa.DateTime(), nullable=True),
+ sa.Column("webhook_sent_at", sa.DateTime(), nullable=True),
+ sa.Column("interim_webhook_sent_at", sa.DateTime(), nullable=True),
+ sa.Column("side_effects_released_at", sa.DateTime(), nullable=True),
+ sa.Column("pinned_browser_session_id", sa.String(), nullable=True),
+ sa.Column("started_at", sa.DateTime(), nullable=True),
+ sa.Column("finished_at", sa.DateTime(), nullable=True),
+ sa.Column("created_at", sa.DateTime(), nullable=False),
+ sa.Column("modified_at", sa.DateTime(), nullable=False),
+ sa.PrimaryKeyConstraint("workflow_run_id", "attempt_number"),
+ )
+ op.create_index(
+ "ix_workflow_run_attempts_organization_created_at",
+ "workflow_run_attempts",
+ ["organization_id", "created_at"],
+ )
+ op.create_index(
+ "ix_workflow_run_attempts_pending_retries",
+ "workflow_run_attempts",
+ ["next_attempt_at", "workflow_run_id", "attempt_number"],
+ postgresql_where=sa.text(
+ "retry_decision = 'retry' AND next_attempt_prepared_at IS NULL AND next_attempt_at IS NOT NULL"
+ ),
+ )
+ op.create_index(
+ "ix_workflow_run_attempts_terminal_releases",
+ "workflow_run_attempts",
+ ["side_effects_released_at"],
+ postgresql_where=sa.text("retry_decision IN ('final', 'revoked', 'abandoned') AND webhook_sent_at IS NULL"),
+ )
+ op.create_index(
+ "ix_workflow_run_attempts_prepared_not_started",
+ "workflow_run_attempts",
+ ["modified_at"],
+ postgresql_where=sa.text("retry_decision IS NULL AND status = 'queued' AND started_at IS NULL"),
+ )
+
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.add_column("workflow_run_blocks", sa.Column("attempt_number", sa.Integer(), nullable=True))
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.add_column("tasks", sa.Column("attempt_number", sa.Integer(), nullable=True))
+
+
+def downgrade() -> None:
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.drop_column("tasks", "attempt_number")
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.drop_column("workflow_run_blocks", "attempt_number")
+ op.drop_index("ix_workflow_run_attempts_prepared_not_started", table_name="workflow_run_attempts")
+ op.drop_index("ix_workflow_run_attempts_terminal_releases", table_name="workflow_run_attempts")
+ op.drop_index("ix_workflow_run_attempts_pending_retries", table_name="workflow_run_attempts")
+ op.drop_index("ix_workflow_run_attempts_organization_created_at", table_name="workflow_run_attempts")
+ op.drop_table("workflow_run_attempts")
diff --git a/alembic/versions/2026_09_15_1919-eee46e1b1dbf_add_durable_workflow_terminal_side_effect_progress.py b/alembic/versions/2026_09_15_1919-eee46e1b1dbf_add_durable_workflow_terminal_side_effect_progress.py
new file mode 100644
index 000000000..17e377aef
--- /dev/null
+++ b/alembic/versions/2026_09_15_1919-eee46e1b1dbf_add_durable_workflow_terminal_side_effect_progress.py
@@ -0,0 +1,33 @@
+"""Add durable workflow terminal side-effect progress.
+
+Revision ID: eee46e1b1dbf
+Revises: 2670d5a61131
+Create Date: 2026-09-15T19:19:18.481815+00:00
+
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "eee46e1b1dbf"
+down_revision: Union[str, None] = "2670d5a61131"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.add_column("workflow_run_attempts", sa.Column("interim_side_effects_progress", sa.JSON(), nullable=True))
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.add_column("workflow_run_attempts", sa.Column("final_side_effects_progress", sa.JSON(), nullable=True))
+
+
+def downgrade() -> None:
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.drop_column("workflow_run_attempts", "final_side_effects_progress")
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.drop_column("workflow_run_attempts", "interim_side_effects_progress")
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.json
index fe5e4cd5c..9ce62d794 100644
--- a/docs/api-reference/openapi.json
+++ b/docs/api-reference/openapi.json
@@ -29215,6 +29215,17 @@
],
"title": "Error Code Mapping"
},
+ "retry_policy": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/WorkflowRetryPolicy"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional policy for retrying eligible terminal workflow runs"
+ },
"workflow_system_prompt": {
"anyOf": [
{
@@ -29475,6 +29486,17 @@
],
"title": "Error Code Mapping"
},
+ "retry_policy": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/WorkflowRetryPolicy"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional policy for retrying eligible terminal workflow runs"
+ },
"workflow_system_prompt": {
"anyOf": [
{
@@ -29707,6 +29729,87 @@
"type": "object",
"title": "WorkflowRequest"
},
+ "WorkflowRetryPolicy": {
+ "properties": {
+ "max_retries": {
+ "type": "integer",
+ "maximum": 5.0,
+ "minimum": 1.0,
+ "title": "Max Retries",
+ "description": "Maximum number of retries after the initial attempt",
+ "default": 1
+ },
+ "delay_seconds": {
+ "type": "integer",
+ "maximum": 3600.0,
+ "minimum": 0.0,
+ "title": "Delay Seconds",
+ "description": "Fixed delay before the next attempt, in seconds",
+ "default": 0
+ },
+ "webhook_on_retry": {
+ "type": "string",
+ "enum": [
+ "final_only",
+ "every_attempt"
+ ],
+ "title": "Webhook On Retry",
+ "description": "Whether to send a webhook for every attempt or only the final attempt",
+ "default": "final_only"
+ },
+ "retry_on": {
+ "items": {
+ "$ref": "#/components/schemas/WorkflowRetryRule"
+ },
+ "type": "array",
+ "minItems": 1,
+ "title": "Retry On",
+ "description": "Terminal status rules that enable retries"
+ }
+ },
+ "type": "object",
+ "required": [
+ "retry_on"
+ ],
+ "title": "WorkflowRetryPolicy"
+ },
+ "WorkflowRetryRule": {
+ "properties": {
+ "status": {
+ "type": "string",
+ "enum": [
+ "completed",
+ "failed",
+ "terminated",
+ "canceled",
+ "timed_out"
+ ],
+ "title": "Status",
+ "description": "Terminal status that triggers a retry rule; canceled is accepted for forward compatibility, but a canceled run never retries in the current runtime, including explicit API/UI cancels."
+ },
+ "error_codes": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string",
+ "minLength": 1
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Error Codes",
+ "description": "Optional error codes. The rule matches when any listed code is present."
+ }
+ },
+ "type": "object",
+ "required": [
+ "status"
+ ],
+ "title": "WorkflowRetryRule"
+ },
"WorkflowRun": {
"properties": {
"workflow_run_id": {
@@ -29804,6 +29907,39 @@
"status": {
"$ref": "#/components/schemas/WorkflowRunStatus"
},
+ "attempt": {
+ "type": "integer",
+ "title": "Attempt",
+ "description": "One-based number of the current workflow run attempt",
+ "default": 1
+ },
+ "retry_pending": {
+ "type": "boolean",
+ "title": "Retry Pending",
+ "description": "Whether another attempt is scheduled for this workflow run",
+ "default": false
+ },
+ "next_attempt_at": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "date-time"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Next Attempt At",
+ "description": "Timestamp when the next workflow run attempt is scheduled"
+ },
+ "attempts": {
+ "items": {
+ "$ref": "#/components/schemas/WorkflowRunAttempt"
+ },
+ "type": "array",
+ "title": "Attempts",
+ "description": "Attempts recorded for this workflow run"
+ },
"extra_http_headers": {
"anyOf": [
{
@@ -30201,6 +30337,121 @@
],
"title": "WorkflowRun"
},
+ "WorkflowRunAttempt": {
+ "properties": {
+ "attempt_number": {
+ "type": "integer",
+ "title": "Attempt Number",
+ "description": "One-based number of this workflow run attempt"
+ },
+ "status": {
+ "$ref": "#/components/schemas/RunStatus",
+ "description": "Status of this workflow run attempt"
+ },
+ "failure_reason": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Failure Reason",
+ "description": "Reason for failure, if the attempt failed"
+ },
+ "error_codes": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Error Codes",
+ "description": "Error codes reported by this attempt"
+ },
+ "started_at": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "date-time"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Started At",
+ "description": "Timestamp when this attempt started"
+ },
+ "finished_at": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "date-time"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Finished At",
+ "description": "Timestamp when this attempt finished"
+ },
+ "retry_decision": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Retry Decision",
+ "description": "Retry decision recorded for this attempt"
+ },
+ "decision_reason": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Decision Reason",
+ "description": "Reason recorded for the retry decision"
+ },
+ "next_attempt_at": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "date-time"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Next Attempt At",
+ "description": "Timestamp when the next attempt is scheduled"
+ },
+ "webhook_sent_at": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "date-time"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Webhook Sent At",
+ "description": "Timestamp when the webhook for this attempt was sent"
+ }
+ },
+ "type": "object",
+ "required": [
+ "attempt_number",
+ "status"
+ ],
+ "title": "WorkflowRunAttempt"
+ },
"WorkflowRunBlock": {
"properties": {
"workflow_run_block_id": {
@@ -30222,6 +30473,17 @@
"type": "string",
"title": "Workflow Run Id"
},
+ "attempt_number": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Attempt Number"
+ },
"organization_id": {
"type": "string",
"title": "Organization Id"
@@ -31568,6 +31830,39 @@
"title": "Run Type",
"description": "Type of run - always workflow_run for workflow runs"
},
+ "attempt": {
+ "type": "integer",
+ "title": "Attempt",
+ "description": "One-based number of the current workflow run attempt",
+ "default": 1
+ },
+ "retry_pending": {
+ "type": "boolean",
+ "title": "Retry Pending",
+ "description": "Whether another attempt is scheduled for this workflow run",
+ "default": false
+ },
+ "next_attempt_at": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "date-time"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Next Attempt At",
+ "description": "Timestamp when the next workflow run attempt is scheduled"
+ },
+ "attempts": {
+ "items": {
+ "$ref": "#/components/schemas/WorkflowRunAttempt"
+ },
+ "type": "array",
+ "title": "Attempts",
+ "description": "Attempts recorded for this workflow run"
+ },
"run_with": {
"type": "string",
"title": "Run With",
@@ -31660,6 +31955,11 @@
"type": {
"$ref": "#/components/schemas/WorkflowRunTimelineType"
},
+ "attempt": {
+ "type": "integer",
+ "title": "Attempt",
+ "default": 1
+ },
"block": {
"anyOf": [
{
diff --git a/docs/developers/going-to-production/webhooks.mdx b/docs/developers/going-to-production/webhooks.mdx
index 09be7f961..2e4ba3bf5 100644
--- a/docs/developers/going-to-production/webhooks.mdx
+++ b/docs/developers/going-to-production/webhooks.mdx
@@ -18,7 +18,7 @@ import WebhookSignatureVerification from "/snippets/webhook-signature-verificati
Agents and task runs are asynchronous. When you call `run_task` or `run_workflow`, the API returns immediately with a run ID, but the actual execution happens in the background and can take variable time.
-Instead of polling the `get_runs` endpoint, you can use Webhooks to get notified when they finish. Webhooks fire only when a run reaches a terminal status: `completed`, `failed`, `terminated`, `timed_out`, or `canceled`.
+Instead of polling the `get_runs` endpoint, you can use Webhooks to get notified when they finish. Webhooks fire when a run reaches a terminal status: `completed`, `failed`, `terminated`, `timed_out`, or `canceled`. A workflow with a retry policy sends one webhook after the final attempt by default.
This page covers setting them up, explains payload structure, signature verification, and handling delivery failures.
@@ -173,6 +173,40 @@ When creating an agent, use `webhook_callback_url` inside `json_definition`; thi
**Watch the parameter names.** Using `webhook_url` when creating an agent (instead of `webhook_callback_url` inside `json_definition`) silently results in no webhook being sent. The API won't return an error. Your runs will just complete without notifications.
</Warning>
+### Workflow retries and webhooks
+
+Add `retry_policy` to a workflow definition to retry selected terminal outcomes. Skyvern keeps the same `workflow_run_id` and records each execution in `attempts[]`.
+
+```json
+{
+ "retry_policy": {
+ "max_retries": 2,
+ "delay_seconds": 10,
+ "webhook_on_retry": "final_only",
+ "retry_on": [
+ {"status": "terminated", "error_codes": ["portal_timeout"]},
+ {"status": "failed"}
+ ]
+ }
+}
+```
+
+`final_only` is the default. Skyvern sends one webhook after the last attempt. Set `webhook_on_retry` to `every_attempt` to receive a webhook after each attempt. Each payload includes the attempt number and retry state. Every attempt shares the same `run_id`. Use `run_id`, `attempt`, and `retry_pending` together as the idempotency key, not `run_id` alone, or your receiver discards the final attempt as a duplicate of the first. A run that is canceled during its retry delay keeps the terminal status of its last attempt, for example `failed`, and sends a second webhook for the same attempt: the first payload has `retry_pending: true`, the second has `retry_pending: false` and the same status. A receiver that keys on `run_id` and `attempt` alone discards that final payload.
+
+Webhook delivery is recorded after delivery. If a worker crashes in that window, Temporal or OSS recovery waits for the bounded delivery grace period and retries while the timestamp is NULL, so endpoints must tolerate duplicates in that crash window. Runs without a webhook URL record completion as "nothing to deliver" and are not retried forever.
+An owner stops accepting its lease 60 seconds before recovery may take it over, leaving that margin as an intentional process-pause window before the next owner proceeds.
+If a worker pauses after the final webhook step starts, recovery may deliver that webhook again. Webhook consumers should tolerate duplicates.
+The final workflow hook runs once per logical run under the same lease contract, except that a process paused across a takeover may observe a second call if it resumes between the fresh ownership check and the hook call.
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `attempt` | integer | Current one-based attempt number |
+| `attempts` | array | Details for all attempts, in order |
+| `retry_pending` | boolean | `true` when another attempt is scheduled |
+| `next_attempt_at` | datetime or null | Planned start time for the next attempt |
+
+When `retry_pending` is `true`, the run can still change its final result. Wait for `retry_pending: false` before processing the run as final.
+
---
## Step 2: Understand the payload
@@ -354,12 +388,12 @@ Even when webhook delivery fails, the task's `output` field may still contain ex
**Recommended pattern:** Always have a fallback polling mechanism for critical agents. If you don't receive a webhook within your expected window, call `get_run` to check if the run completed and retrieve the data directly.
-### Retrying webhooks
+### Replaying webhooks
Once you've identified and fixed the issue, you can replay the webhook using `retry_run_webhook`.
<Note>
-Skyvern does not automatically retry failed webhooks. This is intentional: automatic retries can cause duplicate processing if your server received the payload but returned an error. You must explicitly call `retry_run_webhook` after fixing the issue.
+Workflow retry policies retry workflow execution, not webhook delivery. Webhook delivery remains a separate operation. You must explicitly call `retry_run_webhook` after fixing a delivery issue. The endpoint returns HTTP `409 Conflict` while a workflow retry is pending.
</Note>
<CodeGroup>
@@ -403,7 +437,7 @@ curl -X POST "https://api.skyvern.com/v1/runs/tsk_v2_486305187432193504/retry_we
</Warning>
<Tip>
-**Implement idempotency.** If you call `retry_run_webhook`, you may receive the same payload twice (once from the original attempt that your server processed but returned an error, and once from the retry). Use the `run_id` as an idempotency key: check if you've already processed this run before taking action.
+**Implement idempotency.** If you call `retry_run_webhook`, you may receive the same payload twice (once from the original attempt that your server processed but returned an error, and once from the retry). Use `run_id`, `attempt`, and `retry_pending` together as the idempotency key: check if you've already processed this attempt in this retry state before taking action. Do not key on `run_id` alone. When `webhook_on_retry` is `every_attempt`, every attempt shares one `run_id`, and a receiver that keys on `run_id` alone discards the final attempt. A run canceled during its retry delay keeps the terminal status of its last attempt and sends two payloads for the same attempt, first with `retry_pending: true` and then with `retry_pending: false`, so a receiver that keys on `run_id` and `attempt` alone discards the final one.
</Tip>
You can pass a different `webhook_url` to send the payload to a new endpoint; useful if the original URL was misconfigured.
diff --git a/docs/sdk-reference/workflows/create-workflow.mdx b/docs/sdk-reference/workflows/create-workflow.mdx
index d09f14cf2..609002523 100644
--- a/docs/sdk-reference/workflows/create-workflow.mdx
+++ b/docs/sdk-reference/workflows/create-workflow.mdx
@@ -5,6 +5,40 @@ slug: sdk-reference/workflows/create-workflow
Create a new workflow from a JSON or YAML definition.
+## Retry policy
+
+Add `retry_policy` inside `workflow_definition` to retry eligible top-level runs. Omit the field, or set it to `null`, to disable retries.
+
+| Field | Default | Description |
+|-------|---------|-------------|
+| `max_retries` | `1` | Maximum retries after the initial attempt. Allowed range: `1` to `5`. |
+| `delay_seconds` | `0` | Fixed delay before the next attempt. Allowed range: `0` to `3600`. |
+| `webhook_on_retry` | `final_only` | Use `final_only` for one webhook after the final attempt. Use `every_attempt` for one webhook after each attempt. |
+| `retry_on` | — | One or more rules. Each rule has a terminal `status` and an optional `error_codes` list. The `canceled` status is accepted for forward compatibility. |
+
+A rule matches when the run status matches and any listed error code matches. Omit `error_codes`, or use an empty list, to match any error code for that status. Rules use OR logic. Canceled runs never retry in the current runtime, including explicit API/UI cancels. The policy applies only to top-level runs. Each retry keeps the same `workflow_run_id`. Each attempt uses credits.
+
+The maximum elapsed time limit resets for each attempt, so the total run duration can exceed that limit.
+
+```yaml
+title: Extract Products
+workflow_definition:
+ parameters: []
+ retry_policy:
+ max_retries: 2
+ delay_seconds: 10
+ webhook_on_retry: final_only
+ retry_on:
+ - status: terminated
+ error_codes: [portal_timeout, mfa_failed]
+ - status: failed
+ blocks:
+ - block_type: navigation
+ label: extract_products
+ url: https://example.com/products
+ navigation_goal: Extract the top three products.
+```
+
<CodeGroup>
```python Python
workflow = await client.create_workflow(
diff --git a/skyvern/config.py b/skyvern/config.py
index 80266bf4a..e22331c0d 100644
--- a/skyvern/config.py
+++ b/skyvern/config.py
@@ -946,6 +946,8 @@ class Settings(BaseSettings):
"""How often the OSS/local scheduler scans for due workflow schedules."""
WORKFLOW_SCHEDULE_MAX_CONCURRENT_RUNS: int = 1
"""Maximum number of scheduled workflow runs dispatched concurrently by one OSS server process."""
+ RETRY_DISPATCH_GRACE_SECONDS: int = Field(default=600, ge=600)
+ """OSS dispatch claim grace; the executor also enforces the retry lease takeover minimum."""
# OpenTelemetry Settings
OTEL_ENABLED: bool = False
diff --git a/skyvern/core/script_generations/script_skyvern_page.py b/skyvern/core/script_generations/script_skyvern_page.py
index 4b2853586..0dc0f69bf 100644
--- a/skyvern/core/script_generations/script_skyvern_page.py
+++ b/skyvern/core/script_generations/script_skyvern_page.py
@@ -37,9 +37,11 @@ from skyvern.forge.sdk.api.files import (
check_downloading_files_and_wait_for_download_to_complete,
get_path_for_workflow_download_directory,
list_files_in_directory,
+ resolve_run_download_id,
)
from skyvern.forge.sdk.api.llm.api_handler_factory import get_org_aware_secondary_llm_api_handler
from skyvern.forge.sdk.artifact.models import ArtifactType
+from skyvern.forge.sdk.artifact.storage.base import get_download_retry_started_at
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.db.datetime_utils import naive_utc_now
from skyvern.forge.sdk.db.utils import ACTION_TYPE_TO_CLASS
@@ -205,6 +207,8 @@ class ScriptSkyvernPage(SkyvernPage):
self,
download_dir: Path,
browser_session_id: str | None = None,
+ *,
+ attempt_started_at: datetime | None = None,
) -> None:
context = skyvern_context.current()
if not context or not context.organization_id:
@@ -222,6 +226,7 @@ class ScriptSkyvernPage(SkyvernPage):
organization_id=organization_id,
browser_session_id=browser_session_id,
timeout=download_timeout,
+ attempt_started_at=attempt_started_at,
)
async def _decorate_call(
@@ -261,13 +266,16 @@ class ScriptSkyvernPage(SkyvernPage):
downloaded_files: list[str] | None = None
files_before: list[str] = []
download_dir: Path | None = None
+ attempt_started_at: datetime | None = None
# Capture files before click action for download detection
if action == ActionType.CLICK and context and context.workflow_run_id:
try:
+ download_run_id = resolve_run_download_id(context, fallback_run_id=context.workflow_run_id)
+ attempt_started_at = await get_download_retry_started_at(context.organization_id, download_run_id)
download_dir = get_path_for_workflow_download_directory(context.workflow_run_id)
if download_dir.exists():
- files_before = list_files_in_directory(download_dir)
+ files_before = list_files_in_directory(download_dir, attempt_started_at=attempt_started_at)
if context.browser_session_id and context.organization_id:
browser_session_downloaded_files = await app.STORAGE.list_downloaded_files_in_browser_session(
organization_id=context.organization_id,
@@ -341,8 +349,9 @@ class ScriptSkyvernPage(SkyvernPage):
await self._ensure_download_to_complete(
download_dir=download_dir,
browser_session_id=context.browser_session_id,
+ attempt_started_at=attempt_started_at,
)
- files_after = list_files_in_directory(download_dir)
+ files_after = list_files_in_directory(download_dir, attempt_started_at=attempt_started_at)
if context.browser_session_id and context.organization_id:
browser_session_downloaded_files = (
await app.STORAGE.list_downloaded_files_in_browser_session(
diff --git a/skyvern/core/script_generations/skyvern_page.py b/skyvern/core/script_generations/skyvern_page.py
index c76bfa237..5f1069462 100644
--- a/skyvern/core/script_generations/skyvern_page.py
+++ b/skyvern/core/script_generations/skyvern_page.py
@@ -1331,7 +1331,7 @@ class SkyvernPage(Page):
try:
file_path = await download_file_from_url(
files,
- organization_id=context.organization_id if context else None,
+ organization_id=await self._get_file_organization_id(files),
)
locator = self._locator_scope.locator(selector)
await locator.set_input_files(file_path, **kwargs)
@@ -1369,7 +1369,7 @@ class SkyvernPage(Page):
if not files:
raise ValueError("Parameter 'files' is required but was not provided")
- file_path = await download_file_from_url(files, organization_id=context.organization_id if context else None)
+ file_path = await download_file_from_url(files, organization_id=await self._get_file_organization_id(files))
locator = self._locator_scope.locator(selector)
await locator.set_input_files(file_path, timeout=timeout, **kwargs)
return files
@@ -1533,6 +1533,10 @@ class SkyvernPage(Page):
"""
return
+ async def _get_file_organization_id(self, file_url: str) -> str | None:
+ context = skyvern_context.current()
+ return context.organization_id if context else None
+
@action_wrap(ActionType.DOWNLOAD_FILE)
async def download_file(
self,
@@ -1555,11 +1559,10 @@ class SkyvernPage(Page):
# Use uuid as fallback for empty file_name, matching handler.py behavior
file_name = file_name or str(uuid.uuid4())
- context = skyvern_context.current()
file_path = await download_file_from_url(
download_url,
filename=file_name,
- organization_id=context.organization_id if context else None,
+ organization_id=await self._get_file_organization_id(download_url),
)
return file_path
diff --git a/skyvern/exceptions.py b/skyvern/exceptions.py
index 69c19ec41..b656203d4 100644
--- a/skyvern/exceptions.py
+++ b/skyvern/exceptions.py
@@ -640,6 +640,19 @@ class UnrecognizedWorkflowParameters(SkyvernHTTPException):
super().__init__(message, status_code=HTTPStatus.BAD_REQUEST)
+class WorkflowRetryAttemptLookupError(Exception):
+ pass
+
+
+class WorkflowAttemptDispatchSuperseded(Exception):
+ """The dispatch sweep released this dispatch's stale claim and started the attempt elsewhere."""
+
+ def __init__(self, workflow_run_id: str, attempt_number: int) -> None:
+ super().__init__(f"Workflow run {workflow_run_id} attempt {attempt_number} is owned by a newer dispatch")
+ self.workflow_run_id = workflow_run_id
+ self.attempt_number = attempt_number
+
+
class WorkflowRunParameterPersistenceError(SkyvernException):
def __init__(self, parameter_key: str, workflow_id: str, workflow_run_id: str, reason: str) -> None:
super().__init__(
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index 77fb74b35..3c5d61b10 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -123,6 +123,7 @@ from skyvern.forge.sdk.api.llm.yutori_navigator_response import parse_navigator_
from skyvern.forge.sdk.api.real_gcp import get_gcs_client
from skyvern.forge.sdk.artifact.manager import BulkArtifactCreationRequest
from skyvern.forge.sdk.artifact.models import ArtifactType
+from skyvern.forge.sdk.artifact.storage.base import get_download_retry_started_at
from skyvern.forge.sdk.browser_action_preflight import (
observed_page,
preflight_action,
@@ -1182,6 +1183,7 @@ class ForgeAgent:
download_suffix: str | None,
list_files_before: list[str],
randomize_if_missing: bool,
+ attempt_started_at: datetime | None = None,
) -> list[str]:
"""Rename newly downloaded files for a task before persistence.
@@ -1196,7 +1198,7 @@ class ForgeAgent:
workflow_download_directory = get_path_for_workflow_download_directory(
resolve_run_download_id(context, fallback_run_id=task.workflow_run_id)
)
- list_files_after = list_files_in_directory(workflow_download_directory)
+ list_files_after = list_files_in_directory(workflow_download_directory, attempt_started_at=attempt_started_at)
if task.browser_session_id:
browser_session_downloaded_files_after = await app.STORAGE.list_downloaded_files_in_browser_session(
organization_id=organization_id,
@@ -1420,6 +1422,7 @@ class ForgeAgent:
organization_id: str,
*,
timeout_cap: float | None = None,
+ attempt_started_at: datetime | None = None,
exhausted: set[str] | None = None,
should_cancel: Callable[[], Awaitable[bool]] | None = None,
) -> bool:
@@ -1443,7 +1446,9 @@ class ForgeAgent:
resolve_run_download_id(context, fallback_run_id=task.workflow_run_id)
)
- downloading_files = list_downloading_files_in_directory(workflow_download_directory)
+ downloading_files = list_downloading_files_in_directory(
+ workflow_download_directory, attempt_started_at=attempt_started_at
+ )
if task.browser_session_id:
browser_session_downloading_files = await app.STORAGE.list_downloading_files_in_browser_session(
organization_id=organization_id,
@@ -1559,6 +1564,7 @@ class ForgeAgent:
proxy_location=workflow_run.proxy_location,
extracted_information_schema=task_block.data_schema,
workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=workflow_run_context.attempt_number,
order=task_order,
retry=task_retry,
max_steps_per_run=task_block.max_steps_per_run,
@@ -1628,6 +1634,7 @@ class ForgeAgent:
navigation_payload=None,
organization_id=organization_id,
workflow_run_id=workflow_run_id,
+ attempt_number=app.WORKFLOW_CONTEXT_MANAGER.get_attempt_number(workflow_run_id),
order=task_order,
retry=task_retry,
)
@@ -1847,6 +1854,12 @@ class ForgeAgent:
run_blocks = await app.DATABASE.observer.get_workflow_run_blocks(
workflow_run_id=task.workflow_run_id, organization_id=organization.organization_id
)
+ current_attempt_number = app.WORKFLOW_CONTEXT_MANAGER.get_attempt_number(task.workflow_run_id)
+ run_blocks = [
+ block
+ for block in run_blocks
+ if (block.attempt_number if block.attempt_number is not None else 1) == current_attempt_number
+ ]
previous_block = select_previous_block(run_blocks, task.task_id)
except Exception:
LOG.warning("task_v3 previous-block handoff lookup failed", task_id=task.task_id, exc_info=True)
@@ -1902,6 +1915,9 @@ class ForgeAgent:
return False
download_id = resolve_run_download_id(context, fallback_run_id=task.task_id)
+ attempt_started_at = await get_download_retry_started_at(
+ organization.organization_id, resolve_run_download_id(context, fallback_run_id=task.workflow_run_id)
+ )
# Same baseline v1 takes before its per-step download check, so a file that was already
# sitting in the run's download directory before this block started is never mistaken for
@@ -1917,7 +1933,9 @@ class ForgeAgent:
workflow_download_directory = get_path_for_workflow_download_directory(
resolve_run_download_id(context, fallback_run_id=task.workflow_run_id)
)
- download_baseline_files = list_files_in_directory(workflow_download_directory)
+ download_baseline_files = list_files_in_directory(
+ workflow_download_directory, attempt_started_at=attempt_started_at
+ )
if task.browser_session_id:
browser_session_downloaded_files = await app.STORAGE.list_downloaded_files_in_browser_session(
organization_id=organization.organization_id,
@@ -1965,6 +1983,7 @@ class ForgeAgent:
timeout_cap=loop_deadline_at - time.monotonic(),
exhausted=download_wait_exhausted,
should_cancel=_should_cancel,
+ attempt_started_at=attempt_started_at,
)
if cancelled:
# The run is being canceled; even if a file landed while we waited, don't
@@ -1977,6 +1996,7 @@ class ForgeAgent:
download_suffix=complete_on_download_block.download_suffix,
list_files_before=[*(download_baseline_files or []), *staged_paths],
randomize_if_missing=True,
+ attempt_started_at=attempt_started_at,
)
if not new_files:
return None
@@ -2024,6 +2044,7 @@ class ForgeAgent:
timeout_cap=loop_deadline_at - time.monotonic(),
exhausted=download_wait_exhausted,
should_cancel=_should_cancel,
+ attempt_started_at=attempt_started_at,
)
return None
@@ -2902,6 +2923,9 @@ class ForgeAgent:
)
next_step: Step | None = None
detailed_output: DetailedAgentStepOutput | None = None
+ attempt_started_at = await get_download_retry_started_at(
+ organization.organization_id, resolve_run_download_id(context, fallback_run_id=task.workflow_run_id)
+ )
list_files_before: list[str] = download_baseline_files.copy() if download_baseline_files is not None else []
browser_state: BrowserState | None = None
# Set by a handler that ended the task but could not fail the row, so it skipped cleanup;
@@ -2914,7 +2938,8 @@ class ForgeAgent:
list_files_before = list_files_in_directory(
get_path_for_workflow_download_directory(
resolve_run_download_id(context, fallback_run_id=task.workflow_run_id)
- )
+ ),
+ attempt_started_at=attempt_started_at,
)
if task.browser_session_id and download_baseline_files is None:
browser_session_downloaded_files = await app.STORAGE.list_downloaded_files_in_browser_session(
@@ -3056,7 +3081,9 @@ class ForgeAgent:
retry = False
if task_block and task_block.complete_on_download and task.workflow_run_id:
- await self._wait_for_in_flight_downloads(task, task_block, organization.organization_id)
+ await self._wait_for_in_flight_downloads(
+ task, task_block, organization.organization_id, attempt_started_at=attempt_started_at
+ )
files_to_rename = await self._finalize_downloaded_files_for_task(
task,
@@ -3064,6 +3091,7 @@ class ForgeAgent:
download_suffix=task_block.download_suffix,
list_files_before=list_files_before,
randomize_if_missing=True,
+ attempt_started_at=attempt_started_at,
)
if files_to_rename:
LOG.info(
@@ -7352,12 +7380,16 @@ class ForgeAgent:
async with settle_browser_downloads_for_context(browser_context):
pass
if download_suffix and list_files_before is not None:
+ attempt_started_at = await get_download_retry_started_at(
+ task.organization_id, finalization_run_id
+ )
cleanup_finalized_files = await self._finalize_downloaded_files_for_task(
task,
organization_id=task.organization_id,
download_suffix=download_suffix,
list_files_before=list_files_before,
randomize_if_missing=False,
+ attempt_started_at=attempt_started_at,
)
# Cleanup finalization is the second durable-credit seam: only when it
# proves a new file did the download land, so only then close the popups the
@@ -8836,13 +8868,16 @@ class ForgeAgent:
"""Returns (total_steps_so_far, max_steps_per_workflow_run) when the org has a
run-level cap and this task belongs to a workflow run; otherwise None.
- ``max_steps_per_workflow_run`` is a per-org cap on total step count summed across
- all task blocks within a single workflow run. Distinct from the per-block
+ ``max_steps_per_workflow_run`` is a per-org cap on the step count summed across all
+ task blocks of one attempt of a workflow run, so a retried run may spend up to
+ cap x (max_retries + 1) steps under one run id. Distinct from the per-block
``max_steps_per_run`` ceiling.
"""
if not task.workflow_run_id or not organization.max_steps_per_workflow_run:
return None
- workflow_run_tasks = await app.DATABASE.tasks.get_tasks_by_workflow_run_id(task.workflow_run_id)
+ workflow_run_tasks = await app.DATABASE.tasks.get_tasks_by_workflow_run_id(
+ task.workflow_run_id, attempt_number=task.attempt_number or 1
+ )
task_ids = [t.task_id for t in workflow_run_tasks]
if not task_ids:
return 0, organization.max_steps_per_workflow_run
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index 139cf35e9..5cac0f0df 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -71,6 +71,7 @@ from skyvern.forge.sdk.services import (
from skyvern.forge.sdk.services.credentials import AuthenticatorTotpParseResult
from skyvern.forge.sdk.trace import traced
from skyvern.forge.sdk.workflow.models.block import BaseTaskBlock, BlockTypeVar
+from skyvern.forge.sdk.workflow.retry_policy import WORKFLOW_WEBHOOK_HTTP_TIMEOUT_SECONDS
from skyvern.forge.sdk.workflow.web_search import WebSearchProvider
from skyvern.schemas.run_enums import RunEngine, RunType
from skyvern.schemas.workflows import BlockResult, FileStorageType, FileUploadDestination
@@ -1364,6 +1365,11 @@ class AgentFunction:
"""Fetch per-run analytics metadata. OSS builds have no sidecar table."""
return None
+ async def get_workflow_run_execution_status(
+ self, workflow_run: WorkflowRun
+ ) -> Literal["running", "terminal", "absent", "unknown"]:
+ return "unknown" if workflow_run.job_id else "absent"
+
async def is_block_scoped_workflow_run(self, workflow_run: WorkflowRun) -> bool:
"""Return whether this workflow run was created for scoped block execution."""
return workflow_run.debug_session_id is not None
@@ -2415,7 +2421,7 @@ class AgentFunction:
url: str,
payload: str,
headers: dict[str, str],
- timeout_seconds: float = 30.0,
+ timeout_seconds: float = WORKFLOW_WEBHOOK_HTTP_TIMEOUT_SECONDS,
organization_id: str | None = None,
run_id: str | None = None,
resolved_ips: tuple[str, ...] | None = None,
@@ -2884,6 +2890,26 @@ class AgentFunction:
workflow_run_id: str,
organization_id: str,
status: WorkflowRunStatus,
+ is_final_attempt: bool = True,
+ ) -> None:
+ """Fired after a workflow attempt reaches a final status.
+
+ ``is_final_attempt`` is false for an attempt that will be retried. Overrides must be
+ best-effort and never raise.
+ """
+ return
+
+ async def on_workflow_run_final(
+ self,
+ *,
+ workflow_run_id: str,
+ organization_id: str,
+ status: WorkflowRunStatus,
) -> None:
- """Fired after a workflow run reaches a final status. Overrides must be best-effort and never raise."""
+ """Fired once per logical run after its final retry decision.
+
+ A process paused across a side-effect lease takeover may observe a second call only if it
+ resumes between the fresh ownership check and this call. Overrides must be best-effort and
+ never raise.
+ """
return
diff --git a/skyvern/forge/api_app.py b/skyvern/forge/api_app.py
index 6b0a28375..4626ec277 100644
--- a/skyvern/forge/api_app.py
+++ b/skyvern/forge/api_app.py
@@ -3,6 +3,7 @@
# The server-extra guard must run before FastAPI/Starlette imports.
# ruff: noqa: E402
+import asyncio
import os
import uuid
from contextlib import asynccontextmanager
@@ -41,8 +42,10 @@ from skyvern.forge.sdk.api.llm.custom_llm_registry import load_custom_llm_config
from skyvern.forge.sdk.copilot.tracing_setup import ensure_tracing_initialized
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
+from skyvern.forge.sdk.db.agent_db import AgentDB
from skyvern.forge.sdk.db.exceptions import DatabaseConnectionUnavailableError, NotFoundError, is_connection_failure
from skyvern.forge.sdk.db.models import Base
+from skyvern.forge.sdk.executor.factory import AsyncExecutorFactory
from skyvern.forge.sdk.routes import internal_auth, internal_llms
from skyvern.forge.sdk.routes.google_oauth import google_oauth_router
from skyvern.forge.sdk.routes.google_sheets import google_sheets_router
@@ -255,16 +258,35 @@ def register_agent_route_aliases(fastapi_app: FastAPI) -> None:
route.include_in_schema = False
-def _upgrade_sqlite_organization_slug(connection: Connection) -> None:
- """Add the organization slug column and index to an existing local SQLite database."""
+# Columns that migrations added to tables an older local SQLite database already has. create_all only
+# creates missing tables, so an upgraded install needs each of these added here.
+_SQLITE_ADDED_COLUMNS: tuple[tuple[str, str, str], ...] = (
+ ("organizations", "slug", "VARCHAR"),
+ ("tasks", "attempt_number", "INTEGER"),
+ ("workflow_run_blocks", "attempt_number", "INTEGER"),
+)
+
+
+def upgrade_sqlite_schema(connection: Connection) -> None:
+ """Add the columns and indexes that create_all leaves out of an existing local SQLite database."""
inspector = inspect(connection)
- if "organizations" not in inspector.get_table_names():
- return
- if "slug" not in {column["name"] for column in inspector.get_columns("organizations")}:
- connection.execute(text("ALTER TABLE organizations ADD COLUMN slug VARCHAR"))
- connection.execute(
- text("CREATE UNIQUE INDEX IF NOT EXISTS uq_organizations_slug ON organizations (slug) WHERE slug IS NOT NULL")
- )
+ tables = set(inspector.get_table_names())
+ for table, column, column_type in _SQLITE_ADDED_COLUMNS:
+ if table in tables and column not in {existing["name"] for existing in inspector.get_columns(table)}:
+ connection.execute(text(f"ALTER TABLE {table} ADD COLUMN {column} {column_type}"))
+ if "organizations" in tables:
+ connection.execute(
+ text(
+ "CREATE UNIQUE INDEX IF NOT EXISTS uq_organizations_slug ON organizations (slug) WHERE slug IS NOT NULL"
+ )
+ )
+
+
+async def ensure_sqlite_schema(db: AgentDB) -> None:
+ """Create missing tables and add missing columns to a local SQLite database."""
+ async with db.engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+ await conn.run_sync(upgrade_sqlite_schema)
async def _bootstrap_sqlite() -> None:
@@ -277,9 +299,7 @@ async def _bootstrap_sqlite() -> None:
_ensure_sqlite_dir(settings.DATABASE_STRING)
db = forge_app.DATABASE
- async with db.engine.begin() as conn:
- await conn.run_sync(Base.metadata.create_all)
- await conn.run_sync(_upgrade_sqlite_organization_slug)
+ await ensure_sqlite_schema(db)
# Preserve an existing API key if it's a real value (not the skeleton default).
# settings.SKYVERN_API_KEY already incorporates env vars and .env via pydantic-settings.
@@ -315,6 +335,14 @@ async def _bootstrap_sqlite() -> None:
)
+async def _recover_pending_retries() -> None:
+ try:
+ await AsyncExecutorFactory.get_executor().recover_pending_retries()
+ LOG.info("Pending workflow retry recovery completed")
+ except Exception:
+ LOG.exception("Failed to recover pending workflow retries")
+
+
@asynccontextmanager
async def lifespan(fastapi_app: FastAPI) -> AsyncGenerator[None, Any]:
"""Lifespan context manager for FastAPI app startup and shutdown."""
@@ -376,13 +404,20 @@ async def lifespan(fastapi_app: FastAPI) -> AsyncGenerator[None, Any]:
# lifespan here. This initializes the streamable-http session manager's
# task group which is required for handling MCP requests.
mcp_app = getattr(fastapi_app.state, "mcp_starlette_app", None)
- if mcp_app:
- async with mcp_app.lifespan(mcp_app):
- LOG.info("MCP remote server lifespan started")
+ retry_recovery_task = asyncio.create_task(_recover_pending_retries(), name="workflow-retry-recovery")
+ try:
+ if mcp_app:
+ async with mcp_app.lifespan(mcp_app):
+ LOG.info("MCP remote server lifespan started")
+ yield
+ LOG.info("MCP remote server lifespan stopped")
+ else:
yield
- LOG.info("MCP remote server lifespan stopped")
- else:
- yield
+ finally:
+ retry_recovery_task.cancel()
+ await asyncio.gather(retry_recovery_task, return_exceptions=True)
+ # The initial pass starts the periodic sweep even when cancelled; stop it so the loop can drain.
+ await AsyncExecutorFactory.get_executor().stop_retry_recovery()
# Stop cleanup scheduler
await stop_workflow_schedule_scheduler()
diff --git a/skyvern/forge/sdk/api/files.py b/skyvern/forge/sdk/api/files.py
index 4c853ab31..06dd062bf 100644
--- a/skyvern/forge/sdk/api/files.py
+++ b/skyvern/forge/sdk/api/files.py
@@ -9,6 +9,7 @@ import shutil
import tempfile
import zipfile
from dataclasses import dataclass
+from datetime import datetime
from http import HTTPStatus
from pathlib import Path
from typing import TYPE_CHECKING, Any, NamedTuple, TypeAlias
@@ -32,6 +33,7 @@ from skyvern.exceptions import (
)
from skyvern.forge import app
from skyvern.forge.sdk.artifact.signing import parse_artifact_content_url
+from skyvern.forge.sdk.artifact.storage.base import is_file_from_retry_attempt
from skyvern.forge.sdk.browser_action_policy import canonicalize_origin
from skyvern.forge.sdk.core.aiohttp_helper import (
SSRFGuardedResolver,
@@ -62,6 +64,19 @@ LOG = structlog.get_logger()
# Ids are generated from a 64-bit int, so a real one never exceeds 20 digits.
_UPLOADED_FILE_ID_PATTERN = re.compile(rf"^{UPLOADED_FILE_PREFIX}_[0-9]{{1,20}}$")
+_LOCAL_DOWNLOAD_ROOTS: set[str] = {os.path.realpath(os.path.join(settings.ARTIFACT_STORAGE_PATH, "downloads"))}
+
+
+def register_local_download_root(download_root: str) -> None:
+ _LOCAL_DOWNLOAD_ROOTS.add(os.path.realpath(download_root))
+
+
+def local_file_requires_organization(file_url: str) -> bool:
+ scheme = urlparse(file_url).scheme
+ if scheme not in ("", "file"):
+ return False
+ path = parse_uri_to_path(file_url) if scheme == "file" else file_url
+ return not Path(path).resolve().is_relative_to((Path(REPO_ROOT_DIR) / "downloads").resolve())
def is_uploaded_file_id(value: str) -> bool:
@@ -368,8 +383,8 @@ async def fetch_file_bytes(
raise HttpException(400, "[redacted]", "Too many redirects while downloading file")
-def _resolve_legacy_download_path(candidate_path: str) -> str:
- """Resolve a legacy file:// path and confirm it is inside the repository downloads directory.
+def _resolve_legacy_download_path(candidate_path: str, *, organization_id: str | None = None) -> str:
+ """Resolve a legacy file:// path inside repository downloads or registered download snapshots.
Containment is checked on the realpath with commonpath, so dot segments, percent-decoded dot
segments, symlinks, and sibling directories such as ``downloads-evil`` cannot escape.
@@ -377,18 +392,36 @@ def _resolve_legacy_download_path(candidate_path: str) -> str:
allowed_dir = os.path.realpath(os.path.join(REPO_ROOT_DIR, "downloads"))
resolved_path = os.path.realpath(candidate_path)
try:
- inside_allowed_dir = os.path.commonpath((allowed_dir, resolved_path)) == allowed_dir
+ if os.path.commonpath((allowed_dir, resolved_path)) == allowed_dir:
+ return resolved_path
except ValueError:
- inside_allowed_dir = False
- if not inside_allowed_dir:
- LOG.warning(
- "Legacy local file path traversal blocked",
- candidate_path=candidate_path,
- resolved_path=resolved_path,
- allowed_dir=allowed_dir,
- )
- raise PermissionError("Local file path is outside the downloads directory")
- return resolved_path
+ pass
+ if (
+ organization_id
+ and organization_id not in (".", "..")
+ and not os.path.isabs(organization_id)
+ and "/" not in organization_id
+ and "\\" not in organization_id
+ ):
+ for root in _LOCAL_DOWNLOAD_ROOTS:
+ root = os.path.realpath(root)
+ try:
+ organization_root = os.path.realpath(os.path.join(root, settings.ENV, organization_id))
+ if (
+ os.path.commonpath((root, organization_root)) == root
+ and os.path.commonpath((root, resolved_path)) == root
+ and os.path.commonpath((organization_root, resolved_path)) == organization_root
+ ):
+ return resolved_path
+ except ValueError:
+ continue
+ LOG.warning(
+ "Legacy local file path traversal blocked",
+ candidate_path=candidate_path,
+ resolved_path=resolved_path,
+ allowed_dir=allowed_dir,
+ )
+ raise PermissionError("Local file path is outside the downloads directory")
def validate_download_url(url: str, organization_id: str | None = None) -> bool:
@@ -436,7 +469,7 @@ def validate_download_url(url: str, organization_id: str | None = None) -> bool:
# Validate the file path is within allowed directories
try:
- _resolve_legacy_download_path(parse_uri_to_path(url))
+ _resolve_legacy_download_path(parse_uri_to_path(url), organization_id=organization_id)
return True
except (ValueError, PermissionError):
return False
@@ -525,7 +558,7 @@ async def download_file(
# we only support to download local files when the environment is local
# and the file is in the skyvern downloads directory
if url.startswith("file://") and settings.ENV == "local":
- local_path = _resolve_legacy_download_path(parse_uri_to_path(url))
+ local_path = _resolve_legacy_download_path(parse_uri_to_path(url), organization_id=organization_id)
LOG.info("Downloading file from local file system", url=url)
return local_path
@@ -973,10 +1006,15 @@ def resolve_run_download_id(context: "SkyvernContext | None", fallback_run_id: s
return fallback_run_id
-def list_files_in_directory(directory: Path, recursive: bool = False) -> list[str]:
+def list_files_in_directory(
+ directory: Path, recursive: bool = False, *, attempt_started_at: datetime | None = None
+) -> list[str]:
listed_files: list[str] = []
for root, dirs, files in os.walk(directory):
- listed_files.extend([os.path.join(root, file) for file in files])
+ for file in files:
+ path = os.path.join(root, file)
+ if attempt_started_at is None or is_file_from_retry_attempt(path, attempt_started_at):
+ listed_files.append(path)
if not recursive:
break
@@ -1019,11 +1057,11 @@ def _resolve_extension_rename_twin(download_dir: str, filename: str) -> str:
def list_downloading_files_in_directory(
- directory: Path, downloading_suffix: str = BROWSER_DOWNLOADING_SUFFIX
+ directory: Path, downloading_suffix: str = BROWSER_DOWNLOADING_SUFFIX, *, attempt_started_at: datetime | None = None
) -> list[str]:
# check if there's any file is still downloading
downloading_files: list[str] = []
- for file in list_files_in_directory(directory):
+ for file in list_files_in_directory(directory, attempt_started_at=attempt_started_at):
path = Path(file)
if path.suffix == downloading_suffix:
downloading_files.append(file)
@@ -1065,9 +1103,11 @@ async def check_downloading_files_and_wait_for_download_to_complete(
organization_id: str,
browser_session_id: str | None = None,
timeout: float = BROWSER_DOWNLOAD_TIMEOUT,
+ *,
+ attempt_started_at: datetime | None = None,
) -> None:
# check if there's any file is still downloading
- downloading_files = list_downloading_files_in_directory(download_dir)
+ downloading_files = list_downloading_files_in_directory(download_dir, attempt_started_at=attempt_started_at)
if browser_session_id:
files_in_browser_session = await app.STORAGE.list_downloading_files_in_browser_session(
organization_id=organization_id, browser_session_id=browser_session_id
diff --git a/skyvern/forge/sdk/artifact/manager.py b/skyvern/forge/sdk/artifact/manager.py
index c14ba7704..933e42d7d 100644
--- a/skyvern/forge/sdk/artifact/manager.py
+++ b/skyvern/forge/sdk/artifact/manager.py
@@ -24,6 +24,7 @@ from skyvern.forge.sdk.artifact.signing import (
sign_artifact_url,
verify_artifact_signature,
)
+from skyvern.forge.sdk.artifact.storage.base import artifact_filename_from_uri
from skyvern.forge.sdk.artifact.utils import replace_file_extension
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.db.id import generate_artifact_id
@@ -461,22 +462,14 @@ class ArtifactManager:
row so the file can be served through the signed ``/v1/artifacts/{id}/content``
endpoint.
"""
- # Idempotent on (run_id, uri): if a DOWNLOAD artifact already exists for the
- # same physical file (e.g. a loop iteration re-uploads the same download dir),
- # return the existing artifact_id so signed URLs stay stable across calls —
- # otherwise ``loop_download_filter.to_downloaded_file_signature`` would treat
- # every iteration's URL as new.
+ context = skyvern_context.current()
+ # Retry uploads use attempt-specific URIs; reuse within one attempt keeps loop URLs stable.
existing = await app.DATABASE.artifacts.find_download_artifact(
organization_id=organization_id,
run_id=run_id,
uri=uri,
)
if existing is not None:
- # Changed bytes under the same uri refresh the row's checksum so the loop filter's
- # (filename, checksum, url) signature moves with the content instead of hiding a
- # genuine re-download behind the stale row. A failed refresh propagates: the stale
- # row must not vouch for bytes it does not describe, so the save loop records the
- # file as skipped and workflow finalization's re-save retries the refresh.
if checksum is not None and existing.checksum != checksum:
await app.DATABASE.artifacts.refresh_download_artifact_content(
artifact_id=existing.artifact_id,
@@ -487,7 +480,6 @@ class ArtifactManager:
return existing.artifact_id
artifact_id = generate_artifact_id()
- context = skyvern_context.current()
if workflow_run_id is None and context is not None:
workflow_run_id = context.workflow_run_id
await app.DATABASE.artifacts.create_artifact(
@@ -1482,9 +1474,7 @@ class ArtifactManager:
# in ``bundle_key``; non-bundled artifacts have it as the URI
# basename. Without this fallback the path basename is just
# "content" and the UI falls back to a literal "download" label.
- artifact_name = artifact.bundle_key
- if artifact_name is None and artifact.uri:
- artifact_name = artifact.uri.rsplit("/", 1)[-1] or None
+ artifact_name = artifact.bundle_key or artifact_filename_from_uri(artifact.uri) or None
return self._bundle_content_url(
artifact.artifact_id,
artifact_name=artifact_name,
diff --git a/skyvern/forge/sdk/artifact/storage/azure.py b/skyvern/forge/sdk/artifact/storage/azure.py
index ec34798a0..9986c24bd 100644
--- a/skyvern/forge/sdk/artifact/storage/azure.py
+++ b/skyvern/forge/sdk/artifact/storage/azure.py
@@ -29,8 +29,10 @@ from skyvern.forge.sdk.artifact.storage.base import (
_file_infos_from_download_artifacts,
dedupe_run_scoped_download_artifacts,
download_checksums_by_uri,
+ is_file_from_retry_attempt,
key_is_org_scoped,
presign_with_sensitive_cap,
+ resolve_download_attempt_fail_open,
)
from skyvern.forge.sdk.artifact.storage.run_recording_clips import RUN_RECORDING_PATH_SEGMENT, sync_run_recording_clips
from skyvern.forge.sdk.artifact.utils import replace_file_extension
@@ -537,6 +539,8 @@ class AzureStorage(BaseStorage):
self,
organization_id: str,
run_id: str | None,
+ *,
+ attempt_number: int | None = None,
) -> None:
tier = await self._get_storage_tier_for_org(organization_id)
tags = await self._get_tags_for_org(organization_id)
@@ -548,6 +552,7 @@ class AzureStorage(BaseStorage):
run_id=run_id,
tier=tier,
tags=tags,
+ attempt_number=attempt_number,
)
async def _save_downloaded_files_from_local(
@@ -557,12 +562,19 @@ class AzureStorage(BaseStorage):
run_id: str | None,
tier: StandardBlobTier,
tags: dict[str, str] | None,
+ attempt_number: int | None = None,
) -> None:
"""Save files from local download directory to Azure."""
download_dir = get_download_dir(run_id=run_id)
files = os.listdir(download_dir)
if not files:
return
+ retry_workflow_run_id, attempt_number, retry_attempt_started_at = await resolve_download_attempt_fail_open(
+ organization_id, run_id, attempt_number=attempt_number
+ )
+ retry_attempt = run_id is not None and attempt_number > 1
+ if retry_attempt:
+ base_uri = f"{base_uri}/attempts/{attempt_number}"
already_saved = (
download_checksums_by_uri(
await self._list_download_artifacts_safe(organization_id=organization_id, run_id=run_id)
@@ -580,6 +592,8 @@ class AzureStorage(BaseStorage):
fpath = os.path.join(download_dir, file)
if not os.path.isfile(fpath):
continue
+ if retry_attempt and not is_file_from_retry_attempt(fpath, retry_attempt_started_at):
+ continue
uri = f"{base_uri}/{file}"
checksum = calculate_sha256_for_file(fpath)
# Cleanup runs repeatedly over a growing download dir; re-sending bytes that are
@@ -625,6 +639,7 @@ class AzureStorage(BaseStorage):
run_id=run_id,
uri=uri,
filename=file,
+ workflow_run_id=retry_workflow_run_id if retry_attempt else None,
checksum=checksum,
file_size=file_size,
)
@@ -653,13 +668,20 @@ class AzureStorage(BaseStorage):
# the keyring isn't configured (OSS default) or no artifact rows exist
# (legacy run pre-SKY-8861) we fall back to the legacy listing path so
# downloaded files remain reachable.
+ download_artifacts: list[Artifact] | None = None
if run_id is not None and settings.ARTIFACT_CONTENT_HMAC_KEYRING:
- artifacts = await self._list_download_artifacts_safe(organization_id=organization_id, run_id=run_id)
- artifacts = dedupe_run_scoped_download_artifacts(artifacts)
- if artifacts:
- return await _file_infos_from_download_artifacts(artifacts)
+ download_artifacts = await self._list_download_artifacts_safe(
+ organization_id=organization_id, run_id=run_id
+ )
+ download_artifacts = dedupe_run_scoped_download_artifacts(download_artifacts)
+ if download_artifacts:
+ return await _file_infos_from_download_artifacts(download_artifacts)
- return await self._get_downloaded_files_via_blob_listing(organization_id=organization_id, run_id=run_id)
+ return await self._get_downloaded_files_via_blob_listing(
+ organization_id=organization_id,
+ run_id=run_id,
+ download_artifacts=download_artifacts,
+ )
async def _list_download_artifacts_safe(self, *, organization_id: str, run_id: str) -> list[Artifact]:
try:
@@ -678,8 +700,18 @@ class AzureStorage(BaseStorage):
return []
async def _get_downloaded_files_via_blob_listing(
- self, *, organization_id: str, run_id: str | None
+ self,
+ *,
+ organization_id: str,
+ run_id: str | None,
+ download_artifacts: list[Artifact] | None = None,
) -> list[FileInfo]:
+ if download_artifacts is None and run_id is not None:
+ download_artifacts = await self._list_download_artifacts_safe(
+ organization_id=organization_id,
+ run_id=run_id,
+ )
+ artifacts_by_uri = {artifact.uri: artifact for artifact in download_artifacts or []}
uri = f"azure://{settings.AZURE_STORAGE_CONTAINER_UPLOADS}/{DOWNLOAD_FILE_PREFIX}/{settings.ENV}/{organization_id}/{run_id}"
object_keys = await self.async_client.list_files(uri=uri)
if len(object_keys) == 0:
@@ -691,13 +723,16 @@ class AzureStorage(BaseStorage):
metadata = {}
content_length: int | None = None
+ blob_modified_at = None
object_info = await _get_object_info_safe(self, object_uri)
if object_info:
metadata = object_info.get("Metadata", {})
content_length = object_info.get("ContentLength")
+ blob_modified_at = object_info.get("LastModified")
filename = os.path.basename(key)
checksum = metadata.get("sha256_checksum") if metadata else None
display_name = metadata.get("original_filename", filename) if metadata else filename
+ artifact = artifacts_by_uri.get(object_uri)
sas_urls = await self.async_client.create_sas_urls([object_uri])
if not sas_urls:
@@ -709,6 +744,8 @@ class AzureStorage(BaseStorage):
checksum=checksum,
filename=display_name,
file_size=content_length,
+ modified_at=artifact.modified_at if artifact is not None else blob_modified_at,
+ artifact_id=artifact.artifact_id if artifact is not None else None,
)
)
diff --git a/skyvern/forge/sdk/artifact/storage/base.py b/skyvern/forge/sdk/artifact/storage/base.py
index bd1e1c3a2..cc210759a 100644
--- a/skyvern/forge/sdk/artifact/storage/base.py
+++ b/skyvern/forge/sdk/artifact/storage/base.py
@@ -1,17 +1,25 @@
+import os
from abc import ABC, abstractmethod
from collections import Counter
from collections.abc import Awaitable, Callable
-from datetime import datetime
+from datetime import UTC, datetime
from typing import BinaryIO, cast
+from urllib.parse import unquote
+
+import structlog
from skyvern.forge import app
from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType, LogEntityType
from skyvern.forge.sdk.artifact.signing import SENSITIVE_ARTIFACT_TYPES, SENSITIVE_ARTIFACT_URL_EXPIRY_SECONDS
+from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.models import Step
from skyvern.forge.sdk.schemas.ai_suggestions import AISuggestion
from skyvern.forge.sdk.schemas.files import FileInfo
from skyvern.forge.sdk.schemas.task_v2 import TaskV2, Thought
from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock
+from skyvern.forge.sdk.workflow.loop_download_filter import DownloadedFileSignature
+
+LOG = structlog.get_logger()
# Hour-granularity equivalent of the sensitive cap for the GCS/Azure signing
# clients, whose APIs take hours; max() keeps a future sub-hour cap from
@@ -19,6 +27,130 @@ from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock
SENSITIVE_SHARE_URL_EXPIRY_HOURS = max(1, SENSITIVE_ARTIFACT_URL_EXPIRY_SECONDS // 3600)
+async def resolve_current_attempt(
+ workflow_run_id: str | None,
+ attempt_number: int | None = None,
+) -> tuple[int, datetime | None]:
+ """Resolve the current attempt from durable rows and the process-local context.
+
+ A workflow context can be absent while cleanup is running, including when context
+ initialization failed. The attempt rows are therefore the durable fallback. Read them once
+ so callers can use the same attempt number and start time for the entire save operation. An
+ explicit attempt number takes precedence over the live context and the latest durable row.
+ """
+ if workflow_run_id is None:
+ return attempt_number if attempt_number is not None else 1, None
+
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ if not attempts:
+ return attempt_number if attempt_number is not None else 1, None
+
+ resolved_attempt_number = attempt_number
+ if resolved_attempt_number is None:
+ context = app.WORKFLOW_CONTEXT_MANAGER.workflow_run_contexts.get(workflow_run_id)
+ resolved_attempt_number = (
+ context.attempt_number if context is not None else max(row.attempt_number for row in attempts)
+ )
+ attempt = next((row for row in attempts if row.attempt_number == resolved_attempt_number), None)
+ return resolved_attempt_number, attempt.started_at if attempt is not None else None
+
+
+async def resolve_download_attempt(
+ organization_id: str,
+ run_id: str | None,
+ attempt_number: int | None = None,
+) -> tuple[str | None, int, datetime | None]:
+ """Use the workflow owning the shared download directory, not the saving child."""
+ workflow_run_id = run_id
+ if run_id is not None and run_id.startswith("tsk_v2_"):
+ run = await app.DATABASE.tasks.get_run(run_id, organization_id=organization_id)
+ if run is not None and run.parent_workflow_run_id:
+ workflow_run_id = run.parent_workflow_run_id
+ else:
+ task = await app.DATABASE.observer.get_task_v2(run_id, organization_id=organization_id)
+ workflow_run_id = task.workflow_run_id if task is not None else None
+ if workflow_run_id is None or not workflow_run_id.startswith("wr_"):
+ return None, 1, None
+
+ # Every reader treats attempt 1 as unscoped, so a run live in this process on its first attempt
+ # is resolved without the ancestry walk or the attempt rows. A child run resolves durably: its
+ # downloads belong to the root's attempt.
+ context = skyvern_context.current()
+ if (
+ attempt_number is None
+ and context is not None
+ and context.root_workflow_run_id == workflow_run_id
+ and app.WORKFLOW_CONTEXT_MANAGER.get_attempt_number(workflow_run_id) <= 1
+ and app.WORKFLOW_CONTEXT_MANAGER.has_workflow_run_context(workflow_run_id)
+ ):
+ return workflow_run_id, 1, None
+
+ initial_workflow_run_id = workflow_run_id
+ visited: set[str] = set()
+ while workflow_run_id not in visited:
+ visited.add(workflow_run_id)
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id, organization_id=organization_id
+ )
+ if workflow_run is None or not workflow_run.parent_workflow_run_id:
+ break
+ workflow_run_id = workflow_run.parent_workflow_run_id
+ else:
+ raise ValueError("Cycle in download owner workflow ancestry")
+
+ context = skyvern_context.current()
+ saving_workflow_run_id = context.workflow_run_id if context and context.workflow_run_id else initial_workflow_run_id
+ if saving_workflow_run_id != workflow_run_id:
+ attempt_number = None
+ number, started_at = await resolve_current_attempt(workflow_run_id, attempt_number=attempt_number)
+ return workflow_run_id, number, started_at
+
+
+async def resolve_download_attempt_fail_open(
+ organization_id: str,
+ run_id: str | None,
+ attempt_number: int | None = None,
+) -> tuple[str | None, int, datetime | None]:
+ """Resolve the owner and attempt; a failed lookup treats every file as current instead of none."""
+ try:
+ return await resolve_download_attempt(organization_id, run_id, attempt_number=attempt_number)
+ except Exception:
+ LOG.warning(
+ "Failed to resolve download attempt; treating every downloaded file as current",
+ organization_id=organization_id,
+ run_id=run_id,
+ attempt_number=attempt_number,
+ exc_info=True,
+ )
+ return None, attempt_number or 1, None
+
+
+async def get_download_retry_started_at(organization_id: str | None, run_id: str | None) -> datetime | None:
+ _, attempt_number, started_at = await resolve_download_attempt_fail_open(organization_id or "", run_id)
+ if attempt_number <= 1 or started_at is None:
+ return None
+ return started_at.replace(tzinfo=UTC) if started_at.tzinfo is None else started_at
+
+
+def is_file_from_retry_attempt(file_path: str, attempt_started_at: datetime | None) -> bool:
+ """Whether a local file was modified at or after the current attempt started.
+
+ An unknown start time keeps the file: re-saving a stale file under the current attempt is
+ recoverable, while skipping every file loses the download.
+ """
+ if attempt_started_at is None:
+ return True
+ if attempt_started_at.tzinfo is None:
+ attempt_started_at = attempt_started_at.replace(tzinfo=UTC)
+ else:
+ attempt_started_at = attempt_started_at.astimezone(UTC)
+ try:
+ file_modified_at = datetime.fromtimestamp(os.path.getmtime(file_path), tz=UTC)
+ except OSError:
+ return False
+ return file_modified_at >= attempt_started_at
+
+
def key_is_org_scoped(key: str, allowed_prefixes: tuple[str, ...]) -> bool:
"""Whether an object key sits under one of the caller's org-scoped prefixes.
@@ -79,7 +211,7 @@ async def _file_infos_from_artifacts(artifacts: list[Artifact], *, artifact_type
_ = artifact_type # kept for call-site compatibility; URL hint now sourced from the artifact row.
infos: list[FileInfo] = []
for artifact in artifacts:
- filename = artifact.uri.rsplit("/", 1)[-1] if artifact.uri else ""
+ filename = artifact_filename_from_uri(artifact.uri)
url = await app.ARTIFACT_MANAGER.resolve_share_url(artifact, expiry_seconds=expiry_seconds)
if url is None:
continue
@@ -89,13 +221,24 @@ async def _file_infos_from_artifacts(artifacts: list[Artifact], *, artifact_type
checksum=artifact.checksum,
filename=filename,
file_size=artifact.file_size,
- modified_at=artifact.created_at,
+ modified_at=artifact.modified_at or artifact.created_at,
artifact_id=artifact.artifact_id,
)
)
return infos
+def artifact_filename_from_uri(uri: str | None) -> str:
+ """Basename of an artifact URI without urlparse: "?" and "#" are legal in object-store keys.
+
+ A local file URI percent-encodes its name (managed_file_uri), so only that scheme is decoded.
+ """
+ if not uri:
+ return ""
+ basename = uri.rsplit("/", 1)[-1]
+ return unquote(basename) if uri.startswith("file://") else basename
+
+
def download_checksums_by_uri(artifacts: list[Artifact]) -> dict[str, str]:
"""URI -> SHA-256 for DOWNLOAD rows that carry one.
@@ -354,11 +497,30 @@ class BaseStorage(ABC):
self,
organization_id: str,
run_id: str | None,
+ *,
+ attempt_number: int | None = None,
) -> None:
"""Raises DownloadSaveIncompleteError after the loop when any file could not be fully
saved and registered; every other file already is when it raises, so the save is
retryable-incomplete."""
+ def get_downloaded_file_signature_aliases(self, file_info: FileInfo) -> list[DownloadedFileSignature]:
+ return []
+
+ async def get_current_attempt_downloaded_files(self, organization_id: str, run_id: str | None) -> list[FileInfo]:
+ files = await self.get_downloaded_files(organization_id=organization_id, run_id=run_id)
+ started_at = await get_download_retry_started_at(organization_id, run_id)
+ if started_at is None:
+ return files
+ current_files = []
+ for file_info in files:
+ modified_at = file_info.modified_at
+ if modified_at is not None and modified_at.tzinfo is None:
+ modified_at = modified_at.replace(tzinfo=UTC)
+ if modified_at is None or modified_at >= started_at:
+ current_files.append(file_info)
+ return current_files
+
@abstractmethod
async def get_downloaded_files(self, organization_id: str, run_id: str | None) -> list[FileInfo]:
pass
diff --git a/skyvern/forge/sdk/artifact/storage/gcs.py b/skyvern/forge/sdk/artifact/storage/gcs.py
index 31747949c..3a117fc9d 100644
--- a/skyvern/forge/sdk/artifact/storage/gcs.py
+++ b/skyvern/forge/sdk/artifact/storage/gcs.py
@@ -30,8 +30,10 @@ from skyvern.forge.sdk.artifact.storage.base import (
_file_infos_from_download_artifacts,
dedupe_run_scoped_download_artifacts,
download_checksums_by_uri,
+ is_file_from_retry_attempt,
key_is_org_scoped,
presign_with_sensitive_cap,
+ resolve_download_attempt_fail_open,
)
from skyvern.forge.sdk.artifact.storage.run_recording_clips import (
RUN_RECORDING_CLIPS_SYNC_TIMEOUT_SECONDS,
@@ -550,6 +552,8 @@ class GcsStorage(BaseStorage):
self,
organization_id: str,
run_id: str | None,
+ *,
+ attempt_number: int | None = None,
) -> None:
storage_class = await self._get_storage_class_for_org(organization_id)
tags = await self._get_tags_for_org(organization_id)
@@ -563,6 +567,7 @@ class GcsStorage(BaseStorage):
run_id=run_id,
storage_class=storage_class,
tags=tags,
+ attempt_number=attempt_number,
)
async def _save_downloaded_files_from_local(
@@ -572,12 +577,19 @@ class GcsStorage(BaseStorage):
run_id: str | None,
storage_class: str,
tags: dict[str, str] | None,
+ attempt_number: int | None = None,
) -> None:
"""Save files from local download directory to GCS."""
download_dir = get_download_dir(run_id=run_id)
files = os.listdir(download_dir)
if not files:
return
+ retry_workflow_run_id, attempt_number, retry_attempt_started_at = await resolve_download_attempt_fail_open(
+ organization_id, run_id, attempt_number=attempt_number
+ )
+ retry_attempt = run_id is not None and attempt_number > 1
+ if retry_attempt:
+ base_uri = f"{base_uri}/attempts/{attempt_number}"
already_saved = (
download_checksums_by_uri(
await self._list_download_artifacts_safe(organization_id=organization_id, run_id=run_id)
@@ -595,6 +607,8 @@ class GcsStorage(BaseStorage):
fpath = os.path.join(download_dir, file)
if not os.path.isfile(fpath):
continue
+ if retry_attempt and not is_file_from_retry_attempt(fpath, retry_attempt_started_at):
+ continue
uri = f"{base_uri}/{file}"
checksum = calculate_sha256_for_file(fpath)
# Cleanup runs repeatedly over a growing download dir; re-sending bytes that are
@@ -639,6 +653,7 @@ class GcsStorage(BaseStorage):
run_id=run_id,
uri=uri,
filename=file,
+ workflow_run_id=retry_workflow_run_id if retry_attempt else None,
checksum=checksum,
file_size=file_size,
)
@@ -667,13 +682,20 @@ class GcsStorage(BaseStorage):
# the keyring isn't configured (OSS default) or no artifact rows exist
# (legacy run) we fall back to the legacy listing path so
# downloaded files remain reachable.
+ download_artifacts: list[Artifact] | None = None
if run_id is not None and settings.ARTIFACT_CONTENT_HMAC_KEYRING:
- artifacts = await self._list_download_artifacts_safe(organization_id=organization_id, run_id=run_id)
- artifacts = dedupe_run_scoped_download_artifacts(artifacts)
- if artifacts:
- return await _file_infos_from_download_artifacts(artifacts)
+ download_artifacts = await self._list_download_artifacts_safe(
+ organization_id=organization_id, run_id=run_id
+ )
+ download_artifacts = dedupe_run_scoped_download_artifacts(download_artifacts)
+ if download_artifacts:
+ return await _file_infos_from_download_artifacts(download_artifacts)
- return await self._get_downloaded_files_via_blob_listing(organization_id=organization_id, run_id=run_id)
+ return await self._get_downloaded_files_via_blob_listing(
+ organization_id=organization_id,
+ run_id=run_id,
+ download_artifacts=download_artifacts,
+ )
async def _list_download_artifacts_safe(self, *, organization_id: str, run_id: str) -> list[Artifact]:
try:
@@ -692,8 +714,18 @@ class GcsStorage(BaseStorage):
return []
async def _get_downloaded_files_via_blob_listing(
- self, *, organization_id: str, run_id: str | None
+ self,
+ *,
+ organization_id: str,
+ run_id: str | None,
+ download_artifacts: list[Artifact] | None = None,
) -> list[FileInfo]:
+ if download_artifacts is None and run_id is not None:
+ download_artifacts = await self._list_download_artifacts_safe(
+ organization_id=organization_id,
+ run_id=run_id,
+ )
+ artifacts_by_uri = {artifact.uri: artifact for artifact in download_artifacts or []}
uri = f"gs://{settings.GCS_BUCKET_UPLOADS}/{DOWNLOAD_FILE_PREFIX}/{settings.ENV}/{organization_id}/{run_id}"
object_keys = await self.async_client.list_files(uri=uri)
if len(object_keys) == 0:
@@ -705,13 +737,16 @@ class GcsStorage(BaseStorage):
metadata = {}
content_length: int | None = None
+ blob_modified_at = None
object_info = await _get_object_info_safe(self, object_uri)
if object_info:
metadata = object_info.get("Metadata", {})
content_length = object_info.get("ContentLength")
+ blob_modified_at = object_info.get("LastModified")
filename = os.path.basename(key)
checksum = metadata.get("sha256_checksum") if metadata else None
display_name = metadata.get("original_filename", filename) if metadata else filename
+ artifact = artifacts_by_uri.get(object_uri)
signed_urls = await self.async_client.create_signed_urls([object_uri])
if not signed_urls:
@@ -723,6 +758,8 @@ class GcsStorage(BaseStorage):
checksum=checksum,
filename=display_name,
file_size=content_length,
+ modified_at=artifact.modified_at if artifact is not None else blob_modified_at,
+ artifact_id=artifact.artifact_id if artifact is not None else None,
)
)
diff --git a/skyvern/forge/sdk/artifact/storage/local.py b/skyvern/forge/sdk/artifact/storage/local.py
index 67248aa87..c1cec6e98 100644
--- a/skyvern/forge/sdk/artifact/storage/local.py
+++ b/skyvern/forge/sdk/artifact/storage/local.py
@@ -10,19 +10,30 @@ import structlog
from skyvern.config import settings
from skyvern.constants import DOWNLOAD_FILE_PREFIX
+from skyvern.exceptions import DownloadSaveIncompleteError
+from skyvern.forge import app
from skyvern.forge.sdk.api.files import (
calculate_sha256_for_file,
get_download_dir,
get_skyvern_temp_dir,
parse_uri_to_path,
+ register_local_download_root,
+ wait_for_pending_extension_rename,
)
from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType, LogEntityType
-from skyvern.forge.sdk.artifact.storage.base import FILE_EXTENTSION_MAP, BaseStorage
+from skyvern.forge.sdk.artifact.storage.base import (
+ FILE_EXTENTSION_MAP,
+ BaseStorage,
+ download_checksums_by_uri,
+ is_file_from_retry_attempt,
+ resolve_download_attempt_fail_open,
+)
from skyvern.forge.sdk.models import Step
from skyvern.forge.sdk.schemas.ai_suggestions import AISuggestion
from skyvern.forge.sdk.schemas.files import FileInfo
from skyvern.forge.sdk.schemas.task_v2 import TaskV2, Thought
from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock
+from skyvern.forge.sdk.workflow.loop_download_filter import DownloadedFileSignature, to_downloaded_file_signature
from skyvern.utils.script_file_paths import build_script_file_storage_uri
from skyvern.webeye.session_cookies import SESSION_COOKIES_FILENAME
@@ -80,6 +91,7 @@ def managed_file_uri(path: PurePath) -> str:
class LocalStorage(BaseStorage):
def __init__(self, artifact_path: str = settings.ARTIFACT_STORAGE_PATH) -> None:
self.artifact_path = artifact_path
+ register_local_download_root(os.path.join(self.artifact_path, "downloads"))
def build_uri(self, *, organization_id: str, artifact_id: str, step: Step, artifact_type: ArtifactType) -> str:
file_ext = FILE_EXTENTSION_MAP[artifact_type]
@@ -397,8 +409,58 @@ class LocalStorage(BaseStorage):
if hard_delete:
raise
- async def save_downloaded_files(self, organization_id: str, run_id: str | None) -> None:
- pass
+ async def save_downloaded_files(
+ self,
+ organization_id: str,
+ run_id: str | None,
+ *,
+ attempt_number: int | None = None,
+ ) -> None:
+ if run_id is None:
+ return
+ download_dir = get_download_dir(run_id=run_id)
+ files = os.listdir(download_dir)
+ if not files:
+ return
+ owner_id, number, started_at = await resolve_download_attempt_fail_open(organization_id, run_id, attempt_number)
+ destination = Path(self.artifact_path) / DOWNLOAD_FILE_PREFIX / settings.ENV / organization_id / run_id
+ if number > 1:
+ destination = destination / "attempts" / str(number)
+ artifacts = await app.DATABASE.artifacts.list_artifacts_for_run_by_type(
+ organization_id=organization_id, run_id=run_id, artifact_type=ArtifactType.DOWNLOAD
+ )
+ saved = download_checksums_by_uri(artifacts)
+ skipped: list[str] = []
+ for filename in files:
+ source = Path(download_dir) / filename
+ if not source.is_file():
+ continue
+ filename = await wait_for_pending_extension_rename(download_dir, filename)
+ source = Path(download_dir) / filename
+ if not source.is_file() or (number > 1 and not is_file_from_retry_attempt(str(source), started_at)):
+ continue
+ target = destination / filename
+ uri = managed_file_uri(target.resolve())
+ try:
+ checksum = calculate_sha256_for_file(str(source))
+ if saved.get(uri) == checksum and target.is_file():
+ continue
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(source, target)
+ await app.ARTIFACT_MANAGER.create_download_artifact(
+ organization_id=organization_id,
+ run_id=run_id,
+ workflow_run_id=owner_id,
+ uri=uri,
+ filename=filename,
+ checksum=checksum,
+ file_size=target.stat().st_size,
+ )
+ except Exception:
+ LOG.warning("Failed to preserve local download", filename=filename, run_id=run_id, exc_info=True)
+ skipped.append(filename)
+ if skipped:
+ raise DownloadSaveIncompleteError(skipped)
async def list_downloaded_files_in_browser_session(
self, organization_id: str, browser_session_id: str
@@ -487,24 +549,93 @@ class LocalStorage(BaseStorage):
file_infos.sort(key=lambda f: (f.modified_at is not None, f.modified_at), reverse=True)
return file_infos
+ def get_downloaded_file_signature_aliases(self, file_info: FileInfo) -> list[DownloadedFileSignature]:
+ if not file_info.url.startswith("file://"):
+ return []
+ snapshot_root = (Path(self.artifact_path) / DOWNLOAD_FILE_PREFIX / settings.ENV).resolve()
+ try:
+ parts = Path(parse_uri_to_path(file_info.url)).resolve().relative_to(snapshot_root).parts
+ except ValueError:
+ return []
+ if len(parts) != 3 and not (len(parts) == 5 and parts[2] == "attempts" and parts[3].isdigit()):
+ return []
+ if parts[-1] != file_info.filename:
+ return []
+ live_uri = f"file://{Path(get_download_dir(run_id=parts[1])) / file_info.filename}"
+ return [to_downloaded_file_signature(file_info.model_copy(update={"url": live_uri}))]
+
async def get_downloaded_files(self, organization_id: str, run_id: str | None) -> list[FileInfo]:
download_dir = get_download_dir(run_id=run_id)
- file_infos: list[FileInfo] = []
+ artifacts_by_uri: dict[str, Artifact] = {}
+ if run_id is not None:
+ try:
+ artifacts = await app.DATABASE.artifacts.list_artifacts_for_run_by_type(
+ run_id=run_id,
+ organization_id=organization_id,
+ artifact_type=ArtifactType.DOWNLOAD,
+ )
+ artifacts_by_uri = {artifact.uri: artifact for artifact in artifacts}
+ except Exception:
+ # Local storage remains usable before the Forge app is initialized and during a
+ # transient database outage. The file's stat metadata is still useful to the
+ # attempt filter, and an un-attributed file must be handled fail-open there.
+ LOG.warning(
+ "Failed to load local download artifact attribution",
+ organization_id=organization_id,
+ run_id=run_id,
+ exc_info=True,
+ )
+ snapshot_root = (
+ Path(self.artifact_path) / DOWNLOAD_FILE_PREFIX / settings.ENV / organization_id / str(run_id)
+ ).resolve()
+ snapshots = {
+ uri: artifact
+ for uri, artifact in artifacts_by_uri.items()
+ if uri.startswith("file://")
+ and (snapshot_path := Path(parse_uri_to_path(uri))).is_relative_to(snapshot_root)
+ and snapshot_path.is_file()
+ }
+ snapshot_contents = {
+ (Path(parse_uri_to_path(artifact.uri)).name, artifact.checksum) for artifact in snapshots.values()
+ }
+ file_infos = [
+ FileInfo(
+ url=artifact.uri,
+ checksum=artifact.checksum,
+ filename=Path(parse_uri_to_path(artifact.uri)).name,
+ file_size=artifact.file_size,
+ modified_at=artifact.modified_at or artifact.created_at,
+ artifact_id=artifact.artifact_id,
+ )
+ for artifact in snapshots.values()
+ ]
files_and_folders = os.listdir(download_dir)
for file_or_folder in files_and_folders:
path = os.path.join(download_dir, file_or_folder)
if os.path.isfile(path):
checksum = calculate_sha256_for_file(path)
+ if (file_or_folder, checksum) in snapshot_contents:
+ continue
+ uri = f"file://{path}"
+ artifact = artifacts_by_uri.get(uri)
+ modified_at: datetime | None
+ try:
+ modified_at = datetime.fromtimestamp(os.stat(path).st_mtime, tz=UTC)
+ except OSError:
+ LOG.warning("Failed to get local downloaded file modification time", path=path, exc_info=True)
+ modified_at = artifact.modified_at if artifact is not None else None
try:
file_size = os.path.getsize(path)
except OSError:
LOG.warning("Failed to get local downloaded file size", path=path, exc_info=True)
file_size = None
file_info = FileInfo(
- url=f"file://{path}",
+ url=uri,
checksum=checksum,
filename=file_or_folder,
file_size=file_size,
+ modified_at=modified_at,
+ artifact_id=artifact.artifact_id if artifact is not None else None,
)
file_infos.append(file_info)
return file_infos
diff --git a/skyvern/forge/sdk/artifact/storage/s3.py b/skyvern/forge/sdk/artifact/storage/s3.py
index 5402e7e93..8cbae9cc3 100644
--- a/skyvern/forge/sdk/artifact/storage/s3.py
+++ b/skyvern/forge/sdk/artifact/storage/s3.py
@@ -34,8 +34,10 @@ from skyvern.forge.sdk.artifact.storage.base import (
_file_infos_from_download_artifacts,
dedupe_run_scoped_download_artifacts,
download_checksums_by_uri,
+ is_file_from_retry_attempt,
key_is_org_scoped,
presign_with_sensitive_cap,
+ resolve_download_attempt_fail_open,
)
from skyvern.forge.sdk.artifact.storage.bounded_file import BoundedFileReader
from skyvern.forge.sdk.artifact.storage.run_recording_clips import (
@@ -808,6 +810,8 @@ class S3Storage(BaseStorage):
self,
organization_id: str,
run_id: str | None,
+ *,
+ attempt_number: int | None = None,
) -> None:
sc = await self._get_storage_class_for_org(organization_id, settings.AWS_S3_BUCKET_UPLOADS)
base_uri = (
@@ -819,6 +823,7 @@ class S3Storage(BaseStorage):
run_id=run_id,
base_uri=base_uri,
storage_class=sc,
+ attempt_number=attempt_number,
)
async def _save_downloaded_files_from_local(
@@ -827,12 +832,19 @@ class S3Storage(BaseStorage):
run_id: str | None,
base_uri: str,
storage_class: S3StorageClass,
+ attempt_number: int | None = None,
) -> None:
"""Save files from local download directory to S3."""
download_dir = get_download_dir(run_id=run_id)
files = os.listdir(download_dir)
if not files:
return
+ retry_workflow_run_id, attempt_number, retry_attempt_started_at = await resolve_download_attempt_fail_open(
+ organization_id, run_id, attempt_number=attempt_number
+ )
+ retry_attempt = run_id is not None and attempt_number > 1
+ if retry_attempt:
+ base_uri = f"{base_uri}/attempts/{attempt_number}"
already_saved = (
download_checksums_by_uri(
(await self._list_download_artifacts_safe(organization_id=organization_id, run_id=run_id))[0]
@@ -850,6 +862,8 @@ class S3Storage(BaseStorage):
fpath = os.path.join(download_dir, file)
if not os.path.isfile(fpath):
continue
+ if retry_attempt and not is_file_from_retry_attempt(fpath, retry_attempt_started_at):
+ continue
uri = f"{base_uri}/{file}"
checksum = calculate_sha256_for_file(fpath)
# Cleanup runs repeatedly over a growing download dir; re-sending bytes that are
@@ -898,6 +912,7 @@ class S3Storage(BaseStorage):
run_id=run_id,
uri=uri,
filename=file,
+ workflow_run_id=retry_workflow_run_id if retry_attempt else None,
checksum=checksum,
file_size=file_size,
)
@@ -935,15 +950,16 @@ class S3Storage(BaseStorage):
# or the lookup failed), so an unqueried read is never reported as a read that found nothing.
download_row_count: int | None = None
rows_lookup_failed = False
+ download_artifacts: list[Artifact] | None = None
if run_id is not None and settings.ARTIFACT_CONTENT_HMAC_KEYRING:
- artifacts, rows_lookup_failed = await self._list_download_artifacts_safe(
+ download_artifacts, rows_lookup_failed = await self._list_download_artifacts_safe(
organization_id=organization_id, run_id=run_id
)
if not rows_lookup_failed:
- download_row_count = len(artifacts)
- artifacts = dedupe_run_scoped_download_artifacts(artifacts)
- if artifacts:
- file_infos = await _file_infos_from_download_artifacts(artifacts)
+ download_row_count = len(download_artifacts)
+ download_artifacts = dedupe_run_scoped_download_artifacts(download_artifacts)
+ if download_artifacts:
+ file_infos = await _file_infos_from_download_artifacts(download_artifacts)
if not file_infos:
self._log_empty_downloads_read(
organization_id=organization_id,
@@ -971,7 +987,11 @@ class S3Storage(BaseStorage):
# Legacy fallback — runs predating SKY-8861 (no artifact rows) and
# OSS-default deployments without HMAC signing both arrive here.
- file_infos = await self._get_downloaded_files_via_s3_listing(organization_id=organization_id, run_id=run_id)
+ file_infos = await self._get_downloaded_files_via_s3_listing(
+ organization_id=organization_id,
+ run_id=run_id,
+ download_artifacts=download_artifacts,
+ )
if not file_infos:
self._log_empty_downloads_read(
organization_id=organization_id,
@@ -1061,7 +1081,19 @@ class S3Storage(BaseStorage):
return [], True
return artifacts, False
- async def _get_downloaded_files_via_s3_listing(self, *, organization_id: str, run_id: str | None) -> list[FileInfo]:
+ async def _get_downloaded_files_via_s3_listing(
+ self,
+ *,
+ organization_id: str,
+ run_id: str | None,
+ download_artifacts: list[Artifact] | None = None,
+ ) -> list[FileInfo]:
+ if download_artifacts is None and run_id is not None:
+ download_artifacts, _ = await self._list_download_artifacts_safe(
+ organization_id=organization_id,
+ run_id=run_id,
+ )
+ artifacts_by_uri = {artifact.uri: artifact for artifact in download_artifacts or []}
bucket = settings.AWS_S3_BUCKET_UPLOADS
uri = f"s3://{bucket}/{DOWNLOAD_FILE_PREFIX}/{settings.ENV}/{organization_id}/{run_id}"
object_keys = await self.async_client.list_files(uri=uri)
@@ -1074,15 +1106,18 @@ class S3Storage(BaseStorage):
metadata = {}
content_length: int | None = None
+ blob_modified_at = None
try:
object_info = await self.async_client.get_object_info(object_uri)
metadata = object_info.get("Metadata", {})
content_length = object_info.get("ContentLength")
+ blob_modified_at = object_info.get("LastModified")
except Exception:
LOG.warning("Object info retrieval failed", uri=object_uri, exc_info=True)
filename = os.path.basename(key)
checksum = metadata.get("sha256_checksum") if metadata else None
display_name = metadata.get("original_filename", filename) if metadata else filename
+ artifact = artifacts_by_uri.get(object_uri)
presigned_urls = await self.async_client.create_presigned_urls([object_uri])
if not presigned_urls:
@@ -1094,6 +1129,8 @@ class S3Storage(BaseStorage):
checksum=checksum,
filename=display_name,
file_size=content_length,
+ modified_at=artifact.modified_at if artifact is not None else blob_modified_at,
+ artifact_id=artifact.artifact_id if artifact is not None else None,
)
)
return file_infos
diff --git a/skyvern/forge/sdk/core/skyvern_context.py b/skyvern/forge/sdk/core/skyvern_context.py
index 783269db1..3e51e65d9 100644
--- a/skyvern/forge/sdk/core/skyvern_context.py
+++ b/skyvern/forge/sdk/core/skyvern_context.py
@@ -793,6 +793,23 @@ _context: ContextVar[SkyvernContext | None] = ContextVar(
default=None,
)
+_WORKFLOW_LOG_ATTEMPT: ContextVar[tuple[str, int] | None] = ContextVar("workflow_log_attempt", default=None)
+
+
+@contextmanager
+def workflow_log_attempt(workflow_run_id: str, attempt_number: int) -> Iterator[None]:
+ # Child flush tasks retain this identity even after the workflow context is replaced or removed.
+ token = _WORKFLOW_LOG_ATTEMPT.set((workflow_run_id, attempt_number))
+ try:
+ yield
+ finally:
+ _WORKFLOW_LOG_ATTEMPT.reset(token)
+
+
+def current_workflow_log_attempt(workflow_run_id: str) -> int | None:
+ origin = _WORKFLOW_LOG_ATTEMPT.get()
+ return origin[1] if origin is not None and origin[0] == workflow_run_id else None
+
def current() -> SkyvernContext | None:
"""
diff --git a/skyvern/forge/sdk/db/agent_db.py b/skyvern/forge/sdk/db/agent_db.py
index daa2251eb..a0ccbc99d 100644
--- a/skyvern/forge/sdk/db/agent_db.py
+++ b/skyvern/forge/sdk/db/agent_db.py
@@ -43,6 +43,7 @@ from skyvern.forge.sdk.db.repositories.tags import TagsRepository
from skyvern.forge.sdk.db.repositories.tasks import TasksRepository
from skyvern.forge.sdk.db.repositories.uploaded_files import UploadedFilesRepository
from skyvern.forge.sdk.db.repositories.workflow_parameters import WorkflowParametersRepository
+from skyvern.forge.sdk.db.repositories.workflow_run_attempts import WorkflowRunAttemptsRepository
from skyvern.forge.sdk.db.repositories.workflow_run_credential_selections import (
WorkflowRunCredentialSelectionsRepository,
)
@@ -403,6 +404,7 @@ class AgentDB(BaseAlchemyDB):
sqlite_workflow_creation_lock=self._sqlite_workflow_creation_lock,
)
self.workflow_params = WorkflowParametersRepository(self.Session, debug_enabled, self.is_retryable_error)
+ self.workflow_run_attempts = WorkflowRunAttemptsRepository(self.Session, debug_enabled, self.is_retryable_error)
self.workflow_run_credential_selections = WorkflowRunCredentialSelectionsRepository(
self.Session, debug_enabled, self.is_retryable_error
)
diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.py
index 0dd237876..08e60bec0 100644
--- a/skyvern/forge/sdk/db/models.py
+++ b/skyvern/forge/sdk/db/models.py
@@ -23,6 +23,7 @@ from sqlalchemy.ext.asyncio import AsyncAttrs
from sqlalchemy.orm import DeclarativeBase
from skyvern.forge.sdk.db._soft_delete import SoftDeleteMixin
+from skyvern.forge.sdk.db.datetime_utils import naive_utc_now
from skyvern.forge.sdk.db.enums import TaskType
from skyvern.forge.sdk.db.id import (
generate_action_id,
@@ -152,6 +153,7 @@ class TaskModel(Base):
verification_code_identifier = Column(String, nullable=True)
verification_code_polling_started_at = Column(DateTime, nullable=True)
failure_category = Column(JSON, nullable=True)
+ attempt_number = Column(Integer, nullable=True)
class StepModel(Base):
@@ -850,6 +852,59 @@ class WorkflowRunModel(Base):
)
+class WorkflowRunAttemptModel(Base):
+ __tablename__ = "workflow_run_attempts"
+ __table_args__ = (
+ Index("ix_workflow_run_attempts_organization_created_at", "organization_id", "created_at"),
+ Index(
+ "ix_workflow_run_attempts_pending_retries",
+ "next_attempt_at",
+ "workflow_run_id",
+ "attempt_number",
+ postgresql_where=text(
+ "retry_decision = 'retry' AND next_attempt_prepared_at IS NULL AND next_attempt_at IS NOT NULL"
+ ),
+ ),
+ Index(
+ "ix_workflow_run_attempts_terminal_releases",
+ "side_effects_released_at",
+ postgresql_where=text("retry_decision IN ('final', 'revoked', 'abandoned') AND webhook_sent_at IS NULL"),
+ ),
+ Index(
+ "ix_workflow_run_attempts_prepared_not_started",
+ "modified_at",
+ postgresql_where=text("retry_decision IS NULL AND status = 'queued' AND started_at IS NULL"),
+ ),
+ )
+
+ workflow_run_id = Column(String, primary_key=True)
+ attempt_number = Column(Integer, primary_key=True)
+ organization_id = Column(String, nullable=False)
+ status = Column(String, nullable=False)
+ failure_reason = Column(Text, nullable=True)
+ failure_category = Column(JSON, nullable=True)
+ error_codes = Column(JSON, nullable=True)
+ retry_decision = Column(String, nullable=True)
+ decision_reason = Column(String, nullable=True)
+ next_attempt_at = Column(DateTime, nullable=True)
+ next_attempt_prepared_at = Column(DateTime, nullable=True)
+ webhook_sent_at = Column(DateTime, nullable=True)
+ interim_webhook_sent_at = Column(DateTime, nullable=True)
+ side_effects_released_at = Column(DateTime, nullable=True)
+ interim_side_effects_progress = Column(JSON, nullable=True)
+ final_side_effects_progress = Column(JSON, nullable=True)
+ pinned_browser_session_id = Column(String, nullable=True)
+ started_at = Column(DateTime, nullable=True)
+ finished_at = Column(DateTime, nullable=True)
+ created_at = Column(DateTime, default=naive_utc_now, nullable=False)
+ modified_at = Column(
+ DateTime,
+ default=naive_utc_now,
+ onupdate=naive_utc_now,
+ nullable=False,
+ )
+
+
class WorkflowParameterModel(Base):
__tablename__ = "workflow_parameters"
@@ -1283,6 +1338,7 @@ class WorkflowRunBlockModel(Base):
# Scalar mirror of output["downloaded_files"] length: the JSON output column is
# not CDC-mirrored, so download success would not otherwise be queryable.
downloaded_file_count = Column(Integer, nullable=True)
+ attempt_number = Column(Integer, nullable=True)
created_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)
modified_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow, nullable=False)
diff --git a/skyvern/forge/sdk/db/repositories/artifacts.py b/skyvern/forge/sdk/db/repositories/artifacts.py
index 67bc752cc..db7af945f 100644
--- a/skyvern/forge/sdk/db/repositories/artifacts.py
+++ b/skyvern/forge/sdk/db/repositories/artifacts.py
@@ -4,14 +4,15 @@ import datetime
from typing import TYPE_CHECKING, Any, Callable
import structlog
-from sqlalchemy import and_, delete, or_, select, update
+from sqlalchemy import and_, delete, false, func, or_, select, update
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.sql.elements import ColumnElement
from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType
from skyvern.forge.sdk.db._error_handling import db_operation
from skyvern.forge.sdk.db.base_repository import BaseRepository
-from skyvern.forge.sdk.db.models import ActionModel, ArtifactModel
+from skyvern.forge.sdk.db.datetime_utils import naive_utc_now
+from skyvern.forge.sdk.db.models import ActionModel, ArtifactModel, StepModel, TaskModel, WorkflowRunBlockModel
from skyvern.forge.sdk.db.protocols import RunReader
from skyvern.forge.sdk.db.utils import convert_to_artifact
from skyvern.forge.sdk.trace import traced
@@ -53,6 +54,64 @@ def _session_download_filters(
]
+def _download_attempt_scope_filter(
+ attempt_number: int,
+ attempt_started_at: datetime.datetime | None,
+) -> ColumnElement[bool]:
+ attributed_entity = or_(
+ ArtifactModel.task_id.is_not(None),
+ ArtifactModel.step_id.is_not(None),
+ ArtifactModel.workflow_run_block_id.is_not(None),
+ )
+ task_attempt = (
+ select(1)
+ .select_from(TaskModel)
+ .where(
+ TaskModel.task_id == ArtifactModel.task_id,
+ func.coalesce(TaskModel.attempt_number, 1) == attempt_number,
+ )
+ .exists()
+ )
+ step_attempt = (
+ select(1)
+ .select_from(StepModel)
+ .join(TaskModel, TaskModel.task_id == StepModel.task_id)
+ .where(
+ StepModel.step_id == ArtifactModel.step_id,
+ func.coalesce(TaskModel.attempt_number, 1) == attempt_number,
+ )
+ .exists()
+ )
+ block_attempt = (
+ select(1)
+ .select_from(WorkflowRunBlockModel)
+ .where(
+ WorkflowRunBlockModel.workflow_run_block_id == ArtifactModel.workflow_run_block_id,
+ func.coalesce(WorkflowRunBlockModel.attempt_number, 1) == attempt_number,
+ )
+ .exists()
+ )
+ run_level = (
+ false()
+ if attempt_started_at is None
+ else and_(~attributed_entity, ArtifactModel.created_at >= attempt_started_at)
+ )
+ touched_since_attempt = (
+ false()
+ if attempt_started_at is None
+ else func.coalesce(ArtifactModel.modified_at, ArtifactModel.created_at) >= attempt_started_at
+ )
+ return or_(
+ touched_since_attempt,
+ and_(
+ or_(ArtifactModel.task_id.is_not(None), ArtifactModel.step_id.is_not(None)),
+ or_(task_attempt, step_attempt),
+ ),
+ and_(ArtifactModel.workflow_run_block_id.is_not(None), block_attempt),
+ run_level,
+ )
+
+
class ArtifactsRepository(BaseRepository):
"""Database operations for artifact management."""
@@ -114,7 +173,7 @@ class ArtifactsRepository(BaseRepository):
self,
artifact_id: str,
organization_id: str,
- checksum: str,
+ checksum: str | None,
file_size: int | None,
) -> None:
# file_size is written unconditionally: a None (size unreadable) is more honest than a
@@ -127,7 +186,7 @@ class ArtifactsRepository(BaseRepository):
ArtifactModel.organization_id == organization_id,
ArtifactModel.artifact_type == ArtifactType.DOWNLOAD,
)
- .values(checksum=checksum, file_size=file_size)
+ .values(checksum=checksum, file_size=file_size, modified_at=naive_utc_now())
)
await session.commit()
@@ -511,6 +570,35 @@ class ArtifactsRepository(BaseRepository):
).all()
return [convert_to_artifact(a, self.debug_enabled) for a in artifacts]
+ @db_operation("list_download_artifacts_for_attempt")
+ async def list_download_artifacts_for_attempt(
+ self,
+ run_id: str,
+ organization_id: str,
+ attempt_number: int,
+ attempt_started_at: datetime.datetime | None,
+ ) -> list[Artifact]:
+ """List DOWNLOAD artifacts attributable to one workflow-run attempt.
+
+ Task, step, and workflow-block artifacts use their stamped attempt number (with NULL
+ retaining the legacy attempt-one meaning). Artifacts without one of those attributions
+ are run-level rows and use the attempt start as their lower time bound.
+ """
+ async with self.Session() as session:
+ artifacts = (
+ await session.scalars(
+ select(ArtifactModel)
+ .where(
+ ArtifactModel.run_id == run_id,
+ ArtifactModel.organization_id == organization_id,
+ ArtifactModel.artifact_type == ArtifactType.DOWNLOAD,
+ _download_attempt_scope_filter(attempt_number, attempt_started_at),
+ )
+ .order_by(ArtifactModel.created_at)
+ )
+ ).all()
+ return [convert_to_artifact(a, self.debug_enabled) for a in artifacts]
+
@db_operation("find_artifact_for_browser_session")
async def find_artifact_for_browser_session(
self,
@@ -648,16 +736,16 @@ class ArtifactsRepository(BaseRepository):
browser_session_id: str,
organization_id: str,
run_started_at: datetime.datetime,
+ attempt_number: int | None = None,
) -> set[str]:
"""Ids of the session-scoped DOWNLOAD artifacts attributable to this run, both stamped and
still-unbound in-window rows, so a grader reading before the claim is not short. Ids rather
than a count because a caller combining this with a run-scoped read would double-count."""
+ filters = _session_download_filters(run_id, browser_session_id, organization_id, run_started_at)
+ if attempt_number is not None:
+ filters.append(_download_attempt_scope_filter(attempt_number, run_started_at))
async with self.Session() as session:
- result = await session.scalars(
- select(ArtifactModel.artifact_id).where(
- *_session_download_filters(run_id, browser_session_id, organization_id, run_started_at)
- )
- )
+ result = await session.scalars(select(ArtifactModel.artifact_id).where(*filters))
return set(result.all())
@db_operation("delete_artifact_for_browser_session")
diff --git a/skyvern/forge/sdk/db/repositories/observer.py b/skyvern/forge/sdk/db/repositories/observer.py
index adcc4db11..6a4cfd171 100644
--- a/skyvern/forge/sdk/db/repositories/observer.py
+++ b/skyvern/forge/sdk/db/repositories/observer.py
@@ -418,6 +418,7 @@ class ObserverRepository(BaseRepository):
current_value: str | None = None,
current_index: int | None = None,
ai_fallback_triggered: bool | None = None,
+ attempt_number: int | None = None,
) -> WorkflowRunBlock:
if output is not None:
output = truncate_oversized_jsonb_value(
@@ -438,6 +439,7 @@ class ObserverRepository(BaseRepository):
engine=engine,
current_value=current_value,
current_index=current_index,
+ attempt_number=attempt_number,
script_run=ScriptRunResponse(ai_fallback_triggered=ai_fallback_triggered).model_dump(mode="json")
if ai_fallback_triggered is not None
else None,
diff --git a/skyvern/forge/sdk/db/repositories/tasks.py b/skyvern/forge/sdk/db/repositories/tasks.py
index f2e6a2e69..5e0b71671 100644
--- a/skyvern/forge/sdk/db/repositories/tasks.py
+++ b/skyvern/forge/sdk/db/repositories/tasks.py
@@ -1,12 +1,13 @@
from __future__ import annotations
import asyncio
+from collections.abc import Sequence
from datetime import datetime, timedelta
from decimal import Decimal
-from typing import Any, Sequence
+from typing import Any
import structlog
-from sqlalchemy import and_, delete, func, select, update
+from sqlalchemy import and_, delete, func, or_, select, update
from skyvern.forge.sdk.db._error_handling import db_operation
from skyvern.forge.sdk.db.base_alchemy_db import read_retry
@@ -19,6 +20,7 @@ from skyvern.forge.sdk.db.models import (
StepModel,
TaskModel,
TaskRunModel,
+ WorkflowRunAttemptModel,
WorkflowRunBlockModel,
WorkflowRunModel,
)
@@ -73,6 +75,7 @@ class TasksRepository(BaseRepository):
browser_address: str | None = None,
download_timeout: float | None = None,
include_extracted_text: bool = True,
+ attempt_number: int | None = None,
) -> Task:
# Sanitize text fields to remove NUL bytes and control characters
# that PostgreSQL cannot store in text columns
@@ -126,6 +129,7 @@ class TasksRepository(BaseRepository):
browser_address=browser_address,
download_timeout=download_timeout,
include_extracted_text=include_extracted_text,
+ attempt_number=attempt_number,
)
session.add(new_task)
await session.commit()
@@ -1045,24 +1049,30 @@ class TasksRepository(BaseRepository):
return None
@db_operation("get_last_task_for_workflow_run")
- async def get_last_task_for_workflow_run(self, workflow_run_id: str) -> Task | None:
+ async def get_last_task_for_workflow_run(
+ self, workflow_run_id: str, attempt_number: int | None = None
+ ) -> Task | None:
async with self.Session() as session:
- if task := (
- await session.scalars(
- select(TaskModel).filter_by(workflow_run_id=workflow_run_id).order_by(TaskModel.created_at.desc())
- )
- ).first():
+ query = select(TaskModel).filter_by(workflow_run_id=workflow_run_id)
+ if attempt_number is not None:
+ attempt_filter = TaskModel.attempt_number == attempt_number
+ if attempt_number == 1:
+ attempt_filter = or_(attempt_filter, TaskModel.attempt_number.is_(None))
+ query = query.where(attempt_filter)
+ if task := (await session.scalars(query.order_by(TaskModel.created_at.desc()))).first():
return convert_to_task(task, debug_enabled=self.debug_enabled)
return None
@db_operation("get_tasks_by_workflow_run_id")
- async def get_tasks_by_workflow_run_id(self, workflow_run_id: str) -> list[Task]:
+ async def get_tasks_by_workflow_run_id(self, workflow_run_id: str, attempt_number: int | None = None) -> list[Task]:
async with self.Session() as session:
- tasks = (
- await session.scalars(
- select(TaskModel).filter_by(workflow_run_id=workflow_run_id).order_by(TaskModel.created_at)
- )
- ).all()
+ query = select(TaskModel).filter_by(workflow_run_id=workflow_run_id)
+ if attempt_number is not None:
+ attempt_filter = TaskModel.attempt_number == attempt_number
+ if attempt_number == 1:
+ attempt_filter = or_(attempt_filter, TaskModel.attempt_number.is_(None))
+ query = query.where(attempt_filter)
+ tasks = (await session.scalars(query.order_by(TaskModel.created_at))).all()
return [convert_to_task(task, debug_enabled=self.debug_enabled) for task in tasks]
@db_operation("delete_task_steps")
@@ -1109,9 +1119,11 @@ class TasksRepository(BaseRepository):
status: str,
started_at: datetime | None = None,
finished_at: datetime | None = None,
+ source_workflow_run_id: str | None = None,
) -> None:
"""Best-effort write-through: propagate status from source table to task_runs.
+ Workflow syncs copy the current source row, since retries can outlive a queued sync.
Does NOT raise if the task_runs row is missing (race at creation time).
"""
try:
@@ -1125,8 +1137,20 @@ class TasksRepository(BaseRepository):
update(TaskRunModel)
.where(TaskRunModel.run_id == run_id)
.where(TaskRunModel.organization_id == organization_id)
- .values(**vals)
)
+ if source_workflow_run_id is not None:
+ stmt = stmt.where(
+ WorkflowRunModel.workflow_run_id == source_workflow_run_id,
+ WorkflowRunModel.organization_id == TaskRunModel.organization_id,
+ )
+ # Copy all three fields in the same statement, including cleared timestamps.
+ # Matching status alone cannot distinguish two attempts that both failed.
+ vals = {
+ "status": WorkflowRunModel.status,
+ "started_at": WorkflowRunModel.started_at,
+ "finished_at": WorkflowRunModel.finished_at,
+ }
+ stmt = stmt.values(**vals)
await session.execute(stmt)
await session.commit()
except Exception:
@@ -1231,7 +1255,7 @@ class TasksRepository(BaseRepository):
async with self.Session() as session:
task_run = (
await session.scalars(
- select(TaskRunModel).filter_by(run_id=run_id).filter_by(organization_id=organization_id)
+ select(TaskRunModel).filter_by(run_id=run_id, organization_id=organization_id).with_for_update()
)
).first()
if not task_run:
@@ -1242,12 +1266,27 @@ class TasksRepository(BaseRepository):
)
return
+ attempt_number = 1
+ if task_run.task_run_type == "workflow_run":
+ attempt_number = (
+ await session.scalar(
+ select(func.max(WorkflowRunAttemptModel.attempt_number)).where(
+ WorkflowRunAttemptModel.workflow_run_id == run_id,
+ WorkflowRunAttemptModel.organization_id == organization_id,
+ )
+ )
+ or 1
+ )
+
+ # The workflow activity disables Temporal retries, so its interceptor records cost once per attempt.
if instance_type is not None:
task_run.instance_type = instance_type
if duration_ms is not None:
- task_run.duration_ms = duration_ms
+ task_run.duration_ms = (task_run.duration_ms or 0) + duration_ms if attempt_number >= 2 else duration_ms
if compute_cost is not None:
- task_run.compute_cost = compute_cost
+ task_run.compute_cost = (
+ (task_run.compute_cost or Decimal(0)) + compute_cost if attempt_number >= 2 else compute_cost
+ )
if compute_hourly_rate_id is not None:
task_run.compute_hourly_rate_id = compute_hourly_rate_id
if llm_cost is not None:
diff --git a/skyvern/forge/sdk/db/repositories/workflow_run_attempts.py b/skyvern/forge/sdk/db/repositories/workflow_run_attempts.py
new file mode 100644
index 000000000..1a82fb703
--- /dev/null
+++ b/skyvern/forge/sdk/db/repositories/workflow_run_attempts.py
@@ -0,0 +1,1054 @@
+from __future__ import annotations
+
+from collections.abc import Iterator, Sequence
+from contextlib import contextmanager
+from contextvars import ContextVar
+from datetime import datetime, timedelta
+from typing import Any, Literal, TypedDict
+
+from sqlalchemy import (
+ JSON,
+ ColumnElement,
+ and_,
+ bindparam,
+ case,
+ cast,
+ delete,
+ func,
+ literal,
+ or_,
+ select,
+ type_coerce,
+ update,
+)
+from sqlalchemy.dialects.postgresql import JSONB
+from sqlalchemy.orm import Load, with_expression
+
+from skyvern.forge.sdk.db._error_handling import db_operation
+from skyvern.forge.sdk.db.base_repository import BaseRepository
+from skyvern.forge.sdk.db.datetime_utils import naive_utc_now, to_naive_utc
+from skyvern.forge.sdk.db.exceptions import NotFoundError
+from skyvern.forge.sdk.db.models import TaskRunModel, WorkflowRunAttemptModel, WorkflowRunModel
+from skyvern.schemas.run_enums import TERMINAL_STATUSES
+
+# Keep terminal recovery bounded so a degraded database does not load the entire backlog at once.
+ATTEMPT_RECOVERY_BATCH_SIZE = 200
+# A sweep handles at most this many pages (20,000 rows). The next periodic sweep resumes from a
+# fresh keyset, so an outage cannot make one executor loop unbounded.
+ATTEMPT_RECOVERY_MAX_PAGES = 100
+
+_undecided_recovery_attempt: ContextVar[WorkflowRunAttemptModel | None] = ContextVar(
+ "undecided_recovery_attempt", default=None
+)
+
+
+class AttemptRecoverySuperseded(Exception):
+ pass
+
+
+@contextmanager
+def recovering_undecided_attempt(attempt: WorkflowRunAttemptModel) -> Iterator[None]:
+ token = _undecided_recovery_attempt.set(attempt)
+ try:
+ yield
+ finally:
+ _undecided_recovery_attempt.reset(token)
+
+
+class TerminalSideEffectCheckpoint(TypedDict):
+ completed_effects: list[str]
+ final_hook_invoked: bool
+
+
+def _progress_object(column: ColumnElement, dialect: str) -> ColumnElement:
+ if dialect == "sqlite":
+ return case((func.json_type(column) == "object", column), else_=literal({}, type_=JSON))
+ value = cast(column, JSONB)
+ return case((func.jsonb_typeof(value) == "object", value), else_=literal({}, type_=JSONB))
+
+
+def progress_without_outputs(column: ColumnElement, dialect: str) -> ColumnElement:
+ if dialect == "sqlite":
+ return type_coerce(func.json_remove(column, "$.output_parameters"), JSON)
+ value = cast(column, JSONB)
+ return cast(case((func.jsonb_typeof(value) == "object", value - "output_parameters"), else_=value), JSON)
+
+
+def merge_attempt_progress(column: ColumnElement, updates: dict[str, Any], dialect: str) -> ColumnElement:
+ result = _progress_object(column, dialect)
+ if dialect == "sqlite":
+ for key, value in updates.items():
+ result = func.json_set(result, f"$.{key}", func.json(literal(value, type_=JSON)))
+ return type_coerce(result, JSON)
+ return cast(result.op("||")(literal(updates, type_=JSONB)), JSON)
+
+
+def attempt_metadata_options(dialect: str) -> Load:
+ return with_expression(
+ WorkflowRunAttemptModel.interim_side_effects_progress,
+ progress_without_outputs(WorkflowRunAttemptModel.interim_side_effects_progress, dialect),
+ )
+
+
+def _stale_dispatch_claim_conditions(stale_before: datetime) -> ColumnElement[bool]:
+ return and_(
+ WorkflowRunModel.status == "queued",
+ WorkflowRunModel.started_at.isnot(None),
+ WorkflowRunAttemptModel.workflow_run_id == WorkflowRunModel.workflow_run_id,
+ WorkflowRunAttemptModel.organization_id == WorkflowRunModel.organization_id,
+ WorkflowRunAttemptModel.status == "running",
+ WorkflowRunAttemptModel.started_at.isnot(None),
+ WorkflowRunAttemptModel.retry_decision.is_(None),
+ WorkflowRunAttemptModel.modified_at < stale_before,
+ )
+
+
+class WorkflowRunAttemptsRepository(BaseRepository):
+ @db_operation("create_attempt")
+ async def create_attempt(
+ self,
+ workflow_run_id: str,
+ organization_id: str,
+ attempt_number: int,
+ status: str,
+ pinned_browser_session_id: str | None = None,
+ ) -> WorkflowRunAttemptModel:
+ async with self.Session() as session:
+ attempt = WorkflowRunAttemptModel(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ attempt_number=attempt_number,
+ status=status,
+ pinned_browser_session_id=pinned_browser_session_id,
+ )
+ session.add(attempt)
+ await session.flush()
+ session.expunge(attempt)
+ await session.commit()
+ return attempt
+
+ @db_operation("pin_first_attempt_browser_session_if_unset")
+ async def pin_first_attempt_browser_session_if_unset(
+ self,
+ workflow_run_id: str,
+ organization_id: str,
+ browser_session_id: str,
+ ) -> None:
+ async with self.Session() as session:
+ await session.execute(
+ update(WorkflowRunAttemptModel)
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.organization_id == organization_id,
+ WorkflowRunAttemptModel.attempt_number == 1,
+ WorkflowRunAttemptModel.pinned_browser_session_id.is_(None),
+ )
+ .values(pinned_browser_session_id=browser_session_id, modified_at=naive_utc_now())
+ )
+ await session.commit()
+
+ @db_operation("get_attempts", expected_errors=(AttemptRecoverySuperseded,))
+ async def get_attempts(self, workflow_run_id: str) -> list[WorkflowRunAttemptModel]:
+ async with self.Session() as session:
+ attempts = (
+ await session.scalars(
+ select(WorkflowRunAttemptModel)
+ .options(attempt_metadata_options(session.bind.dialect.name))
+ .where(WorkflowRunAttemptModel.workflow_run_id == workflow_run_id)
+ .order_by(WorkflowRunAttemptModel.attempt_number)
+ )
+ ).all()
+ recovering = _undecided_recovery_attempt.get()
+ if recovering is not None and recovering.workflow_run_id == workflow_run_id:
+ current = max(attempts, key=lambda row: row.attempt_number, default=None)
+ if (
+ current is None
+ or current.attempt_number != recovering.attempt_number
+ or current.retry_decision is not None
+ or current.started_at is None
+ or current.modified_at != recovering.modified_at
+ ):
+ raise AttemptRecoverySuperseded
+ return list(attempts)
+
+ @db_operation("get_interim_payload_snapshot")
+ async def get_interim_payload_snapshot(self, workflow_run_id: str, attempt_number: int) -> dict[str, Any]:
+ async with self.Session() as session:
+ return dict(
+ await session.scalar(
+ select(WorkflowRunAttemptModel.interim_side_effects_progress).where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ )
+ )
+ or {}
+ )
+
+ @db_operation("get_latest_attempts_for_runs")
+ async def get_latest_attempts_for_runs(self, workflow_run_ids: Sequence[str]) -> dict[str, WorkflowRunAttemptModel]:
+ if not workflow_run_ids:
+ return {}
+
+ ranked_attempts = (
+ select(
+ WorkflowRunAttemptModel.workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number,
+ func.row_number()
+ .over(
+ partition_by=WorkflowRunAttemptModel.workflow_run_id,
+ order_by=WorkflowRunAttemptModel.attempt_number.desc(),
+ )
+ .label("attempt_rank"),
+ )
+ .where(WorkflowRunAttemptModel.workflow_run_id.in_(workflow_run_ids))
+ .subquery()
+ )
+ query = select(WorkflowRunAttemptModel).join(
+ ranked_attempts,
+ and_(
+ WorkflowRunAttemptModel.workflow_run_id == ranked_attempts.c.workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == ranked_attempts.c.attempt_number,
+ ranked_attempts.c.attempt_rank == 1,
+ ),
+ )
+
+ async with self.Session() as session:
+ attempts = (await session.scalars(query.options(attempt_metadata_options(session.bind.dialect.name)))).all()
+ return {attempt.workflow_run_id: attempt for attempt in attempts}
+
+ @db_operation("list_stale_pending_retries")
+ async def list_stale_pending_retries(self, cutoff: datetime) -> list[WorkflowRunAttemptModel]:
+ normalized_cutoff = to_naive_utc(cutoff)
+ assert normalized_cutoff is not None
+ async with self.Session() as session:
+ attempts = (
+ await session.scalars(
+ select(WorkflowRunAttemptModel)
+ .options(attempt_metadata_options(session.bind.dialect.name))
+ .where(
+ WorkflowRunAttemptModel.retry_decision == "retry",
+ WorkflowRunAttemptModel.next_attempt_prepared_at.is_(None),
+ WorkflowRunAttemptModel.next_attempt_at.isnot(None),
+ WorkflowRunAttemptModel.next_attempt_at < normalized_cutoff,
+ )
+ .order_by(
+ WorkflowRunAttemptModel.next_attempt_at.asc(),
+ WorkflowRunAttemptModel.workflow_run_id.asc(),
+ WorkflowRunAttemptModel.attempt_number.asc(),
+ )
+ )
+ ).all()
+ return list(attempts)
+
+ @db_operation("list_attempts_needing_recovery")
+ async def list_attempts_needing_recovery(
+ self,
+ cutoff: datetime,
+ *,
+ cursor: tuple[datetime, str, int] | None = None,
+ limit: int = ATTEMPT_RECOVERY_BATCH_SIZE,
+ ) -> list[WorkflowRunAttemptModel]:
+ normalized_cutoff = to_naive_utc(cutoff)
+ assert normalized_cutoff is not None
+ if limit <= 0:
+ raise ValueError("Recovery page limit must be positive")
+ async with self.Session() as session:
+ retry_attempts = and_(
+ WorkflowRunAttemptModel.retry_decision == "retry",
+ WorkflowRunAttemptModel.next_attempt_prepared_at.is_(None),
+ WorkflowRunAttemptModel.next_attempt_at.isnot(None),
+ )
+ terminal_attempts = and_(
+ WorkflowRunAttemptModel.retry_decision.in_(
+ ["final", "revoked", "abandoned"],
+ ),
+ or_(
+ WorkflowRunAttemptModel.side_effects_released_at.is_(None),
+ WorkflowRunAttemptModel.side_effects_released_at < normalized_cutoff,
+ ),
+ WorkflowRunAttemptModel.webhook_sent_at.is_(None),
+ )
+ interim_attempts = and_(
+ WorkflowRunAttemptModel.retry_decision == "retry",
+ WorkflowRunAttemptModel.next_attempt_prepared_at.isnot(None),
+ WorkflowRunAttemptModel.interim_webhook_sent_at.is_(None),
+ or_(
+ WorkflowRunAttemptModel.side_effects_released_at.is_(None),
+ WorkflowRunAttemptModel.side_effects_released_at < normalized_cutoff,
+ ),
+ )
+ prepared_attempts = and_(
+ WorkflowRunAttemptModel.retry_decision.is_(None),
+ WorkflowRunAttemptModel.status == "queued",
+ WorkflowRunAttemptModel.started_at.is_(None),
+ WorkflowRunAttemptModel.modified_at < normalized_cutoff,
+ )
+ # A run can reach a terminal status before its attempt starts (a cancel while queued), so
+ # the attempt's started_at does not gate this branch.
+ undecided_terminal_attempts = and_(
+ WorkflowRunAttemptModel.retry_decision.is_(None),
+ WorkflowRunAttemptModel.modified_at < normalized_cutoff,
+ WorkflowRunModel.status.in_(TERMINAL_STATUSES),
+ )
+ decision_timestamp = func.coalesce(
+ WorkflowRunAttemptModel.next_attempt_at,
+ WorkflowRunAttemptModel.modified_at,
+ )
+ conditions = [
+ or_(retry_attempts, terminal_attempts, interim_attempts, prepared_attempts, undecided_terminal_attempts)
+ ]
+ if cursor is not None:
+ cursor_timestamp, cursor_workflow_run_id, cursor_attempt_number = cursor
+ normalized_cursor_timestamp = to_naive_utc(cursor_timestamp)
+ assert normalized_cursor_timestamp is not None
+ conditions.append(
+ or_(
+ decision_timestamp > normalized_cursor_timestamp,
+ and_(
+ decision_timestamp == normalized_cursor_timestamp,
+ WorkflowRunAttemptModel.workflow_run_id > cursor_workflow_run_id,
+ ),
+ and_(
+ decision_timestamp == normalized_cursor_timestamp,
+ WorkflowRunAttemptModel.workflow_run_id == cursor_workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number > cursor_attempt_number,
+ ),
+ )
+ )
+ query = (
+ select(WorkflowRunAttemptModel)
+ .options(attempt_metadata_options(session.bind.dialect.name))
+ .outerjoin(
+ WorkflowRunModel,
+ and_(
+ WorkflowRunModel.workflow_run_id == WorkflowRunAttemptModel.workflow_run_id,
+ WorkflowRunModel.organization_id == WorkflowRunAttemptModel.organization_id,
+ ),
+ )
+ .where(*conditions)
+ .order_by(
+ decision_timestamp.asc(),
+ WorkflowRunAttemptModel.workflow_run_id.asc(),
+ WorkflowRunAttemptModel.attempt_number.asc(),
+ )
+ .limit(limit)
+ )
+ attempts = (await session.scalars(query)).all()
+ return list(attempts)
+
+ @db_operation("list_stale_dispatch_claims")
+ async def list_stale_dispatch_claims(
+ self,
+ stale_before: datetime,
+ *,
+ cursor: tuple[str, int] | None = None,
+ limit: int = ATTEMPT_RECOVERY_BATCH_SIZE,
+ ) -> list[WorkflowRunAttemptModel]:
+ normalized_cutoff = to_naive_utc(stale_before)
+ assert normalized_cutoff is not None
+ if limit <= 0:
+ raise ValueError("Recovery page limit must be positive")
+ query = (
+ select(WorkflowRunAttemptModel)
+ .join(WorkflowRunModel, WorkflowRunModel.workflow_run_id == WorkflowRunAttemptModel.workflow_run_id)
+ .where(_stale_dispatch_claim_conditions(normalized_cutoff))
+ .order_by(WorkflowRunAttemptModel.workflow_run_id, WorkflowRunAttemptModel.attempt_number)
+ .limit(limit)
+ )
+ if cursor is not None:
+ workflow_run_id, attempt_number = cursor
+ query = query.where(
+ or_(
+ WorkflowRunAttemptModel.workflow_run_id > workflow_run_id,
+ and_(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number > attempt_number,
+ ),
+ )
+ )
+ async with self.Session() as session:
+ query = query.options(attempt_metadata_options(session.bind.dialect.name))
+ return list((await session.scalars(query)).all())
+
+ @db_operation("release_stale_dispatch_claim")
+ async def release_stale_dispatch_claim(
+ self, workflow_run_id: str, organization_id: str, attempt_number: int, *, stale_before: datetime
+ ) -> bool:
+ normalized_cutoff = to_naive_utc(stale_before)
+ assert normalized_cutoff is not None
+ now = naive_utc_now()
+ attempt_conditions = (
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.organization_id == organization_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ WorkflowRunAttemptModel.status == "running",
+ WorkflowRunAttemptModel.started_at.isnot(None),
+ WorkflowRunAttemptModel.retry_decision.is_(None),
+ WorkflowRunAttemptModel.modified_at < normalized_cutoff,
+ )
+ async with self.Session() as session:
+ # Lock the run before the attempt, as in claim_prepared_attempt_execution. Both resets
+ # commit together; the complete stale predicate is checked by the conditional run update.
+ run_release = await session.execute(
+ update(WorkflowRunModel)
+ .where(
+ WorkflowRunModel.workflow_run_id == workflow_run_id,
+ WorkflowRunModel.organization_id == organization_id,
+ WorkflowRunModel.status == "queued",
+ WorkflowRunModel.started_at.isnot(None),
+ select(WorkflowRunAttemptModel.workflow_run_id).where(*attempt_conditions).exists(),
+ )
+ .values(started_at=None, modified_at=now)
+ .returning(WorkflowRunModel.workflow_run_id)
+ )
+ if run_release.scalar_one_or_none() is None:
+ return False
+ attempt_release = await session.execute(
+ update(WorkflowRunAttemptModel)
+ .where(*attempt_conditions)
+ .values(started_at=None, status="queued", modified_at=now)
+ .returning(WorkflowRunAttemptModel.attempt_number)
+ )
+ if attempt_release.scalar_one_or_none() is None:
+ await session.rollback()
+ return False
+ await session.commit()
+ return True
+
+ @db_operation("mark_attempt_inputs_unrecoverable")
+ async def mark_attempt_inputs_unrecoverable(self, workflow_run_id: str, attempt_number: int) -> None:
+ async with self.Session() as session:
+ await session.execute(
+ update(WorkflowRunAttemptModel)
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ WorkflowRunAttemptModel.retry_decision.is_(None),
+ )
+ .values(decision_reason="unrecoverable_block_outputs", modified_at=naive_utc_now())
+ )
+ await session.commit()
+
+ @db_operation("refresh_attempt_finished_at")
+ async def refresh_attempt_finished_at(
+ self, workflow_run_id: str, attempt_number: int, *, finished_at: datetime
+ ) -> WorkflowRunAttemptModel | None:
+ normalized_finished_at = to_naive_utc(finished_at)
+ assert normalized_finished_at is not None
+ async with self.Session() as session:
+ refreshed = (
+ await session.scalars(
+ update(WorkflowRunAttemptModel)
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ WorkflowRunAttemptModel.retry_decision.isnot(None),
+ or_(
+ WorkflowRunAttemptModel.finished_at.is_(None),
+ WorkflowRunAttemptModel.finished_at < normalized_finished_at,
+ ),
+ )
+ .values(finished_at=normalized_finished_at, modified_at=naive_utc_now())
+ .returning(WorkflowRunAttemptModel)
+ .options(attempt_metadata_options(session.bind.dialect.name))
+ )
+ ).one_or_none()
+ if refreshed is not None:
+ session.expunge(refreshed)
+ await session.commit()
+ return refreshed
+
+ @db_operation("fail_prepared_workflow_run")
+ async def fail_prepared_workflow_run(
+ self,
+ workflow_run_id: str,
+ organization_id: str,
+ attempt_number: int,
+ failure_reason: str,
+ ) -> bool:
+ now = naive_utc_now()
+ prepared_attempt = select(WorkflowRunAttemptModel.workflow_run_id).where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ WorkflowRunAttemptModel.retry_decision.is_(None),
+ WorkflowRunAttemptModel.status == "queued",
+ WorkflowRunAttemptModel.started_at.is_(None),
+ )
+ async with self.Session() as session:
+ result = await session.execute(
+ update(WorkflowRunModel)
+ .where(
+ WorkflowRunModel.workflow_run_id == workflow_run_id,
+ WorkflowRunModel.organization_id == organization_id,
+ WorkflowRunModel.status == "queued",
+ WorkflowRunModel.started_at.is_(None),
+ prepared_attempt.exists(),
+ )
+ .values(status="failed", failure_reason=failure_reason, finished_at=now, modified_at=now)
+ .returning(WorkflowRunModel.workflow_run_id)
+ )
+ claimed = result.scalar_one_or_none() is not None
+ if claimed:
+ await session.execute(
+ update(WorkflowRunAttemptModel)
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ )
+ .values(
+ status="failed",
+ retry_decision="abandoned",
+ decision_reason="prepared_attempt_never_started",
+ failure_reason=failure_reason,
+ finished_at=now,
+ modified_at=now,
+ )
+ )
+ # The runs list reads finished_at from the task_runs mirror that retry preparation cleared.
+ await session.execute(
+ update(TaskRunModel)
+ .where(
+ TaskRunModel.run_id == workflow_run_id,
+ TaskRunModel.organization_id == organization_id,
+ TaskRunModel.task_run_type == "workflow_run",
+ )
+ .values(status="failed", finished_at=now, modified_at=now)
+ )
+ await session.commit()
+ return claimed
+
+ @db_operation("claim_prepared_attempt_execution")
+ async def claim_prepared_attempt_execution(
+ self, workflow_run_id: str, organization_id: str, attempt_number: int
+ ) -> datetime | None:
+ now = naive_utc_now()
+ conditions = (
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.organization_id == organization_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ WorkflowRunAttemptModel.status == "queued",
+ WorkflowRunAttemptModel.retry_decision.is_(None),
+ WorkflowRunAttemptModel.started_at.is_(None),
+ )
+ async with self.Session() as session:
+ run_claim = await session.execute(
+ update(WorkflowRunModel)
+ .where(
+ WorkflowRunModel.workflow_run_id == workflow_run_id,
+ WorkflowRunModel.organization_id == organization_id,
+ WorkflowRunModel.status == "queued",
+ WorkflowRunModel.started_at.is_(None),
+ select(WorkflowRunAttemptModel.workflow_run_id).where(*conditions).exists(),
+ )
+ .values(started_at=now, modified_at=now)
+ .returning(WorkflowRunModel.workflow_run_id)
+ )
+ if run_claim.scalar_one_or_none() is None:
+ return None
+ attempt_claim = await session.execute(
+ update(WorkflowRunAttemptModel)
+ .where(*conditions)
+ .values(started_at=now, status="running", modified_at=now)
+ .returning(WorkflowRunAttemptModel.started_at)
+ )
+ started_at = attempt_claim.scalar_one_or_none()
+ if started_at is None:
+ await session.rollback()
+ return None
+ await session.commit()
+ return started_at
+
+ @db_operation("finalize_attempt", expected_errors=(AttemptRecoverySuperseded,))
+ async def finalize_attempt(
+ self,
+ workflow_run_id: str,
+ attempt_number: int,
+ *,
+ status: str,
+ failure_reason: str | None,
+ failure_category: list[dict[str, Any]] | None,
+ error_codes: list[str] | None,
+ finished_at: datetime,
+ retry_decision: str,
+ decision_reason: str | None,
+ next_attempt_at: datetime | None,
+ ) -> WorkflowRunAttemptModel:
+ normalized_finished_at = to_naive_utc(finished_at)
+ assert normalized_finished_at is not None
+ next_attempt_at = to_naive_utc(next_attempt_at)
+ now = naive_utc_now()
+ recovering = _undecided_recovery_attempt.get()
+ recovery_conditions: list[ColumnElement[bool]] = []
+ if (
+ recovering is not None
+ and recovering.workflow_run_id == workflow_run_id
+ and recovering.attempt_number == attempt_number
+ ):
+ recovery_conditions.append(WorkflowRunAttemptModel.modified_at == recovering.modified_at)
+ async with self.Session() as session:
+ finalized_attempt = (
+ await session.scalars(
+ update(WorkflowRunAttemptModel)
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ WorkflowRunAttemptModel.retry_decision.is_(None),
+ *recovery_conditions,
+ )
+ .values(
+ status=status,
+ failure_reason=failure_reason,
+ failure_category=failure_category,
+ error_codes=error_codes,
+ finished_at=normalized_finished_at,
+ retry_decision=retry_decision,
+ decision_reason=decision_reason,
+ next_attempt_at=next_attempt_at,
+ modified_at=now,
+ )
+ .returning(WorkflowRunAttemptModel)
+ .options(attempt_metadata_options(session.bind.dialect.name))
+ )
+ ).one_or_none()
+ if recovery_conditions and finalized_attempt is None:
+ raise AttemptRecoverySuperseded
+ revoked_attempt = (
+ await session.scalars(
+ update(WorkflowRunAttemptModel)
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ WorkflowRunAttemptModel.retry_decision == "revoked",
+ )
+ .values(
+ status=case(
+ (
+ WorkflowRunAttemptModel.status.in_(TERMINAL_STATUSES),
+ WorkflowRunAttemptModel.status,
+ ),
+ else_=bindparam(
+ "terminal_status",
+ status,
+ type_=WorkflowRunAttemptModel.status.type,
+ ),
+ ),
+ failure_reason=func.coalesce(
+ WorkflowRunAttemptModel.failure_reason,
+ bindparam(
+ "revoked_failure_reason",
+ failure_reason,
+ type_=WorkflowRunAttemptModel.failure_reason.type,
+ ),
+ ),
+ failure_category=func.coalesce(
+ WorkflowRunAttemptModel.failure_category,
+ bindparam(
+ "revoked_failure_category",
+ failure_category,
+ type_=WorkflowRunAttemptModel.failure_category.type,
+ ),
+ ),
+ error_codes=func.coalesce(
+ WorkflowRunAttemptModel.error_codes,
+ bindparam(
+ "revoked_error_codes",
+ error_codes,
+ type_=WorkflowRunAttemptModel.error_codes.type,
+ ),
+ ),
+ finished_at=func.coalesce(
+ WorkflowRunAttemptModel.finished_at,
+ bindparam(
+ "revoked_finished_at",
+ normalized_finished_at,
+ type_=WorkflowRunAttemptModel.finished_at.type,
+ ),
+ ),
+ modified_at=now,
+ )
+ .returning(WorkflowRunAttemptModel)
+ .options(attempt_metadata_options(session.bind.dialect.name))
+ )
+ ).one_or_none()
+ attempt = revoked_attempt or finalized_attempt
+ if attempt is None:
+ attempt = (
+ await session.scalars(
+ select(WorkflowRunAttemptModel)
+ .options(attempt_metadata_options(session.bind.dialect.name))
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ )
+ )
+ ).one_or_none()
+ if attempt is None:
+ raise NotFoundError(f"Workflow run attempt not found: {workflow_run_id}/{attempt_number}")
+ session.expunge(attempt)
+ await session.commit()
+ return attempt
+
+ @db_operation("revoke_or_abandon_attempt")
+ async def revoke_or_abandon_attempt(
+ self,
+ workflow_run_id: str,
+ attempt_number: int,
+ decision: str,
+ reason: str,
+ status: str | None = None,
+ failure_reason: str | None = None,
+ finished_at: datetime | None = None,
+ failure_category: list[dict[str, Any]] | None = None,
+ error_codes: list[str] | None = None,
+ lease_takeover_seconds: int | None = None,
+ ) -> WorkflowRunAttemptModel | None:
+ eligible_decision = or_(
+ WorkflowRunAttemptModel.retry_decision == "retry",
+ WorkflowRunAttemptModel.retry_decision.is_(None),
+ )
+ now = naive_utc_now()
+ if decision in {"revoked", "abandoned"}:
+ expected_decision = and_(
+ eligible_decision,
+ WorkflowRunAttemptModel.next_attempt_prepared_at.is_(None),
+ )
+ if decision == "abandoned":
+ if lease_takeover_seconds is None:
+ raise ValueError("lease_takeover_seconds is required when abandoning an attempt")
+ lease_available = or_(
+ WorkflowRunAttemptModel.side_effects_released_at.is_(None),
+ WorkflowRunAttemptModel.side_effects_released_at < now - timedelta(seconds=lease_takeover_seconds),
+ )
+ expected_decision = or_(
+ and_(expected_decision, lease_available),
+ and_(
+ WorkflowRunAttemptModel.retry_decision == "abandoned",
+ WorkflowRunAttemptModel.finished_at.is_(None),
+ ),
+ )
+ else:
+ expected_decision = WorkflowRunAttemptModel.retry_decision == "retry"
+ if reason == "process_restart":
+ if lease_takeover_seconds is None:
+ raise ValueError("lease_takeover_seconds is required for stale retry recovery")
+ expected_decision = and_(
+ expected_decision,
+ WorkflowRunAttemptModel.retry_decision == "retry",
+ WorkflowRunAttemptModel.next_attempt_prepared_at.is_(None),
+ WorkflowRunAttemptModel.next_attempt_at < now - timedelta(seconds=lease_takeover_seconds),
+ )
+ values: dict[str, Any] = {
+ "retry_decision": decision,
+ "decision_reason": reason,
+ "modified_at": now,
+ }
+ if decision in {"revoked", "abandoned"}:
+ # An interim retry webhook may have claimed this attempt before cancellation or a
+ # stale-retry recovery won the abandonment race. The final abandonment path must be
+ # able to claim the remaining terminal effects for the same attempt. Preserve a
+ # claim when a concurrent abandonment re-reads an already-abandoned row, otherwise
+ # two finalizers could both become side-effect winners.
+ values["side_effects_released_at"] = case(
+ (eligible_decision, None),
+ else_=WorkflowRunAttemptModel.side_effects_released_at,
+ )
+ if status is not None:
+ # ``status`` is the non-null current lifecycle value, so an abandonment that happens
+ # before the terminal transition must promote it from running/queued to the terminal
+ # status supplied by that transition. Nullable terminal metadata below is fill-once.
+ values["status"] = status
+ if failure_reason is not None:
+ values["failure_reason"] = func.coalesce(
+ WorkflowRunAttemptModel.failure_reason,
+ bindparam(
+ "abandon_failure_reason",
+ failure_reason,
+ type_=WorkflowRunAttemptModel.failure_reason.type,
+ ),
+ )
+ if failure_category is not None:
+ values["failure_category"] = func.coalesce(
+ WorkflowRunAttemptModel.failure_category,
+ bindparam(
+ "abandon_failure_category",
+ failure_category,
+ type_=WorkflowRunAttemptModel.failure_category.type,
+ ),
+ )
+ if error_codes is not None:
+ values["error_codes"] = func.coalesce(
+ WorkflowRunAttemptModel.error_codes,
+ bindparam(
+ "abandon_error_codes",
+ error_codes,
+ type_=WorkflowRunAttemptModel.error_codes.type,
+ ),
+ )
+ normalized_finished_at = to_naive_utc(finished_at)
+ if normalized_finished_at is not None:
+ values["finished_at"] = func.coalesce(
+ WorkflowRunAttemptModel.finished_at,
+ bindparam(
+ "abandon_finished_at",
+ normalized_finished_at,
+ type_=WorkflowRunAttemptModel.finished_at.type,
+ ),
+ )
+ async with self.Session() as session:
+ attempt = (
+ await session.scalars(
+ update(WorkflowRunAttemptModel)
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ expected_decision,
+ )
+ .values(**values)
+ .returning(WorkflowRunAttemptModel)
+ .options(attempt_metadata_options(session.bind.dialect.name))
+ )
+ ).one_or_none()
+ if attempt is not None:
+ session.expunge(attempt)
+ await session.commit()
+ return attempt
+
+ @db_operation("reserve_attempt_webhook_delivery")
+ async def reserve_attempt_webhook_delivery(
+ self,
+ workflow_run_id: str,
+ attempt_number: int,
+ *,
+ kind: Literal["interim", "final"],
+ expected_claim_at: datetime | None,
+ max_attempts: int,
+ ) -> int | None:
+ if kind == "interim":
+ completion_column = WorkflowRunAttemptModel.interim_webhook_sent_at
+ progress_column = WorkflowRunAttemptModel.interim_side_effects_progress
+ elif kind == "final":
+ completion_column = WorkflowRunAttemptModel.webhook_sent_at
+ progress_column = WorkflowRunAttemptModel.final_side_effects_progress
+ else:
+ raise ValueError(f"Unsupported workflow attempt webhook kind: {kind}")
+ conditions = [
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ WorkflowRunAttemptModel.side_effects_released_at == to_naive_utc(expected_claim_at),
+ completion_column.is_(None),
+ ]
+ async with self.Session() as session:
+ attempt = await session.scalar(
+ select(WorkflowRunAttemptModel)
+ .options(attempt_metadata_options(session.bind.dialect.name))
+ .where(*conditions)
+ .with_for_update()
+ )
+ if attempt is None:
+ return None
+ progress = dict(getattr(attempt, progress_column.key) or {})
+ delivery_attempts = progress.get("webhook_delivery_attempts", 0)
+ now = naive_utc_now()
+ values: dict[str, Any] = {"modified_at": now}
+ if delivery_attempts >= max_attempts:
+ # A process can stop after reserving its last call, before recording exhaustion.
+ progress["webhook_delivery_exhausted_at"] = now.isoformat()
+ values[completion_column.key] = now
+ reserved_attempt = 0
+ else:
+ reserved_attempt = delivery_attempts + 1
+ progress["webhook_delivery_attempts"] = reserved_attempt
+ values[progress_column.key] = merge_attempt_progress(progress_column, progress, session.bind.dialect.name)
+ await session.execute(update(WorkflowRunAttemptModel).where(*conditions).values(**values))
+ await session.commit()
+ return reserved_attempt
+
+ @db_operation("claim_attempt_webhook")
+ async def claim_attempt_webhook(
+ self,
+ workflow_run_id: str,
+ attempt_number: int,
+ kind: Literal["interim", "final"] = "final",
+ *,
+ expected_claim_at: datetime | None = None,
+ delivery_attempted: bool = False,
+ delivery_exhausted: bool = False,
+ ) -> bool:
+ if kind == "interim":
+ claim_column = WorkflowRunAttemptModel.interim_webhook_sent_at
+ progress_column = WorkflowRunAttemptModel.interim_side_effects_progress
+ elif kind == "final":
+ claim_column = WorkflowRunAttemptModel.webhook_sent_at
+ progress_column = WorkflowRunAttemptModel.final_side_effects_progress
+ else:
+ raise ValueError(f"Unsupported workflow attempt webhook kind: {kind}")
+
+ now = naive_utc_now()
+ conditions = [
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ claim_column.is_(None),
+ ]
+ if expected_claim_at is not None:
+ normalized_expected_claim_at = to_naive_utc(expected_claim_at)
+ assert normalized_expected_claim_at is not None
+ conditions.append(WorkflowRunAttemptModel.side_effects_released_at == normalized_expected_claim_at)
+ async with self.Session() as session:
+ values: dict[str, Any] = {claim_column.key: now, "modified_at": now}
+ if delivery_attempted or delivery_exhausted:
+ progress = dict(
+ await session.scalar(
+ select(progress_without_outputs(progress_column, session.bind.dialect.name))
+ .where(*conditions)
+ .with_for_update()
+ )
+ or {}
+ )
+ if delivery_exhausted:
+ progress["webhook_delivery_exhausted_at"] = now.isoformat()
+ else:
+ progress["webhook_delivery_attempted"] = True
+ values[progress_column.key] = merge_attempt_progress(
+ progress_column, progress, session.bind.dialect.name
+ )
+ result = await session.execute(update(WorkflowRunAttemptModel).where(*conditions).values(**values))
+ await session.commit()
+ return bool(result.rowcount)
+
+ @db_operation("claim_attempt_side_effects")
+ async def claim_attempt_side_effects(
+ self,
+ workflow_run_id: str,
+ attempt_number: int,
+ kind: Literal["interim", "final"] = "final",
+ *,
+ expected_claim_at: datetime | None = None,
+ stale_before: datetime | None = None,
+ expected_retry_decision: str | None = None,
+ ) -> datetime | None:
+ if kind == "interim":
+ completion_column = WorkflowRunAttemptModel.interim_webhook_sent_at
+ elif kind == "final":
+ completion_column = WorkflowRunAttemptModel.webhook_sent_at
+ else:
+ raise ValueError(f"Unsupported workflow attempt side-effect kind: {kind}")
+
+ claim_condition = WorkflowRunAttemptModel.side_effects_released_at.is_(None)
+ if expected_claim_at is not None:
+ normalized_expected_claim_at = to_naive_utc(expected_claim_at)
+ assert normalized_expected_claim_at is not None
+ normalized_stale_before = to_naive_utc(stale_before)
+ assert normalized_stale_before is not None
+ claim_condition = and_(
+ WorkflowRunAttemptModel.side_effects_released_at == normalized_expected_claim_at,
+ WorkflowRunAttemptModel.side_effects_released_at < normalized_stale_before,
+ )
+
+ now = naive_utc_now()
+ conditions = [
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ completion_column.is_(None),
+ claim_condition,
+ ]
+ if expected_retry_decision is not None:
+ conditions.append(WorkflowRunAttemptModel.retry_decision == expected_retry_decision)
+ async with self.Session() as session:
+ result = await session.execute(
+ update(WorkflowRunAttemptModel)
+ .where(*conditions)
+ .values(side_effects_released_at=now, modified_at=now)
+ .returning(WorkflowRunAttemptModel.side_effects_released_at)
+ )
+ claimed_at = result.scalar_one_or_none()
+ await session.commit()
+ return claimed_at
+
+ @db_operation("save_side_effect_progress")
+ async def save_side_effect_progress(
+ self,
+ workflow_run_id: str,
+ attempt_number: int,
+ *,
+ kind: Literal["interim", "final"],
+ expected_claim_at: datetime,
+ progress: TerminalSideEffectCheckpoint,
+ ) -> bool:
+ """Checkpoint only the current owner's release, keeping interim and final progress separate."""
+ claim_at = to_naive_utc(expected_claim_at)
+ assert claim_at is not None
+ if kind == "interim":
+ progress_column = WorkflowRunAttemptModel.interim_side_effects_progress
+ decision_condition = WorkflowRunAttemptModel.retry_decision == "retry"
+ elif kind == "final":
+ progress_column = WorkflowRunAttemptModel.final_side_effects_progress
+ decision_condition = WorkflowRunAttemptModel.retry_decision.in_(["final", "revoked", "abandoned"])
+ else:
+ raise ValueError(f"Unsupported workflow attempt side-effect kind: {kind}")
+ conditions = [
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ WorkflowRunAttemptModel.side_effects_released_at == claim_at,
+ decision_condition,
+ ]
+ async with self.Session() as session:
+ checkpoint = await session.scalar(
+ select(progress_without_outputs(progress_column, session.bind.dialect.name))
+ .where(*conditions)
+ .with_for_update()
+ )
+ # Delivery evidence and release checkpoints share JSON storage and must survive either writer.
+ checkpoint = {**(checkpoint or {}), **progress}
+ result = await session.execute(
+ update(WorkflowRunAttemptModel)
+ .where(*conditions)
+ .values(
+ {
+ progress_column: merge_attempt_progress(progress_column, checkpoint, session.bind.dialect.name),
+ WorkflowRunAttemptModel.modified_at: naive_utc_now(),
+ }
+ )
+ )
+ await session.commit()
+ return bool(result.rowcount)
+
+ @db_operation("clear_failed_interim_side_effect_lease")
+ async def clear_failed_interim_side_effect_lease(
+ self,
+ workflow_run_id: str,
+ attempt_number: int,
+ expected_claim_at: datetime,
+ ) -> bool:
+ """Release an interim side-effect lease after its owner failed before recording delivery.
+
+ The conditional update keeps a takeover winner from being cleared by the failed owner.
+ Final-release leases are intentionally never cleared here: a final effect may have
+ reached a once-only hook before failing, so recovery must retain the takeover bound.
+ """
+ normalized_expected_claim_at = to_naive_utc(expected_claim_at)
+ assert normalized_expected_claim_at is not None
+ now = naive_utc_now()
+ async with self.Session() as session:
+ result = await session.execute(
+ update(WorkflowRunAttemptModel)
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ WorkflowRunAttemptModel.retry_decision == "retry",
+ WorkflowRunAttemptModel.side_effects_released_at == normalized_expected_claim_at,
+ WorkflowRunAttemptModel.interim_webhook_sent_at.is_(None),
+ )
+ .values(side_effects_released_at=None, modified_at=now)
+ )
+ await session.commit()
+ return bool(result.rowcount)
+
+ @db_operation("delete_attempts_for_run")
+ async def delete_attempts_for_run(self, workflow_run_id: str) -> None:
+ async with self.Session() as session:
+ await session.execute(
+ delete(WorkflowRunAttemptModel).where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ )
+ )
+ await session.commit()
diff --git a/skyvern/forge/sdk/db/repositories/workflow_run_credential_selections.py b/skyvern/forge/sdk/db/repositories/workflow_run_credential_selections.py
index 72e1d9cc5..77b1d08aa 100644
--- a/skyvern/forge/sdk/db/repositories/workflow_run_credential_selections.py
+++ b/skyvern/forge/sdk/db/repositories/workflow_run_credential_selections.py
@@ -117,43 +117,61 @@ class WorkflowRunCredentialSelectionsRepository(BaseRepository):
credential_ids: list[str],
) -> str:
async with self.Session() as session:
- lock_key = f"wrcs:{organization_id}:{workflow_permanent_id}:{parameter_key}"
- # The lock, idempotency check, LRU read, and insert must stay in this transaction.
- await self._take_rotation_advisory_lock(session, lock_key)
-
- existing = await self._get_selection(
- session,
- workflow_run_id=workflow_run_id,
- parameter_key=parameter_key,
- )
- if existing:
- return existing
-
- latest_selections = await self._get_latest_selections(
+ credential_id = await self._create_round_robin_selection(
session,
- organization_id=organization_id,
- workflow_permanent_id=workflow_permanent_id,
- parameter_key=parameter_key,
- credential_ids=credential_ids,
- )
- unseen = next((candidate for candidate in credential_ids if candidate not in latest_selections), None)
- credential_id = (
- unseen
- if unseen is not None
- else min(credential_ids, key=lambda candidate: latest_selections[candidate])
- )
-
- selection = WorkflowRunCredentialSelectionModel(
organization_id=organization_id,
workflow_run_id=workflow_run_id,
workflow_permanent_id=workflow_permanent_id,
parameter_key=parameter_key,
- credential_id=credential_id,
+ credential_ids=credential_ids,
)
- session.add(selection)
await session.commit()
return credential_id
+ async def _create_round_robin_selection(
+ self,
+ session: AsyncSession,
+ *,
+ organization_id: str,
+ workflow_run_id: str,
+ workflow_permanent_id: str,
+ parameter_key: str,
+ credential_ids: list[str],
+ ) -> str:
+ lock_key = f"wrcs:{organization_id}:{workflow_permanent_id}:{parameter_key}"
+ # The lock, idempotency check, LRU read, and insert must stay in this transaction.
+ await self._take_rotation_advisory_lock(session, lock_key)
+
+ existing = await self._get_selection(
+ session,
+ workflow_run_id=workflow_run_id,
+ parameter_key=parameter_key,
+ )
+ if existing:
+ return existing
+
+ latest_selections = await self._get_latest_selections(
+ session,
+ organization_id=organization_id,
+ workflow_permanent_id=workflow_permanent_id,
+ parameter_key=parameter_key,
+ credential_ids=credential_ids,
+ )
+ unseen = next((candidate for candidate in credential_ids if candidate not in latest_selections), None)
+ credential_id = (
+ unseen if unseen is not None else min(credential_ids, key=lambda candidate: latest_selections[candidate])
+ )
+
+ selection = WorkflowRunCredentialSelectionModel(
+ organization_id=organization_id,
+ workflow_run_id=workflow_run_id,
+ workflow_permanent_id=workflow_permanent_id,
+ parameter_key=parameter_key,
+ credential_id=credential_id,
+ )
+ session.add(selection)
+ return credential_id
+
@db_operation("create_workflow_run_credential_selection", log_errors=False)
async def create_selection(
self,
diff --git a/skyvern/forge/sdk/db/repositories/workflow_runs.py b/skyvern/forge/sdk/db/repositories/workflow_runs.py
index e7153b336..6cb469629 100644
--- a/skyvern/forge/sdk/db/repositories/workflow_runs.py
+++ b/skyvern/forge/sdk/db/repositories/workflow_runs.py
@@ -1,31 +1,43 @@
from __future__ import annotations
+import json
from collections.abc import AsyncIterator, Callable, Sequence
from contextlib import asynccontextmanager
+from dataclasses import dataclass
from datetime import datetime, timedelta
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, Literal
from typing import cast as typing_cast
import structlog
+from pydantic import ValidationError
from sqlalchemy import (
ColumnElement,
+ Integer,
Label,
Select,
Text,
and_,
+ case,
cast,
+ delete,
exists,
func,
literal,
literal_column,
or_,
select,
+ true,
update,
)
from sqlalchemy.dialects.postgresql import JSONB
-from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.exc import IntegrityError, SQLAlchemyError
+from sqlalchemy.ext.compiler import compiles
+from sqlalchemy.orm import load_only
+from sqlalchemy.sql.compiler import SQLCompiler
+from sqlalchemy.sql.selectable import Join
from skyvern.exceptions import WorkflowParameterNotFound, WorkflowRunNotFound
+from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType
from skyvern.forge.sdk.db._error_handling import db_operation
from skyvern.forge.sdk.db.base_alchemy_db import read_retry
from skyvern.forge.sdk.db.base_repository import BaseRepository
@@ -39,18 +51,24 @@ if TYPE_CHECKING:
from skyvern.forge.sdk.db._sentinels import _UNSET
from skyvern.forge.sdk.db.models import (
+ ArtifactModel,
PersistentBrowserSessionModel,
+ StepModel,
TaskModel,
TaskRunModel,
WorkflowModel,
WorkflowParameterModel,
+ WorkflowRunAttemptModel,
WorkflowRunBlockModel,
+ WorkflowRunCredentialSelectionModel,
WorkflowRunModel,
WorkflowRunOutputParameterModel,
WorkflowRunParameterModel,
)
from skyvern.forge.sdk.db.protocols import WorkflowParameterReader
+from skyvern.forge.sdk.db.repositories.workflow_run_attempts import attempt_metadata_options, merge_attempt_progress
from skyvern.forge.sdk.db.utils import (
+ convert_to_artifact,
convert_to_task,
convert_to_workflow_run,
convert_to_workflow_run_output_parameter,
@@ -61,8 +79,11 @@ from skyvern.forge.sdk.db.utils import (
from skyvern.forge.sdk.log_artifacts import save_workflow_run_logs
from skyvern.forge.sdk.schemas.persistent_browser_sessions import FORCED_WORKFLOW_SESSION_RUNNABLE_TYPE
from skyvern.forge.sdk.schemas.tasks import Task
+from skyvern.forge.sdk.workflow.constants import INTERIM_OUTPUT_SNAPSHOT_MAX_BYTES
+from skyvern.forge.sdk.workflow.credential_selection import clear_credential_selections_for_retry
from skyvern.forge.sdk.workflow.models.parameter import WorkflowParameter
from skyvern.forge.sdk.workflow.models.workflow import (
+ WorkflowDefinition,
WorkflowRun,
WorkflowRunOutputParameter,
WorkflowRunParameter,
@@ -70,11 +91,60 @@ from skyvern.forge.sdk.workflow.models.workflow import (
resolve_reuse_browser_session,
)
from skyvern.forge.sdk.workflow.sequential_key import is_reuse_admission_off
-from skyvern.schemas.runs import MAX_SEARCH_FETCH_LIMIT, ProxyLocationInput, RunType
+from skyvern.schemas.runs import MAX_SEARCH_FETCH_LIMIT, TERMINAL_STATUSES, ProxyLocationInput, RunType
LOG = structlog.get_logger()
+class _AncestryJoin(Join):
+ inherit_cache = True
+
+
+@compiles(_AncestryJoin, "sqlite")
+def _compile_ancestry_join(element: _AncestryJoin, compiler: SQLCompiler, **kwargs: Any) -> str:
+ # SQLite only preserves loop order for CROSS JOIN, including when parent-id statistics are sparse.
+ return compiler.visit_join(element, **kwargs).replace(" JOIN ", " CROSS JOIN ", 1)
+
+
+def _bounded_interim_outputs(outputs: Sequence[WorkflowRunOutputParameterModel]) -> dict[str, Any]:
+ entries = [
+ {
+ "output_parameter_id": output.output_parameter_id,
+ "value": output.value,
+ "created_at": output.created_at.isoformat(),
+ }
+ for output in outputs
+ ]
+ marker = {"truncated": True, "reason": "interim_output_snapshot_budget_exceeded"}
+ value_sizes = [len(json.dumps(entry["value"]).encode("utf-8")) for entry in entries]
+ envelope_size = len(json.dumps({"output_parameters": [], "omitted_output_count": len(entries)}).encode("utf-8")) - 2
+ size = (
+ envelope_size
+ + 2
+ + max(0, len(entries) - 1) * 2
+ + sum(
+ len(json.dumps({**entry, "value": None}).encode("utf-8")) - 4 + value_size
+ for entry, value_size in zip(entries, value_sizes)
+ )
+ )
+ marker_size = len(json.dumps(marker).encode("utf-8"))
+ for index in sorted(range(len(entries)), key=value_sizes.__getitem__, reverse=True):
+ if size <= INTERIM_OUTPUT_SNAPSHOT_MAX_BYTES:
+ break
+ if value_sizes[index] > marker_size:
+ entries[index]["value"] = marker.copy()
+ size -= value_sizes[index] - marker_size
+ retained: list[dict[str, Any]] = []
+ retained_size = envelope_size + 2
+ for entry in entries:
+ entry_size = len(json.dumps(entry).encode("utf-8")) + (2 if retained else 0)
+ if retained_size + entry_size > INTERIM_OUTPUT_SNAPSHOT_MAX_BYTES:
+ break
+ retained.append(entry)
+ retained_size += entry_size
+ return {"output_parameters": retained, "omitted_output_count": len(entries) - len(retained)}
+
+
def _noncredential_lane_variants(base: Select) -> tuple[Select, Select]:
"""Split the widened non-session lane into two index-eligible candidates whose union equals
``browser_session_id IS NULL OR sequential_credential_id IS NOT NULL``.
@@ -118,6 +188,96 @@ def _merge_script_run(
return merged
+async def _allocate_serialized_queue_ticket(
+ session: Any,
+ *,
+ organization_id: str,
+ workflow_run_id: str,
+) -> datetime:
+ """Allocate the monotonic queue ticket used by serialized workflow publication."""
+ latest_ticket = await session.scalar(
+ select(func.max(WorkflowRunModel.queued_at))
+ .where(WorkflowRunModel.organization_id == organization_id)
+ .where(WorkflowRunModel.workflow_run_id != workflow_run_id)
+ .where(
+ WorkflowRunModel.status.in_(
+ [
+ WorkflowRunStatus.queued,
+ WorkflowRunStatus.running,
+ WorkflowRunStatus.paused,
+ ]
+ )
+ )
+ )
+ database_now = await session.scalar(select(func.now()))
+ if database_now is None:
+ raise RuntimeError("Database did not return a serialized queue timestamp")
+ database_now = to_naive_utc(database_now)
+ assert database_now is not None
+ if latest_ticket is None:
+ return database_now
+ latest_ticket_utc = to_naive_utc(latest_ticket)
+ assert latest_ticket_utc is not None
+ return max(database_now, latest_ticket_utc + timedelta(microseconds=1))
+
+
+@dataclass(frozen=True)
+class PrepareNextAttemptResult:
+ """The durable outcome of one caller trying to reopen a retry attempt."""
+
+ status: Literal["inserted", "already_prepared", "failed"]
+ pinned_browser_session_id: str | None = None
+ serialized_identity: bool = False
+
+
+async def _has_serialized_publication_identity(
+ session: Any,
+ workflow_run: WorkflowRunModel,
+ *,
+ browser_session_id: str | None,
+ browser_address: str | None,
+ sequential_credential_id: str | None = None,
+ use_existing_browser_session: bool = True,
+) -> bool:
+ """Return the publication-lane predicate shared by publication and retry preparation."""
+ effective_browser_session_id = (
+ workflow_run.browser_session_id
+ if use_existing_browser_session and browser_session_id is None
+ else browser_session_id
+ )
+ credential_id = sequential_credential_id or workflow_run.sequential_credential_id
+ active_reuse_bound_key = (
+ workflow_run.reuse_bound_key if not is_reuse_admission_off(workflow_run.reuse_bound_key) else None
+ )
+ serialized_publication = bool(
+ credential_id
+ or (effective_browser_session_id and not workflow_run.debug_session_id)
+ or browser_address
+ or workflow_run.sequential_key
+ or active_reuse_bound_key
+ )
+ if not serialized_publication and workflow_run.workflow_id:
+ workflow = await session.get(
+ WorkflowModel,
+ workflow_run.workflow_id,
+ options=[load_only(WorkflowModel.run_sequentially, WorkflowModel.reuse_browser_session)],
+ )
+ serialized_publication = bool(
+ workflow
+ and (
+ workflow.run_sequentially
+ or (
+ not workflow_run.start_fresh_browser
+ and resolve_reuse_browser_session(
+ run_override=workflow_run.reuse_browser_session,
+ workflow_default=workflow.reuse_browser_session,
+ )
+ )
+ )
+ )
+ return serialized_publication
+
+
class WorkflowRunsRepository(BaseRepository):
"""Database operations for workflow runs."""
@@ -338,67 +498,23 @@ class WorkflowRunsRepository(BaseRepository):
if status:
workflow_run.status = status
if status and status == WorkflowRunStatus.queued and workflow_run.queued_at is None:
- credential_id = sequential_credential_id or workflow_run.sequential_credential_id
- active_reuse_bound_key = (
- workflow_run.reuse_bound_key
- if not is_reuse_admission_off(workflow_run.reuse_bound_key)
- else None
+ serialized_publication = await _has_serialized_publication_identity(
+ session,
+ workflow_run,
+ browser_session_id=workflow_run.browser_session_id,
+ browser_address=workflow_run.browser_address,
+ sequential_credential_id=sequential_credential_id,
)
- serialized_publication = bool(
- credential_id
- or (workflow_run.browser_session_id and not workflow_run.debug_session_id)
- or workflow_run.browser_address
- or workflow_run.sequential_key
- or active_reuse_bound_key
- )
- if not serialized_publication and workflow_run.workflow_id:
- workflow = await session.get(WorkflowModel, workflow_run.workflow_id)
- serialized_publication = bool(
- workflow
- and (
- workflow.run_sequentially
- or (
- not workflow_run.start_fresh_browser
- and resolve_reuse_browser_session(
- run_override=workflow_run.reuse_browser_session,
- workflow_default=workflow.reuse_browser_session,
- )
- )
- )
- )
if serialized_publication:
# The caller holds every composed publication-lane lock until this transaction
# commits. Advance beyond every active serialized ticket in the organization,
# so all composed lanes share one comparable clock even when database transaction
# time or an application host clock moved backwards.
- latest_ticket = await session.scalar(
- select(func.max(WorkflowRunModel.queued_at))
- .where(WorkflowRunModel.organization_id == workflow_run.organization_id)
- .where(WorkflowRunModel.workflow_run_id != workflow_run_id)
- .where(
- WorkflowRunModel.status.in_(
- [
- WorkflowRunStatus.queued,
- WorkflowRunStatus.running,
- WorkflowRunStatus.paused,
- ]
- )
- )
+ workflow_run.queued_at = await _allocate_serialized_queue_ticket(
+ session,
+ organization_id=workflow_run.organization_id,
+ workflow_run_id=workflow_run_id,
)
- database_now = await session.scalar(select(func.now()))
- if database_now is None:
- raise RuntimeError("Database did not return a credential publication timestamp")
- database_now = to_naive_utc(database_now)
- assert database_now is not None
- if latest_ticket is not None:
- latest_ticket_utc = to_naive_utc(latest_ticket)
- assert latest_ticket_utc is not None
- workflow_run.queued_at = max(
- database_now,
- latest_ticket_utc + timedelta(microseconds=1),
- )
- else:
- workflow_run.queued_at = database_now
else:
workflow_run.queued_at = naive_utc_now()
if status and status == WorkflowRunStatus.running and workflow_run.started_at is None:
@@ -889,6 +1005,7 @@ class WorkflowRunsRepository(BaseRepository):
TaskRunModel.title.label("title"),
TaskRunModel.started_at.label("started_at"),
TaskRunModel.finished_at.label("finished_at"),
+ WorkflowRunModel.finished_at.label("workflow_run_finished_at"),
TaskRunModel.created_at.label("created_at"),
effective_wpid.label("workflow_permanent_id"),
TaskRunModel.script_run.label("script_run"),
@@ -975,6 +1092,7 @@ class WorkflowRunsRepository(BaseRepository):
WorkflowModel.title.label("title"),
WorkflowRunModel.started_at.label("started_at"),
WorkflowRunModel.finished_at.label("finished_at"),
+ WorkflowRunModel.finished_at.label("workflow_run_finished_at"),
WorkflowRunModel.created_at.label("created_at"),
WorkflowRunModel.workflow_permanent_id.label("workflow_permanent_id"),
WorkflowRunModel.script_run.label("script_run"),
@@ -1179,6 +1297,389 @@ class WorkflowRunsRepository(BaseRepository):
workflow_run = max(candidates, key=lambda run: run.modified_at)
return convert_to_workflow_run(workflow_run)
+ @db_operation("delete_retry_history_for_reset")
+ async def delete_retry_history_for_reset(self, workflow_run_id: str, organization_id: str) -> None:
+ async with self.Session() as session:
+ await session.execute(
+ delete(WorkflowRunAttemptModel).where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.organization_id == organization_id,
+ )
+ )
+ await session.execute(
+ delete(WorkflowRunCredentialSelectionModel).where(
+ WorkflowRunCredentialSelectionModel.organization_id == organization_id,
+ WorkflowRunCredentialSelectionModel.workflow_run_id.startswith(
+ f"{workflow_run_id}:attempt:", autoescape=True
+ ),
+ )
+ )
+ await session.commit()
+
+ @db_operation("queue_initial_dispatch")
+ async def queue_initial_dispatch(self, workflow_run_id: str, attempt_number: int) -> bool:
+ """Move a created run and its created attempt to queued in one transaction.
+
+ False when the run is missing or no longer created or queued, so the caller must not dispatch it.
+ """
+ now = naive_utc_now()
+ async with self.Session() as session:
+ workflow_run = (
+ await session.scalars(select(WorkflowRunModel).filter_by(workflow_run_id=workflow_run_id))
+ ).first()
+ if workflow_run is None:
+ return False
+ if workflow_run.status == WorkflowRunStatus.created:
+ queued_at = workflow_run.queued_at
+ if queued_at is None:
+ serialized_publication = await _has_serialized_publication_identity(
+ session,
+ workflow_run,
+ browser_session_id=workflow_run.browser_session_id,
+ browser_address=workflow_run.browser_address,
+ )
+ queued_at = (
+ await _allocate_serialized_queue_ticket(
+ session, organization_id=workflow_run.organization_id, workflow_run_id=workflow_run_id
+ )
+ if serialized_publication
+ else now
+ )
+ # A cancel committed since the caller's read must win: the status predicate re-evaluates
+ # against the latest committed row.
+ moved = await session.execute(
+ update(WorkflowRunModel)
+ .where(
+ WorkflowRunModel.workflow_run_id == workflow_run_id,
+ WorkflowRunModel.status == WorkflowRunStatus.created.value,
+ )
+ .values(status=WorkflowRunStatus.queued.value, queued_at=queued_at, modified_at=now)
+ )
+ if moved.rowcount != 1:
+ await session.rollback()
+ return False
+ elif workflow_run.status != WorkflowRunStatus.queued:
+ return False
+ await session.execute(
+ update(WorkflowRunAttemptModel)
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ WorkflowRunAttemptModel.status == "created",
+ WorkflowRunAttemptModel.started_at.is_(None),
+ WorkflowRunAttemptModel.retry_decision.is_(None),
+ )
+ .values(status="queued", modified_at=now)
+ )
+ await session.commit()
+ return True
+
+ @db_operation("prepare_next_attempt_atomic")
+ async def prepare_next_attempt_atomic(
+ self,
+ workflow_run_id: str,
+ organization_id: str,
+ from_attempt: int,
+ expected_status: WorkflowRunStatus | str,
+ browser_session_id: str | None,
+ clear_browser_address: bool = True,
+ replacement_browser_address: str | None = None,
+ ) -> PrepareNextAttemptResult:
+ expected_status_value = (
+ expected_status.value if isinstance(expected_status, WorkflowRunStatus) else expected_status
+ )
+ now = naive_utc_now()
+ async with self.Session() as session:
+ try:
+ workflow_run = await session.scalar(
+ select(WorkflowRunModel)
+ .where(
+ WorkflowRunModel.workflow_run_id == workflow_run_id,
+ WorkflowRunModel.organization_id == organization_id,
+ )
+ .with_for_update()
+ )
+ if workflow_run is None:
+ await session.rollback()
+ return PrepareNextAttemptResult(status="failed")
+
+ current_attempt = await session.scalar(
+ select(WorkflowRunAttemptModel)
+ .options(attempt_metadata_options(session.bind.dialect.name))
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.organization_id == organization_id,
+ WorkflowRunAttemptModel.attempt_number == from_attempt,
+ )
+ .with_for_update()
+ )
+
+ async def read_committed_preparation() -> PrepareNextAttemptResult:
+ locked_attempt = await session.scalar(
+ select(WorkflowRunAttemptModel)
+ .options(attempt_metadata_options(session.bind.dialect.name))
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.organization_id == organization_id,
+ WorkflowRunAttemptModel.attempt_number == from_attempt,
+ )
+ .with_for_update()
+ )
+ if locked_attempt is None or locked_attempt.next_attempt_prepared_at is None:
+ return PrepareNextAttemptResult(status="failed")
+
+ next_attempt = await session.scalar(
+ select(WorkflowRunAttemptModel)
+ .options(attempt_metadata_options(session.bind.dialect.name))
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.organization_id == organization_id,
+ WorkflowRunAttemptModel.attempt_number == from_attempt + 1,
+ )
+ )
+ if next_attempt is None:
+ return PrepareNextAttemptResult(status="failed")
+
+ prepared_browser_session_id = (
+ next_attempt.pinned_browser_session_id
+ or locked_attempt.pinned_browser_session_id
+ or browser_session_id
+ )
+ serialized_identity = await _has_serialized_publication_identity(
+ session,
+ workflow_run,
+ browser_session_id=workflow_run.browser_session_id,
+ browser_address=workflow_run.browser_address,
+ use_existing_browser_session=False,
+ )
+ return PrepareNextAttemptResult(
+ status="already_prepared",
+ pinned_browser_session_id=prepared_browser_session_id,
+ serialized_identity=serialized_identity,
+ )
+
+ if current_attempt is not None and current_attempt.next_attempt_prepared_at is not None:
+ next_attempt = await session.scalar(
+ select(WorkflowRunAttemptModel)
+ .options(attempt_metadata_options(session.bind.dialect.name))
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.organization_id == organization_id,
+ WorkflowRunAttemptModel.attempt_number == from_attempt + 1,
+ )
+ )
+ if next_attempt is None:
+ await session.rollback()
+ return PrepareNextAttemptResult(status="failed")
+
+ current_status = await session.scalar(
+ select(WorkflowRunModel.status).where(
+ WorkflowRunModel.workflow_run_id == workflow_run_id,
+ WorkflowRunModel.organization_id == organization_id,
+ )
+ )
+ prepared_run_statuses = {
+ WorkflowRunStatus.queued.value,
+ WorkflowRunStatus.running.value,
+ *TERMINAL_STATUSES,
+ }
+ if current_status in prepared_run_statuses:
+ prepared_browser_session_id = (
+ next_attempt.pinned_browser_session_id
+ or current_attempt.pinned_browser_session_id
+ or browser_session_id
+ )
+ serialized_identity = await _has_serialized_publication_identity(
+ session,
+ workflow_run,
+ browser_session_id=workflow_run.browser_session_id,
+ browser_address=workflow_run.browser_address,
+ use_existing_browser_session=False,
+ )
+ await session.rollback()
+ return PrepareNextAttemptResult(
+ status="already_prepared",
+ pinned_browser_session_id=prepared_browser_session_id,
+ serialized_identity=serialized_identity,
+ )
+
+ await session.rollback()
+ return PrepareNextAttemptResult(status="failed")
+
+ prepared = await session.execute(
+ update(WorkflowRunAttemptModel)
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.organization_id == organization_id,
+ WorkflowRunAttemptModel.attempt_number == from_attempt,
+ WorkflowRunAttemptModel.retry_decision == "retry",
+ WorkflowRunAttemptModel.next_attempt_prepared_at.is_(None),
+ )
+ .values(next_attempt_prepared_at=now, modified_at=now)
+ )
+ if prepared.rowcount != 1:
+ preparation = await read_committed_preparation()
+ if preparation.status == "already_prepared":
+ await session.rollback()
+ return preparation
+ await session.rollback()
+ return PrepareNextAttemptResult(status="failed")
+
+ browser_address = (
+ None if clear_browser_address else (replacement_browser_address or workflow_run.browser_address)
+ )
+ serialized_identity = await _has_serialized_publication_identity(
+ session,
+ workflow_run,
+ browser_session_id=browser_session_id,
+ browser_address=browser_address,
+ use_existing_browser_session=False,
+ )
+ queued_at = (
+ await _allocate_serialized_queue_ticket(
+ session,
+ organization_id=organization_id,
+ workflow_run_id=workflow_run_id,
+ )
+ if serialized_identity
+ else now
+ )
+
+ attempt_usage = {
+ "queued_at": workflow_run.queued_at.isoformat() if workflow_run.queued_at else None,
+ "browser_session_id": workflow_run.browser_session_id,
+ "credits_used": workflow_run.credits_used or 0,
+ "cached_credits_used": workflow_run.cached_credits_used or 0,
+ }
+ reopened_values: dict[str, object] = {
+ "status": WorkflowRunStatus.queued.value,
+ "queued_at": queued_at,
+ "started_at": None,
+ "finished_at": None,
+ "failure_reason": None,
+ "failure_category": None,
+ "browser_session_id": browser_session_id,
+ "modified_at": now,
+ }
+ if clear_browser_address:
+ reopened_values["browser_address"] = None
+ elif replacement_browser_address is not None:
+ reopened_values["browser_address"] = replacement_browser_address
+
+ reopened = await session.execute(
+ update(WorkflowRunModel)
+ .where(
+ WorkflowRunModel.workflow_run_id == workflow_run_id,
+ WorkflowRunModel.organization_id == organization_id,
+ WorkflowRunModel.status == expected_status_value,
+ )
+ .values(**reopened_values)
+ )
+ if reopened.rowcount != 1:
+ preparation = await read_committed_preparation()
+ if preparation.status == "already_prepared":
+ await session.rollback()
+ return preparation
+ await session.rollback()
+ return PrepareNextAttemptResult(status="failed")
+
+ assert current_attempt is not None
+ # The historical attempt response reads this snapshot after the delete below,
+ # so every handoff takes it; the output budget keeps the row small.
+ outputs = (
+ await session.scalars(
+ select(WorkflowRunOutputParameterModel)
+ .where(WorkflowRunOutputParameterModel.workflow_run_id == workflow_run_id)
+ .order_by(WorkflowRunOutputParameterModel.created_at)
+ )
+ ).all()
+ snapshot = {**attempt_usage, **_bounded_interim_outputs(outputs)}
+ await session.execute(
+ update(WorkflowRunAttemptModel)
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == from_attempt,
+ )
+ .values(
+ interim_side_effects_progress=merge_attempt_progress(
+ WorkflowRunAttemptModel.interim_side_effects_progress,
+ snapshot,
+ session.bind.dialect.name,
+ )
+ )
+ .execution_options(synchronize_session=False)
+ )
+ await session.execute(
+ delete(WorkflowRunOutputParameterModel).where(
+ WorkflowRunOutputParameterModel.workflow_run_id == workflow_run_id,
+ )
+ )
+ has_credential_selections = await session.scalar(
+ select(
+ exists().where(
+ WorkflowRunCredentialSelectionModel.workflow_run_id == workflow_run_id,
+ WorkflowRunCredentialSelectionModel.organization_id == organization_id,
+ )
+ )
+ )
+ if has_credential_selections:
+ workflow = await session.scalar(
+ select(WorkflowModel).where(
+ WorkflowModel.workflow_id == workflow_run.workflow_id,
+ WorkflowModel.organization_id == organization_id,
+ )
+ )
+ workflow_definition = None
+ if workflow is not None:
+ try:
+ workflow_definition = WorkflowDefinition.model_validate(workflow.workflow_definition)
+ except ValidationError:
+ pass
+ await clear_credential_selections_for_retry(
+ workflow_run_id,
+ organization_id,
+ from_attempt + 1,
+ workflow_definition=workflow_definition,
+ session=session,
+ browser_address_replaced=replacement_browser_address is not None,
+ )
+ session.add(
+ WorkflowRunAttemptModel(
+ workflow_run_id=workflow_run_id,
+ attempt_number=from_attempt + 1,
+ organization_id=organization_id,
+ status=WorkflowRunStatus.queued.value,
+ pinned_browser_session_id=browser_session_id,
+ created_at=now,
+ modified_at=now,
+ )
+ )
+ await session.flush()
+
+ await session.execute(
+ update(TaskRunModel)
+ .where(
+ TaskRunModel.run_id == workflow_run_id,
+ TaskRunModel.organization_id == organization_id,
+ TaskRunModel.task_run_type == "workflow_run",
+ )
+ .values(
+ status=WorkflowRunStatus.queued.value,
+ started_at=None,
+ finished_at=None,
+ modified_at=now,
+ )
+ )
+ await session.commit()
+ except IntegrityError:
+ await session.rollback()
+ return PrepareNextAttemptResult(status="failed")
+ return PrepareNextAttemptResult(
+ status="inserted",
+ pinned_browser_session_id=browser_session_id,
+ serialized_identity=serialized_identity,
+ )
+
@db_operation("get_workflow_runs_by_ids")
async def get_workflow_runs_by_ids(
self,
@@ -1961,11 +2462,128 @@ class WorkflowRunsRepository(BaseRepository):
)
return results
+ @db_operation("get_artifacts_for_attempt")
+ async def get_artifacts_for_attempt(
+ self,
+ workflow_run_id: str,
+ organization_id: str,
+ attempt_number: int,
+ started_at: datetime | None,
+ successor_started_at: datetime | None,
+ *,
+ artifact_run_id: str | None = None,
+ ) -> list[Artifact]:
+ artifact_run_id = artifact_run_id or workflow_run_id
+ descendants = select(
+ cast(literal(workflow_run_id), Text).label("workflow_run_id"),
+ cast(literal(None), Integer).label("attempt_number"),
+ ).cte("attempt_descendants", recursive=True)
+ child = WorkflowRunModel.__table__.alias("attempt_child")
+ spawning_block = WorkflowRunBlockModel.__table__.alias("attempt_spawning_block")
+ child_attempt = case(
+ (
+ descendants.c.workflow_run_id == workflow_run_id,
+ func.coalesce(spawning_block.c.attempt_number, 1),
+ ),
+ else_=descendants.c.attempt_number,
+ ).label("attempt_number")
+ parent_link = child.c.parent_workflow_run_id == descendants.c.workflow_run_id
+ block_link = and_(
+ spawning_block.c.organization_id == organization_id,
+ spawning_block.c.workflow_run_id == descendants.c.workflow_run_id,
+ )
+ parent_source = child
+ block_source = spawning_block
+ if self._dialect_name == "sqlite":
+ parent_source = _AncestryJoin(descendants, child, parent_link)
+ block_source = _AncestryJoin(descendants, spawning_block, block_link)
+ parent_children = (
+ select(child.c.workflow_run_id, descendants.c.attempt_number)
+ .select_from(parent_source)
+ .where(parent_link, child.c.organization_id == organization_id, child.c.workflow_run_id != workflow_run_id)
+ .correlate(descendants)
+ )
+ block_children = (
+ select(child.c.workflow_run_id, child_attempt)
+ .select_from(block_source.join(child, child.c.workflow_run_id == spawning_block.c.block_workflow_run_id))
+ .where(block_link, child.c.organization_id == organization_id, child.c.workflow_run_id != workflow_run_id)
+ .correlate(descendants)
+ )
+ if self._dialect_name == "sqlite":
+ descendants = descendants.union(parent_children, block_children)
+ else:
+ # PostgreSQL permits one recursive reference; LATERAL keeps both indexed branches correlated to it.
+ children = parent_children.union_all(block_children).lateral("attempt_children")
+ descendants = descendants.union(
+ select(children.c.workflow_run_id, children.c.attempt_number).select_from(
+ descendants.join(children, true())
+ )
+ )
+
+ def relative_attempt(owner: Any, counter: Any) -> Any:
+ return case(
+ (owner == workflow_run_id, func.coalesce(counter, 1)),
+ else_=select(func.max(descendants.c.attempt_number))
+ .where(descendants.c.workflow_run_id == owner)
+ .correlate_except(descendants)
+ .scalar_subquery(),
+ )
+
+ task_attempt = (
+ select(relative_attempt(TaskModel.workflow_run_id, TaskModel.attempt_number))
+ .where(TaskModel.task_id == ArtifactModel.task_id)
+ .scalar_subquery()
+ )
+ step_attempt = (
+ select(relative_attempt(TaskModel.workflow_run_id, TaskModel.attempt_number))
+ .join(StepModel, StepModel.task_id == TaskModel.task_id)
+ .where(StepModel.step_id == ArtifactModel.step_id)
+ .scalar_subquery()
+ )
+ block_attempt = (
+ select(relative_attempt(WorkflowRunBlockModel.workflow_run_id, WorkflowRunBlockModel.attempt_number))
+ .where(WorkflowRunBlockModel.workflow_run_block_id == ArtifactModel.workflow_run_block_id)
+ .scalar_subquery()
+ )
+ attributed_attempt = case(
+ (ArtifactModel.task_id.isnot(None), task_attempt),
+ (ArtifactModel.step_id.isnot(None), step_attempt),
+ (ArtifactModel.workflow_run_block_id.isnot(None), block_attempt),
+ else_=None,
+ )
+ window = [attributed_attempt.is_(None)]
+ if started_at is not None:
+ window.append(ArtifactModel.created_at >= to_naive_utc(started_at))
+ if successor_started_at is not None:
+ window.append(ArtifactModel.created_at < to_naive_utc(successor_started_at))
+ async with self.Session() as session:
+ rows = (
+ await session.scalars(
+ select(ArtifactModel)
+ .where(
+ or_(ArtifactModel.run_id == artifact_run_id, ArtifactModel.workflow_run_id == artifact_run_id),
+ ArtifactModel.organization_id == organization_id,
+ ArtifactModel.artifact_type.in_(
+ [
+ ArtifactType.DOWNLOAD,
+ ArtifactType.RECORDING,
+ ArtifactType.SCREENSHOT_ACTION,
+ ArtifactType.SCREENSHOT_FINAL,
+ ]
+ ),
+ or_(attributed_attempt == attempt_number, and_(*window)),
+ )
+ .order_by(ArtifactModel.created_at)
+ )
+ ).all()
+ return [convert_to_artifact(row, self.debug_enabled) for row in rows]
+
@db_operation("get_workflow_run_block_errors")
async def get_workflow_run_block_errors(
self,
workflow_run_id: str,
organization_id: str | None = None,
+ attempt_number: int | None = None,
) -> list[tuple[str, list[str], str | None, Any, str]]:
"""Return block provenance and error details for errored blocks in stable creation order."""
async with self.Session() as session:
@@ -1978,6 +2596,12 @@ class WorkflowRunsRepository(BaseRepository):
).filter_by(workflow_run_id=workflow_run_id)
if organization_id is not None:
query = query.filter_by(organization_id=organization_id)
+ if attempt_number is not None:
+ attempt_filter = WorkflowRunBlockModel.attempt_number == attempt_number
+ if attempt_number == 1:
+ # Blocks written before attempt tracking carry no attempt number.
+ attempt_filter = or_(attempt_filter, WorkflowRunBlockModel.attempt_number.is_(None))
+ query = query.where(attempt_filter)
query = query.where(WorkflowRunBlockModel.error_codes.isnot(None))
query = query.order_by(WorkflowRunBlockModel.created_at, WorkflowRunBlockModel.workflow_run_block_id)
rows = (await session.execute(query)).all()
diff --git a/skyvern/forge/sdk/db/utils.py b/skyvern/forge/sdk/db/utils.py
index e719b6f88..376cc5dcd 100644
--- a/skyvern/forge/sdk/db/utils.py
+++ b/skyvern/forge/sdk/db/utils.py
@@ -377,6 +377,7 @@ def convert_to_task(task_obj: TaskModel, debug_enabled: bool = False, workflow_p
extra_http_headers=task_obj.extra_http_headers,
cdp_connect_headers=task_obj.cdp_connect_headers,
workflow_run_id=task_obj.workflow_run_id,
+ attempt_number=task_obj.attempt_number,
workflow_permanent_id=workflow_permanent_id,
order=task_obj.order,
retry=task_obj.retry,
@@ -886,6 +887,7 @@ def convert_to_workflow_run_block(
block = WorkflowRunBlock(
workflow_run_block_id=workflow_run_block_model.workflow_run_block_id,
workflow_run_id=workflow_run_block_model.workflow_run_id,
+ attempt_number=workflow_run_block_model.attempt_number,
block_workflow_run_id=workflow_run_block_model.block_workflow_run_id,
organization_id=workflow_run_block_model.organization_id,
parent_workflow_run_block_id=workflow_run_block_model.parent_workflow_run_block_id,
diff --git a/skyvern/forge/sdk/executor/async_executor.py b/skyvern/forge/sdk/executor/async_executor.py
index e012b8f62..e11775785 100644
--- a/skyvern/forge/sdk/executor/async_executor.py
+++ b/skyvern/forge/sdk/executor/async_executor.py
@@ -7,6 +7,14 @@ from skyvern.forge.sdk.schemas.organizations import Organization
class AsyncExecutor(abc.ABC):
+ async def recover_pending_retries(self) -> None:
+ """Recover retry decisions left pending by an executor process restart."""
+ return
+
+ async def stop_retry_recovery(self) -> None:
+ """Stop any periodic retry recovery started by recover_pending_retries."""
+ return
+
@abc.abstractmethod
async def execute_task(
self,
diff --git a/skyvern/forge/sdk/executor/background_task_executor.py b/skyvern/forge/sdk/executor/background_task_executor.py
index aa5e4b4fa..1cbee40d9 100644
--- a/skyvern/forge/sdk/executor/background_task_executor.py
+++ b/skyvern/forge/sdk/executor/background_task_executor.py
@@ -1,22 +1,43 @@
import asyncio
from collections.abc import Callable, Coroutine
from dataclasses import replace
+from datetime import timedelta
+from types import SimpleNamespace
from typing import Any
import structlog
from fastapi import BackgroundTasks, Request
-from skyvern.exceptions import BackgroundSequentialCredentialUnsupported, OrganizationNotFound
+from skyvern.config import settings
+from skyvern.exceptions import (
+ BackgroundSequentialCredentialUnsupported,
+ OrganizationNotFound,
+)
from skyvern.forge import app
from skyvern.forge.sdk.api.llm.custom_llm_registry import prepare_org_llm_runtime
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
+from skyvern.forge.sdk.db.datetime_utils import naive_utc_now, to_naive_utc
+from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType
+from skyvern.forge.sdk.db.repositories.workflow_run_attempts import (
+ ATTEMPT_RECOVERY_BATCH_SIZE,
+ ATTEMPT_RECOVERY_MAX_PAGES,
+)
from skyvern.forge.sdk.executor.async_executor import AsyncExecutor
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.schemas.persistent_browser_sessions import FORCED_WORKFLOW_SESSION_RUNNABLE_TYPE
from skyvern.forge.sdk.schemas.task_v2 import TaskV2Status
from skyvern.forge.sdk.schemas.tasks import TaskStatus
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
+from skyvern.forge.sdk.workflow.retry_policy import (
+ LEASE_TAKEOVER_SECONDS,
+ RetryDecision,
+ finalize_abandoned_attempt,
+ get_recorded_decision,
+ latest_attempt_awaiting_preparation,
+ prepare_next_attempt_result,
+ queue_initial_attempt,
+)
from skyvern.schemas.browser_session_close import BrowserSessionCloseReason
from skyvern.schemas.runs import RunEngine, RunType
from skyvern.services import script_service, task_v2_service
@@ -49,6 +70,569 @@ class BackgroundTaskExecutor(AsyncExecutor):
# Prevent GC of fire-and-forget asyncio tasks (e.g. when running without FastAPI BackgroundTasks).
_background_tasks: set[asyncio.Task] = set() # noqa: RUF012
+ def __init__(self) -> None:
+ self._retry_recovery_sweep_task: asyncio.Task | None = None
+ self._fresh_retries_recovered = False
+ self._retry_resume_tasks: set[asyncio.Task] = set()
+ 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]]] = {}
+
+ async def recover_pending_retries(self) -> None:
+ # The lifespan only logs a failed initial pass; the periodic sweep must start regardless.
+ try:
+ await self._recover_pending_retries_once(resume_fresh=True)
+ self._fresh_retries_recovered = True
+ finally:
+ self._start_retry_recovery_sweep()
+
+ async def stop_retry_recovery(self) -> None:
+ tasks = [
+ task
+ for task in (self._retry_recovery_sweep_task, *self._retry_resume_tasks)
+ if task is not None and not task.done()
+ ]
+ if not tasks:
+ return
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+
+ def _start_retry_recovery_sweep(self) -> None:
+ if self._retry_recovery_sweep_task is not None and not self._retry_recovery_sweep_task.done():
+ return
+ task = asyncio.create_task(self._retry_recovery_sweep())
+ self._retry_recovery_sweep_task = task
+ self._background_tasks.add(task)
+
+ def clear_sweep(completed_task: asyncio.Task) -> None:
+ self._background_tasks.discard(completed_task)
+ if self._retry_recovery_sweep_task is completed_task:
+ self._retry_recovery_sweep_task = None
+
+ task.add_done_callback(clear_sweep)
+
+ async def _retry_recovery_sweep(self) -> None:
+ while True:
+ await asyncio.sleep(LEASE_TAKEOVER_SECONDS)
+ try:
+ # Fresh rows found at startup stay unowned until one pass resumes them; later passes leave
+ # fresh rows to their in-process owners.
+ await self._recover_pending_retries_once(resume_fresh=not self._fresh_retries_recovered)
+ self._fresh_retries_recovered = True
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ LOG.exception("Retry recovery sweep failed")
+
+ async def _recover_pending_retries_once(self, *, resume_fresh: bool) -> None:
+ # Retry failed local entries immediately; process-loss recovery waits for the dispatch grace.
+ for attempt, _execution_kwargs in list(self._retry_dispatches_needing_recovery.values()):
+ self._schedule_retry_resume(attempt)
+
+ await self._recover_stale_dispatch_claims()
+
+ async def process_attempt(attempt: Any, _release_only: bool) -> None:
+ if attempt.retry_decision == "retry":
+ next_attempt_at = getattr(attempt, "next_attempt_at", None)
+ if next_attempt_at is None:
+ return
+ next_attempt_at = to_naive_utc(next_attempt_at)
+ if next_attempt_at is None:
+ return
+ key = (attempt.workflow_run_id, attempt.attempt_number)
+ if key in self._scheduled_retry_resumes:
+ return
+ if key in self._retry_resumes_needing_recovery:
+ self._schedule_retry_resume(attempt)
+ return
+ cutoff = naive_utc_now() - timedelta(seconds=LEASE_TAKEOVER_SECONDS)
+ if next_attempt_at < cutoff:
+ await self._abandon_stale_retry(attempt)
+ elif resume_fresh:
+ self._schedule_retry_resume(attempt)
+ elif attempt.retry_decision is None and attempt.started_at is not None:
+ recovered = await app.WORKFLOW_SERVICE.recover_undecided_terminal_attempt(attempt)
+ if recovered is not None:
+ self._schedule_retry_resume(recovered)
+ elif (
+ attempt.retry_decision is None
+ and (terminal_run := await app.WORKFLOW_SERVICE.terminal_workflow_run(attempt)) is not None
+ ):
+ recovered = await app.WORKFLOW_SERVICE.recover_undecided_terminal_attempt(
+ attempt, workflow_run=terminal_run
+ )
+ if recovered is not None:
+ self._schedule_retry_resume(recovered)
+ elif (
+ attempt.retry_decision is None
+ and attempt.status == WorkflowRunStatus.queued.value
+ and attempt.started_at is None
+ ):
+ modified_at = to_naive_utc(attempt.modified_at)
+ if modified_at is not None and modified_at < naive_utc_now() - timedelta(
+ seconds=LEASE_TAKEOVER_SECONDS
+ ):
+ self._schedule_retry_resume(attempt)
+ elif attempt.retry_decision in {"final", "revoked", "abandoned"}:
+ self._retry_resumes_needing_recovery.discard((attempt.workflow_run_id, attempt.attempt_number))
+ await self._release_unreleased_terminal_effects(attempt)
+
+ await app.WORKFLOW_SERVICE.recover_pending_workflow_attempts(process_attempt=process_attempt)
+
+ async def _recover_stale_dispatch_claims(self) -> None:
+ grace_seconds = max(600, LEASE_TAKEOVER_SECONDS, settings.RETRY_DISPATCH_GRACE_SECONDS)
+ stale_before = naive_utc_now() - timedelta(seconds=grace_seconds)
+ cursor: tuple[str, int] | None = None
+ for _page_number in range(ATTEMPT_RECOVERY_MAX_PAGES):
+ attempts = await app.DATABASE.workflow_run_attempts.list_stale_dispatch_claims(stale_before, cursor=cursor)
+ if not attempts:
+ break
+ for attempt in attempts:
+ # A resumer for the previous attempt can already be dispatching this run's next attempt.
+ if any(run_id == attempt.workflow_run_id for run_id, _number in self._scheduled_retry_resumes):
+ continue
+ try:
+ released = await app.DATABASE.workflow_run_attempts.release_stale_dispatch_claim(
+ attempt.workflow_run_id,
+ attempt.organization_id,
+ attempt.attempt_number,
+ stale_before=stale_before,
+ )
+ if not released:
+ continue
+ attempt.started_at = None
+ attempt.status = WorkflowRunStatus.queued.value
+ self._schedule_retry_resume(attempt)
+ except Exception:
+ LOG.exception(
+ "Failed to recover stale workflow retry dispatch claim",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ last_attempt = attempts[-1]
+ cursor = (last_attempt.workflow_run_id, last_attempt.attempt_number)
+ if len(attempts) < ATTEMPT_RECOVERY_BATCH_SIZE:
+ break
+ else:
+ LOG.warning("Stale workflow retry dispatch recovery reached its page limit")
+
+ async def _abandon_stale_retry(self, attempt: Any) -> None:
+ await self._abandon_retry(attempt, reason="process_restart")
+
+ async def _abandon_retry(self, attempt: Any, *, reason: str) -> None:
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ )
+ if workflow_run is None:
+ LOG.warning(
+ "Cannot recover stale retry because its workflow run is missing",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ return
+
+ if reason == "process_restart":
+ execution_status = await app.AGENT_FUNCTION.get_workflow_run_execution_status(workflow_run)
+ if execution_status not in {"absent", "terminal"}:
+ return
+ is_final = workflow_run.status.is_final()
+ decision = await finalize_abandoned_attempt(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ reason=reason,
+ status=workflow_run.status if is_final else None,
+ failure_reason=workflow_run.failure_reason if is_final else None,
+ finished_at=workflow_run.finished_at if is_final else None,
+ attempt_number=attempt.attempt_number,
+ )
+ if decision.retry:
+ LOG.info(
+ "Skipped abandoning stale retry because its terminal side-effect lease is still young",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ return
+ await self._run_terminal_side_effects(workflow_run, decision)
+
+ async def _release_unreleased_terminal_effects(self, attempt: Any) -> None:
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ )
+ if workflow_run is None:
+ LOG.warning(
+ "Cannot recover terminal effects because its workflow run is missing",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ return
+
+ decision = RetryDecision(
+ retry=False,
+ attempt_number=attempt.attempt_number,
+ delay_seconds=0,
+ send_webhook_now=True,
+ decision_reason=attempt.decision_reason,
+ )
+ await self._run_terminal_side_effects(
+ workflow_run,
+ decision,
+ side_effects_claim_at=getattr(attempt, "side_effects_released_at", None),
+ )
+
+ async def _run_terminal_side_effects(
+ self,
+ workflow_run: Any,
+ decision: RetryDecision,
+ *,
+ side_effects_claim_at: Any = None,
+ ) -> None:
+ try:
+ api_key = await self._get_valid_api_key(workflow_run.organization_id)
+ except Exception:
+ LOG.exception(
+ "Failed to load organization API token for terminal recovery",
+ organization_id=workflow_run.organization_id,
+ )
+ api_key = None
+ kwargs: dict[str, Any] = {"api_key": api_key} if api_key is not None else {}
+ if side_effects_claim_at is not None:
+ kwargs["side_effects_claim_at"] = side_effects_claim_at
+ run_with_retries = app.WORKFLOW_SERVICE._run_terminal_side_effects_with_retries
+ await run_with_retries(workflow_run, decision, **kwargs)
+
+ async def _release_pending_interim_effects(self, attempt: Any, workflow_run: Any, api_key: str) -> bool:
+ """Complete a failed interim release before its durable retry attempt is prepared."""
+ if not hasattr(attempt, "interim_webhook_sent_at") or attempt.interim_webhook_sent_at is not None:
+ return True
+
+ decision = await get_recorded_decision(
+ attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ if decision is None or not decision.retry:
+ LOG.warning(
+ "Cannot recover interim workflow webhook without a retry decision",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ return False
+
+ outcome = await app.WORKFLOW_SERVICE._run_interim_side_effects_with_retries(
+ workflow_run,
+ decision,
+ api_key=api_key,
+ side_effects_claim_at=getattr(attempt, "side_effects_released_at", None),
+ )
+ if outcome not in {"released", "already_released"}:
+ LOG.warning(
+ "Interim workflow webhook release did not complete; leaving retry unprepared",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ outcome=outcome,
+ )
+ return False
+
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(attempt.workflow_run_id)
+ current_attempt = next((row for row in attempts if row.attempt_number == attempt.attempt_number), None)
+ if current_attempt is None or getattr(current_attempt, "interim_webhook_sent_at", None) is None:
+ LOG.warning(
+ "Interim workflow webhook release returned without its completion marker; leaving retry unprepared",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ return False
+ return True
+
+ async def _get_valid_api_key(self, organization_id: str) -> str | None:
+ organizations = getattr(app.DATABASE, "organizations", None)
+ get_valid_org_auth_token = getattr(organizations, "get_valid_org_auth_token", None)
+ if get_valid_org_auth_token is None:
+ return None
+ org_auth_token = await get_valid_org_auth_token(
+ organization_id=organization_id,
+ token_type=OrganizationAuthTokenType.api.value,
+ )
+ return org_auth_token.token if org_auth_token else None
+
+ async def _initialize_retry_resume(self, attempt: Any, *, prepared: bool) -> tuple[Organization, str] | None:
+ deadline = naive_utc_now() + timedelta(seconds=LEASE_TAKEOVER_SECONDS)
+ backoff_seconds = 1.0
+ previous_missing: str | None = None
+ while True:
+ missing: str | None = None
+ try:
+ organization = await app.DATABASE.organizations.get_organization(attempt.organization_id)
+ if organization is None:
+ missing = "organization"
+ else:
+ api_key = await self._get_valid_api_key(attempt.organization_id)
+ if api_key is None:
+ missing = "API token"
+ else:
+ # Initialization stays ahead of the dispatch claim so a transient failure here
+ # leaves a prepared attempt for the next sweep instead of consuming the retry.
+ await initialize_skyvern_state_file(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ )
+ await prepare_org_llm_runtime(app.DATABASE, attempt.organization_id, organization)
+ return organization, api_key
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ LOG.exception(
+ "Failed to initialize workflow retry recovery; will retry",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ if missing is not None and missing == previous_missing:
+ LOG.warning(
+ "Cannot resume retry because organization or API token is missing after confirmation",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ missing=missing,
+ )
+ if prepared:
+ claimed = await app.DATABASE.workflow_run_attempts.fail_prepared_workflow_run(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ attempt_number=attempt.attempt_number,
+ failure_reason=f"Workflow retry cannot resume because its {missing} is unavailable.",
+ )
+ if claimed:
+ await self._abandon_retry(
+ attempt, reason="missing_organization" if missing == "organization" else "missing_api_token"
+ )
+ return None
+ previous_missing = missing
+ remaining_seconds = (deadline - naive_utc_now()).total_seconds()
+ if remaining_seconds <= 0:
+ self._retry_resumes_needing_recovery.add((attempt.workflow_run_id, attempt.attempt_number))
+ LOG.warning(
+ "Workflow retry initialization timed out; leaving recovery to the next sweep",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ return None
+ await asyncio.sleep(min(backoff_seconds, remaining_seconds))
+ backoff_seconds = min(backoff_seconds * 2, 30.0)
+
+ def _schedule_retry_resume(self, attempt: Any) -> None:
+ key = (attempt.workflow_run_id, attempt.attempt_number)
+ if key in self._scheduled_retry_resumes:
+ return
+ self._scheduled_retry_resumes.add(key)
+ try:
+ task = self._schedule(None, self._resume_pending_retry, attempt)
+ except Exception:
+ self._scheduled_retry_resumes.discard(key)
+ raise
+ if task is not None:
+ self._retry_resume_tasks.add(task)
+ task.add_done_callback(self._retry_resume_tasks.discard)
+
+ async def _resume_pending_retry(self, attempt: Any) -> None:
+ key = (attempt.workflow_run_id, attempt.attempt_number)
+ claimed_prepared_execution = False
+ execution_dispatched = False
+ self._retry_resumes_needing_recovery.discard(key)
+ try:
+ pending_dispatch = self._retry_dispatches_needing_recovery.get(key)
+ if pending_dispatch is not None:
+ execution_dispatched = True
+ await self._dispatch_retry_resume(pending_dispatch[0], pending_dispatch[1])
+ return
+ prepared = getattr(attempt, "retry_decision", "retry") is None
+ if not prepared:
+ next_attempt_at = to_naive_utc(attempt.next_attempt_at)
+ if next_attempt_at is None:
+ return
+ delay_seconds = (next_attempt_at - naive_utc_now()).total_seconds()
+ if delay_seconds > 0:
+ await asyncio.sleep(delay_seconds)
+ if prepared:
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ )
+ if (
+ workflow_run is None
+ or workflow_run.status != WorkflowRunStatus.queued
+ or workflow_run.started_at is not None
+ ):
+ return
+ execution_status = await app.AGENT_FUNCTION.get_workflow_run_execution_status(workflow_run)
+ if execution_status not in {"absent", "terminal"}:
+ return
+
+ if getattr(attempt, "decision_reason", None) == "unrecoverable_block_outputs":
+ if prepared:
+ claimed = await app.DATABASE.workflow_run_attempts.fail_prepared_workflow_run(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ attempt_number=attempt.attempt_number,
+ failure_reason="Workflow retry inputs cannot be restored after a process restart.",
+ )
+ if not claimed:
+ return
+ await self._abandon_retry(attempt, reason="unrecoverable_block_outputs")
+ return
+ initialization = await self._initialize_retry_resume(attempt, prepared=prepared)
+ if initialization is None:
+ return
+ organization, api_key = initialization
+
+ if not prepared and hasattr(attempt, "interim_webhook_sent_at") and attempt.interim_webhook_sent_at is None:
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ )
+ if workflow_run is None:
+ LOG.warning(
+ "Cannot recover interim workflow webhook because its workflow run is missing",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ return
+ if not await self._release_pending_interim_effects(attempt, workflow_run, api_key):
+ return
+
+ if prepared:
+ claim_stamp = await app.DATABASE.workflow_run_attempts.claim_prepared_attempt_execution(
+ attempt.workflow_run_id, attempt.organization_id, attempt.attempt_number
+ )
+ if not claim_stamp:
+ return
+ attempt.started_at = claim_stamp
+ claimed_prepared_execution = True
+
+ if prepared:
+ pinned_browser_session_id = attempt.pinned_browser_session_id
+ attempt_number = attempt.attempt_number
+ else:
+ preparation = await prepare_next_attempt_result(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ from_attempt=attempt.attempt_number,
+ clear_browser_address=False,
+ )
+ if preparation.status == "already_prepared":
+ return
+ if preparation.status == "failed":
+ await self._abandon_retry(attempt, reason="prepare_cas_failed")
+ return
+ pinned_browser_session_id = preparation.pinned_browser_session_id
+ attempt_number = attempt.attempt_number + 1
+
+ execution_kwargs: dict[str, Any] = {
+ "workflow_run_id": attempt.workflow_run_id,
+ "api_key": api_key,
+ "organization": organization,
+ "browser_session_id": pinned_browser_session_id,
+ "block_labels": None,
+ "block_outputs": None,
+ "need_call_webhook": True,
+ "attempt_number": attempt_number,
+ }
+ if prepared:
+ execution_kwargs["prepared_attempt_claimed"] = True
+ execution_kwargs["dispatch_claim_started_at"] = attempt.started_at
+ execution_dispatched = True
+ await self._dispatch_retry_resume(attempt, execution_kwargs)
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ LOG.exception(
+ "Failed to resume pending workflow retry",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ if claimed_prepared_execution and not execution_dispatched:
+ if not await self._retry_dispatch_claim_is_current(attempt):
+ return
+ failed_run = await app.WORKFLOW_SERVICE.mark_workflow_run_as_failed_if_not_final(
+ workflow_run_id=attempt.workflow_run_id,
+ failure_reason="Workflow retry recovery could not initialize execution.",
+ )
+ if failed_run is not None:
+ await self._abandon_retry(attempt, reason="retry_resume_failed")
+ elif not execution_dispatched:
+ self._retry_resumes_needing_recovery.add(key)
+ finally:
+ self._scheduled_retry_resumes.discard(key)
+
+ async def _retry_dispatch_claim_is_current(self, attempt: Any) -> bool:
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(attempt.workflow_run_id)
+ current = next((row for row in attempts if row.attempt_number == attempt.attempt_number), None)
+ if (
+ current is not None
+ and current.started_at is not None
+ and to_naive_utc(current.started_at) == to_naive_utc(attempt.started_at)
+ and current.retry_decision is None
+ ):
+ return True
+ LOG.warning(
+ "Workflow retry dispatch claim was replaced; abandoning obsolete dispatch",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ return False
+
+ async def _dispatch_retry_resume(self, attempt: Any, execution_kwargs: dict[str, Any]) -> None:
+ key = (attempt.workflow_run_id, attempt.attempt_number)
+ self._retry_dispatches_needing_recovery.pop(key, None)
+ execution_started = False
+
+ def on_execution_start() -> None:
+ nonlocal execution_started
+ execution_started = True
+
+ try:
+ if execution_kwargs.get("prepared_attempt_claimed") and not await self._retry_dispatch_claim_is_current(
+ attempt
+ ):
+ self._retry_resumes_needing_recovery.discard(key)
+ return
+ # Initialization belongs to the dispatch: a failure here is re-dispatched by the sweep, whereas a
+ # created attempt that never reached the dispatch matches no recovery predicate.
+ await initialize_skyvern_state_file(
+ workflow_run_id=attempt.workflow_run_id, organization_id=attempt.organization_id
+ )
+ await prepare_org_llm_runtime(app.DATABASE, attempt.organization_id, execution_kwargs.get("organization"))
+ await app.WORKFLOW_SERVICE.execute_workflow_with_retries(
+ **execution_kwargs, on_execution_start=on_execution_start
+ )
+ except Exception:
+ if execution_started:
+ # The attempt ran, so a durable retry decision can already exist; the sweep resumes it.
+ pending_key = await self._pending_retry_key(attempt.workflow_run_id, fallback=key)
+ if pending_key is not None:
+ self._retry_resumes_needing_recovery.add(pending_key)
+ raise
+ self._retry_dispatches_needing_recovery[key] = (attempt, execution_kwargs)
+ self._retry_resumes_needing_recovery.add(key)
+ LOG.exception(
+ "Workflow retry entry failed before execution; leaving recovery to the next sweep",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=execution_kwargs["attempt_number"],
+ )
+
+ async def _pending_retry_key(self, workflow_run_id: str, *, fallback: tuple[str, int]) -> tuple[str, int] | None:
+ try:
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ except Exception:
+ LOG.warning(
+ "Failed to read workflow attempts after a retry owner failure; leaving recovery to the next sweep",
+ workflow_run_id=workflow_run_id,
+ exc_info=True,
+ )
+ return fallback
+ latest = latest_attempt_awaiting_preparation(attempts)
+ return None if latest is None else (workflow_run_id, latest.attempt_number)
+
def _schedule(
self,
background_tasks: BackgroundTasks | None,
@@ -56,13 +640,14 @@ class BackgroundTaskExecutor(AsyncExecutor):
/,
*args: Any,
**kwargs: Any,
- ) -> None:
+ ) -> asyncio.Task | None:
if background_tasks:
background_tasks.add_task(func, *args, **kwargs)
- return
+ return None
task = asyncio.create_task(_run_with_own_context(func, *args, **kwargs))
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
+ return task
async def execute_task(
self,
@@ -153,6 +738,22 @@ class BackgroundTaskExecutor(AsyncExecutor):
workflow_run_id,
organization_id=organization.organization_id,
)
+ try:
+ attempt_rows = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ except 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.
+ LOG.warning(
+ "Failed to load workflow retry attempts; scheduling as an attempt-one run",
+ workflow_run_id=workflow_run_id,
+ exc_info=True,
+ )
+ attempt_rows = []
+ attempt_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
+ # below makes the dispatch recoverable, or a restart would run the whole workflow instead.
+ await app.DATABASE.workflow_run_attempts.mark_attempt_inputs_unrecoverable(workflow_run_id, attempt_number)
if workflow_run and workflow_run.sequential_credential_id:
if workflow_run.browser_session_id:
persistent_browser_session = await app.DATABASE.browser_sessions.get_persistent_browser_session(
@@ -184,23 +785,51 @@ class BackgroundTaskExecutor(AsyncExecutor):
),
cascade_children=True,
)
+ if attempt_rows:
+ 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:
+ decision = await finalize_abandoned_attempt(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization.organization_id,
+ reason="sequential_credential_unsupported",
+ status=terminal_run.status,
+ failure_reason=terminal_run.failure_reason,
+ finished_at=terminal_run.finished_at,
+ )
+ await app.WORKFLOW_SERVICE._run_terminal_side_effects_with_retries(
+ terminal_run,
+ decision,
+ api_key=api_key,
+ )
raise BackgroundSequentialCredentialUnsupported(workflow_run_id)
- await initialize_skyvern_state_file(
- workflow_run_id=workflow_run_id, organization_id=organization.organization_id
- )
- await prepare_org_llm_runtime(app.DATABASE, organization.organization_id, organization)
-
- self._schedule(
- background_tasks,
- app.WORKFLOW_SERVICE.execute_workflow,
- workflow_run_id=workflow_run_id,
- api_key=api_key,
- organization=organization,
- browser_session_id=browser_session_id,
- block_labels=block_labels,
- block_outputs=block_outputs,
+ attempt = next(
+ (row for row in attempt_rows if row.attempt_number == attempt_number),
+ SimpleNamespace(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization.organization_id,
+ attempt_number=attempt_number,
+ ),
)
+ # A dispatch lost with the process is recovered by the prepared-attempt sweep, which admits only a
+ # queued run and attempt. The write re-reads the run, so it runs even when the lookups failed.
+ if not await queue_initial_attempt(workflow_run_id, attempt_number):
+ return
+ execution_kwargs: dict[str, Any] = {
+ "workflow_run_id": workflow_run_id,
+ "api_key": api_key,
+ "organization": organization,
+ "browser_session_id": browser_session_id,
+ "block_labels": block_labels,
+ "block_outputs": block_outputs,
+ "need_call_webhook": True,
+ "attempt_number": attempt_number,
+ "claim_initial_attempt": True,
+ }
+ self._schedule(background_tasks, self._dispatch_retry_resume, attempt, execution_kwargs)
async def execute_task_v2(
self,
diff --git a/skyvern/forge/sdk/forge_log.py b/skyvern/forge/sdk/forge_log.py
index db6f4b092..59bcafa4a 100644
--- a/skyvern/forge/sdk/forge_log.py
+++ b/skyvern/forge/sdk/forge_log.py
@@ -667,6 +667,10 @@ def skyvern_logs_processor(logger: logging.Logger, method_name: str, event_dict:
context = skyvern_context.current()
if context:
log_entry = dict(event_dict)
+ if workflow_run_id := log_entry.get("workflow_run_id"):
+ attempt_number = skyvern_context.current_workflow_log_attempt(workflow_run_id)
+ if attempt_number is not None:
+ log_entry["workflow_run_attempt_number"] = attempt_number
context.log.append(log_entry)
return event_dict
diff --git a/skyvern/forge/sdk/log_artifacts.py b/skyvern/forge/sdk/log_artifacts.py
index 536f8c719..371f138fe 100644
--- a/skyvern/forge/sdk/log_artifacts.py
+++ b/skyvern/forge/sdk/log_artifacts.py
@@ -5,12 +5,24 @@ import structlog
from skyvern.config import settings
from skyvern.forge import app
from skyvern.forge.sdk.artifact.models import ArtifactType, LogEntityType
+from skyvern.forge.sdk.artifact.storage.base import resolve_current_attempt
from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.db.id import generate_artifact_id
from skyvern.forge.skyvern_json_encoder import SkyvernJSONLogEncoder
from skyvern.forge.skyvern_log_encoder import SkyvernLogEncoder
LOG = structlog.get_logger()
+workflow_log_attempt = skyvern_context.workflow_log_attempt
+
+
+def current_workflow_log_attempt(workflow_run_id: str) -> int | None:
+ attempt_number = skyvern_context.current_workflow_log_attempt(workflow_run_id)
+ if attempt_number is not None:
+ return attempt_number
+ workflow_context = app.WORKFLOW_CONTEXT_MANAGER.workflow_run_contexts.get(workflow_run_id)
+ return workflow_context.attempt_number if workflow_context is not None else None
+
def primary_key_from_log_entity_type(log_entity_type: LogEntityType) -> str:
if log_entity_type == LogEntityType.STEP:
@@ -100,6 +112,7 @@ async def save_workflow_run_logs(workflow_run_id: str) -> None:
organization_id = context.organization_id
current_workflow_run_log = [entry for entry in log if entry.get("workflow_run_id", "") == workflow_run_id]
+ attempt_number = current_workflow_log_attempt(workflow_run_id)
await _save_log_artifacts(
log=current_workflow_run_log,
@@ -107,6 +120,7 @@ async def save_workflow_run_logs(workflow_run_id: str) -> None:
log_entity_id=workflow_run_id,
organization_id=organization_id,
workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
)
@@ -147,6 +161,7 @@ async def _save_log_artifacts(
task_id: str | None = None,
workflow_run_id: str | None = None,
workflow_run_block_id: str | None = None,
+ attempt_number: int | None = None,
) -> None:
try:
if not settings.ENABLE_LOG_ARTIFACTS:
@@ -158,8 +173,28 @@ async def _save_log_artifacts(
log_entity_id=log_entity_id,
)
return
- log_json = json.dumps(log, cls=SkyvernJSONLogEncoder, indent=2)
+ if workflow_run_id and log_entity_type == LogEntityType.WORKFLOW_RUN:
+ attempt_number, _ = await resolve_current_attempt(workflow_run_id, attempt_number=attempt_number)
+ log = [
+ entry
+ for entry in log
+ if entry.get("workflow_run_attempt_number") is None
+ or entry["workflow_run_attempt_number"] == attempt_number
+ ]
+ log_json = json.dumps(log, cls=SkyvernJSONLogEncoder, indent=2)
+ await _save_workflow_log_artifact(
+ workflow_run_id, organization_id, attempt_number, ArtifactType.SKYVERN_LOG_RAW, log_json.encode()
+ )
+ await _save_workflow_log_artifact(
+ workflow_run_id,
+ organization_id,
+ attempt_number,
+ ArtifactType.SKYVERN_LOG,
+ SkyvernLogEncoder.encode(log).encode(),
+ )
+ return
+ log_json = json.dumps(log, cls=SkyvernJSONLogEncoder, indent=2)
log_artifact = await app.DATABASE.artifacts.get_artifact_by_entity_id(
artifact_type=ArtifactType.SKYVERN_LOG_RAW,
step_id=step_id,
@@ -231,3 +266,38 @@ async def _save_log_artifacts(
workflow_run_block_id=workflow_run_block_id,
exc_info=True,
)
+
+
+async def _save_workflow_log_artifact(
+ workflow_run_id: str, organization_id: str, attempt_number: int, artifact_type: ArtifactType, data: bytes
+) -> None:
+ log_entity_id = workflow_run_id if attempt_number == 1 else f"{workflow_run_id}/attempts/{attempt_number}"
+ log_directory = f"/logs/{LogEntityType.WORKFLOW_RUN}/{log_entity_id}"
+ artifacts = await app.DATABASE.artifacts.get_artifacts_by_entity_id(
+ artifact_type=artifact_type, workflow_run_id=workflow_run_id, organization_id=organization_id
+ )
+ artifact = next(
+ (artifact for artifact in artifacts if artifact.uri.rsplit("/", 1)[0].endswith(log_directory)),
+ None,
+ )
+ if artifact is not None:
+ await app.ARTIFACT_MANAGER.update_artifact_data(
+ artifact_id=artifact.artifact_id, organization_id=organization_id, data=data, primary_key="workflow_run_id"
+ )
+ return
+ uri = app.STORAGE.build_log_uri(
+ organization_id=organization_id,
+ log_entity_type=LogEntityType.WORKFLOW_RUN,
+ log_entity_id=log_entity_id,
+ artifact_type=artifact_type,
+ )
+ # Keep upload tracking keyed by the run ID so finalization still waits for these writes.
+ await app.ARTIFACT_MANAGER._create_artifact(
+ aio_task_primary_key=workflow_run_id,
+ artifact_id=generate_artifact_id(),
+ artifact_type=artifact_type,
+ uri=uri,
+ organization_id=organization_id,
+ workflow_run_id=workflow_run_id,
+ data=data,
+ )
diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.py
index 57e6ddead..a655fb105 100644
--- a/skyvern/forge/sdk/routes/agent_protocol.py
+++ b/skyvern/forge/sdk/routes/agent_protocol.py
@@ -4,7 +4,7 @@ import random
import time
import unicodedata
from collections.abc import Sequence
-from datetime import datetime
+from datetime import UTC, datetime
from enum import Enum
from typing import Annotated, Any
from urllib.parse import parse_qs, quote, urlparse
@@ -60,6 +60,7 @@ from skyvern.forge.sdk.artifact.signing import (
parse_keyring,
verify_artifact_signature,
)
+from skyvern.forge.sdk.artifact.storage.base import artifact_filename_from_uri
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.curl_converter import curl_to_http_request_block_params
from skyvern.forge.sdk.core.permissions.permission_checker_factory import PermissionCheckerFactory
@@ -150,6 +151,7 @@ from skyvern.forge.sdk.workflow.models.workflow import (
WorkflowRunStatus,
WorkflowRunWithWorkflowResponse,
)
+from skyvern.forge.sdk.workflow.retry_policy import is_retry_pending
from skyvern.forge.sdk.workflow.service import capped_task_v1_response, capped_task_v2
from skyvern.schemas.artifacts import EntityType, entity_type_to_param
from skyvern.schemas.folders import Folder, FolderCreate, FolderUpdate, UpdateWorkflowFolderRequest
@@ -3103,15 +3105,6 @@ def _build_attachment_disposition(filename: str) -> str:
return f"attachment; filename=\"{ascii_part}\"; filename*=UTF-8''{encoded}"
-def _artifact_filename_from_uri(uri: str | None) -> str:
- """Extract the basename from an ``s3://``/``azure://`` URI without using
- ``urlparse`` — that would split on ``?``/``#`` characters, which are legal
- in S3 keys."""
- if not uri:
- return ""
- return uri.rsplit("/", 1)[-1]
-
-
def _artifact_response_config(artifact: Artifact) -> tuple[str, str]:
"""Return (media_type, Content-Disposition) for the artifact content response.
@@ -3119,7 +3112,7 @@ def _artifact_response_config(artifact: Artifact) -> tuple[str, str]:
so browsers never render user-supplied content inline (SKY-8862). All other
types keep the historical ``inline`` behaviour.
"""
- raw_name = _artifact_filename_from_uri(artifact.uri)
+ raw_name = artifact_filename_from_uri(artifact.uri)
if artifact.artifact_type in {ArtifactType.RECORDING, ArtifactType.SESSION_REPLAY}:
_, dot, extension = raw_name.lower().rpartition(".")
media_type = _VIDEO_CONTENT_TYPES_BY_EXTENSION.get(
@@ -3825,25 +3818,12 @@ async def _cancel_workflow_run(workflow_run_id: str, organization_id: str, x_api
expected_runnable_id=workflow_run.workflow_run_id,
)
- # get all the child workflow runs and cancel them
- child_workflow_runs = await app.DATABASE.workflow_runs.get_workflow_runs_by_parent_workflow_run_id(
- parent_workflow_run_id=workflow_run_id,
+ await run_service.cancel_workflow_run(
+ workflow_run_id,
organization_id=organization_id,
+ api_key=x_api_key,
)
- for child_workflow_run in child_workflow_runs:
- if child_workflow_run.status not in [
- WorkflowRunStatus.running,
- WorkflowRunStatus.created,
- WorkflowRunStatus.queued,
- WorkflowRunStatus.paused,
- ]:
- continue
- await app.WORKFLOW_SERVICE.mark_workflow_run_as_canceled(child_workflow_run.workflow_run_id)
-
- await app.WORKFLOW_SERVICE.mark_workflow_run_as_canceled(workflow_run_id)
- await app.WORKFLOW_SERVICE.execute_workflow_webhook(workflow_run, api_key=x_api_key)
-
async def _continue_workflow_run(workflow_run_id: str, organization_id: str) -> None:
workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
@@ -4248,6 +4228,7 @@ async def get_runs(
runs = await app.DATABASE.workflow_runs.get_all_runs(
current_org.organization_id, page=page, page_size=page_size, status=status, search_key=search_key
)
+ await app.WORKFLOW_SERVICE._attach_latest_attempt_views([run for run in runs if isinstance(run, WorkflowRun)])
return ORJSONResponse([run.model_dump() for run in runs])
@@ -4411,7 +4392,28 @@ async def get_runs_v2(
failure_category=failure_category,
)
items = [TaskRunListItem.model_validate(row) for row in rows]
- return ORJSONResponse([item.model_dump(mode="json") for item in items])
+ workflow_run_ids = [row["run_id"] for row in rows if row["task_run_type"] == RunType.workflow_run.value]
+ latest_attempts = await app.DATABASE.workflow_run_attempts.get_latest_attempts_for_runs(workflow_run_ids)
+ response_items = []
+ for row, item in zip(rows, items, strict=True):
+ response_item = item.model_dump(mode="json")
+ response_item.update({"attempt": 1, "retry_pending": False, "next_attempt_at": None})
+ latest_attempt = latest_attempts.get(row["run_id"])
+ if latest_attempt is not None:
+ retry_pending = is_retry_pending(
+ RunStatus(row["status"]),
+ row["workflow_run_finished_at"],
+ latest_attempt,
+ )
+ response_item.update(
+ {
+ "attempt": latest_attempt.attempt_number,
+ "retry_pending": retry_pending,
+ "next_attempt_at": latest_attempt.next_attempt_at if retry_pending else None,
+ }
+ )
+ response_items.append(response_item)
+ return ORJSONResponse(response_items)
@legacy_base_router.get(
@@ -5930,7 +5932,7 @@ async def _flatten_workflow_run_timeline_recursive(
TaskV2 blocks are replaced with their internal workflow run blocks.
Other blocks (like ForLoop) are kept with their children recursively processed.
"""
- result = []
+ result: list[WorkflowRunTimeline] = []
# Check if this is a TaskV2 block that needs to be flattened
if timeline.block and timeline.block.block_type == BlockType.TaskV2:
@@ -5941,7 +5943,16 @@ async def _flatten_workflow_run_timeline_recursive(
workflow_run_id=timeline.block.block_workflow_run_id,
cap_output_values=cap_output_values,
)
- result.extend(nested_timeline)
+
+ def inherit_attempt(item: WorkflowRunTimeline) -> WorkflowRunTimeline:
+ return item.model_copy(
+ update={
+ "attempt": timeline.attempt,
+ "children": [inherit_attempt(child) for child in item.children],
+ }
+ )
+
+ result.extend(inherit_attempt(item) for item in nested_timeline)
else:
LOG.warning(
"Block workflow run id is not set for task_v2 block",
@@ -5964,6 +5975,7 @@ async def _flatten_workflow_run_timeline_recursive(
# Create a new timeline with processed children
processed_timeline = WorkflowRunTimeline(
type=timeline.type,
+ attempt=timeline.attempt,
block=timeline.block,
thought=timeline.thought,
children=new_children,
@@ -6007,12 +6019,54 @@ async def _flatten_workflow_run_timeline(
)
final_workflow_run_block_timeline.extend(flattened)
+ def as_utc(value: datetime) -> datetime:
+ if value.tzinfo is None:
+ return value.replace(tzinfo=UTC)
+ return value.astimezone(UTC)
+
if task_v2_obj and task_v2_obj.observer_cruise_id:
thought_timeline = await task_v2_service.get_thought_timelines(
task_v2_id=task_v2_obj.observer_cruise_id,
organization_id=organization_id,
cap_output_values=cap_output_values,
)
+ attempt_rows = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ block_attempts: dict[str, int] = {}
+
+ def collect_block_attempts(items: list[WorkflowRunTimeline]) -> None:
+ for item in items:
+ if item.block is not None:
+ block_attempts[item.block.workflow_run_block_id] = item.attempt
+ collect_block_attempts(item.children)
+
+ collect_block_attempts(final_workflow_run_block_timeline)
+ started_attempts = sorted(
+ (row for row in attempt_rows if row.started_at is not None),
+ key=lambda row: as_utc(row.started_at) if row.started_at is not None else datetime.min.replace(tzinfo=UTC),
+ )
+
+ def thought_attempt(thought: Any) -> int:
+ if thought.workflow_run_block_id in block_attempts:
+ return block_attempts[thought.workflow_run_block_id]
+ thought_time = as_utc(thought.created_at)
+ for index, attempt_row in enumerate(started_attempts):
+ started_at = attempt_row.started_at
+ if started_at is None:
+ continue
+ started_at = as_utc(started_at)
+ next_started_at = started_attempts[index + 1].started_at if index + 1 < len(started_attempts) else None
+ if next_started_at is not None:
+ next_started_at = as_utc(next_started_at)
+ if thought_time >= started_at and (next_started_at is None or thought_time < next_started_at):
+ return attempt_row.attempt_number
+ return 1
+
+ thought_timeline = [
+ timeline.model_copy(update={"attempt": thought_attempt(timeline.thought)})
+ if timeline.thought is not None
+ else timeline
+ for timeline in thought_timeline
+ ]
final_workflow_run_block_timeline.extend(thought_timeline)
- final_workflow_run_block_timeline.sort(key=lambda x: x.created_at, reverse=True)
+ final_workflow_run_block_timeline.sort(key=lambda x: as_utc(x.created_at), reverse=True)
return final_workflow_run_block_timeline
diff --git a/skyvern/forge/sdk/routes/sdk.py b/skyvern/forge/sdk/routes/sdk.py
index d83ccecc9..8e9a0ab28 100644
--- a/skyvern/forge/sdk/routes/sdk.py
+++ b/skyvern/forge/sdk/routes/sdk.py
@@ -38,6 +38,14 @@ LOG = structlog.get_logger()
_sdk_action_context_refcounts: dict[str, int] = {}
+async def _resolve_sdk_action_attempt_number(workflow_run_id: str) -> int:
+ """A run live in this process knows its attempt; one owned elsewhere needs the durable rows."""
+ if app.WORKFLOW_CONTEXT_MANAGER.has_workflow_run_context(workflow_run_id):
+ return app.WORKFLOW_CONTEXT_MANAGER.get_attempt_number(workflow_run_id)
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ return max((row.attempt_number for row in attempts), default=1)
+
+
def _acquire_sdk_action_context(workflow_run_id: str) -> None:
_sdk_action_context_refcounts[workflow_run_id] = _sdk_action_context_refcounts.get(workflow_run_id, 0) + 1
@@ -131,6 +139,7 @@ async def _run_sdk_action(
)
task_type = TaskType.synthetic_sdk_action
+ attempt_number = await _resolve_sdk_action_attempt_number(workflow_run.workflow_run_id)
task = await app.DATABASE.tasks.create_task(
organization_id=organization_id,
url=action_request.url,
@@ -142,6 +151,7 @@ async def _run_sdk_action(
browser_session_id=browser_session_id,
browser_address=browser_address,
task_type=task_type,
+ attempt_number=attempt_number,
)
if created_workflow_run:
@@ -161,6 +171,7 @@ async def _run_sdk_action(
organization_id=organization_id,
block_type=BlockType.ACTION,
task_id=task.task_id,
+ attempt_number=attempt_number,
)
_acquire_sdk_action_context(workflow_run.workflow_run_id)
@@ -183,6 +194,7 @@ async def _run_sdk_action(
None,
workflow,
mask_secrets=getattr(workflow, "mask_secrets", False),
+ attempt_number=attempt_number,
)
context = skyvern_context.ensure_context()
diff --git a/skyvern/forge/sdk/schemas/tasks.py b/skyvern/forge/sdk/schemas/tasks.py
index 81765da77..4a9a53925 100644
--- a/skyvern/forge/sdk/schemas/tasks.py
+++ b/skyvern/forge/sdk/schemas/tasks.py
@@ -333,6 +333,7 @@ class Task(TaskBase):
)
organization_id: str
workflow_run_id: str | None = None
+ attempt_number: int | None = None
workflow_permanent_id: str | None = None
browser_session_id: str | None = None
order: int | None = None
diff --git a/skyvern/forge/sdk/schemas/workflow_runs.py b/skyvern/forge/sdk/schemas/workflow_runs.py
index 0e153c5c8..319679a48 100644
--- a/skyvern/forge/sdk/schemas/workflow_runs.py
+++ b/skyvern/forge/sdk/schemas/workflow_runs.py
@@ -16,6 +16,7 @@ class WorkflowRunBlock(BaseModel):
workflow_run_block_id: str
block_workflow_run_id: str | None = None
workflow_run_id: str
+ attempt_number: int | None = None
organization_id: str
description: str | None = None
parent_workflow_run_block_id: str | None = None
@@ -87,6 +88,7 @@ class WorkflowRunTimelineType(StrEnum):
class WorkflowRunTimeline(BaseModel):
type: WorkflowRunTimelineType
+ attempt: int = 1
block: WorkflowRunBlock | None = None
thought: Thought | None = None
children: list[WorkflowRunTimeline] = []
diff --git a/skyvern/forge/sdk/submission/shadow.py b/skyvern/forge/sdk/submission/shadow.py
index c6eec1563..e752f7182 100644
--- a/skyvern/forge/sdk/submission/shadow.py
+++ b/skyvern/forge/sdk/submission/shadow.py
@@ -108,6 +108,11 @@ async def _load_context(
else:
assert workflow_run is not None
tasks = await app.DATABASE.tasks.get_tasks_by_workflow_run_id(workflow_run_id=workflow_run.workflow_run_id)
+ current_attempt = next(
+ (item.attempt_number or 1 for item in tasks if item.task_id == last_step.task_id),
+ max((item.attempt_number or 1 for item in tasks), default=1),
+ )
+ tasks = [item for item in tasks if (item.attempt_number or 1) == current_attempt]
organization_id = workflow_run.organization_id
workflow_run_id = workflow_run.workflow_run_id
run_status = str(workflow_run.status)
diff --git a/skyvern/forge/sdk/workflow/constants.py b/skyvern/forge/sdk/workflow/constants.py
index ef6ec51ee..e3d3f80cb 100644
--- a/skyvern/forge/sdk/workflow/constants.py
+++ b/skyvern/forge/sdk/workflow/constants.py
@@ -6,3 +6,6 @@ creating a cycle.
# Safety-net cap on serialized JSON size for a single jsonb-column value (SKY-9779).
OUTPUT_PARAMETER_MAX_VALUE_BYTES = 100 * 1024 * 1024
+
+# Historical delivery gets 1% of the per-value storage guard across all output values.
+INTERIM_OUTPUT_SNAPSHOT_MAX_BYTES = 1024 * 1024
diff --git a/skyvern/forge/sdk/workflow/context_manager.py b/skyvern/forge/sdk/workflow/context_manager.py
index 0e5490d0c..04a813295 100644
--- a/skyvern/forge/sdk/workflow/context_manager.py
+++ b/skyvern/forge/sdk/workflow/context_manager.py
@@ -128,6 +128,8 @@ def resolve_credential_parameter_binding(
class WorkflowRunContext:
+ attempt_number: int = 1
+
@classmethod
async def init(
cls,
@@ -153,6 +155,7 @@ class WorkflowRunContext:
workflow: "Workflow | None" = None,
inherited_workflow_system_prompt: str | None = None,
mask_secrets: bool = False,
+ attempt_number: int = 1,
) -> Self:
# key is label name
workflow_run_context = cls(
@@ -164,6 +167,7 @@ class WorkflowRunContext:
workflow=workflow,
inherited_workflow_system_prompt=inherited_workflow_system_prompt,
mask_secrets=mask_secrets,
+ attempt_number=attempt_number,
)
workflow_run_context.organization_id = organization.organization_id
@@ -259,11 +263,13 @@ class WorkflowRunContext:
workflow: "Workflow | None" = None,
inherited_workflow_system_prompt: str | None = None,
mask_secrets: bool = False,
+ attempt_number: int = 1,
) -> None:
self.workflow_title = workflow_title
self.workflow_id = workflow_id
self.workflow_permanent_id = workflow_permanent_id
self.workflow_run_id = workflow_run_id
+ self.attempt_number = attempt_number
self.workflow = workflow
self.mask_secrets: bool = mask_secrets
# Joined raw workflow_system_prompt(s) from ancestor workflows (outermost
@@ -1031,8 +1037,11 @@ class WorkflowRunContext:
cached = self.resolved_credential_parameter_ids.get(parameter.key)
if cached:
return cached
- selected_credential_id = None
- if parameter.credential_ids:
+ selected_credential_id = await app.DATABASE.workflow_run_credential_selections.get_selection(
+ workflow_run_id=self.workflow_run_id,
+ parameter_key=parameter.key,
+ )
+ if selected_credential_id is None and parameter.credential_ids:
selected_credential_id = await select_credential_for_run(
workflow_run_id=self.workflow_run_id,
organization_id=organization_id,
@@ -1041,11 +1050,6 @@ class WorkflowRunContext:
credential_ids=parameter.credential_ids,
selection_strategy=parameter.selection_strategy,
)
- elif parameter.fallback_credential_ids:
- selected_credential_id = await app.DATABASE.workflow_run_credential_selections.get_selection(
- workflow_run_id=self.workflow_run_id,
- parameter_key=parameter.key,
- )
registered_parameter_values = {
key: self.resolved_credential_parameter_ids.get(key, self.values[key])
for key in self.parameters
@@ -2024,6 +2028,7 @@ class WorkflowContextManager:
workflow: "Workflow | None" = None,
inherited_workflow_system_prompt: str | None = None,
mask_secrets: bool = False,
+ attempt_number: int = 1,
) -> WorkflowRunContext:
workflow_run_context = await WorkflowRunContext.init(
self.aws_client,
@@ -2040,6 +2045,7 @@ class WorkflowContextManager:
workflow,
inherited_workflow_system_prompt=inherited_workflow_system_prompt,
mask_secrets=mask_secrets,
+ attempt_number=attempt_number,
)
self.workflow_run_contexts[workflow_run_id] = workflow_run_context
return workflow_run_context
@@ -2048,6 +2054,10 @@ class WorkflowContextManager:
self._validate_workflow_run_context(workflow_run_id)
return self.workflow_run_contexts[workflow_run_id]
+ def get_attempt_number(self, workflow_run_id: str) -> int:
+ context = self.workflow_run_contexts.get(workflow_run_id)
+ return context.attempt_number if context is not None else 1
+
def remove_workflow_run_context(self, workflow_run_id: str) -> None:
self.workflow_run_contexts.pop(workflow_run_id, None)
diff --git a/skyvern/forge/sdk/workflow/credential_selection.py b/skyvern/forge/sdk/workflow/credential_selection.py
index 5e8da3366..dbef09817 100644
--- a/skyvern/forge/sdk/workflow/credential_selection.py
+++ b/skyvern/forge/sdk/workflow/credential_selection.py
@@ -1,11 +1,25 @@
from __future__ import annotations
import random
+from collections import Counter
+from typing import TYPE_CHECKING
import structlog
+from sqlalchemy import select, update
from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import AsyncSession
from skyvern.forge import app
+from skyvern.forge.sdk.db.enums import BrowserSeedSource
+from skyvern.forge.sdk.db.models import (
+ CredentialModel,
+ WorkflowRunCredentialSelectionModel,
+ WorkflowRunModel,
+)
+from skyvern.forge.sdk.workflow.models.parameter import CredentialParameter
+
+if TYPE_CHECKING:
+ from skyvern.forge.sdk.workflow.models.workflow import WorkflowDefinition
LOG = structlog.get_logger()
@@ -68,3 +82,151 @@ async def select_credential_for_run(
strategy=strategy,
)
return selected
+
+
+async def clear_credential_selections_for_retry(
+ workflow_run_id: str,
+ organization_id: str,
+ attempt_number: int,
+ *,
+ workflow_definition: WorkflowDefinition | None,
+ session: AsyncSession | None = None,
+ browser_address_replaced: bool = False,
+) -> None:
+ if attempt_number < 2 or workflow_definition is None:
+ return
+ if session is None:
+ async with app.DATABASE.Session() as owned_session:
+ await clear_credential_selections_for_retry(
+ workflow_run_id,
+ organization_id,
+ attempt_number,
+ workflow_definition=workflow_definition,
+ session=owned_session,
+ browser_address_replaced=browser_address_replaced,
+ )
+ await owned_session.commit()
+ return
+ selections = (
+ await session.scalars(
+ select(WorkflowRunCredentialSelectionModel).where(
+ WorkflowRunCredentialSelectionModel.workflow_run_id == workflow_run_id,
+ WorkflowRunCredentialSelectionModel.organization_id == organization_id,
+ )
+ )
+ ).all()
+ if not selections:
+ return
+ workflow_run = await session.scalar(
+ select(WorkflowRunModel).where(
+ WorkflowRunModel.workflow_run_id == workflow_run_id,
+ WorkflowRunModel.organization_id == organization_id,
+ )
+ )
+ if workflow_run is None:
+ return
+ # Atomic retry preparation has already restored the next attempt's session. Its cookies must
+ # stay paired with the current credentials.
+ if workflow_run.browser_session_id:
+ LOG.info(
+ "Skipped retry credential rotation because the browser session is retained",
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ attempt_number=attempt_number,
+ browser_session_id=workflow_run.browser_session_id,
+ )
+ return
+ if workflow_run.browser_address and not browser_address_replaced:
+ LOG.info(
+ "Skipped retry credential rotation because browser_address is retained",
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ attempt_number=attempt_number,
+ )
+ return
+ parameter_key_counts = Counter(parameter.key for parameter in workflow_definition.parameters)
+ pools = {
+ parameter.key: parameter
+ for parameter in workflow_definition.parameters
+ if isinstance(parameter, CredentialParameter)
+ and parameter.credential_ids
+ and parameter_key_counts[parameter.key] == 1
+ }
+ candidate_ids = {selection.credential_id for selection in selections}
+ for selection in selections:
+ if parameter := pools.get(selection.parameter_key):
+ candidate_ids.update({parameter.credential_id, *(parameter.credential_ids or [])})
+ parallel_credential_ids = set(
+ (
+ await session.scalars(
+ select(CredentialModel.credential_id).where(
+ CredentialModel.organization_id == organization_id,
+ CredentialModel.credential_id.in_(candidate_ids),
+ CredentialModel.run_sequentially.is_(False),
+ CredentialModel.deleted_at.is_(None),
+ )
+ )
+ ).all()
+ )
+ # Only Temporal can admit a sequential credential. Rotate only verified parallel pools from
+ # the execution definition; credential side tables can be stale after an in-place edit.
+ rotating_selections = [
+ selection
+ for selection in selections
+ if selection.credential_id != workflow_run.sequential_credential_id
+ and selection.parameter_key in pools
+ and {
+ selection.credential_id,
+ pools[selection.parameter_key].credential_id,
+ *(pools[selection.parameter_key].credential_ids or []),
+ }
+ <= parallel_credential_ids
+ ]
+ if not rotating_selections:
+ return
+ # This column has no run FK: an attempt-qualified key frees the current binding's unique slot,
+ # while the unchanged parameter key and timestamp keep the row visible to LRU history queries.
+ credential_changed = False
+ for selection in sorted(rotating_selections, key=lambda selection: selection.parameter_key):
+ await session.execute(
+ update(WorkflowRunCredentialSelectionModel)
+ .where(WorkflowRunCredentialSelectionModel.selection_id == selection.selection_id)
+ .values(workflow_run_id=f"{workflow_run_id}:attempt:{attempt_number - 1}")
+ )
+ parameter = pools[selection.parameter_key]
+ credential_ids = parameter.credential_ids or []
+ if normalize_selection_strategy(parameter.selection_strategy) == RANDOM:
+ candidates = [credential_id for credential_id in credential_ids if credential_id != selection.credential_id]
+ selected_credential_id = random.choice(candidates or credential_ids)
+ session.add(
+ WorkflowRunCredentialSelectionModel(
+ organization_id=organization_id,
+ workflow_run_id=workflow_run_id,
+ workflow_permanent_id=selection.workflow_permanent_id,
+ parameter_key=selection.parameter_key,
+ credential_id=selected_credential_id,
+ )
+ )
+ else:
+ selected_credential_id = (
+ await app.DATABASE.workflow_run_credential_selections._create_round_robin_selection(
+ session,
+ organization_id=organization_id,
+ workflow_run_id=workflow_run_id,
+ workflow_permanent_id=selection.workflow_permanent_id,
+ parameter_key=selection.parameter_key,
+ credential_ids=credential_ids,
+ )
+ )
+ credential_changed = credential_changed or selected_credential_id != selection.credential_id
+ if credential_changed:
+ # Own memory is also segmented by the selected credentials, including its write-back sink.
+ await session.execute(
+ update(WorkflowRunModel)
+ .where(
+ WorkflowRunModel.workflow_run_id == workflow_run_id,
+ WorkflowRunModel.organization_id == organization_id,
+ WorkflowRunModel.browser_seed_source.in_([BrowserSeedSource.credential, BrowserSeedSource.own_memory]),
+ )
+ .values(browser_profile_id=None, browser_seed_source=None, browser_sink_profile_id=None)
+ )
diff --git a/skyvern/forge/sdk/workflow/loop_download_filter.py b/skyvern/forge/sdk/workflow/loop_download_filter.py
index dfcea0e23..fe7f12e7c 100644
--- a/skyvern/forge/sdk/workflow/loop_download_filter.py
+++ b/skyvern/forge/sdk/workflow/loop_download_filter.py
@@ -1,5 +1,6 @@
import urllib.parse
from collections import Counter
+from collections.abc import Callable, Iterable
from typing import Any, TypeAlias
from skyvern.forge.sdk.schemas.files import FileInfo
@@ -31,6 +32,8 @@ def to_downloaded_file_signature(file_info: FileInfo) -> DownloadedFileSignature
def filter_downloaded_files_for_current_iteration(
downloaded_files: list[FileInfo],
loop_internal_state: dict[str, Any] | None,
+ *,
+ aliases: Callable[[FileInfo], Iterable[DownloadedFileSignature]] | None = None,
) -> list[FileInfo]:
"""Filters downloaded files excluding previous iteration matches"""
if not loop_internal_state:
@@ -55,7 +58,15 @@ def filter_downloaded_files_for_current_iteration(
if previous_file_counter[signature] > 0:
previous_file_counter[signature] -= 1
continue
- current_iteration_files.append(file_info)
+ if aliases is not None:
+ for alias in aliases(file_info):
+ if previous_file_counter[alias] > 0:
+ previous_file_counter[alias] -= 1
+ break
+ else:
+ current_iteration_files.append(file_info)
+ else:
+ current_iteration_files.append(file_info)
return current_iteration_files
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 990b01f23..ecca50a9f 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -143,6 +143,7 @@ from skyvern.forge.sdk.api.llm.exceptions import (
)
from skyvern.forge.sdk.api.llm.schema_validator import validate_schema
from skyvern.forge.sdk.artifact.models import ArtifactType
+from skyvern.forge.sdk.artifact.storage.base import get_download_retry_started_at, is_file_from_retry_attempt
from skyvern.forge.sdk.copilot.block_goal_wrapping import compose_mini_goal
from skyvern.forge.sdk.copilot.code_block_security import INERT_SLOT_NAME
from skyvern.forge.sdk.copilot.reached_download_target import (
@@ -374,7 +375,7 @@ async def capture_block_download_baseline(
"""
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
- baseline_files = await app.STORAGE.get_downloaded_files(
+ baseline_files = await app.STORAGE.get_current_attempt_downloaded_files(
organization_id=organization_id,
run_id=resolve_run_download_id(context, fallback_run_id=workflow_run_id),
)
@@ -472,6 +473,27 @@ def local_download_dir_file_identities(download_run_id: str | None) -> set[tuple
return None
+def current_attempt_local_download_dir_file_identities(
+ download_run_id: str | None,
+ attempt_started_at: datetime | None,
+ *,
+ baseline: set[tuple[str, int, int]] | None = None,
+) -> set[tuple[str, int, int]] | None:
+ identities = local_download_dir_file_identities(download_run_id)
+ if identities is None:
+ return None
+ if attempt_started_at is None:
+ return identities
+ baseline_names = {identity[0] for identity in baseline or set()}
+ # An old mtime requires a changed entry in the raw baseline, not merely a newly appearing name.
+ return {
+ identity
+ for identity in identities
+ if identity[2] / 1_000_000_000 >= attempt_started_at.timestamp()
+ or (baseline is not None and identity[0] in baseline_names and identity not in baseline)
+ }
+
+
def download_binding_of(browser_state: BrowserState | None) -> DownloadBinding:
return browser_state.browser_artifacts.download_binding if browser_state else DownloadBinding.RUN_DIR
@@ -615,7 +637,9 @@ class ParquetExportMixin:
return []
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
- return await app.STORAGE.get_downloaded_files(organization_id=organization_id, run_id=run_download_id)
+ return await app.STORAGE.get_current_attempt_downloaded_files(
+ organization_id=organization_id, run_id=run_download_id
+ )
except Exception:
LOG.warning(
"Failed to read registered Parquet exports",
@@ -1581,6 +1605,7 @@ class Block(BaseModel, abc.ABC):
workflow_run_block = await app.DATABASE.observer.create_workflow_run_block(
workflow_run_id=workflow_run_id,
organization_id=organization_id,
+ attempt_number=app.WORKFLOW_CONTEXT_MANAGER.get_attempt_number(workflow_run_id),
parent_workflow_run_block_id=parent_workflow_run_block_id,
label=self.label,
block_type=self.block_type,
@@ -1916,12 +1941,19 @@ class BaseTaskBlock(Block):
self._apply_workflow_system_prompt(workflow_run_context)
@staticmethod
- async def get_task_order(workflow_run_id: str, current_retry: int) -> tuple[int, int]:
+ async def get_task_order(
+ workflow_run_id: str,
+ current_retry: int,
+ attempt_number: int | None = None,
+ ) -> tuple[int, int]:
"""
Returns the order and retry for the next task in the workflow run as a tuple.
"""
+ if attempt_number is None:
+ attempt_number = app.WORKFLOW_CONTEXT_MANAGER.get_attempt_number(workflow_run_id)
last_task_for_workflow_run = await app.DATABASE.tasks.get_last_task_for_workflow_run(
- workflow_run_id=workflow_run_id
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
)
# If there is no previous task, the order will be 0 and the retry will be 0.
if last_task_for_workflow_run is None:
@@ -2390,7 +2422,7 @@ class BaseTaskBlock(Block):
downloaded_files: list[FileInfo] = []
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
- downloaded_files = await app.STORAGE.get_downloaded_files(
+ downloaded_files = await app.STORAGE.get_current_attempt_downloaded_files(
organization_id=workflow_run.organization_id,
run_id=current_context.run_id
if current_context and current_context.run_id
@@ -2403,6 +2435,7 @@ class BaseTaskBlock(Block):
downloaded_files = filter_downloaded_files_for_current_iteration(
downloaded_files,
current_context.loop_internal_state if current_context else None,
+ aliases=app.STORAGE.get_downloaded_file_signature_aliases,
)
task_screenshot_artifacts = await app.WORKFLOW_SERVICE.get_recent_task_screenshot_artifacts(
@@ -2491,7 +2524,7 @@ class BaseTaskBlock(Block):
downloaded_files = []
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
- downloaded_files = await app.STORAGE.get_downloaded_files(
+ downloaded_files = await app.STORAGE.get_current_attempt_downloaded_files(
organization_id=workflow_run.organization_id,
run_id=current_context.run_id
if current_context and current_context.run_id
@@ -2505,6 +2538,7 @@ class BaseTaskBlock(Block):
downloaded_files = filter_downloaded_files_for_current_iteration(
downloaded_files,
current_context.loop_internal_state if current_context else None,
+ aliases=app.STORAGE.get_downloaded_file_signature_aliases,
)
task_screenshot_artifacts = await app.WORKFLOW_SERVICE.get_recent_task_screenshot_artifacts(
@@ -3405,7 +3439,7 @@ class ForLoopBlock(Block):
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
downloaded_file_sigs_before = [
to_downloaded_file_signature(fi)
- for fi in await app.STORAGE.get_downloaded_files(
+ for fi in await app.STORAGE.get_current_attempt_downloaded_files(
organization_id=organization_id or "",
run_id=resolve_run_download_id(loop_context, fallback_run_id=workflow_run_id),
)
@@ -4140,7 +4174,7 @@ class WhileLoopBlock(Block):
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
downloaded_file_sigs_before = [
to_downloaded_file_signature(fi)
- for fi in await app.STORAGE.get_downloaded_files(
+ for fi in await app.STORAGE.get_current_attempt_downloaded_files(
organization_id=organization_id or "",
run_id=resolve_run_download_id(loop_context, fallback_run_id=workflow_run_id),
)
@@ -6215,7 +6249,7 @@ async def wrapper({default_args}):
return None
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
- files = await app.STORAGE.get_downloaded_files(
+ files = await app.STORAGE.get_current_attempt_downloaded_files(
organization_id=organization_id,
run_id=download_run_id or workflow_run_id,
)
@@ -6248,6 +6282,7 @@ async def wrapper({default_args}):
workflow_run_block_id: str,
organization_id: str | None,
skipped_file_names: set[str],
+ attempt_started_at: datetime | None = None,
authored_registration: bool = False,
) -> tuple[Any, str | None]:
"""Bind registration evidence into the block output, returning a failure reason if it cannot.
@@ -6286,6 +6321,7 @@ async def wrapper({default_args}):
downloaded_files = filter_downloaded_files_for_current_iteration(
downloaded_files,
current_context.loop_internal_state if current_context else None,
+ aliases=app.STORAGE.get_downloaded_file_signature_aliases,
)
output = bind_downloaded_files_to_output(result, downloaded_files)
await self._record_unregistered_download_intent(
@@ -6315,7 +6351,11 @@ async def wrapper({default_args}):
if downloaded_files:
_log_verdict_skipped_for_partial_save()
return output, None
- download_dir_after = local_download_dir_file_identities(resolved_download_id)
+ download_dir_after = current_attempt_local_download_dir_file_identities(
+ resolved_download_id,
+ attempt_started_at,
+ baseline=download_dir_before,
+ )
if download_dir_after is None or download_dir_before is None:
LOG.warning(
"codeblock.download_binding_verdict_skipped",
@@ -6808,6 +6848,7 @@ async def wrapper({default_args}):
navigation_payload=None,
organization_id=organization_id,
workflow_run_id=workflow_run_id,
+ attempt_number=workflow_run_context.attempt_number,
order=task_order,
retry=task_retry,
max_steps_per_run=heal_max_steps,
@@ -6836,6 +6877,7 @@ async def wrapper({default_args}):
parent_workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
task_id=escalation_task.task_id,
+ attempt_number=workflow_run_context.attempt_number,
label="Self-heal recovery",
block_type=BlockType.TASK,
)
@@ -6881,7 +6923,7 @@ async def wrapper({default_args}):
downloaded_files: list[FileInfo] = []
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
- downloaded_files = await app.STORAGE.get_downloaded_files(
+ downloaded_files = await app.STORAGE.get_current_attempt_downloaded_files(
organization_id=organization_id,
run_id=current_context.run_id if current_context.run_id else workflow_run_id,
)
@@ -6890,6 +6932,7 @@ async def wrapper({default_args}):
downloaded_files = filter_downloaded_files_for_current_iteration(
downloaded_files,
current_context.loop_internal_state,
+ aliases=app.STORAGE.get_downloaded_file_signature_aliases,
)
task_output = TaskOutput.from_task(updated_task, downloaded_files)
output_parameter_value = workflow_run_context.mask_secrets_in_data(task_output.model_dump())
@@ -7274,6 +7317,7 @@ async def wrapper({default_args}):
resolved_download_id: str | None,
download_dir_before: set[tuple[str, int, int]] | None,
session_bound: bool,
+ attempt_started_at: datetime | None,
download_binding_kind: str | None = None,
result: dict[str, Any] | list | str | None = None,
) -> dict[str, Any] | None:
@@ -7289,7 +7333,11 @@ async def wrapper({default_args}):
skipped_file_names: set[str] = set()
needs_registration = session_bound
if not session_bound:
- download_dir_after = local_download_dir_file_identities(resolved_download_id)
+ download_dir_after = current_attempt_local_download_dir_file_identities(
+ resolved_download_id,
+ attempt_started_at,
+ baseline=download_dir_before,
+ )
if download_dir_after is None or download_dir_before is None:
return None
new_files = download_dir_after - download_dir_before
@@ -7325,6 +7373,7 @@ async def wrapper({default_args}):
downloaded_files=downloaded_files,
skipped_file_names=skipped_file_names,
download_dir_before=download_dir_before,
+ attempt_started_at=attempt_started_at,
resolved_download_id=resolved_download_id,
workflow_run_context=workflow_run_context,
workflow_run_id=workflow_run_id,
@@ -7427,6 +7476,7 @@ async def wrapper({default_args}):
engine: str,
resolved_download_id: str | None,
download_dir_before: set[tuple[str, int, int]] | None,
+ attempt_started_at: datetime | None,
output_parameter_value: dict[str, Any] | list | str | None = None,
error_codes: list[str] | None = None,
) -> BlockResult:
@@ -7442,6 +7492,7 @@ async def wrapper({default_args}):
organization_id=organization_id,
resolved_download_id=resolved_download_id,
download_dir_before=download_dir_before,
+ attempt_started_at=attempt_started_at,
session_bound=session_download_lane_active(browser_state),
download_binding_kind=download_binding_of(browser_state).value,
result=output_parameter_value,
@@ -7485,6 +7536,7 @@ async def wrapper({default_args}):
page: Page | None = None,
resolved_download_id: str | None = None,
download_dir_before: set[tuple[str, int, int]] | None = None,
+ attempt_started_at: datetime | None = None,
redaction_parameters: dict[str, Any] | None = None,
) -> BlockResult:
resolved_redaction_parameters = redaction_parameters or {}
@@ -7545,6 +7597,7 @@ async def wrapper({default_args}):
downloaded_files=downloaded_files,
skipped_file_names=skipped_file_names,
download_dir_before=download_dir_before,
+ attempt_started_at=attempt_started_at,
resolved_download_id=resolved_download_id,
workflow_run_context=workflow_run_context,
workflow_run_id=workflow_run_id,
@@ -7591,6 +7644,7 @@ async def wrapper({default_args}):
organization_id=organization_id,
resolved_download_id=resolved_download_id,
download_dir_before=download_dir_before,
+ attempt_started_at=attempt_started_at,
session_bound=session_download_lane_active(browser_state),
download_binding_kind=download_binding_of(browser_state).value,
result=result.output_parameter_value,
@@ -8035,6 +8089,9 @@ async def wrapper({default_args}):
)
resolved_download_id = resolve_run_download_id(block_context, fallback_run_id=workflow_run_id)
+ attempt_started_at = await get_download_retry_started_at(
+ organization_id or workflow_run_context.organization_id, resolved_download_id
+ )
download_dir_before = local_download_dir_file_identities(resolved_download_id)
browser_state = await self.get_or_create_browser_state(
workflow_run_id=workflow_run_id,
@@ -8402,6 +8459,7 @@ async def wrapper({default_args}):
page=page,
resolved_download_id=resolved_download_id,
download_dir_before=download_dir_before,
+ attempt_started_at=attempt_started_at,
redaction_parameters=serialized_parameter_values,
)
if secure_code_block_result.block_result is None:
@@ -8424,6 +8482,7 @@ async def wrapper({default_args}):
engine="secure_runner",
resolved_download_id=resolved_download_id,
download_dir_before=download_dir_before,
+ attempt_started_at=attempt_started_at,
)
# failure=None does not imply success: infra arms (no browser/page, runner raise,
# invalid output) return a failed block_result with no healable failure metadata.
@@ -8458,7 +8517,11 @@ async def wrapper({default_args}):
download_run_id=resolved_download_id,
)
secure_skipped_file_names: set[str] = set()
- secure_dir_after = local_download_dir_file_identities(resolved_download_id)
+ secure_dir_after = current_attempt_local_download_dir_file_identities(
+ resolved_download_id,
+ attempt_started_at,
+ baseline=download_dir_before,
+ )
secure_registered_names = {file_info.filename for file_info in host_files or []}
# An unreadable snapshot is unknown, never empty: coverage cannot be proven,
# so the save runs rather than being skipped on a coerced empty diff. A
@@ -8497,6 +8560,7 @@ async def wrapper({default_args}):
downloaded_files=host_files,
skipped_file_names=secure_skipped_file_names,
download_dir_before=download_dir_before,
+ attempt_started_at=attempt_started_at,
resolved_download_id=resolved_download_id,
workflow_run_context=workflow_run_context,
workflow_run_id=workflow_run_id,
@@ -8628,6 +8692,7 @@ async def wrapper({default_args}):
engine="inline",
resolved_download_id=resolved_download_id,
download_dir_before=download_dir_before,
+ attempt_started_at=attempt_started_at,
)
except asyncio.TimeoutError:
await recorder.persist(recorder.recorded_actions())
@@ -8648,6 +8713,7 @@ async def wrapper({default_args}):
engine="inline",
resolved_download_id=resolved_download_id,
download_dir_before=download_dir_before,
+ attempt_started_at=attempt_started_at,
)
except Exception as e:
# Exact type, not isinstance: the IllegitCompleteScriptTermination subclass means the
@@ -8667,6 +8733,7 @@ async def wrapper({default_args}):
engine="inline",
resolved_download_id=resolved_download_id,
download_dir_before=download_dir_before,
+ attempt_started_at=attempt_started_at,
)
failing_line = user_code_line_from_exception(e)
declared_error = self._extract_declared_error(e, workflow_run_context)
@@ -8689,6 +8756,7 @@ async def wrapper({default_args}):
organization_id=organization_id,
resolved_download_id=resolved_download_id,
download_dir_before=download_dir_before,
+ attempt_started_at=attempt_started_at,
session_bound=session_download_lane_active(browser_state),
download_binding_kind=download_binding_of(browser_state).value,
result=failure_output,
@@ -8720,6 +8788,7 @@ async def wrapper({default_args}):
page=page,
resolved_download_id=resolved_download_id,
download_dir_before=download_dir_before,
+ attempt_started_at=attempt_started_at,
redaction_parameters=serialized_parameter_values,
)
if (
@@ -8819,6 +8888,7 @@ async def wrapper({default_args}):
organization_id=organization_id,
resolved_download_id=resolved_download_id,
download_dir_before=download_dir_before,
+ attempt_started_at=attempt_started_at,
session_bound=session_download_lane_active(browser_state),
download_binding_kind=download_binding_of(browser_state).value,
result=failure_output,
@@ -8856,6 +8926,7 @@ async def wrapper({default_args}):
page=page,
resolved_download_id=resolved_download_id,
download_dir_before=download_dir_before,
+ attempt_started_at=attempt_started_at,
redaction_parameters=serialized_parameter_values,
)
@@ -8889,6 +8960,7 @@ async def wrapper({default_args}):
downloaded_files=downloaded_files,
skipped_file_names=skipped_file_names,
download_dir_before=download_dir_before,
+ attempt_started_at=attempt_started_at,
resolved_download_id=resolved_download_id,
workflow_run_context=workflow_run_context,
workflow_run_id=workflow_run_id,
@@ -9847,7 +9919,16 @@ class UploadToS3Block(Block):
client = self.get_async_aws_client()
# is the file path a file or a directory?
if os.path.isdir(resolved_path):
- files = os.listdir(resolved_path)
+ attempt_started_at = await get_download_retry_started_at(
+ organization_id or workflow_run_context.organization_id,
+ resolve_run_download_id(context, fallback_run_id=workflow_run_id),
+ )
+ files = [
+ name
+ for name in os.listdir(resolved_path)
+ if attempt_started_at is None
+ or is_file_from_retry_attempt(os.path.join(resolved_path, name), attempt_started_at)
+ ]
if len(files) > MAX_UPLOAD_FILE_COUNT:
raise ValueError("Too many files in the directory, not uploading")
for file in files:
@@ -10508,10 +10589,16 @@ class FileDestinationBlock(Block):
*,
download_files_path: str,
max_file_count: int,
+ attempt_started_at: datetime | None = None,
) -> list[str]:
files_to_upload = []
if os.path.isdir(download_files_path):
- files = os.listdir(download_files_path)
+ files = [
+ name
+ for name in os.listdir(download_files_path)
+ if attempt_started_at is None
+ or is_file_from_retry_attempt(os.path.join(download_files_path, name), attempt_started_at)
+ ]
if len(files) > max_file_count:
raise ValueError(f"Too many files in the directory, not uploading. Max: {max_file_count}")
for file in files:
@@ -10648,6 +10735,7 @@ class FileDestinationBlock(Block):
run_download_id: str | None,
download_files_path: str,
max_file_count: int,
+ attempt_started_at: datetime | None = None,
) -> tuple[list[str] | None, str]:
"""Return alternate local files plus a failure-reason count label.
@@ -10665,6 +10753,7 @@ class FileDestinationBlock(Block):
alternate_files = self._get_files_to_upload_from_download_dir(
download_files_path=candidate_download_files_path,
max_file_count=max_file_count,
+ attempt_started_at=attempt_started_at,
)
except ValueError:
LOG.warning(
@@ -10741,7 +10830,7 @@ class FileDestinationBlock(Block):
run_download_id: str | None,
context: SkyvernContext | None,
) -> list[FileInfo] | None:
- """Return registered downloads, or None when the signal is unknown.
+ """Return registered downloads from the current attempt, or None when the signal is unknown.
A timeout on any candidate stays unknown even if later candidates might be empty; an empty later lookup cannot
prove that the timed-out candidate had no downloads, so the caller fails closed.
@@ -10763,7 +10852,7 @@ class FileDestinationBlock(Block):
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
registered_downloaded_files.extend(
- await app.STORAGE.get_downloaded_files(
+ await app.STORAGE.get_current_attempt_downloaded_files(
organization_id=organization_id,
run_id=candidate_run_id,
)
@@ -10867,9 +10956,13 @@ class FileUploadBlock(FileDestinationBlock):
if self.storage_type in {FileStorageType.S3, FileStorageType.GOOGLE_DRIVE, FileStorageType.SFTP}
else AZURE_BLOB_STORAGE_MAX_UPLOAD_FILE_COUNT
)
+ attempt_started_at = await get_download_retry_started_at(
+ organization_id or workflow_run_context.organization_id, run_download_id
+ )
files_to_upload = self._get_files_to_upload_from_download_dir(
download_files_path=download_files_path,
max_file_count=max_file_count,
+ attempt_started_at=attempt_started_at,
)
if not files_to_upload and not self.continue_on_empty:
@@ -10885,6 +10978,7 @@ class FileUploadBlock(FileDestinationBlock):
run_download_id=run_download_id,
download_files_path=download_files_path,
max_file_count=max_file_count,
+ attempt_started_at=attempt_started_at,
),
self._get_browser_session_downloaded_files_for_empty_scan(
organization_id=organization_id or workflow_run_context.organization_id,
@@ -11316,7 +11410,12 @@ class SendEmailBlock(Block):
reason="the hostname resolves to a private or internal address, which is not allowed",
) from None
- def _get_file_paths(self, workflow_run_context: WorkflowRunContext, workflow_run_id: str) -> list[str]:
+ def _get_file_paths(
+ self,
+ workflow_run_context: WorkflowRunContext,
+ workflow_run_id: str,
+ attempt_started_at: datetime | None = None,
+ ) -> list[str]:
file_paths = []
context = skyvern_context.current()
run_id = context.run_id if context and context.run_id else workflow_run_id
@@ -11349,6 +11448,10 @@ class SendEmailBlock(Block):
if os.path.exists(path):
if os.path.isdir(path):
for file in os.listdir(path):
+ if attempt_started_at is not None and not is_file_from_retry_attempt(
+ os.path.join(path, file), attempt_started_at
+ ):
+ continue
if os.path.isdir(os.path.join(path, file)):
LOG.warning("SendEmailBlock Skipping directory", file=file)
continue
@@ -11402,7 +11505,11 @@ class SendEmailBlock(Block):
file_names_by_hash: dict[str, list[str]] = defaultdict(list)
- for filename in self._get_file_paths(workflow_run_context, workflow_run_id):
+ attempt_started_at = await get_download_retry_started_at(
+ organization_id or workflow_run_context.organization_id,
+ resolve_run_download_id(skyvern_context.current(), fallback_run_id=workflow_run_id),
+ )
+ for filename in self._get_file_paths(workflow_run_context, workflow_run_id, attempt_started_at):
if filename.startswith(("s3://", "gs://", "azure://", "http://", "https://")):
path = await download_file(filename, organization_id=organization_id)
else:
@@ -13824,7 +13931,7 @@ class FileDownloadBlock(BaseTaskBlock, FileDestinationBlock):
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
- downloaded_files = await app.STORAGE.get_downloaded_files(
+ downloaded_files = await app.STORAGE.get_current_attempt_downloaded_files(
organization_id=organization_id,
run_id=run_download_id,
)
@@ -13983,6 +14090,9 @@ class FileDownloadBlock(BaseTaskBlock, FileDestinationBlock):
context = skyvern_context.current()
run_download_id = resolve_run_download_id(context, fallback_run_id=workflow_run_id) or workflow_run_id
download_files_path = str(get_path_for_workflow_download_directory(run_download_id).absolute())
+ attempt_started_at = await get_download_retry_started_at(
+ organization_id or early_context.organization_id, run_download_id
+ )
try:
pre_download_filenames = os.listdir(download_files_path)
except FileNotFoundError:
@@ -14101,6 +14211,12 @@ class FileDownloadBlock(BaseTaskBlock, FileDestinationBlock):
files_to_upload: list[str] = []
for filename in post_download_filenames:
local_file = os.path.join(download_files_path, filename)
+ if (
+ attempt_started_at is not None
+ and filename not in pre_mtimes
+ and not is_file_from_retry_attempt(local_file, attempt_started_at)
+ ):
+ continue
try:
if not os.path.isfile(local_file):
if os.path.isdir(local_file):
@@ -14139,7 +14255,9 @@ class FileDownloadBlock(BaseTaskBlock, FileDestinationBlock):
current_mtime_ns = os.stat(local_file).st_mtime_ns
except OSError:
continue
- if current_mtime_ns > baseline_mtime_ns:
+ if current_mtime_ns > baseline_mtime_ns or (
+ attempt_started_at is not None and current_mtime_ns != baseline_mtime_ns
+ ):
files_to_upload.append(local_file)
if not files_to_upload:
@@ -14450,7 +14568,7 @@ class TaskV2Block(Block):
downloaded_files: list[FileInfo] = []
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
- downloaded_files = await app.STORAGE.get_downloaded_files(
+ downloaded_files = await app.STORAGE.get_current_attempt_downloaded_files(
organization_id=organization_id or "",
run_id=download_lookup_run_id,
)
@@ -14459,6 +14577,7 @@ class TaskV2Block(Block):
downloaded_files = filter_downloaded_files_for_current_iteration(
downloaded_files,
loop_internal_state,
+ aliases=app.STORAGE.get_downloaded_file_signature_aliases,
)
task_v2_output = {
@@ -15207,7 +15326,7 @@ class PrintPageBlock(Block):
return []
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
- return await app.STORAGE.get_downloaded_files(
+ return await app.STORAGE.get_current_attempt_downloaded_files(
organization_id=organization_id,
run_id=storage_run_id,
)
@@ -15313,6 +15432,7 @@ class PrintPageBlock(Block):
downloaded_files = filter_downloaded_files_for_current_iteration(
downloaded_files,
current_context.loop_internal_state if current_context else None,
+ aliases=app.STORAGE.get_downloaded_file_signature_aliases,
)
output = {
"filename": filename,
diff --git a/skyvern/forge/sdk/workflow/models/pdf_fill_block.py b/skyvern/forge/sdk/workflow/models/pdf_fill_block.py
index 6e2dc86cb..838baf166 100644
--- a/skyvern/forge/sdk/workflow/models/pdf_fill_block.py
+++ b/skyvern/forge/sdk/workflow/models/pdf_fill_block.py
@@ -1043,7 +1043,9 @@ class PdfFillBlock(Block):
return []
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
- return await app.STORAGE.get_downloaded_files(organization_id=organization_id, run_id=workflow_run_id)
+ return await app.STORAGE.get_current_attempt_downloaded_files(
+ organization_id=organization_id, run_id=workflow_run_id
+ )
except Exception:
return []
@@ -1214,6 +1216,7 @@ class PdfFillBlock(Block):
downloaded_files = filter_downloaded_files_for_current_iteration(
downloaded_files,
current_context.loop_internal_state if current_context else None,
+ aliases=app.STORAGE.get_downloaded_file_signature_aliases,
)
# The run-level download list can hold other blocks' files; narrow to this block's filled PDF so a
# downstream block consuming `{{ this_output }}` resolves to the right file (extract_file_url reads [0]).
diff --git a/skyvern/forge/sdk/workflow/models/workflow.py b/skyvern/forge/sdk/workflow/models/workflow.py
index 2d60e45ab..42d4f7942 100644
--- a/skyvern/forge/sdk/workflow/models/workflow.py
+++ b/skyvern/forge/sdk/workflow/models/workflow.py
@@ -37,13 +37,14 @@ from skyvern.schemas.runs import (
BROWSER_TYPE_ATTACH_CONFLICT_MESSAGE,
ProxyLocationInput,
ScriptRunResponse,
+ WorkflowRunAttempt,
_browser_address_is_server_assigned,
_browser_session_is_server_assigned,
_validate_browser_address,
browser_type_attach_conflict,
normalize_browser_type,
)
-from skyvern.schemas.workflows import WorkflowStatus
+from skyvern.schemas.workflows import WorkflowRetryPolicy, WorkflowStatus
from skyvern.utils.secret_headers import mask_header_values
from skyvern.utils.url_validators import validate_url
@@ -167,6 +168,10 @@ class WorkflowDefinition(BaseModel):
blocks: List[BlockTypeVar]
finally_block_label: str | None = None
error_code_mapping: dict[str, str] | None = None
+ retry_policy: WorkflowRetryPolicy | None = Field(
+ default=None,
+ description="Optional policy for retrying eligible terminal workflow runs",
+ )
workflow_system_prompt: str | None = None
completion_contract: dict[str, Any] | None = Field(
default=None,
@@ -329,6 +334,19 @@ class WorkflowRun(BaseModel):
reuse_bound_key: str | None = Field(default=None, exclude=True)
debug_session_id: str | None = None
status: WorkflowRunStatus
+ attempt: int = Field(default=1, description="One-based number of the current workflow run attempt")
+ retry_pending: bool = Field(
+ default=False,
+ description="Whether another attempt is scheduled for this workflow run",
+ )
+ next_attempt_at: datetime | None = Field(
+ default=None,
+ description="Timestamp when the next workflow run attempt is scheduled",
+ )
+ attempts: list[WorkflowRunAttempt] = Field(
+ default_factory=list,
+ description="Attempts recorded for this workflow run",
+ )
extra_http_headers: dict[str, str] | None = None
cdp_connect_headers: dict[str, str] | None = None
proxy_location: ProxyLocationInput = None
@@ -474,6 +492,19 @@ class WorkflowRunResponseBase(BaseModel):
return self.workflow_run_id
status: WorkflowRunStatus
+ attempt: int = Field(default=1, description="One-based number of the current workflow run attempt")
+ retry_pending: bool = Field(
+ default=False,
+ description="Whether another attempt is scheduled for this workflow run",
+ )
+ next_attempt_at: datetime | None = Field(
+ default=None,
+ description="Timestamp when the next workflow run attempt is scheduled",
+ )
+ attempts: list[WorkflowRunAttempt] = Field(
+ default_factory=list,
+ description="Attempts recorded for this workflow run",
+ )
failure_reason: str | None = None
failure_category: list[dict[str, Any]] | None = None
retried_from_workflow_run_id: str | None = None
diff --git a/skyvern/forge/sdk/workflow/retry_policy.py b/skyvern/forge/sdk/workflow/retry_policy.py
new file mode 100644
index 000000000..b8da38dad
--- /dev/null
+++ b/skyvern/forge/sdk/workflow/retry_policy.py
@@ -0,0 +1,657 @@
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+from typing import Any, Literal, TypeAlias
+
+import structlog
+from sqlalchemy import update
+from sqlalchemy.exc import IntegrityError
+
+from skyvern.exceptions import WorkflowNotFound, WorkflowNotFoundForWorkflowRun
+from skyvern.forge import app
+from skyvern.forge.sdk.cache import extraction_cache
+from skyvern.forge.sdk.db.datetime_utils import naive_utc_now, to_naive_utc
+from skyvern.forge.sdk.db.models import WorkflowRunAttemptModel
+from skyvern.forge.sdk.db.repositories.workflow_runs import PrepareNextAttemptResult
+from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowRun, WorkflowRunStatus
+from skyvern.schemas.runs import RunStatus, WorkflowRunAttempt
+from skyvern.schemas.workflows import WorkflowRetryPolicy
+from skyvern.services.webhook_delivery import (
+ WEBHOOK_DELIVERY_MAX_ATTEMPTS,
+ WEBHOOK_DELIVERY_MAX_RETRY_AFTER_SECONDS,
+ WEBHOOK_DELIVERY_RETRY_BASE_DELAY_SECONDS,
+)
+
+LOG = structlog.get_logger()
+
+ATTEMPT_QUEUE_WRITE_MAX_ATTEMPTS = 3
+ATTEMPT_QUEUE_WRITE_RETRY_DELAY_SECONDS = 0.1
+
+RETRY_DECISION_RETRY = "retry"
+RETRY_DECISION_FINAL = "final"
+RETRY_DECISION_REVOKED = "revoked"
+RETRY_DECISION_ABANDONED = "abandoned"
+RETRY_DECISION_GRACE_SECONDS = 600
+LEASE_SAFETY_MARGIN_SECONDS = 60
+
+# Keep webhook timing in the OSS layer so the HTTP client, service-side delivery wrapper, and
+# Temporal's bounded fallback grace share one replay-stable value without importing cloud code.
+WORKFLOW_WEBHOOK_HTTP_TIMEOUT_SECONDS = 30.0
+# Leave one additional timeout window plus the original five-second cushion after the complete
+# delivery budget, so fallback cannot race the final in-flight request at the old 35-second mark.
+WEBHOOK_FALLBACK_GRACE_MARGIN_SECONDS = WORKFLOW_WEBHOOK_HTTP_TIMEOUT_SECONDS + 5.0
+WEBHOOK_FALLBACK_GRACE_SECONDS = (
+ WEBHOOK_DELIVERY_MAX_ATTEMPTS * WORKFLOW_WEBHOOK_HTTP_TIMEOUT_SECONDS
+ + (WEBHOOK_DELIVERY_MAX_ATTEMPTS - 1)
+ * max(
+ WEBHOOK_DELIVERY_MAX_RETRY_AFTER_SECONDS,
+ WEBHOOK_DELIVERY_RETRY_BASE_DELAY_SECONDS * 2**WEBHOOK_DELIVERY_MAX_ATTEMPTS,
+ )
+ + WEBHOOK_FALLBACK_GRACE_MARGIN_SECONDS
+)
+# The policy terminal release owns these effects serially before the final webhook. Keep this
+# geometry in one replay-stable OSS constant so Temporal's activity deadline, lease recovery, and
+# webhook-only fallback cannot drift apart.
+TERMINAL_SIDE_EFFECT_TIMEOUT_SECONDS = WORKFLOW_WEBHOOK_HTTP_TIMEOUT_SECONDS
+TERMINAL_SIDE_EFFECT_COUNT = 5
+TERMINAL_RELEASE_TOTAL_BOUND_SECONDS = (
+ TERMINAL_SIDE_EFFECT_COUNT * TERMINAL_SIDE_EFFECT_TIMEOUT_SECONDS
+ + WEBHOOK_FALLBACK_GRACE_SECONDS
+ + LEASE_SAFETY_MARGIN_SECONDS
+)
+# An interim release either records the no-webhook marker (one ordinary side effect) or delivers
+# the every-attempt webhook. The latter is the larger bound and therefore covers both paths.
+INTERIM_RELEASE_TOTAL_BOUND_SECONDS = max(
+ TERMINAL_SIDE_EFFECT_TIMEOUT_SECONDS,
+ WEBHOOK_FALLBACK_GRACE_SECONDS,
+)
+# The once-only tail is guarded as one unit: the hook and final webhook must both fit before a
+# takeover may restart the sequence. The completion marker is written by the webhook effect.
+TERMINAL_SIDE_EFFECT_TAIL_BOUND_SECONDS = TERMINAL_SIDE_EFFECT_TIMEOUT_SECONDS + WEBHOOK_FALLBACK_GRACE_SECONDS
+# This is the only age at which a competing owner may take over a terminal-release lease. The
+# default retry backoff is capped at 100 seconds, so 15 attempts span this bound even after the
+# original owner's 60-second heartbeat timeout.
+LEASE_TAKEOVER_SECONDS = max(
+ RETRY_DECISION_GRACE_SECONDS,
+ TERMINAL_RELEASE_TOTAL_BOUND_SECONDS + LEASE_SAFETY_MARGIN_SECONDS,
+)
+assert TERMINAL_RELEASE_TOTAL_BOUND_SECONDS + LEASE_SAFETY_MARGIN_SECONDS <= LEASE_TAKEOVER_SECONDS
+assert INTERIM_RELEASE_TOTAL_BOUND_SECONDS + LEASE_SAFETY_MARGIN_SECONDS <= LEASE_TAKEOVER_SECONDS
+TERMINAL_RELEASE_RETRY_MAX_ATTEMPTS = 15
+# Each reserved delivery call makes at most three HTTP requests, for at most 45 requests per kind and attempt.
+WORKFLOW_WEBHOOK_DELIVERY_MAX_ATTEMPTS = 15
+
+TerminalSideEffectOutcome: TypeAlias = Literal[
+ "released",
+ "already_released",
+ "lease_held_by_other_young",
+ "fenced_out",
+ "effect_failed",
+]
+
+
+@dataclass(frozen=True)
+class RetryDecision:
+ retry: bool
+ attempt_number: int
+ delay_seconds: int
+ send_webhook_now: bool
+ decision_reason: str | None
+ next_attempt_at: datetime | None = None
+
+
+def remaining_retry_delay_seconds(decision: RetryDecision, *, now: datetime | None = None) -> float:
+ """Seconds until the recorded next attempt; the policy delay when no time was recorded."""
+ next_attempt_at = to_naive_utc(decision.next_attempt_at)
+ if next_attempt_at is None:
+ return float(decision.delay_seconds)
+ return max(0.0, (next_attempt_at - (now or naive_utc_now())).total_seconds())
+
+
+def evaluate_retry_policy(
+ policy: WorkflowRetryPolicy,
+ status: WorkflowRunStatus,
+ error_codes: set[str],
+ retries_used: int,
+) -> tuple[bool, str]:
+ if status is WorkflowRunStatus.canceled:
+ return False, "canceled"
+ if retries_used >= policy.max_retries:
+ return False, "budget_exhausted"
+
+ for rule in policy.retry_on:
+ if rule.status == status.value and (not rule.error_codes or error_codes.intersection(rule.error_codes)):
+ return True, "matched"
+ return False, "no_match"
+
+
+@dataclass(frozen=True)
+class AttemptView:
+ attempt: int
+ retry_pending: bool
+ next_attempt_at: datetime | None
+ attempts: list[WorkflowRunAttempt]
+
+
+AttemptRecord: TypeAlias = WorkflowRunAttemptModel
+
+
+async def _get_retry_policy(
+ workflow_run: WorkflowRun,
+ workflow: Workflow | None = None,
+) -> WorkflowRetryPolicy | None:
+ if workflow is None:
+ try:
+ workflow = await app.WORKFLOW_SERVICE.get_workflow_by_workflow_run_id(
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=workflow_run.organization_id,
+ filter_deleted=False,
+ )
+ except (WorkflowNotFound, WorkflowNotFoundForWorkflowRun):
+ return None
+ return resolve_workflow_retry_policy(workflow)
+
+
+def resolve_workflow_retry_policy(workflow: Workflow | None) -> WorkflowRetryPolicy | None:
+ """Resolve policy presence from the pinned workflow definition, not attempt rows."""
+ if workflow is None:
+ return None
+ definition = getattr(workflow, "workflow_definition", None)
+ policy = getattr(definition, "retry_policy", None)
+ return policy if isinstance(policy, WorkflowRetryPolicy) else None
+
+
+def _attempt_from_record(record: AttemptRecord) -> WorkflowRunAttempt:
+ final_progress = record.final_side_effects_progress or {}
+ interim_progress = record.interim_side_effects_progress or {}
+ final_delivery_attempted = final_progress.get("webhook_delivery_attempted") is True and not final_progress.get(
+ "webhook_delivery_exhausted_at"
+ )
+ interim_delivery_attempted = interim_progress.get(
+ "webhook_delivery_attempted"
+ ) is True and not interim_progress.get("webhook_delivery_exhausted_at")
+ return WorkflowRunAttempt(
+ attempt_number=record.attempt_number,
+ status=record.status.value if isinstance(record.status, WorkflowRunStatus) else record.status,
+ failure_reason=record.failure_reason,
+ error_codes=list(record.error_codes or []),
+ started_at=record.started_at,
+ finished_at=record.finished_at,
+ retry_decision=record.retry_decision,
+ decision_reason=record.decision_reason,
+ next_attempt_at=record.next_attempt_at,
+ webhook_sent_at=(record.webhook_sent_at if final_delivery_attempted else None)
+ or (record.interim_webhook_sent_at if interim_delivery_attempted else None),
+ )
+
+
+def is_retry_pending(
+ status: WorkflowRunStatus | RunStatus,
+ finished_at: datetime | None,
+ latest_attempt: AttemptRecord,
+) -> bool:
+ """Return the retry-pending state shared by detail and list responses."""
+ if not status.is_final():
+ return False
+
+ retry_decision = latest_attempt.retry_decision
+ if retry_decision == RETRY_DECISION_RETRY:
+ return latest_attempt.next_attempt_prepared_at is None
+ if retry_decision is not None:
+ return False
+
+ finished_at = to_naive_utc(finished_at)
+ return finished_at is not None and abs(naive_utc_now() - finished_at) <= timedelta(
+ seconds=RETRY_DECISION_GRACE_SECONDS
+ )
+
+
+def latest_attempt_awaiting_preparation(attempts: Sequence[AttemptRecord]) -> AttemptRecord | None:
+ """The newest attempt whose recorded retry has not been prepared yet."""
+ latest = max(attempts, key=lambda row: row.attempt_number, default=None)
+ if latest is None or latest.retry_decision != RETRY_DECISION_RETRY or latest.next_attempt_prepared_at is not None:
+ return None
+ return latest
+
+
+def _is_retry_pending(run: WorkflowRun, latest_attempt: AttemptRecord) -> bool:
+ return is_retry_pending(run.status, run.finished_at, latest_attempt)
+
+
+def compute_attempt_view(
+ run: WorkflowRun,
+ attempt_rows: Sequence[AttemptRecord],
+ policy: WorkflowRetryPolicy | None = None,
+ target_attempt_number: int | None = None,
+) -> AttemptView:
+ if not attempt_rows:
+ return AttemptView(
+ attempt=1,
+ retry_pending=False,
+ next_attempt_at=None,
+ attempts=[
+ WorkflowRunAttempt(
+ attempt_number=1,
+ status=run.status.value,
+ failure_reason=run.failure_reason,
+ error_codes=[],
+ started_at=run.started_at,
+ finished_at=run.finished_at,
+ )
+ ],
+ )
+
+ ordered_rows = sorted(attempt_rows, key=lambda row: row.attempt_number)
+ historical = target_attempt_number is not None and target_attempt_number < ordered_rows[-1].attempt_number
+ if target_attempt_number is not None and historical:
+ ordered_rows = [row for row in ordered_rows if row.attempt_number <= target_attempt_number]
+ if not ordered_rows or ordered_rows[-1].attempt_number != target_attempt_number:
+ raise ValueError(f"Workflow attempt {target_attempt_number} not found")
+ last = ordered_rows[-1]
+ attempts = [_attempt_from_record(row) for row in ordered_rows]
+
+ if last.finished_at is None and not historical:
+ live_attempt = attempts[-1]
+ attempts[-1] = WorkflowRunAttempt(
+ attempt_number=live_attempt.attempt_number,
+ status=run.status.value,
+ failure_reason=run.failure_reason,
+ error_codes=live_attempt.error_codes,
+ started_at=run.started_at,
+ finished_at=run.finished_at,
+ retry_decision=live_attempt.retry_decision,
+ decision_reason=live_attempt.decision_reason,
+ next_attempt_at=live_attempt.next_attempt_at,
+ webhook_sent_at=live_attempt.webhook_sent_at,
+ )
+
+ # Historical interim delivery describes the retry decision before its successor was prepared.
+ retry_pending = last.retry_decision == RETRY_DECISION_RETRY if historical else _is_retry_pending(run, last)
+ return AttemptView(
+ attempt=last.attempt_number,
+ retry_pending=retry_pending,
+ # A revoked or abandoned row keeps its scheduled time for recovery bookkeeping only.
+ next_attempt_at=last.next_attempt_at if retry_pending else None,
+ attempts=attempts,
+ )
+
+
+def is_top_level_run(workflow_run: WorkflowRun) -> bool:
+ # Mirrors the top-level exclusions in credential_fallback.py.
+ return not (
+ getattr(workflow_run, "parent_workflow_run_id", None)
+ or getattr(workflow_run, "debug_session_id", None)
+ or getattr(workflow_run, "copilot_session_id", None)
+ )
+
+
+async def is_retry_eligible_run(
+ workflow_run: WorkflowRun,
+ organization_id: str,
+ workflow: Workflow | None = None,
+) -> bool:
+ if not is_top_level_run(workflow_run):
+ return False
+ if await _get_retry_policy(workflow_run, workflow) is None:
+ return False
+
+ is_block_scoped_run = await app.AGENT_FUNCTION.is_block_scoped_workflow_run(workflow_run)
+ if not is_block_scoped_run:
+ is_block_scoped_run = await app.DATABASE.debug.has_block_run_for_workflow_run(
+ organization_id=organization_id,
+ workflow_run_id=workflow_run.workflow_run_id,
+ )
+ return not is_block_scoped_run
+
+
+async def ensure_attempt_row(
+ workflow_run: WorkflowRun,
+ organization_id: str,
+ requested_browser_session_id: str | None,
+ workflow: Workflow | None = None,
+) -> bool:
+ if not await is_retry_eligible_run(workflow_run, organization_id, workflow):
+ return False
+
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run.workflow_run_id)
+ if any(attempt.attempt_number == 1 for attempt in attempts):
+ return True
+
+ try:
+ await app.DATABASE.workflow_run_attempts.create_attempt(
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=organization_id,
+ attempt_number=1,
+ status=workflow_run.status.value,
+ pinned_browser_session_id=requested_browser_session_id,
+ )
+ except IntegrityError:
+ # A concurrent setup call may have committed the same primary key between the read and
+ # insert. Confirm that exact row before treating the conflict as the idempotent success.
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run.workflow_run_id)
+ if not any(attempt.attempt_number == 1 for attempt in attempts):
+ raise
+ return True
+
+
+async def queue_initial_attempt(workflow_run_id: str, attempt_number: int) -> bool:
+ """Queue a new run's durable rows before its dispatch, retrying a failed write.
+
+ Dispatch recovery claims only a queued, unstarted run whose attempt is queued, so both rows move in one
+ transaction. False means the run is no longer dispatchable. The last write failure is re-raised instead of
+ letting a dispatch start that a restart cannot recover.
+ """
+ for queue_attempt in range(1, ATTEMPT_QUEUE_WRITE_MAX_ATTEMPTS + 1):
+ try:
+ queued = await app.DATABASE.workflow_runs.queue_initial_dispatch(workflow_run_id, attempt_number)
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ if queue_attempt == ATTEMPT_QUEUE_WRITE_MAX_ATTEMPTS:
+ LOG.warning(
+ "Failed to mark the initial workflow attempt queued; the dispatch was not started",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ queue_attempt=queue_attempt,
+ )
+ raise
+ delay_seconds = ATTEMPT_QUEUE_WRITE_RETRY_DELAY_SECONDS * queue_attempt
+ LOG.warning(
+ "Failed to mark the initial workflow attempt queued; retrying before dispatch",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ queue_attempt=queue_attempt,
+ delay_seconds=delay_seconds,
+ exc_info=True,
+ )
+ await asyncio.sleep(delay_seconds)
+ continue
+ if not queued:
+ LOG.info(
+ "Workflow run is no longer dispatchable; skipping the dispatch",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ )
+ return queued
+ raise AssertionError("unreachable")
+
+
+async def mark_attempt_started(workflow_run_id: str, attempt_number: int) -> bool:
+ """Record the attempt start; False when the row is missing, already started, or finalized."""
+ now = naive_utc_now()
+ async with app.DATABASE.workflow_run_attempts.Session() as session:
+ result = await session.execute(
+ update(WorkflowRunAttemptModel)
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ WorkflowRunAttemptModel.started_at.is_(None),
+ # finalize_attempt never sets started_at, so a cancel that lands between the run's
+ # running write and this one must not be overwritten back to running.
+ WorkflowRunAttemptModel.retry_decision.is_(None),
+ )
+ .values(started_at=now, status=WorkflowRunStatus.running.value, modified_at=now)
+ )
+ await session.commit()
+ return bool(result.rowcount)
+
+
+def _decision_from_attempt(
+ attempt: AttemptRecord,
+ policy: WorkflowRetryPolicy | None,
+) -> RetryDecision:
+ decision = attempt.retry_decision
+ retry = decision == RETRY_DECISION_RETRY
+ delay_seconds = policy.delay_seconds if policy is not None and retry else 0
+ send_webhook_now = retry and policy is not None and policy.webhook_on_retry == "every_attempt"
+ return RetryDecision(
+ retry=retry,
+ attempt_number=attempt.attempt_number,
+ delay_seconds=delay_seconds,
+ send_webhook_now=send_webhook_now or not retry,
+ decision_reason=attempt.decision_reason,
+ next_attempt_at=attempt.next_attempt_at if retry else None,
+ )
+
+
+async def get_recorded_decision(
+ workflow_run_id: str,
+ attempt_number: int | None = None,
+) -> RetryDecision | None:
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ if not attempts:
+ return None
+ attempt = (
+ next((row for row in attempts if row.attempt_number == attempt_number), None)
+ if attempt_number is not None
+ else max(attempts, key=lambda row: row.attempt_number)
+ )
+ if attempt is None:
+ return None
+ if attempt.retry_decision is None:
+ return None
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(workflow_run_id)
+ policy = await _get_retry_policy(workflow_run) if workflow_run is not None else None
+ return _decision_from_attempt(attempt, policy)
+
+
+async def on_terminal_transition(
+ workflow_run: WorkflowRun,
+ status: WorkflowRunStatus,
+ failure_reason: str | None,
+ failure_category: list[dict[str, Any]] | None,
+ attempt_number: int | None = None,
+) -> RetryDecision:
+ if not status.is_final():
+ raise ValueError(f"Cannot record retry decision for non-terminal status: {status.value}")
+
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run.workflow_run_id)
+ if not attempts:
+ return RetryDecision(False, attempt_number or 1, 0, True, "no_attempt_row")
+
+ attempt = (
+ next((row for row in attempts if row.attempt_number == attempt_number), None)
+ if attempt_number is not None
+ else max(attempts, key=lambda row: row.attempt_number)
+ )
+ if attempt is None:
+ return RetryDecision(False, attempt_number or 1, 0, True, "attempt_not_found")
+ attempt_number = attempt.attempt_number
+ policy = await _get_retry_policy(workflow_run)
+ existing_decision = attempt.retry_decision
+ if (
+ existing_decision is not None
+ and existing_decision != RETRY_DECISION_REVOKED
+ and (existing_decision != RETRY_DECISION_ABANDONED or attempt.finished_at is not None)
+ ):
+ # A finally block reopens the run and terminalizes it again. The decision stays frozen, but
+ # the attempt's end time must cover that work: compute cost is priced through finished_at.
+ refreshed = await app.DATABASE.workflow_run_attempts.refresh_attempt_finished_at(
+ workflow_run.workflow_run_id, attempt_number, finished_at=naive_utc_now()
+ )
+ return _decision_from_attempt(refreshed or attempt, policy)
+
+ tasks, blocks = await asyncio.gather(
+ app.DATABASE.tasks.get_tasks_by_workflow_run_id(workflow_run.workflow_run_id),
+ app.DATABASE.observer.get_workflow_run_blocks(
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=workflow_run.organization_id,
+ ),
+ )
+ error_codes: set[str] = set()
+ for task in tasks:
+ task_attempt = task.attempt_number or 1
+ if task_attempt != attempt_number:
+ continue
+ for error in task.errors:
+ error_code = error.get("error_code")
+ if isinstance(error_code, str):
+ error_codes.add(error_code)
+ for block in blocks:
+ block_attempt = block.attempt_number or 1
+ if block_attempt != attempt_number:
+ continue
+ error_codes.update(code for code in (block.error_codes or []) if isinstance(code, str))
+
+ finished_at = naive_utc_now()
+
+ if existing_decision == RETRY_DECISION_ABANDONED:
+ await app.DATABASE.workflow_run_attempts.revoke_or_abandon_attempt(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ decision=RETRY_DECISION_ABANDONED,
+ reason=attempt.decision_reason or RETRY_DECISION_ABANDONED,
+ status=status.value,
+ failure_reason=failure_reason,
+ failure_category=failure_category,
+ error_codes=sorted(error_codes),
+ finished_at=finished_at,
+ lease_takeover_seconds=LEASE_TAKEOVER_SECONDS,
+ )
+ refreshed_attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run.workflow_run_id)
+ refreshed_attempt = next((row for row in refreshed_attempts if row.attempt_number == attempt_number), attempt)
+ return _decision_from_attempt(refreshed_attempt, policy)
+
+ retry = False
+ decision_reason: str | None = "no_match"
+ next_attempt_at: datetime | None = None
+ retry_decision = RETRY_DECISION_FINAL
+ if existing_decision == RETRY_DECISION_REVOKED:
+ decision_reason = attempt.decision_reason
+ next_attempt_at = attempt.next_attempt_at
+ retry_decision = RETRY_DECISION_REVOKED
+ elif attempt.decision_reason == "unrecoverable_block_outputs":
+ decision_reason = attempt.decision_reason
+ retry_decision = RETRY_DECISION_ABANDONED
+ elif policy is not None:
+ retries_used = sum(1 for row in attempts if row.retry_decision == RETRY_DECISION_RETRY)
+ retry, decision_reason = evaluate_retry_policy(policy, status, error_codes, retries_used)
+ if retry:
+ next_attempt_at = naive_utc_now() + timedelta(seconds=policy.delay_seconds)
+ retry_decision = RETRY_DECISION_RETRY
+
+ finalized = await app.DATABASE.workflow_run_attempts.finalize_attempt(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ status=status.value,
+ failure_reason=failure_reason,
+ failure_category=failure_category,
+ error_codes=sorted(error_codes),
+ finished_at=finished_at,
+ retry_decision=retry_decision,
+ decision_reason=None if retry else decision_reason,
+ next_attempt_at=next_attempt_at,
+ )
+ return _decision_from_attempt(finalized, policy)
+
+
+async def prepare_next_attempt_result(
+ workflow_run_id: str,
+ organization_id: str,
+ from_attempt: int,
+ clear_browser_address: bool = True,
+ replacement_browser_address: str | None = None,
+) -> PrepareNextAttemptResult:
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ current_attempt = next(
+ (row for row in attempts if row.attempt_number == from_attempt),
+ None,
+ )
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ )
+ if current_attempt is None or workflow_run is None:
+ return PrepareNextAttemptResult(status="failed")
+
+ pinned_browser_session_id = current_attempt.pinned_browser_session_id
+ preparation = await app.DATABASE.workflow_runs.prepare_next_attempt_atomic(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ from_attempt=from_attempt,
+ expected_status=workflow_run.status,
+ browser_session_id=pinned_browser_session_id,
+ clear_browser_address=clear_browser_address,
+ replacement_browser_address=replacement_browser_address,
+ )
+ if preparation.status != "inserted":
+ return preparation
+
+ app.WORKFLOW_CONTEXT_MANAGER.remove_workflow_run_context(workflow_run_id)
+ extraction_cache.clear_workflow_run(workflow_run_id)
+ return preparation
+
+
+async def finalize_abandoned_attempt(
+ workflow_run_id: str,
+ organization_id: str,
+ reason: str,
+ status: WorkflowRunStatus | str | None = None,
+ failure_reason: str | None = None,
+ finished_at: datetime | None = None,
+ attempt_number: int | None = None,
+) -> RetryDecision:
+ workflow_run: WorkflowRun | None = None
+ if status is None or failure_reason is None or finished_at is None:
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ )
+ if workflow_run is not None and workflow_run.status.is_final():
+ if status is None:
+ status = workflow_run.status
+ if failure_reason is None:
+ failure_reason = workflow_run.failure_reason
+ if finished_at is None:
+ finished_at = workflow_run.finished_at
+
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ if not attempts:
+ return RetryDecision(False, attempt_number or 1, 0, True, reason)
+
+ target_attempt = (
+ next((row for row in attempts if row.attempt_number == attempt_number), None)
+ if attempt_number is not None
+ else max(attempts, key=lambda row: row.attempt_number)
+ )
+ if target_attempt is None:
+ return RetryDecision(False, attempt_number or 1, 0, True, "attempt_not_found")
+ attempt_number = target_attempt.attempt_number
+ abandoned_attempt = await app.DATABASE.workflow_run_attempts.revoke_or_abandon_attempt(
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ decision=RETRY_DECISION_ABANDONED,
+ reason=reason,
+ status=status.value if isinstance(status, WorkflowRunStatus) else status,
+ failure_reason=failure_reason,
+ finished_at=finished_at,
+ lease_takeover_seconds=LEASE_TAKEOVER_SECONDS,
+ )
+
+ if abandoned_attempt:
+ return RetryDecision(
+ retry=False,
+ attempt_number=abandoned_attempt.attempt_number,
+ delay_seconds=0,
+ send_webhook_now=True,
+ decision_reason=abandoned_attempt.decision_reason or reason,
+ )
+
+ # A concurrent preparation or cancellation may have finalized this exact row after the
+ # snapshot above. Preserve that durable decision instead of converting it to abandonment or
+ # accidentally reading a newer attempt's row.
+ refreshed_attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ refreshed_attempt = next(
+ (row for row in refreshed_attempts if row.attempt_number == attempt_number),
+ target_attempt,
+ )
+ if workflow_run is None:
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ )
+ policy = await _get_retry_policy(workflow_run) if workflow_run is not None else None
+ return _decision_from_attempt(refreshed_attempt, policy)
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index 354dfb3ed..0a7bbda71 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -68,8 +68,10 @@ from skyvern.exceptions import (
SkyvernException,
SkyvernHTTPException,
UnrecognizedWorkflowParameters,
+ WorkflowAttemptDispatchSuperseded,
WorkflowNotFound,
WorkflowNotFoundForWorkflowRun,
+ WorkflowRetryAttemptLookupError,
WorkflowRunNotFound,
WorkflowRunParameterPersistenceError,
get_user_facing_exception_message,
@@ -79,7 +81,7 @@ from skyvern.forge.failure_classifier import classify_from_failure_reason
from skyvern.forge.prompts import prompt_engine
from skyvern.forge.sdk.api.files import is_temp_working_dir, resolve_run_download_id
from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType
-from skyvern.forge.sdk.artifact.storage.base import _file_infos_from_download_artifacts
+from skyvern.forge.sdk.artifact.storage.base import _file_infos_from_download_artifacts, artifact_filename_from_uri
from skyvern.forge.sdk.browser_action_policy import BrowserActionPolicy
from skyvern.forge.sdk.cache import extraction_cache
from skyvern.forge.sdk.cache.factory import CacheFactory
@@ -87,8 +89,17 @@ from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.security import generate_skyvern_webhook_signature
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.db._sentinels import _UNSET
+from skyvern.forge.sdk.db.datetime_utils import naive_utc_now, to_naive_utc
from skyvern.forge.sdk.db.enums import BrowserSeedSource, OrganizationAuthTokenType, WorkflowRunTriggerType
from skyvern.forge.sdk.db.id import generate_output_parameter_id, generate_workflow_id, generate_workflow_parameter_id
+from skyvern.forge.sdk.db.models import WorkflowRunAttemptModel
+from skyvern.forge.sdk.db.repositories.workflow_run_attempts import (
+ ATTEMPT_RECOVERY_BATCH_SIZE,
+ ATTEMPT_RECOVERY_MAX_PAGES,
+ AttemptRecoverySuperseded,
+ recovering_undecided_attempt,
+)
+from skyvern.forge.sdk.db.repositories.workflow_runs import PrepareNextAttemptResult
from skyvern.forge.sdk.enterprise_features import collect_enterprise_gated_run_features
from skyvern.forge.sdk.experimentation.enrich_tree import resolve_enrich_tree_for_context
from skyvern.forge.sdk.experimentation.transient_ui_capture import resolve_transient_ui_capture_arm
@@ -189,6 +200,33 @@ from skyvern.forge.sdk.workflow.models.workflow import (
resolve_reuse_browser_session,
should_acquire_reused_session,
)
+from skyvern.forge.sdk.workflow.retry_policy import (
+ LEASE_SAFETY_MARGIN_SECONDS,
+ LEASE_TAKEOVER_SECONDS,
+ RETRY_DECISION_ABANDONED,
+ RETRY_DECISION_FINAL,
+ RETRY_DECISION_RETRY,
+ RETRY_DECISION_REVOKED,
+ TERMINAL_RELEASE_RETRY_MAX_ATTEMPTS,
+ TERMINAL_SIDE_EFFECT_TAIL_BOUND_SECONDS,
+ TERMINAL_SIDE_EFFECT_TIMEOUT_SECONDS,
+ WEBHOOK_FALLBACK_GRACE_SECONDS,
+ WORKFLOW_WEBHOOK_DELIVERY_MAX_ATTEMPTS,
+ WORKFLOW_WEBHOOK_HTTP_TIMEOUT_SECONDS,
+ RetryDecision,
+ TerminalSideEffectOutcome,
+ compute_attempt_view,
+ ensure_attempt_row,
+ finalize_abandoned_attempt,
+ get_recorded_decision,
+ is_retry_eligible_run,
+ is_retry_pending,
+ mark_attempt_started,
+ on_terminal_transition,
+ prepare_next_attempt_result,
+ remaining_retry_delay_seconds,
+ resolve_workflow_retry_policy,
+)
from skyvern.forge.sdk.workflow.runtime_completion import (
ContractVerdict,
grade_completion_contract,
@@ -251,6 +289,12 @@ from skyvern.services.script_review_cap import (
v2_script_review_cap_key,
v3_script_review_cap_key,
)
+from skyvern.services.script_reviewer import (
+ BlockReviewResult,
+ ScriptReviewer,
+ load_filtered_run_param_values,
+ store_review_artifacts,
+)
from skyvern.services.script_reviewer_v3.cohort import is_v3_cohort
from skyvern.services.script_reviewer_v3.postrun import v3_review_post_run
from skyvern.services.webhook_delivery import (
@@ -260,6 +304,7 @@ from skyvern.services.webhook_delivery import (
)
from skyvern.services.workflow_script_service import ( # noqa: F401 -- re-exported; several tests import it from this module
BLOCK_TYPES_THAT_SHOULD_BE_CACHED,
+ create_script_version_from_review,
is_block_type_cacheable,
)
from skyvern.utils.contained_effects import contained_effect
@@ -296,6 +341,8 @@ TRIGGER_RUN_TAG_KEY = "skyvern.trigger"
TARGET_DOMAIN_RUN_TAG_KEY = "skyvern.target_domain"
CREATION_RUN_TAG_CALLER_ID = "system:creation-tagging"
COMPLETION_RUN_TAG_CALLER_ID = "system:completion-tagging"
+WORKFLOW_ATTEMPT_LOOKUP_MAX_ATTEMPTS = 3
+WORKFLOW_ATTEMPT_LOOKUP_RETRY_DELAY_SECONDS = 0.1
MAX_REPORTED_PARAMETER_KEYS = 20
MAX_REPORTED_PARAMETER_KEY_LENGTH = 64
@@ -984,6 +1031,14 @@ def _as_utc(dt: datetime) -> datetime:
return dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+def _queued_seconds(workflow_run: WorkflowRun) -> float:
+ if workflow_run.started_at is None:
+ return 0.0
+ # A retry re-queues the run, so its wait is measured from that queue ticket, not the run's creation.
+ queue_start = workflow_run.queued_at or workflow_run.created_at
+ return (workflow_run.started_at.replace(tzinfo=UTC) - queue_start.replace(tzinfo=UTC)).total_seconds()
+
+
def _task_v3_ab_arm_for_duration_log(workflow_run_id: str) -> str | None:
"""Failure-safe wrapper around ``resolved_workflow_block_engine_arm_label`` (which owns the
three-way contract): telemetry only, so a lookup failure must never break run finalization —
@@ -1238,6 +1293,14 @@ class WorkflowBrowserCleanupResult:
browser_session_write_back_attempted: bool = False
+@dataclass
+class TerminalSideEffectProgress:
+ claim_at: datetime | None = None
+ completed_effects: set[str] = field(default_factory=set)
+ final_hook_failed: bool = False
+ final_hook_invoked: bool = False
+
+
@dataclass(frozen=True)
class ReusedSessionOwnerProof:
is_terminal: bool
@@ -1473,6 +1536,326 @@ def _browser_lease_failure_category(exc: Exception) -> list[dict] | None:
]
+async def _get_recovery_api_key(organization_id: str) -> str | None:
+ organizations = getattr(app.DATABASE, "organizations", None)
+ get_valid_org_auth_token = getattr(organizations, "get_valid_org_auth_token", None)
+ if get_valid_org_auth_token is None:
+ return None
+ try:
+ org_auth_token = await get_valid_org_auth_token(
+ organization_id=organization_id,
+ token_type=OrganizationAuthTokenType.api.value,
+ )
+ except Exception:
+ LOG.exception(
+ "Failed to load organization API token for workflow retry recovery", organization_id=organization_id
+ )
+ return None
+ return org_auth_token.token if org_auth_token else None
+
+
+async def _recover_stale_retry_attempt(attempt: Any) -> None:
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ )
+ if workflow_run is None:
+ LOG.warning(
+ "Cannot recover stale retry because its workflow run is missing",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ return
+
+ execution_status = await app.AGENT_FUNCTION.get_workflow_run_execution_status(workflow_run)
+ if execution_status not in {"absent", "terminal"}:
+ return
+ is_final = workflow_run.status.is_final()
+ decision = await finalize_abandoned_attempt(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ reason="process_restart",
+ status=workflow_run.status if is_final else None,
+ failure_reason=workflow_run.failure_reason if is_final else None,
+ finished_at=workflow_run.finished_at if is_final else None,
+ attempt_number=attempt.attempt_number,
+ )
+ if decision.retry:
+ LOG.info(
+ "Skipped abandoning stale retry because its terminal side-effect lease is still young",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ return
+
+ api_key = await _get_recovery_api_key(workflow_run.organization_id)
+ await app.WORKFLOW_SERVICE._run_terminal_side_effects_with_retries(
+ workflow_run,
+ decision,
+ api_key=api_key,
+ )
+
+
+async def _recover_prepared_attempt(attempt: Any) -> None:
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ )
+ if workflow_run is None:
+ LOG.warning(
+ "Cannot recover prepared retry because its workflow run is missing",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ return
+
+ if workflow_run.status != WorkflowRunStatus.queued or workflow_run.started_at is not None:
+ return
+ execution_status = await app.AGENT_FUNCTION.get_workflow_run_execution_status(workflow_run)
+ if execution_status not in {"absent", "terminal"}:
+ LOG.info(
+ "Skipping prepared retry recovery while execution ownership is active or unknown",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ execution_status=execution_status,
+ )
+ return
+
+ failure_reason = "Workflow retry attempt was prepared but never started before recovery."
+ claimed = await app.DATABASE.workflow_run_attempts.fail_prepared_workflow_run(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ attempt_number=attempt.attempt_number,
+ failure_reason=failure_reason,
+ )
+ if not claimed:
+ return
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ )
+ if workflow_run is None:
+ return
+
+ status = workflow_run.status if workflow_run.status.is_final() else WorkflowRunStatus.failed
+ finished_at = getattr(workflow_run, "finished_at", None) or naive_utc_now()
+ decision = await finalize_abandoned_attempt(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ reason="prepared_attempt_never_started",
+ status=status,
+ failure_reason=getattr(workflow_run, "failure_reason", None) or failure_reason,
+ finished_at=finished_at,
+ attempt_number=attempt.attempt_number,
+ )
+ if decision.retry:
+ LOG.info(
+ "Skipped abandoning stale retry because its terminal side-effect lease is still young",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ return
+
+ api_key = await _get_recovery_api_key(workflow_run.organization_id)
+ await app.WORKFLOW_SERVICE._run_terminal_side_effects_with_retries(
+ workflow_run,
+ decision,
+ api_key=api_key,
+ )
+
+
+async def _terminal_workflow_run(attempt: Any) -> WorkflowRun | None:
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ )
+ if workflow_run is None or not workflow_run.status.is_final():
+ return None
+ return workflow_run
+
+
+async def _recover_undecided_terminal_attempt(
+ attempt: WorkflowRunAttemptModel, workflow_run: WorkflowRun | None = None
+) -> WorkflowRunAttemptModel | None:
+ # The sweeps pass the row they already loaded; workflow_runs is high-traffic, so it is read once.
+ if workflow_run is None:
+ workflow_run = await _terminal_workflow_run(attempt)
+ if workflow_run is None or not workflow_run.status.is_final():
+ return None
+ execution_status = await app.AGENT_FUNCTION.get_workflow_run_execution_status(workflow_run)
+ if execution_status not in {"absent", "terminal"}:
+ return None
+
+ # The run can finish before its decision; fence recovery reads and writes against a concurrent finalizer.
+ try:
+ with recovering_undecided_attempt(attempt):
+ decision = await on_terminal_transition(
+ workflow_run,
+ workflow_run.status,
+ workflow_run.failure_reason,
+ workflow_run.failure_category,
+ attempt_number=attempt.attempt_number,
+ )
+ except AttemptRecoverySuperseded:
+ return None
+ api_key = await _get_recovery_api_key(workflow_run.organization_id)
+ outcome = await app.WORKFLOW_SERVICE._run_terminal_side_effects_with_retries(
+ workflow_run, decision, api_key=api_key
+ )
+ if not decision.retry or outcome in {"lease_held_by_other_young", "fenced_out"}:
+ return None
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(attempt.workflow_run_id)
+ return next(
+ (
+ row
+ for row in attempts
+ if row.attempt_number == attempt.attempt_number
+ and row.retry_decision == RETRY_DECISION_RETRY
+ and row.next_attempt_prepared_at is None
+ ),
+ None,
+ )
+
+
+async def _recover_unreleased_terminal_attempt(attempt: Any, *, interim: bool = False) -> None:
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ )
+ if workflow_run is None:
+ LOG.warning(
+ "Cannot recover terminal effects because its workflow run is missing",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ return
+
+ if interim:
+ decision = await get_recorded_decision(attempt.workflow_run_id, attempt_number=attempt.attempt_number)
+ if decision is None or not decision.retry:
+ return
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(attempt.workflow_run_id)
+ if any(
+ row.attempt_number > attempt.attempt_number
+ and (row.webhook_sent_at is not None or row.interim_webhook_sent_at is not None)
+ for row in attempts
+ ):
+ # A later attempt already claimed a webhook; this attempt's retry_pending payload would move consumers back.
+ LOG.info(
+ "Skipping interim webhook recovery because a later attempt already delivered a webhook",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ )
+ await app.DATABASE.workflow_run_attempts.claim_attempt_webhook(
+ attempt.workflow_run_id, attempt.attempt_number, "interim"
+ )
+ return
+ else:
+ decision = RetryDecision(
+ retry=False,
+ attempt_number=attempt.attempt_number,
+ delay_seconds=0,
+ send_webhook_now=True,
+ decision_reason=attempt.decision_reason,
+ )
+ api_key = await _get_recovery_api_key(workflow_run.organization_id)
+ side_effects_claim_at = getattr(attempt, "side_effects_released_at", None)
+ kwargs: dict[str, Any] = {"api_key": api_key}
+ if side_effects_claim_at is not None:
+ kwargs.update(
+ {
+ "side_effects_claim_at": side_effects_claim_at,
+ "side_effects_stale_before": naive_utc_now() - timedelta(seconds=LEASE_TAKEOVER_SECONDS),
+ }
+ )
+ await app.WORKFLOW_SERVICE._run_terminal_side_effects_with_retries(workflow_run, decision, **kwargs)
+
+
+async def recover_pending_workflow_attempts(
+ *,
+ release_only: bool = False,
+ process_attempt: Callable[[Any, bool], Awaitable[None]] | None = None,
+) -> None:
+ """Recover durable retry rows with bounded keyset pagination.
+
+ ``release_only`` is used by cloud maintenance: it abandons stale pending decisions and releases
+ terminal effects, but never schedules a fresh workflow execution. The OSS executor supplies its
+ own per-attempt handler so its startup pass can retain the existing resume behavior.
+ """
+ cutoff = naive_utc_now() - timedelta(seconds=LEASE_TAKEOVER_SECONDS)
+ cursor: tuple[Any, str, int] | None = None
+ for _page_number in range(ATTEMPT_RECOVERY_MAX_PAGES):
+ if cursor is None:
+ attempts = await app.DATABASE.workflow_run_attempts.list_attempts_needing_recovery(cutoff)
+ else:
+ attempts = await app.DATABASE.workflow_run_attempts.list_attempts_needing_recovery(
+ cutoff,
+ cursor=cursor,
+ )
+ if not attempts:
+ break
+
+ for attempt in attempts:
+ try:
+ if (
+ attempt.retry_decision == RETRY_DECISION_RETRY
+ and getattr(attempt, "next_attempt_prepared_at", None) is not None
+ ):
+ await _recover_unreleased_terminal_attempt(attempt, interim=True)
+ elif process_attempt is not None:
+ await process_attempt(attempt, release_only)
+ elif attempt.retry_decision is None and attempt.started_at is not None:
+ await _recover_undecided_terminal_attempt(attempt)
+ elif attempt.retry_decision == RETRY_DECISION_RETRY:
+ next_attempt_at = to_naive_utc(getattr(attempt, "next_attempt_at", None))
+ if next_attempt_at is not None and next_attempt_at < cutoff:
+ await _recover_stale_retry_attempt(attempt)
+ elif (
+ attempt.retry_decision is None
+ and (terminal_run := await _terminal_workflow_run(attempt)) is not None
+ ):
+ await _recover_undecided_terminal_attempt(attempt, workflow_run=terminal_run)
+ elif (
+ attempt.retry_decision is None
+ and attempt.status == WorkflowRunStatus.queued.value
+ and attempt.started_at is None
+ ):
+ await _recover_prepared_attempt(attempt)
+ elif attempt.retry_decision in {
+ RETRY_DECISION_FINAL,
+ RETRY_DECISION_REVOKED,
+ RETRY_DECISION_ABANDONED,
+ }:
+ await _recover_unreleased_terminal_attempt(attempt)
+ except Exception:
+ LOG.exception(
+ "Failed to recover workflow run attempt",
+ workflow_run_id=attempt.workflow_run_id,
+ attempt_number=attempt.attempt_number,
+ retry_decision=attempt.retry_decision,
+ )
+
+ last_attempt = attempts[-1]
+ decision_timestamp = to_naive_utc(
+ getattr(last_attempt, "next_attempt_at", None) or getattr(last_attempt, "modified_at", None)
+ )
+ if decision_timestamp is None:
+ LOG.warning(
+ "Stopping workflow retry recovery because the page has no decision timestamp",
+ workflow_run_id=last_attempt.workflow_run_id,
+ attempt_number=last_attempt.attempt_number,
+ )
+ break
+ cursor = (decision_timestamp, last_attempt.workflow_run_id, last_attempt.attempt_number)
+ if len(attempts) < ATTEMPT_RECOVERY_BATCH_SIZE:
+ break
+ else:
+ LOG.warning(
+ "Workflow retry recovery reached its page limit; remaining attempts wait for the next sweep",
+ max_pages=ATTEMPT_RECOVERY_MAX_PAGES,
+ )
+
+
_WORKFLOW_SAVE_FINGERPRINT_DOMAIN = b"skyvern.workflow_save_fingerprint.v2\0"
@@ -1493,6 +1876,26 @@ class WorkflowService:
# Prevent GC of fire-and-forget asyncio tasks (e.g. task_run sync).
_background_tasks: set[asyncio.Task] = set() # noqa: RUF012
+ async def recover_undecided_terminal_attempt(
+ self, attempt: WorkflowRunAttemptModel, workflow_run: WorkflowRun | None = None
+ ) -> WorkflowRunAttemptModel | None:
+ return await _recover_undecided_terminal_attempt(attempt, workflow_run=workflow_run)
+
+ async def terminal_workflow_run(self, attempt: Any) -> WorkflowRun | None:
+ return await _terminal_workflow_run(attempt)
+
+ async def recover_pending_workflow_attempts(
+ self,
+ *,
+ release_only: bool = False,
+ process_attempt: Callable[[Any, bool], Awaitable[None]] | None = None,
+ ) -> None:
+ """Recover durable retry rows through the shared workflow service instance."""
+ await recover_pending_workflow_attempts(
+ release_only=release_only,
+ process_attempt=process_attempt,
+ )
+
@staticmethod
async def _record_workflow_run_metadata_best_effort(
*,
@@ -1927,6 +2330,9 @@ class WorkflowService:
workflow_run_id: str,
organization_id: str,
filenames: set[str],
+ attempt_rows: Sequence[Any] | None = None,
+ attempt_number: int | None = None,
+ historical_artifacts: list[Artifact] | None = None,
) -> list[FileInfo]:
"""Look up DOWNLOAD artifact rows for the workflow run and filter to
the given filename set.
@@ -1944,12 +2350,27 @@ class WorkflowService:
"""
if not workflow_run_id or not organization_id or not filenames:
return []
+ context = skyvern_context.current()
+ download_run_id = resolve_run_download_id(context, fallback_run_id=workflow_run_id) or workflow_run_id
try:
- artifacts = await app.DATABASE.artifacts.list_artifacts_for_run_by_type(
- run_id=workflow_run_id,
- organization_id=organization_id,
- artifact_type=ArtifactType.DOWNLOAD,
- )
+ if historical_artifacts is not None and download_run_id == workflow_run_id:
+ artifacts = [
+ artifact for artifact in historical_artifacts if artifact.artifact_type == ArtifactType.DOWNLOAD
+ ]
+ elif attempt_rows and attempt_number is not None:
+ artifacts = await self._list_download_artifacts_for_attempt(
+ run_id=download_run_id,
+ organization_id=organization_id,
+ attempt_rows=attempt_rows,
+ attempt_number=attempt_number,
+ attribution_workflow_run_id=workflow_run_id,
+ )
+ else:
+ artifacts = await app.DATABASE.artifacts.list_artifacts_for_run_by_type(
+ run_id=workflow_run_id,
+ organization_id=organization_id,
+ artifact_type=ArtifactType.DOWNLOAD,
+ )
except Exception:
LOG.warning(
"Failed to refresh block-output downloaded_files via run-id lookup",
@@ -1963,12 +2384,136 @@ class WorkflowService:
matched: list[Artifact] = []
seen: set[str] = set()
for artifact in artifacts:
- basename = artifact.uri.rsplit("/", 1)[-1] if artifact.uri else ""
+ basename = artifact_filename_from_uri(artifact.uri)
if basename in filenames and basename not in seen:
matched.append(artifact)
seen.add(basename)
return await _file_infos_from_download_artifacts(matched)
+ @staticmethod
+ def _attempt_started_at(attempt_rows: Sequence[Any], attempt_number: int) -> datetime | None:
+ attempt = next((row for row in attempt_rows if row.attempt_number == attempt_number), None)
+ return attempt.started_at if attempt is not None else None
+
+ @staticmethod
+ def _successor_attempt_boundary(attempt_rows: Sequence[Any], attempt_number: int) -> datetime | None:
+ successor = next((row for row in attempt_rows if row.attempt_number == attempt_number + 1), None)
+ return (successor.started_at or successor.created_at) if successor is not None else None
+
+ async def _list_download_artifacts_for_attempt(
+ self,
+ *,
+ run_id: str,
+ organization_id: str,
+ attempt_rows: Sequence[Any],
+ attempt_number: int,
+ attribution_workflow_run_id: str | None = None,
+ ) -> list[Artifact]:
+ if any(row.attempt_number > attempt_number for row in attempt_rows):
+ artifacts = await app.DATABASE.workflow_runs.get_artifacts_for_attempt(
+ attribution_workflow_run_id or run_id,
+ organization_id,
+ attempt_number,
+ self._attempt_started_at(attempt_rows, attempt_number),
+ self._successor_attempt_boundary(attempt_rows, attempt_number),
+ **(
+ {"artifact_run_id": run_id}
+ if attribution_workflow_run_id and attribution_workflow_run_id != run_id
+ else {}
+ ),
+ )
+ return [artifact for artifact in artifacts if artifact.artifact_type == ArtifactType.DOWNLOAD]
+ list_for_attempt = getattr(app.DATABASE.artifacts, "list_download_artifacts_for_attempt", None)
+ if list_for_attempt is None:
+ return []
+ return await list_for_attempt(
+ run_id=run_id,
+ organization_id=organization_id,
+ attempt_number=attempt_number,
+ attempt_started_at=self._attempt_started_at(attempt_rows, attempt_number),
+ )
+
+ async def _download_artifact_ids_for_attempt(
+ self,
+ *,
+ run_id: str,
+ organization_id: str,
+ attempt_rows: Sequence[Any],
+ attempt_number: int,
+ historical_artifacts: list[Artifact] | None = None,
+ attribution_workflow_run_id: str | None = None,
+ ) -> set[str]:
+ if historical_artifacts is not None:
+ return {
+ artifact.artifact_id
+ for artifact in historical_artifacts
+ if artifact.artifact_type == ArtifactType.DOWNLOAD
+ }
+ try:
+ artifacts = await self._list_download_artifacts_for_attempt(
+ run_id=run_id,
+ organization_id=organization_id,
+ attempt_rows=attempt_rows,
+ attempt_number=attempt_number,
+ attribution_workflow_run_id=attribution_workflow_run_id,
+ )
+ except Exception:
+ LOG.warning(
+ "Failed to scope downloaded files to workflow attempt",
+ run_id=run_id,
+ organization_id=organization_id,
+ attempt_number=attempt_number,
+ exc_info=True,
+ )
+ return set()
+ return {artifact.artifact_id for artifact in artifacts}
+
+ def _filter_downloaded_files_to_attempt(
+ self,
+ files: list[FileInfo],
+ *,
+ attempt_rows: Sequence[Any] | None,
+ attempt_number: int | None,
+ artifact_ids: set[str] | None,
+ ) -> list[FileInfo]:
+ """Keep permissive attribution for live completion checks; historical files need an ID match or a bounded timestamp."""
+ if not attempt_rows or attempt_number is None:
+ return files
+ attempt_row = next((row for row in attempt_rows if row.attempt_number == attempt_number), None)
+ # A prepared attempt that has not started owns nothing yet; its row's creation bounds prior files.
+ attempt_started_at = (attempt_row.started_at or attempt_row.created_at) if attempt_row is not None else None
+ unstarted = attempt_row is not None and attempt_row.started_at is None
+ historical = any(row.attempt_number > attempt_number for row in attempt_rows)
+ successor_started_at = self._successor_attempt_boundary(attempt_rows, attempt_number)
+
+ def is_before_attempt_start(file_info: FileInfo) -> bool:
+ # An unknown timestamp counts as current for a live attempt and as prior for one not started.
+ if file_info.modified_at is None:
+ return unstarted
+ return attempt_started_at is not None and _as_utc(file_info.modified_at) < _as_utc(attempt_started_at)
+
+ scoped: list[FileInfo] = []
+ for file_info in files:
+ if historical:
+ if file_info.artifact_id:
+ if artifact_ids is not None and file_info.artifact_id in artifact_ids:
+ scoped.append(file_info)
+ continue
+ if (
+ file_info.modified_at is None
+ or successor_started_at is None
+ or _as_utc(file_info.modified_at) >= _as_utc(successor_started_at)
+ ):
+ continue
+ if (
+ file_info.artifact_id
+ and artifact_ids is not None
+ and file_info.artifact_id in artifact_ids
+ or not is_before_attempt_start(file_info)
+ ):
+ scoped.append(file_info)
+ return scoped
+
@staticmethod
def _collect_artifact_ids(value: Any) -> tuple[list[str], list[str]]:
"""Sync scan of the block-output tree → (screenshot_ids, download_ids). No DB calls."""
@@ -1997,12 +2542,34 @@ class WorkflowService:
value: Any,
organization_id: str | None,
workflow_run_id: str,
+ attempt_rows: Sequence[Any] | None = None,
+ attempt_number: int | None = None,
+ historical_artifacts: list[Artifact] | None = None,
+ current_attempt_artifacts: list[Artifact] | None = None,
) -> Any:
"""Two-pass batch URL refresh: scan artifact IDs (sync), fetch all in 2 parallel DB calls, substitute in-place."""
if not organization_id:
return value
screenshot_ids, download_ids = WorkflowService._collect_artifact_ids(value)
+ download_scope_active = bool(attempt_rows and attempt_number is not None)
+ if attempt_rows and attempt_number is not None and download_ids:
+ context = skyvern_context.current()
+ download_run_id = resolve_run_download_id(context, fallback_run_id=workflow_run_id) or workflow_run_id
+ scoped_download_ids = await self._download_artifact_ids_for_attempt(
+ run_id=download_run_id,
+ organization_id=organization_id,
+ attempt_rows=attempt_rows,
+ attempt_number=attempt_number,
+ historical_artifacts=historical_artifacts if download_run_id == workflow_run_id else None,
+ attribution_workflow_run_id=workflow_run_id,
+ )
+ download_ids = [artifact_id for artifact_id in download_ids if artifact_id in scoped_download_ids]
+ # Block outputs collect screenshot ids across the whole run; a retried run exposes only its attempt's.
+ screenshot_scope = historical_artifacts if historical_artifacts is not None else current_attempt_artifacts
+ if screenshot_scope is not None:
+ allowed_ids = {artifact.artifact_id for artifact in screenshot_scope}
+ screenshot_ids = [artifact_id for artifact_id in screenshot_ids if artifact_id in allowed_ids]
all_ids = list(dict.fromkeys(screenshot_ids + download_ids))
url_map: dict[str, str] = {}
@@ -2020,17 +2587,27 @@ class WorkflowService:
continue
url_map[artifact.artifact_id] = url
if artifact.artifact_id in download_id_set:
- filename = artifact.uri.rsplit("/", 1)[-1] if artifact.uri else ""
+ filename = artifact_filename_from_uri(artifact.uri)
fileinfo_map[artifact.artifact_id] = FileInfo(
url=url,
checksum=artifact.checksum,
filename=filename,
file_size=artifact.file_size,
- modified_at=artifact.created_at,
+ modified_at=artifact.modified_at or artifact.created_at,
artifact_id=artifact.artifact_id,
)
- return await self._substitute_artifact_urls(value, url_map, fileinfo_map, workflow_run_id, organization_id)
+ return await self._substitute_artifact_urls(
+ value,
+ url_map,
+ fileinfo_map,
+ workflow_run_id,
+ organization_id,
+ attempt_rows=attempt_rows,
+ attempt_number=attempt_number,
+ download_scope_active=download_scope_active,
+ historical_artifacts=historical_artifacts,
+ )
async def _substitute_artifact_urls(
self,
@@ -2039,6 +2616,10 @@ class WorkflowService:
fileinfo_map: dict[str, FileInfo],
workflow_run_id: str,
organization_id: str | None,
+ attempt_rows: Sequence[Any] | None = None,
+ attempt_number: int | None = None,
+ historical_artifacts: list[Artifact] | None = None,
+ download_scope_active: bool = False,
) -> Any:
"""Substitute artifact IDs with pre-built URLs and FileInfos (no DB in the common path).
@@ -2062,7 +2643,7 @@ class WorkflowService:
refreshed = [
fileinfo_map[aid] for aid in value["downloaded_file_artifact_ids"] if aid in fileinfo_map
]
- if refreshed:
+ if refreshed or download_scope_active:
value["downloaded_files"] = [fi.model_dump(mode="json") for fi in refreshed]
value["downloaded_file_urls"] = [fi.url for fi in refreshed]
elif value.get("downloaded_files") and organization_id:
@@ -2079,32 +2660,64 @@ class WorkflowService:
workflow_run_id=workflow_run_id,
organization_id=organization_id,
filenames=stored_filenames,
+ historical_artifacts=historical_artifacts,
+ attempt_rows=attempt_rows,
+ attempt_number=attempt_number,
)
- if refreshed:
+ if refreshed or download_scope_active:
value["downloaded_files"] = [fi.model_dump(mode="json") for fi in refreshed]
value["downloaded_file_urls"] = [fi.url for fi in refreshed]
+ elif download_scope_active:
+ value["downloaded_files"] = []
+ value["downloaded_file_urls"] = []
elif has_old_format:
# Legacy snapshots without artifact IDs — one query per run (not per block), already O(1).
task_id = value.get("task_id")
if value.get("task_screenshots"):
- value["task_screenshots"] = await self.get_recent_task_screenshot_urls(
- organization_id=organization_id,
- task_id=task_id,
- )
+ if historical_artifacts is not None:
+ value["task_screenshots"] = await self.get_recent_workflow_screenshot_urls(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ historical_artifacts=[
+ artifact for artifact in historical_artifacts if artifact.task_id == task_id
+ ],
+ )
+ else:
+ value["task_screenshots"] = await self.get_recent_task_screenshot_urls(
+ organization_id=organization_id,
+ task_id=task_id,
+ )
if value.get("workflow_screenshots"):
value["workflow_screenshots"] = await self.get_recent_workflow_screenshot_urls(
workflow_run_id=workflow_run_id,
organization_id=organization_id,
+ historical_artifacts=historical_artifacts,
)
else:
for k, v in value.items():
value[k] = await self._substitute_artifact_urls(
- v, url_map, fileinfo_map, workflow_run_id, organization_id
+ v,
+ url_map,
+ fileinfo_map,
+ workflow_run_id,
+ organization_id,
+ attempt_rows=attempt_rows,
+ attempt_number=attempt_number,
+ download_scope_active=download_scope_active,
+ historical_artifacts=historical_artifacts,
)
elif isinstance(value, list):
for i, item in enumerate(value):
value[i] = await self._substitute_artifact_urls(
- item, url_map, fileinfo_map, workflow_run_id, organization_id
+ item,
+ url_map,
+ fileinfo_map,
+ workflow_run_id,
+ organization_id,
+ attempt_rows=attempt_rows,
+ attempt_number=attempt_number,
+ download_scope_active=download_scope_active,
+ historical_artifacts=historical_artifacts,
)
return value
@@ -2585,6 +3198,7 @@ class WorkflowService:
copilot_session_id: str | None = None,
resolved_workflow_id: str | None = None,
tag_write_context: TagWriteContext | None = None,
+ block_scoped: bool = False,
shares_parent_browser: bool = False,
server_owned_browser_type: str | None = None,
) -> WorkflowRun:
@@ -2725,6 +3339,8 @@ class WorkflowService:
fallback_attempt=fallback_attempt,
ignore_inherited_workflow_system_prompt=ignore_inherited_workflow_system_prompt,
copilot_session_id=resolved_copilot_session_id,
+ workflow=workflow,
+ block_scoped=block_scoped,
)
try:
await self._apply_initial_run_metadata_tags(
@@ -3082,8 +3698,7 @@ class WorkflowService:
type — and stamp the resolved profile plus its provenance (browser_seed_source) on the run.
This is where the credential's saved profile is resolved (the mid-run login-block stamp lands
too late for code/cached and early-block runs)."""
- # Resolve once: a run whose seed was already stamped is never re-resolved, so storage state or
- # a fresh credential selection can never change a settled seed.
+ # Retry preparation invalidates credential-derived seeds atomically with credential rotation.
if workflow_run.browser_seed_source is not None:
return workflow_run
# A run bound to a live browser session is governed by that session: the browser manager
@@ -4951,8 +5566,89 @@ class WorkflowService:
)
return fallback_workflow_run, WorkflowRunStatus.timed_out, timeout_failure_reason
- @traced(name="skyvern.workflow.execute", role="wrapper")
- async def execute_workflow(
+ async def _wait_for_retry_sequential_clearance(
+ self, workflow_run: WorkflowRun, attempt_number: int
+ ) -> WorkflowRun | None:
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run.workflow_run_id)
+ current_attempt = next((row for row in attempts if row.attempt_number == attempt_number), None)
+ # Each attempt's durable preparation timestamp bounds admission across recovery re-entries.
+ admission_run = workflow_run.model_copy(
+ update={
+ "started_at": current_attempt.created_at
+ if current_attempt is not None and current_attempt.created_at is not None
+ else workflow_run.created_at
+ }
+ )
+ remaining_seconds = _get_workflow_run_max_elapsed_timeout_seconds(admission_run)
+ try:
+ async with asyncio.timeout(remaining_seconds):
+ while True:
+ try:
+ current = await self.get_workflow_run(
+ workflow_run.workflow_run_id, workflow_run.organization_id
+ )
+ if current.status.is_final():
+ return current
+ blocker = await app.DATABASE.workflow_runs.get_blocking_sequential_workflow_run(
+ workflow_run.workflow_run_id
+ )
+ if blocker is None:
+ return None
+ except Exception:
+ LOG.warning(
+ "Failed to check retry sequential clearance; keeping the attempt queued",
+ workflow_run_id=workflow_run.workflow_run_id,
+ exc_info=True,
+ )
+ await asyncio.sleep(1)
+ except TimeoutError:
+ return await self.mark_workflow_run_as_timed_out(
+ workflow_run.workflow_run_id,
+ failure_reason="Workflow run exceeded its remaining runtime while waiting for sequential clearance.",
+ )
+
+ async def _prepare_recorded_retry(
+ self,
+ workflow_run_id: str,
+ organization_id: str,
+ decision: RetryDecision,
+ ) -> PrepareNextAttemptResult | None:
+ """Read the recorded decision after its delay and prepare the successor; None when superseded."""
+ # The recovery sweep abandons an unprepared retry after LEASE_TAKEOVER_SECONDS; retry until then.
+ deadline = naive_utc_now() + timedelta(seconds=LEASE_TAKEOVER_SECONDS)
+ backoff_seconds = 1.0
+ while True:
+ try:
+ latest_decision = await get_recorded_decision(workflow_run_id, attempt_number=decision.attempt_number)
+ if latest_decision is None or not latest_decision.retry:
+ LOG.info(
+ "Workflow retry owner stopped before preparing a superseded attempt",
+ workflow_run_id=workflow_run_id,
+ attempt_number=decision.attempt_number,
+ )
+ return None
+ return await prepare_next_attempt_result(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ from_attempt=decision.attempt_number,
+ clear_browser_address=False,
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ remaining_seconds = (deadline - naive_utc_now()).total_seconds()
+ if remaining_seconds <= 0:
+ raise
+ LOG.warning(
+ "Failed to prepare the next workflow attempt; retrying",
+ workflow_run_id=workflow_run_id,
+ attempt_number=decision.attempt_number,
+ exc_info=True,
+ )
+ await asyncio.sleep(min(backoff_seconds, remaining_seconds))
+ backoff_seconds = min(backoff_seconds * 2, 30.0)
+
+ async def execute_workflow_with_retries(
self,
workflow_run_id: str,
api_key: str | None,
@@ -4963,32 +5659,385 @@ class WorkflowService:
need_call_webhook: bool = True,
workflow_override: Workflow | None = None,
requested_completion_contract: dict[str, Any] | None = None,
+ attempt_number: int = 1,
+ prepared_attempt_claimed: bool = False,
+ claim_initial_attempt: bool = False,
+ dispatch_claim_started_at: datetime | None = None,
+ *,
+ on_execution_start: Callable[[], None] | None = None,
+ initialize_attempt: Callable[[str | None], Awaitable[str | None]] | None = None,
) -> WorkflowRun:
- """Execute a workflow.
+ """Run a workflow and keep the caller's concurrency slot through retry finalization.
- When the workflow_run row has ``ignore_inherited_workflow_system_prompt``
- set (populated at spawn time by a ``WorkflowTriggerBlock`` whose
- ``ignore_workflow_system_prompt`` flag is True), the child workflow
- starts with a clean slate — no inherited prompt from the ancestor
- chain. Persisting the intent on the row means the flag is honored for
- both sync and async (Temporal-dispatched) trigger modes.
+ The background executor and the local scheduler both use this coroutine. A run without an
+ attempt row follows the ordinary execution path, including its caller-selected webhook
+ behavior; policy runs keep the retry loop and terminal side effects in this awaited task.
+ ``claim_initial_attempt`` claims the first attempt like a prepared one: the caller queued it
+ for a dispatch that the recovery sweep can also claim.
"""
organization_id = organization.organization_id
+ for lookup_attempt in range(1, WORKFLOW_ATTEMPT_LOOKUP_MAX_ATTEMPTS + 1):
+ try:
+ attempt_rows = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ break
+ except asyncio.CancelledError:
+ raise
+ except Exception as error:
+ if lookup_attempt == WORKFLOW_ATTEMPT_LOOKUP_MAX_ATTEMPTS:
+ raise WorkflowRetryAttemptLookupError(
+ f"Failed to load workflow retry attempts after {lookup_attempt} attempts "
+ f"for {workflow_run_id}; execution was not started."
+ ) from error
+ delay_seconds = WORKFLOW_ATTEMPT_LOOKUP_RETRY_DELAY_SECONDS * lookup_attempt
+ LOG.warning(
+ "Failed to load workflow retry attempts; retrying before execution",
+ workflow_run_id=workflow_run_id,
+ lookup_attempt=lookup_attempt,
+ delay_seconds=delay_seconds,
+ exc_info=True,
+ )
+ await asyncio.sleep(delay_seconds)
+ if not attempt_rows:
+ if initialize_attempt is not None:
+ api_key = await initialize_attempt(browser_session_id)
+ if api_key is None:
+ return await self.get_workflow_run(workflow_run_id, organization_id)
+ if on_execution_start is not None:
+ on_execution_start()
+ return await self.execute_workflow(
+ workflow_run_id=workflow_run_id,
+ api_key=api_key,
+ organization=organization,
+ block_labels=block_labels,
+ block_outputs=block_outputs,
+ browser_session_id=browser_session_id,
+ need_call_webhook=need_call_webhook,
+ workflow_override=workflow_override,
+ requested_completion_contract=requested_completion_contract,
+ attempt_number=attempt_number,
+ )
- LOG.info(
- "Executing workflow",
- workflow_run_id=workflow_run_id,
- organization_id=organization_id,
- browser_session_id=browser_session_id,
- block_labels=block_labels,
- block_outputs=block_outputs,
- )
- workflow_run = await self.get_workflow_run(workflow_run_id=workflow_run_id, organization_id=organization_id)
+ if block_labels or block_outputs:
+ await app.DATABASE.workflow_run_attempts.mark_attempt_inputs_unrecoverable(workflow_run_id, attempt_number)
- # Guard: if the run was canceled while queued (before Temporal picked it up), don't
- # overwrite the canceled status with running. Checked BEFORE workflow resolution so a run
- # whose stamped workflow version was deleted after cancellation does not raise
- # WorkflowNotFound on a late worker pickup.
+ retry_gate_run: WorkflowRun | None = None
+ if attempt_number > 1:
+ recovered_run = await self.get_workflow_run(workflow_run_id, organization_id)
+ serialized_identity = bool(
+ (recovered_run.browser_session_id and not recovered_run.debug_session_id)
+ or recovered_run.browser_address
+ or recovered_run.sequential_credential_id
+ or recovered_run.sequential_key
+ or recovered_run.depends_on_workflow_run_id
+ or (recovered_run.reuse_bound_key and not is_reuse_admission_off(recovered_run.reuse_bound_key))
+ )
+ if not serialized_identity:
+ workflow = await self.get_workflow_by_workflow_run_id(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ filter_deleted=False,
+ )
+ serialized_identity = bool(
+ workflow.run_sequentially
+ or (
+ not recovered_run.start_fresh_browser
+ and resolve_reuse_browser_session(
+ run_override=recovered_run.reuse_browser_session,
+ workflow_default=workflow.reuse_browser_session,
+ )
+ )
+ )
+ if serialized_identity:
+ retry_gate_run = recovered_run
+ while True:
+ if retry_gate_run is not None:
+ try:
+ stopped_run = await self._wait_for_retry_sequential_clearance(retry_gate_run, attempt_number)
+ except asyncio.CancelledError:
+ # Only shutdown cancels this owner; the prepared attempt stays queued for recovery.
+ LOG.info(
+ "Workflow retry owner stopped while waiting for sequential clearance; leaving the attempt for recovery",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ )
+ raise
+ if stopped_run is not None:
+ final_decision = await finalize_abandoned_attempt(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ reason="sequential_gate_stopped",
+ status=stopped_run.status,
+ failure_reason=stopped_run.failure_reason,
+ finished_at=stopped_run.finished_at,
+ attempt_number=attempt_number,
+ )
+ await self._run_terminal_side_effects_with_retries(stopped_run, final_decision, api_key=api_key)
+ return stopped_run
+ retry_gate_run = None
+ if not prepared_attempt_claimed and (attempt_number > 1 or claim_initial_attempt):
+ claimed = await app.DATABASE.workflow_run_attempts.claim_prepared_attempt_execution(
+ workflow_run_id, organization_id, attempt_number
+ )
+ if not claimed:
+ LOG.info(
+ "Workflow attempt is owned by another dispatch; skipping execution",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ )
+ return await self.get_workflow_run(workflow_run_id, organization_id)
+ dispatch_claim_started_at = claimed
+ if attempt_number > 1:
+ current_context = skyvern_context.current()
+ if current_context and current_context.browser_session_runnable_id == workflow_run_id:
+ # A pinned session survives retries, but its released ownership generation does not.
+ current_context.browser_session_runnable_id = None
+ current_context.browser_session_runnable_generation_id = None
+ prepared_attempt_claimed = False
+ with skyvern_context.workflow_log_attempt(workflow_run_id, attempt_number):
+ try:
+ if on_execution_start is not None:
+ on_execution_start()
+ if initialize_attempt is not None:
+ api_key = await initialize_attempt(browser_session_id)
+ if initialize_attempt is not None and api_key is None:
+ workflow_run = await self.get_workflow_run(workflow_run_id, organization_id)
+ if not workflow_run.status.is_final():
+ return workflow_run
+ else:
+ workflow_run = await self.execute_workflow(
+ workflow_run_id=workflow_run_id,
+ api_key=api_key,
+ organization=organization,
+ block_labels=block_labels,
+ block_outputs=block_outputs,
+ browser_session_id=browser_session_id,
+ need_call_webhook=False,
+ workflow_override=workflow_override,
+ requested_completion_contract=requested_completion_contract,
+ attempt_number=attempt_number,
+ dispatch_claim_started_at=dispatch_claim_started_at,
+ )
+ except asyncio.CancelledError:
+ raise
+ except WorkflowAttemptDispatchSuperseded:
+ LOG.warning(
+ "Workflow attempt dispatch was superseded; leaving the attempt to its new owner",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ )
+ return await self.get_workflow_run(workflow_run_id, organization_id)
+ except Exception as error:
+ LOG.exception(
+ "Workflow attempt raised; releasing retry-policy terminal effects",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ )
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ )
+ if workflow_run is None:
+ raise
+
+ if not workflow_run.status.is_final():
+ failed_workflow_run = await self.mark_workflow_run_as_failed_if_not_final(
+ workflow_run_id=workflow_run_id,
+ failure_reason=str(error),
+ cascade_children=True,
+ )
+ if failed_workflow_run is not None:
+ workflow_run = failed_workflow_run
+ else:
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ )
+ if workflow_run is None:
+ raise
+
+ decision = await get_recorded_decision(workflow_run_id, attempt_number=attempt_number)
+ if decision is None:
+ decision = await on_terminal_transition(
+ workflow_run,
+ workflow_run.status,
+ workflow_run.failure_reason,
+ workflow_run.failure_category,
+ attempt_number=attempt_number,
+ )
+ if not decision.retry:
+ await self._run_terminal_side_effects_with_retries(workflow_run, decision, api_key=api_key)
+ raise
+
+ try:
+ terminal_effects_outcome = await self._run_interim_side_effects_with_retries(
+ workflow_run,
+ decision,
+ api_key=api_key,
+ )
+ if terminal_effects_outcome in {
+ "lease_held_by_other_young",
+ "fenced_out",
+ }:
+ return workflow_run
+ if terminal_effects_outcome == "effect_failed":
+ LOG.warning(
+ "Continuing workflow retry after interim delivery failed; recovery will retry delivery",
+ workflow_run_id=workflow_run_id,
+ attempt_number=decision.attempt_number,
+ )
+ await asyncio.sleep(remaining_retry_delay_seconds(decision))
+ preparation = await self._prepare_recorded_retry(workflow_run_id, organization_id, decision)
+ if preparation is None:
+ return workflow_run
+ if preparation.status == "inserted":
+ attempt_number = decision.attempt_number + 1
+ browser_session_id = preparation.pinned_browser_session_id
+ if preparation.serialized_identity or workflow_run.depends_on_workflow_run_id:
+ retry_gate_run = workflow_run
+ continue
+ if preparation.status == "already_prepared":
+ return workflow_run
+
+ final_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ )
+ if final_run is None:
+ raise
+ final_decision = await finalize_abandoned_attempt(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ reason="prepare_cas_failed",
+ status=final_run.status,
+ failure_reason=final_run.failure_reason,
+ finished_at=final_run.finished_at,
+ attempt_number=decision.attempt_number,
+ )
+ await self._run_terminal_side_effects_with_retries(final_run, final_decision, api_key=api_key)
+ return final_run
+ except asyncio.CancelledError:
+ LOG.info(
+ "Workflow retry owner stopped before preparing the next attempt; leaving the retry for recovery",
+ workflow_run_id=workflow_run_id,
+ attempt_number=decision.attempt_number,
+ )
+ raise
+
+ refreshed_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ )
+ if refreshed_run is not None:
+ workflow_run = refreshed_run
+
+ decision = await get_recorded_decision(workflow_run_id, attempt_number=attempt_number)
+ if decision is None:
+ decision = await on_terminal_transition(
+ workflow_run,
+ workflow_run.status,
+ workflow_run.failure_reason,
+ workflow_run.failure_category,
+ attempt_number=attempt_number,
+ )
+ if not decision.retry:
+ await self._run_terminal_side_effects_with_retries(workflow_run, decision, api_key=api_key)
+ return workflow_run
+
+ try:
+ terminal_effects_outcome = await self._run_interim_side_effects_with_retries(
+ workflow_run,
+ decision,
+ api_key=api_key,
+ )
+ if terminal_effects_outcome in {
+ "lease_held_by_other_young",
+ "fenced_out",
+ }:
+ return workflow_run
+ if terminal_effects_outcome == "effect_failed":
+ LOG.warning(
+ "Continuing workflow retry after interim delivery failed; recovery will retry delivery",
+ workflow_run_id=workflow_run_id,
+ attempt_number=decision.attempt_number,
+ )
+ await asyncio.sleep(remaining_retry_delay_seconds(decision))
+ preparation = await self._prepare_recorded_retry(workflow_run_id, organization_id, decision)
+ if preparation is None:
+ return workflow_run
+ if preparation.status == "inserted":
+ attempt_number = decision.attempt_number + 1
+ browser_session_id = preparation.pinned_browser_session_id
+ if preparation.serialized_identity or workflow_run.depends_on_workflow_run_id:
+ retry_gate_run = workflow_run
+ continue
+ if preparation.status == "already_prepared":
+ return workflow_run
+
+ final_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ )
+ if final_run is None:
+ return workflow_run
+ final_decision = await finalize_abandoned_attempt(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ reason="prepare_cas_failed",
+ status=final_run.status,
+ failure_reason=final_run.failure_reason,
+ finished_at=final_run.finished_at,
+ attempt_number=decision.attempt_number,
+ )
+ await self._run_terminal_side_effects_with_retries(final_run, final_decision, api_key=api_key)
+ return final_run
+ except asyncio.CancelledError:
+ LOG.info(
+ "Workflow retry owner stopped before preparing the next attempt; leaving the retry for recovery",
+ workflow_run_id=workflow_run_id,
+ attempt_number=decision.attempt_number,
+ )
+ raise
+
+ @traced(name="skyvern.workflow.execute", role="wrapper")
+ async def execute_workflow(
+ self,
+ workflow_run_id: str,
+ api_key: str | None,
+ organization: Organization,
+ block_labels: list[str] | None = None,
+ block_outputs: dict[str, Any] | None = None,
+ browser_session_id: str | None = None,
+ need_call_webhook: bool = True,
+ workflow_override: Workflow | None = None,
+ requested_completion_contract: dict[str, Any] | None = None,
+ attempt_number: int = 1,
+ dispatch_claim_started_at: datetime | None = None,
+ ) -> WorkflowRun:
+ """Execute a workflow.
+
+ When the workflow_run row has ``ignore_inherited_workflow_system_prompt``
+ set (populated at spawn time by a ``WorkflowTriggerBlock`` whose
+ ``ignore_workflow_system_prompt`` flag is True), the child workflow
+ starts with a clean slate — no inherited prompt from the ancestor
+ chain. Persisting the intent on the row means the flag is honored for
+ both sync and async (Temporal-dispatched) trigger modes.
+ """
+ organization_id = organization.organization_id
+
+ LOG.info(
+ "Executing workflow",
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ browser_session_id=browser_session_id,
+ block_labels=block_labels,
+ block_outputs=block_outputs,
+ )
+ workflow_run = await self.get_workflow_run(workflow_run_id=workflow_run_id, organization_id=organization_id)
+
+ # Guard: if the run was canceled while queued (before Temporal picked it up), don't
+ # overwrite the canceled status with running. Checked BEFORE workflow resolution so a run
+ # whose stamped workflow version was deleted after cancellation does not raise
+ # WorkflowNotFound on a late worker pickup.
if workflow_run.status == WorkflowRunStatus.canceled:
LOG.info(
"Workflow run was canceled before execution started, skipping",
@@ -5000,7 +6049,11 @@ class WorkflowService:
# Resolve the exact version stamped on the run (run.workflow_id is always set), not the
# latest published version, so a publish between run creation and execution does not change
# what executes.
- workflow = workflow_override or await self.get_workflow(workflow_id=workflow_run.workflow_id)
+ workflow = workflow_override or await self.get_workflow_by_workflow_run_id(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ filter_deleted=False,
+ )
browser_profile_id = workflow_run.browser_profile_id
browser_session_id = browser_session_id or workflow_run.browser_session_id
close_browser_on_completion = browser_session_id is None and not workflow_run.browser_address
@@ -5025,6 +6078,7 @@ class WorkflowService:
browser_session_id=browser_session_id,
close_browser_on_completion=close_browser_on_completion,
need_call_webhook=need_call_webhook,
+ attempt_number=attempt_number,
)
return workflow_run
@@ -5056,6 +6110,7 @@ class WorkflowService:
browser_session_id=browser_session_id,
close_browser_on_completion=close_browser_on_completion,
need_call_webhook=need_call_webhook,
+ attempt_number=attempt_number,
)
return workflow_run
@@ -5083,6 +6138,7 @@ class WorkflowService:
browser_session_id=browser_session_id,
close_browser_on_completion=close_browser_on_completion,
need_call_webhook=need_call_webhook,
+ attempt_number=attempt_number,
)
return workflow_run
@@ -5098,6 +6154,37 @@ class WorkflowService:
current_status=workflow_run.status,
)
return workflow_run
+ if not await mark_attempt_started(workflow_run_id, attempt_number):
+ attempt_rows = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ started_attempt = next((row for row in attempt_rows if row.attempt_number == attempt_number), None)
+ # A re-entered activity finds started_at already set and continues. A finalized row means a
+ # cancel won between the run's running write and this one, so the run must not act after it.
+ if started_attempt is not None and started_attempt.retry_decision is not None:
+ LOG.info(
+ "execute_workflow aborting: attempt finalized before it started",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ retry_decision=started_attempt.retry_decision,
+ )
+ return (
+ await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=workflow_run_id, organization_id=organization_id
+ )
+ or workflow_run
+ )
+ # A claim stamp that no longer matches the row was released as stale and re-issued to
+ # another dispatch, which now owns this attempt.
+ if (
+ started_attempt is not None
+ and dispatch_claim_started_at is not None
+ and to_naive_utc(started_attempt.started_at) != to_naive_utc(dispatch_claim_started_at)
+ ):
+ LOG.warning(
+ "execute_workflow aborting: the attempt's dispatch claim was replaced",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ )
+ raise WorkflowAttemptDispatchSuperseded(workflow_run_id, attempt_number)
# Get all context parameters from the workflow definition
context_parameters = [
@@ -5140,6 +6227,24 @@ class WorkflowService:
)
)
try:
+ if attempt_number > 1 and workflow_run.browser_seed_source is None:
+ parameter_values = {parameter.key: run_parameter.value for parameter, run_parameter in wp_wps_tuples}
+ parameter_values.update(
+ await self._select_rotating_credential_parameters_for_render(
+ workflow=workflow,
+ workflow_run=workflow_run,
+ organization_id=organization_id,
+ parameter_values=parameter_values,
+ )
+ )
+ workflow_run = await self._resolve_and_stamp_run_seed(
+ workflow=workflow,
+ workflow_run=workflow_run,
+ parameter_values=parameter_values,
+ explicit_request_browser_profile_id=browser_profile_id,
+ start_fresh=resolve_start_fresh(workflow_run.start_fresh_browser, browser_profile_id),
+ )
+ browser_profile_id = workflow_run.browser_profile_id
await app.WORKFLOW_CONTEXT_MANAGER.initialize_workflow_run_context(
organization,
workflow_run_id,
@@ -5154,6 +6259,7 @@ class WorkflowService:
workflow,
inherited_workflow_system_prompt=inherited_workflow_system_prompt,
mask_secrets=getattr(workflow, "mask_secrets", False),
+ attempt_number=attempt_number,
)
except Exception as e:
LOG.exception(
@@ -5174,6 +6280,7 @@ class WorkflowService:
browser_session_id=browser_session_id,
close_browser_on_completion=close_browser_on_completion,
need_call_webhook=need_call_webhook,
+ attempt_number=attempt_number,
)
return workflow_run
@@ -5213,6 +6320,7 @@ class WorkflowService:
browser_session_id=browser_session_id,
close_browser_on_completion=False,
need_call_webhook=need_call_webhook,
+ attempt_number=attempt_number,
)
return workflow_run
@@ -5284,6 +6392,7 @@ class WorkflowService:
browser_session_id=browser_session_id,
close_browser_on_completion=close_browser_on_completion,
need_call_webhook=need_call_webhook,
+ attempt_number=attempt_number,
)
return workflow_run
# Start background task to periodically renew the browser session
@@ -5693,6 +6802,7 @@ class WorkflowService:
self._finalize_workflow_run_status(
workflow_run_id=workflow_run_id,
workflow_run=workflow_run,
+ workflow=workflow,
is_partial_run=run_selection_is_partial(workflow, block_labels),
requested_completion_contract=requested_completion_contract,
pre_finally_status=pre_finally_status,
@@ -5796,6 +6906,7 @@ class WorkflowService:
browser_session_id=browser_session_id,
close_browser_on_completion=close_browser_on_completion,
need_call_webhook=need_call_webhook,
+ attempt_number=attempt_number,
browser_cleanup_result=browser_cleanup_result,
browser_persistence_status=browser_persistence_status,
skip_browser_session_write_back=browser_write_back_exhausted,
@@ -7879,6 +8990,12 @@ class WorkflowService:
if workflow_run_context:
return await workflow_run_context.resolve_credential_parameter_id(parameter, organization_id)
+ selected = await app.DATABASE.workflow_run_credential_selections.get_selection(
+ workflow_run_id=workflow_run_id,
+ parameter_key=parameter.key,
+ )
+ if selected is not None:
+ return selected
if parameter.credential_ids:
return await select_credential_for_run(
workflow_run_id=workflow_run_id,
@@ -7888,12 +9005,6 @@ class WorkflowService:
credential_ids=parameter.credential_ids,
selection_strategy=parameter.selection_strategy,
)
- if parameter.fallback_credential_ids:
- selected = await app.DATABASE.workflow_run_credential_selections.get_selection(
- workflow_run_id=workflow_run_id,
- parameter_key=parameter.key,
- )
- return selected or parameter.credential_id
return parameter.credential_id
async def _apply_login_block_credential_proxy_pin(
@@ -9351,7 +10462,7 @@ class WorkflowService:
search_key: str | None = None,
error_code: str | None = None,
) -> list[WorkflowRun]:
- return await app.DATABASE.workflow_runs.get_workflow_runs(
+ workflow_runs = await app.DATABASE.workflow_runs.get_workflow_runs(
organization_id=organization_id,
page=page,
page_size=page_size,
@@ -9360,6 +10471,24 @@ class WorkflowService:
search_key=search_key,
error_code=error_code,
)
+ return await self._attach_latest_attempt_views(workflow_runs)
+
+ async def _attach_latest_attempt_views(self, workflow_runs: list[WorkflowRun]) -> list[WorkflowRun]:
+ for workflow_run in workflow_runs:
+ workflow_run.attempts = []
+ workflow_run_ids = [workflow_run.workflow_run_id for workflow_run in workflow_runs]
+ if not workflow_run_ids:
+ return workflow_runs
+ latest_attempts = await app.DATABASE.workflow_run_attempts.get_latest_attempts_for_runs(workflow_run_ids)
+ for workflow_run in workflow_runs:
+ latest_attempt = latest_attempts.get(workflow_run.workflow_run_id)
+ if latest_attempt is None:
+ continue
+ attempt_view = compute_attempt_view(workflow_run, [latest_attempt])
+ workflow_run.attempt = attempt_view.attempt
+ workflow_run.retry_pending = attempt_view.retry_pending
+ workflow_run.next_attempt_at = attempt_view.next_attempt_at
+ return workflow_runs
async def get_workflow_runs_count(
self,
@@ -9385,7 +10514,7 @@ class WorkflowService:
created_at_end: datetime | None = None,
run_tags: Sequence[tuple[str | None, str | None]] | None = None,
) -> list[WorkflowRun]:
- return await app.DATABASE.workflow_runs.get_workflow_runs_for_workflow_permanent_id(
+ workflow_runs = await app.DATABASE.workflow_runs.get_workflow_runs_for_workflow_permanent_id(
workflow_permanent_id=workflow_permanent_id,
organization_id=organization_id,
page=page,
@@ -9398,6 +10527,7 @@ class WorkflowService:
created_at_end=created_at_end,
run_tags=run_tags,
)
+ return await self._attach_latest_attempt_views(workflow_runs)
async def get_workflow_runs_for_browser_session(
self,
@@ -9406,12 +10536,13 @@ class WorkflowService:
page: int = 1,
page_size: int = 10,
) -> list[WorkflowRun]:
- return await app.DATABASE.workflow_runs.get_workflow_runs_for_browser_session(
+ workflow_runs = await app.DATABASE.workflow_runs.get_workflow_runs_for_browser_session(
browser_session_id=browser_session_id,
organization_id=organization_id,
page=page,
page_size=page_size,
)
+ return await self._attach_latest_attempt_views(workflow_runs)
async def create_workflow_run(
self,
@@ -9431,7 +10562,10 @@ class WorkflowService:
fallback_attempt: int | None = None,
ignore_inherited_workflow_system_prompt: bool = False,
copilot_session_id: str | None = None,
+ workflow: Workflow | None = None,
+ block_scoped: bool = False,
) -> WorkflowRun:
+ requested_browser_session_id = workflow_request.browser_session_id
# validate the browser session or profile id
browser_profile_id = workflow_request.browser_profile_id
if workflow_request.browser_session_id:
@@ -9474,12 +10608,12 @@ class WorkflowService:
# admission decision is authoritative: later flag changes stop new runs but never revoke an
# in-flight run or strip the forced-session fallback that was selected at admission.
browser_session_id = workflow_request.browser_session_id
- workflow: Workflow | None = None
will_acquire_reused_session = False
persisted_reuse_bound_key: str | None = None
persisted_reuse_browser_session = workflow_request.reuse_browser_session
if not browser_session_id:
- workflow = await self.get_workflow(workflow_id=workflow_id)
+ if workflow is None:
+ workflow = await self.get_workflow(workflow_id=workflow_id)
configured_reuse = should_acquire_reused_session(
browser_session_id=None,
start_fresh_browser=workflow_request.start_fresh_browser,
@@ -9551,6 +10685,16 @@ class WorkflowService:
ignore_inherited_workflow_system_prompt=ignore_inherited_workflow_system_prompt,
copilot_session_id=copilot_session_id,
)
+ # A block run creates its block-run rows only after setup, so the caller's intent
+ # is the only block-scoped signal enrolment can see here.
+ has_attempt_row = False
+ if not block_scoped:
+ has_attempt_row = await ensure_attempt_row(
+ workflow_run=workflow_run,
+ requested_browser_session_id=requested_browser_session_id,
+ organization_id=organization_id,
+ workflow=workflow,
+ )
LOG.info(
"Force-creating browser session for workflow run",
workflow_permanent_id=workflow_permanent_id,
@@ -9632,12 +10776,6 @@ class WorkflowService:
**browser_type_kwargs,
)
browser_session_id = browser_session.persistent_browser_session_id
- LOG.info(
- "Browser session created for workflow run",
- workflow_permanent_id=workflow_permanent_id,
- workflow_run_id=workflow_run.workflow_run_id,
- browser_session_id=browser_session_id,
- )
workflow_run = await app.DATABASE.workflow_runs.update_workflow_run(
workflow_run_id=workflow_run.workflow_run_id,
browser_session_id=browser_session_id,
@@ -9651,10 +10789,74 @@ class WorkflowService:
organization_id=organization_id,
exc_info=True,
)
+ else:
+ # The run row cannot distinguish forced sessions from sessions leased during
+ # execution. Require its retry pin before setup can return the assigned run.
+ if has_attempt_row:
+ for pin_attempt in range(2):
+ try:
+ await app.DATABASE.workflow_run_attempts.pin_first_attempt_browser_session_if_unset(
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=organization_id,
+ browser_session_id=browser_session_id,
+ )
+ break
+ except Exception:
+ if pin_attempt == 0:
+ LOG.warning(
+ "Retrying failed forced browser session pin",
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=organization_id,
+ browser_session_id=browser_session_id,
+ exc_info=True,
+ )
+ continue
+ failure_reason = "Failed to pin forced browser session for workflow retry"
+ LOG.exception(
+ failure_reason,
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=organization_id,
+ browser_session_id=browser_session_id,
+ )
+ try:
+ await finalize_abandoned_attempt(
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=organization_id,
+ attempt_number=1,
+ reason="forced_browser_session_pin_failed",
+ status=WorkflowRunStatus.failed,
+ failure_reason=failure_reason,
+ finished_at=datetime.now(UTC),
+ )
+ await self.mark_workflow_run_as_failed(
+ workflow_run.workflow_run_id, failure_reason=failure_reason
+ )
+ finally:
+ try:
+ await app.PERSISTENT_SESSIONS_MANAGER.close_session(
+ organization_id,
+ browser_session_id,
+ reason=BrowserSessionCloseReason.aborted,
+ )
+ except Exception:
+ with contained_effect("record forced browser session cleanup failure"):
+ LOG.warning(
+ "Failed to close forced browser session after pin failure",
+ workflow_run_id=workflow_run.workflow_run_id,
+ browser_session_id=browser_session_id,
+ exc_info=True,
+ )
+ raise
+ LOG.info(
+ "Browser session created for workflow run",
+ workflow_permanent_id=workflow_permanent_id,
+ workflow_run_id=workflow_run.workflow_run_id,
+ browser_session_id=browser_session_id,
+ )
return workflow_run
- return await app.DATABASE.workflow_runs.create_workflow_run(
+ workflow_run = await app.DATABASE.workflow_runs.create_workflow_run(
workflow_permanent_id=workflow_permanent_id,
workflow_id=workflow_id,
organization_id=organization_id,
@@ -9687,6 +10889,14 @@ class WorkflowService:
ignore_inherited_workflow_system_prompt=ignore_inherited_workflow_system_prompt,
copilot_session_id=copilot_session_id,
)
+ if not block_scoped:
+ await ensure_attempt_row(
+ workflow_run=workflow_run,
+ requested_browser_session_id=requested_browser_session_id,
+ organization_id=organization_id,
+ workflow=workflow,
+ )
+ return workflow_run
async def _cascade_child_entities_on_terminal(self, workflow_run_id: str, status: WorkflowRunStatus) -> None:
if status != WorkflowRunStatus.timed_out:
@@ -9756,52 +10966,819 @@ class WorkflowService:
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
- async def _update_workflow_run_status(
+ async def _run_workflow_run_terminal_hooks(
self,
+ *,
workflow_run_id: str,
+ workflow_id: str,
+ organization_id: str,
status: WorkflowRunStatus,
- failure_reason: str | None = None,
- run_with: str | None = None,
- ai_fallback: bool | None = None,
- failure_category: list[dict] | None = None,
- ) -> WorkflowRun:
- # Final transitions are claimed conditionally so run-minutes emit exactly once
- # per run even when a cancel and the run's own finalizer race; the loser still
- # performs the unconditional overwrite the finalizer has always done, silently.
- flipped_to_final = False
- workflow_run: WorkflowRun | None = None
- if status.is_final():
- workflow_run = await app.DATABASE.workflow_runs.update_workflow_run_if_not_final(
+ workflow_run: WorkflowRun,
+ ) -> None:
+ await app.AGENT_FUNCTION.on_workflow_run_completed(
+ organization_id=organization_id,
+ workflow_id=workflow_id,
+ workflow_run_id=workflow_run_id,
+ status=status,
+ workflow_run=workflow_run,
+ )
+
+ async def _side_effects_lease_is_current(
+ self,
+ *,
+ workflow_run_id: str,
+ attempt_number: int,
+ claim_at: datetime | None,
+ completion_kind: Literal["interim", "final"] = "final",
+ effect_bound_seconds: float = TERMINAL_SIDE_EFFECT_TIMEOUT_SECONDS,
+ ) -> bool:
+ if claim_at is None:
+ return True
+ expected_claim_at = to_naive_utc(claim_at)
+ assert expected_claim_at is not None
+ try:
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ except Exception:
+ LOG.warning(
+ "Failed to verify workflow terminal side-effect lease; fencing owner",
workflow_run_id=workflow_run_id,
- status=status,
- failure_reason=failure_reason,
- run_with=run_with,
- ai_fallback=ai_fallback,
- failure_category=failure_category,
+ attempt_number=attempt_number,
+ exc_info=True,
)
- flipped_to_final = workflow_run is not None
- if workflow_run is None:
- workflow_run = await app.DATABASE.workflow_runs.update_workflow_run(
+ return False
+ attempt = next((row for row in attempts if row.attempt_number == attempt_number), None)
+ current_claim_at = to_naive_utc(getattr(attempt, "side_effects_released_at", None))
+ if current_claim_at != expected_claim_at:
+ LOG.info(
+ "Workflow terminal side-effect owner fenced out",
workflow_run_id=workflow_run_id,
- status=status,
- failure_reason=failure_reason,
- run_with=run_with,
- ai_fallback=ai_fallback,
- failure_category=failure_category,
+ attempt_number=attempt_number,
)
- await self._after_workflow_run_status_write(workflow_run, status, emit_run_minutes=flipped_to_final)
- return workflow_run
+ return False
+ assert current_claim_at is not None
- async def _update_workflow_run_status_if_not_final(
- self,
- workflow_run_id: str,
- status: WorkflowRunStatus,
- failure_reason: str | None = None,
- run_with: str | None = None,
- failure_category: list[dict] | None = None,
- finalized_by: str | None = None,
- run_minutes_recorded_through: datetime | None = None,
- ) -> WorkflowRun | None:
+ completion_marker = getattr(
+ attempt,
+ "interim_webhook_sent_at" if completion_kind == "interim" else "webhook_sent_at",
+ None,
+ )
+ if completion_marker is not None:
+ LOG.info(
+ "Workflow terminal side-effect completion was already recorded",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ completion_kind=completion_kind,
+ )
+ return False
+
+ lease_age_seconds = (naive_utc_now() - current_claim_at).total_seconds()
+ recovery_deadline_seconds = LEASE_TAKEOVER_SECONDS - LEASE_SAFETY_MARGIN_SECONDS
+ if lease_age_seconds + effect_bound_seconds > recovery_deadline_seconds:
+ LOG.info(
+ "Workflow terminal side-effect lease cannot cover the next effect",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ lease_age_seconds=lease_age_seconds,
+ effect_bound_seconds=effect_bound_seconds,
+ recovery_deadline_seconds=recovery_deadline_seconds,
+ lease_safety_margin_seconds=LEASE_SAFETY_MARGIN_SECONDS,
+ )
+ return False
+
+ return True
+
+ async def _terminal_tail_owner_is_current(
+ self,
+ *,
+ workflow_run_id: str,
+ attempt_number: int,
+ claim_at: datetime | None,
+ completion_kind: Literal["interim", "final"] = "final",
+ ) -> bool:
+ """Freshly fence the once-only tail without refusing a merely old-but-current lease."""
+ expected_claim_at = to_naive_utc(claim_at)
+ try:
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ except Exception:
+ LOG.warning(
+ "Failed to verify workflow terminal tail owner; fencing owner",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ exc_info=True,
+ )
+ return False
+ attempt = next((row for row in attempts if row.attempt_number == attempt_number), None)
+ if attempt is None:
+ return False
+ completion_marker = getattr(
+ attempt,
+ "interim_webhook_sent_at" if completion_kind == "interim" else "webhook_sent_at",
+ None,
+ )
+ if completion_marker is not None:
+ return False
+ current_claim_at = to_naive_utc(getattr(attempt, "side_effects_released_at", None))
+ # The repository returns the issued token, but accepting a null token here preserves the
+ # legacy boolean test/fake seam: a fresh row with no replacement token is still the owner
+ # when the claim result did not expose one. A non-null token always has to match exactly.
+ return current_claim_at == expected_claim_at
+
+ async def _terminal_side_effect_outcome_after_fence(
+ self,
+ *,
+ workflow_run_id: str,
+ attempt_number: int,
+ claim_at: datetime | None,
+ completion_kind: Literal["interim", "final"],
+ claim_owned_by_this_invocation: bool = False,
+ ) -> TerminalSideEffectOutcome:
+ """Classify a failed fenced claim so Temporal can retry only a live foreign owner."""
+ try:
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ except Exception:
+ LOG.warning(
+ "Failed to classify fenced workflow terminal side effects",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ exc_info=True,
+ )
+ return "fenced_out"
+ attempt = next((row for row in attempts if row.attempt_number == attempt_number), None)
+ if attempt is None:
+ return "fenced_out"
+ completion_marker = getattr(
+ attempt,
+ "interim_webhook_sent_at" if completion_kind == "interim" else "webhook_sent_at",
+ None,
+ )
+ if completion_marker is not None:
+ return "already_released"
+
+ current_claim_at = to_naive_utc(getattr(attempt, "side_effects_released_at", None))
+ expected_claim_at = to_naive_utc(claim_at)
+ if current_claim_at == expected_claim_at:
+ if claim_owned_by_this_invocation:
+ return "fenced_out"
+ if current_claim_at is not None:
+ lease_age_seconds = (naive_utc_now() - current_claim_at).total_seconds()
+ if lease_age_seconds < LEASE_TAKEOVER_SECONDS:
+ return "lease_held_by_other_young"
+ return "fenced_out"
+ if current_claim_at is not None:
+ lease_age_seconds = (naive_utc_now() - current_claim_at).total_seconds()
+ if lease_age_seconds < LEASE_TAKEOVER_SECONDS:
+ return "lease_held_by_other_young"
+ return "fenced_out"
+
+ async def _workflow_webhook_fallback_is_current(
+ self,
+ *,
+ workflow_run_id: str,
+ attempt_number: int,
+ expected_claim_at: datetime | None,
+ ) -> bool:
+ """Re-read the attempt immediately before a claim-less fallback delivery.
+
+ The fallback has no service-side lease token of its own. It may only use the row it just
+ read when the completion marker is still empty and any existing lease is at least one full
+ terminal-release bound old; a changed token means another owner won the race.
+ """
+ try:
+ attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ except Exception:
+ LOG.warning(
+ "Failed to verify workflow webhook fallback lease; skipping delivery",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ exc_info=True,
+ )
+ return False
+ attempt = next((row for row in attempts if row.attempt_number == attempt_number), None)
+ if attempt is None:
+ return False
+ if getattr(attempt, "webhook_sent_at", None) is not None:
+ return False
+ current_claim_at = to_naive_utc(getattr(attempt, "side_effects_released_at", None))
+ normalized_expected_claim_at = to_naive_utc(expected_claim_at)
+ if normalized_expected_claim_at is not None and current_claim_at != normalized_expected_claim_at:
+ return False
+ if current_claim_at is None:
+ return True
+ return (naive_utc_now() - current_claim_at).total_seconds() >= LEASE_TAKEOVER_SECONDS
+
+ async def _run_fenced_terminal_side_effect(
+ self,
+ *,
+ workflow_run_id: str,
+ attempt_number: int,
+ claim_at: datetime | None,
+ effect_name: str,
+ effect: Callable[[], Awaitable[Any]],
+ completion_kind: Literal["interim", "final"] = "final",
+ heartbeat: Callable[..., Any] | None = None,
+ timeout_seconds: float = TERMINAL_SIDE_EFFECT_TIMEOUT_SECONDS,
+ check_lease: bool = True,
+ ) -> bool | Literal["effect_failed"]:
+ if check_lease and not await self._side_effects_lease_is_current(
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=claim_at,
+ completion_kind=completion_kind,
+ effect_bound_seconds=timeout_seconds,
+ ):
+ return False
+ try:
+ async with asyncio.timeout(timeout_seconds):
+ await effect()
+ except TimeoutError:
+ if effect_name in {"final workflow webhook", "interim workflow webhook"}:
+ LOG.warning(
+ "Workflow webhook timed out; leaving delivery pending",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ exc_info=True,
+ )
+ return "effect_failed"
+ # The delivery layer has its own bounded retry window. Preserve the historical
+ # best-effort treatment of an exhausted effect timeout and let the next effect run.
+ LOG.warning(
+ "Workflow terminal side effect timed out; continuing to the next effect",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ effect=effect_name,
+ timeout_seconds=timeout_seconds,
+ exc_info=True,
+ )
+ except Exception:
+ LOG.warning(
+ "Workflow terminal side effect failed; stopping the release",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ effect=effect_name,
+ exc_info=True,
+ )
+ return "effect_failed"
+ if heartbeat is not None:
+ try:
+ heartbeat()
+ except Exception:
+ LOG.warning(
+ "Failed to heartbeat between workflow terminal side effects",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ effect=effect_name,
+ exc_info=True,
+ )
+ return True
+
+ async def _clear_failed_interim_side_effect_lease(
+ self,
+ *,
+ workflow_run_id: str,
+ attempt_number: int,
+ claim_at: datetime | None,
+ ) -> None:
+ if claim_at is None:
+ return
+ clear_lease = getattr(
+ app.DATABASE.workflow_run_attempts,
+ "clear_failed_interim_side_effect_lease",
+ None,
+ )
+ if clear_lease is None:
+ return
+ try:
+ await clear_lease(workflow_run_id, attempt_number, claim_at)
+ except Exception:
+ # Keep the lease when the cleanup CAS itself fails. Recovery will retry after the
+ # normal takeover bound instead of risking two interim release owners.
+ LOG.warning(
+ "Failed to clear failed interim workflow terminal side-effect lease",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ exc_info=True,
+ )
+
+ async def _run_interim_side_effects_with_retries(
+ self,
+ workflow_run: WorkflowRun,
+ decision: RetryDecision,
+ *,
+ api_key: str | None = None,
+ side_effects_claim_at: datetime | None = None,
+ heartbeat: Callable[..., Any] | None = None,
+ ) -> TerminalSideEffectOutcome:
+ """Retry a failed OSS interim release without preparing its next attempt.
+
+ An interim failure clears only the failed lease, so this same delayed-retry owner can
+ make a bounded number of fresh claims. A final-release failure keeps its lease and is
+ handled by the takeover/recovery path instead.
+ """
+ if not decision.retry:
+ raise ValueError("Interim terminal side effects require a retry decision")
+
+ return await self._run_terminal_side_effects_with_retries(
+ workflow_run,
+ decision,
+ api_key=api_key,
+ side_effects_claim_at=side_effects_claim_at,
+ heartbeat=heartbeat,
+ )
+
+ async def _run_terminal_side_effects_with_retries(
+ self,
+ workflow_run: WorkflowRun,
+ decision: RetryDecision,
+ *,
+ api_key: str | None | object = _UNSET,
+ side_effects_claim_at: datetime | None = None,
+ side_effects_stale_before: datetime | None = None,
+ heartbeat: Callable[..., Any] | None = None,
+ ) -> TerminalSideEffectOutcome:
+ """Retry from the failed effect using durable progress and this invocation's acquired claim."""
+ progress = TerminalSideEffectProgress()
+ outcome: TerminalSideEffectOutcome = "effect_failed"
+ for retry_number in range(TERMINAL_RELEASE_RETRY_MAX_ATTEMPTS):
+ call_kwargs: dict[str, Any] = {"progress": progress}
+ if api_key is not _UNSET:
+ call_kwargs["api_key"] = cast(str | None, api_key)
+ if retry_number == 0:
+ if side_effects_claim_at is not None:
+ call_kwargs["side_effects_claim_at"] = side_effects_claim_at
+ if side_effects_stale_before is not None:
+ call_kwargs["side_effects_stale_before"] = side_effects_stale_before
+ elif progress.claim_at is not None and not decision.retry:
+ call_kwargs["side_effects_claim_at"] = progress.claim_at
+ call_kwargs["side_effects_stale_before"] = naive_utc_now()
+ if heartbeat is not None:
+ call_kwargs["heartbeat"] = heartbeat
+
+ outcome = await self.run_terminal_side_effects(workflow_run, decision, **call_kwargs)
+ if outcome != "effect_failed" or progress.final_hook_failed:
+ return outcome
+
+ LOG.warning(
+ "Workflow terminal side-effect release exhausted in-process retries",
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=decision.attempt_number,
+ outcome=outcome,
+ max_attempts=TERMINAL_RELEASE_RETRY_MAX_ATTEMPTS,
+ )
+ return outcome
+
+ async def run_terminal_side_effects(
+ self,
+ workflow_run: WorkflowRun,
+ decision: RetryDecision | None,
+ api_key: str | None = None,
+ side_effects_claim_at: datetime | None = None,
+ side_effects_stale_before: datetime | None = None,
+ heartbeat: Callable[..., Any] | None = None,
+ progress: TerminalSideEffectProgress | None = None,
+ ) -> TerminalSideEffectOutcome:
+ if progress is None:
+ progress = TerminalSideEffectProgress()
+ attempt_rows = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run.workflow_run_id)
+ attempt_number = (
+ decision.attempt_number
+ if decision is not None
+ else max((attempt.attempt_number for attempt in attempt_rows), default=1)
+ )
+ policy_attempt = bool(attempt_rows)
+ # Keep the no-policy path's release decision and fire-and-forget effects unchanged. Policy
+ # attempts use the durable claim below even for interim webhook decisions.
+ claimed_terminal_side_effects = (decision is None or not decision.retry) if not policy_attempt else False
+ claim_owned_by_this_invocation = False
+ attempt_revoked = False
+ if policy_attempt:
+ # The same claim gates all policy-attempt side effects, including an interim webhook.
+ # A retry that is later abandoned clears this claim before its final release. A
+ # recovery caller may pass the old timestamp so the repository can re-acquire an
+ # expired lease with a compare-and-set update.
+ claim_kwargs: dict[str, Any] = {}
+ if decision is not None and decision.retry:
+ claim_kwargs["kind"] = "interim"
+ target_attempt = next(
+ (row for row in attempt_rows if row.attempt_number == attempt_number),
+ None,
+ )
+ target_retry_decision = getattr(target_attempt, "retry_decision", None)
+ attempt_revoked = target_retry_decision == RETRY_DECISION_REVOKED
+ if decision is not None and decision.retry:
+ expected_retry_decision = RETRY_DECISION_RETRY
+ elif target_attempt is not None and hasattr(target_attempt, "retry_decision"):
+ expected_retry_decision = (
+ target_retry_decision
+ if target_retry_decision
+ in {
+ RETRY_DECISION_FINAL,
+ RETRY_DECISION_REVOKED,
+ RETRY_DECISION_ABANDONED,
+ }
+ else RETRY_DECISION_FINAL
+ )
+ else:
+ expected_retry_decision = None
+ if expected_retry_decision is not None:
+ claim_kwargs["expected_retry_decision"] = expected_retry_decision
+ if side_effects_claim_at is not None:
+ claim_kwargs.update(
+ {
+ "expected_claim_at": side_effects_claim_at,
+ "stale_before": side_effects_stale_before
+ or naive_utc_now() - timedelta(seconds=LEASE_TAKEOVER_SECONDS),
+ }
+ )
+ claim_result = await app.DATABASE.workflow_run_attempts.claim_attempt_side_effects(
+ workflow_run.workflow_run_id,
+ attempt_number,
+ **claim_kwargs,
+ )
+ claimed_terminal_side_effects = bool(claim_result)
+ claim_owned_by_this_invocation = claimed_terminal_side_effects
+ if isinstance(claim_result, datetime):
+ # The value written by the successful CAS is the fencing token. A recovery caller
+ # passes the old token, but all following effects must use this newly-issued one.
+ side_effects_claim_at = claim_result
+ progress.claim_at = claim_result
+ # Read after claiming: the previous owner could checkpoint between our first read
+ # and the takeover, but cannot write progress under the newly issued token.
+ claimed_rows = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run.workflow_run_id)
+ claimed_attempt = next((row for row in claimed_rows if row.attempt_number == attempt_number), None)
+ progress_column = (
+ "interim_side_effects_progress"
+ if decision is not None and decision.retry
+ else "final_side_effects_progress"
+ )
+ checkpoint = getattr(claimed_attempt, progress_column, None) or {}
+ progress.completed_effects = set(checkpoint.get("completed_effects", []))
+ progress.final_hook_invoked = checkpoint.get("final_hook_invoked", False)
+
+ if not claimed_terminal_side_effects:
+ return await self._terminal_side_effect_outcome_after_fence(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ completion_kind="interim" if decision is not None and decision.retry else "final",
+ claim_owned_by_this_invocation=claim_owned_by_this_invocation,
+ )
+
+ if claimed_terminal_side_effects:
+ is_final_decision = decision is None or not decision.retry
+ if policy_attempt:
+ # Policy-run effects are part of the lease-protected sequence. A stale takeover
+ # changes the row timestamp, so the old owner stops before its next effect.
+ async def handle_fenced_effect_result(
+ result: bool | Literal["effect_failed"],
+ completion_kind: Literal["interim", "final"],
+ ) -> TerminalSideEffectOutcome | None:
+ if result == "effect_failed":
+ if decision is not None and decision.retry:
+ await self._clear_failed_interim_side_effect_lease(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ )
+ return "effect_failed"
+ if result:
+ return None
+ return await self._terminal_side_effect_outcome_after_fence(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ completion_kind=completion_kind,
+ claim_owned_by_this_invocation=claim_owned_by_this_invocation,
+ )
+
+ async def save_progress() -> bool:
+ assert progress is not None
+ if side_effects_claim_at is None:
+ return True
+ return await app.DATABASE.workflow_run_attempts.save_side_effect_progress(
+ workflow_run.workflow_run_id,
+ attempt_number,
+ kind="final" if is_final_decision else "interim",
+ expected_claim_at=side_effects_claim_at,
+ progress={
+ "completed_effects": sorted(progress.completed_effects),
+ "final_hook_invoked": progress.final_hook_invoked,
+ },
+ )
+
+ async def run_effect_once(**kwargs: Any) -> bool | Literal["effect_failed"]:
+ assert progress is not None
+ effect_name = kwargs["effect_name"]
+ if effect_name in progress.completed_effects:
+ return True
+ if effect_name == "workflow final hook":
+ if progress.final_hook_invoked:
+ return True
+ # Checkpoint before invocation: an uncertain hook outcome must never be
+ # invoked again, even if this process dies before recording completion.
+ progress.final_hook_invoked = True
+ if not await save_progress():
+ return False
+ if not await self._terminal_tail_owner_is_current(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ ):
+ return False
+ result = await self._run_fenced_terminal_side_effect(**kwargs)
+ if result is True:
+ progress.completed_effects.add(effect_name)
+ if not await save_progress():
+ return False
+ elif result == "effect_failed" and effect_name == "workflow final hook":
+ progress.final_hook_failed = True
+ return result
+
+ if is_final_decision:
+ effect_result = await run_effect_once(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ effect_name="delete run attachments",
+ effect=lambda: uploaded_file_service.delete_files_attached_to_run(
+ run_id=workflow_run.workflow_run_id,
+ timeout_seconds=TERMINAL_SIDE_EFFECT_TIMEOUT_SECONDS,
+ ),
+ heartbeat=heartbeat,
+ )
+ effect_outcome = await handle_fenced_effect_result(effect_result, "final")
+ if effect_outcome is not None:
+ return effect_outcome
+
+ async def start_credential_fallback_unless_canceled() -> None:
+ # A revoked attempt is a user cancel during the retry delay. The run keeps
+ # the last attempt's failed status, so the fallback's own status gate would
+ # start a new run under another credential right after the cancel.
+ if attempt_revoked:
+ return
+ await self._start_credential_fallback_retry_best_effort(workflow_run)
+
+ # These effects are idempotent and must run before the once-only tail. A
+ # recovery restart may repeat them safely after an owner is fenced out.
+ effect_result = await run_effect_once(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ effect_name="credential fallback retry",
+ effect=start_credential_fallback_unless_canceled,
+ heartbeat=heartbeat,
+ )
+ effect_outcome = await handle_fenced_effect_result(effect_result, "final")
+ if effect_outcome is not None:
+ return effect_outcome
+
+ effect_result = await run_effect_once(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ effect_name="completion run tags",
+ effect=lambda: self._apply_completion_run_tags_best_effort(workflow_run),
+ heartbeat=heartbeat,
+ )
+ effect_outcome = await handle_fenced_effect_result(effect_result, "final")
+ if effect_outcome is not None:
+ return effect_outcome
+
+ effect_result = await run_effect_once(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ effect_name="workflow terminal hooks",
+ effect=lambda: self._run_workflow_run_terminal_hooks(
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=workflow_run.organization_id,
+ workflow_id=workflow_run.workflow_id,
+ status=workflow_run.status,
+ workflow_run=workflow_run,
+ ),
+ heartbeat=heartbeat,
+ )
+ effect_outcome = await handle_fenced_effect_result(effect_result, "final")
+ if effect_outcome is not None:
+ return effect_outcome
+
+ # Guard the complete once-only tail once for its total bound. Fresh token and
+ # marker checks immediately before each once-only effect fence a paused owner
+ # after a takeover without refusing an otherwise current old lease.
+ if not await self._side_effects_lease_is_current(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ completion_kind="final",
+ effect_bound_seconds=TERMINAL_SIDE_EFFECT_TAIL_BOUND_SECONDS,
+ ):
+ return await self._terminal_side_effect_outcome_after_fence(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ completion_kind="final",
+ claim_owned_by_this_invocation=claim_owned_by_this_invocation,
+ )
+
+ if not await self._terminal_tail_owner_is_current(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ completion_kind="final",
+ ):
+ return await self._terminal_side_effect_outcome_after_fence(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ completion_kind="final",
+ claim_owned_by_this_invocation=claim_owned_by_this_invocation,
+ )
+
+ effect_result = await run_effect_once(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ effect_name="workflow final hook",
+ effect=lambda: app.AGENT_FUNCTION.on_workflow_run_final(
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=workflow_run.organization_id,
+ status=workflow_run.status,
+ ),
+ heartbeat=heartbeat,
+ check_lease=False,
+ )
+ effect_outcome = await handle_fenced_effect_result(effect_result, "final")
+ if effect_outcome is not None:
+ return effect_outcome
+
+ if is_final_decision:
+ if not await self._terminal_tail_owner_is_current(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ completion_kind="final",
+ ):
+ return await self._terminal_side_effect_outcome_after_fence(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ completion_kind="final",
+ claim_owned_by_this_invocation=claim_owned_by_this_invocation,
+ )
+
+ webhook_kwargs: dict[str, Any] = {"claim_kind": "final"}
+ if side_effects_claim_at is not None:
+ webhook_kwargs.update(
+ {
+ "side_effects_claim_at": side_effects_claim_at,
+ "attempt_number": attempt_number,
+ }
+ )
+ webhook_kwargs["skip_side_effects_lease_check"] = True
+ effect_result = await run_effect_once(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ effect_name="final workflow webhook",
+ effect=lambda: self.execute_workflow_webhook(workflow_run, api_key, **webhook_kwargs),
+ heartbeat=heartbeat,
+ timeout_seconds=WEBHOOK_FALLBACK_GRACE_SECONDS,
+ check_lease=False,
+ )
+ effect_outcome = await handle_fenced_effect_result(effect_result, "final")
+ if effect_outcome is not None:
+ return effect_outcome
+ elif decision is not None and decision.send_webhook_now:
+ webhook_kwargs = {"claim_kind": "interim"}
+ if side_effects_claim_at is not None:
+ webhook_kwargs.update(
+ {
+ "side_effects_claim_at": side_effects_claim_at,
+ "attempt_number": attempt_number,
+ }
+ )
+ effect_result = await run_effect_once(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ effect_name="interim workflow webhook",
+ effect=lambda: self.execute_workflow_webhook(workflow_run, api_key, **webhook_kwargs),
+ completion_kind="interim",
+ heartbeat=heartbeat,
+ timeout_seconds=WEBHOOK_FALLBACK_GRACE_SECONDS,
+ )
+ effect_outcome = await handle_fenced_effect_result(effect_result, "interim")
+ if effect_outcome is not None:
+ return effect_outcome
+ elif decision is not None:
+ # A retry without an every-attempt webhook still completed its release. Record
+ # that there was nothing to deliver so recovery does not select this row forever.
+ marker_kwargs: dict[str, Any] = {"kind": "interim"}
+ if side_effects_claim_at is not None:
+ marker_kwargs["expected_claim_at"] = side_effects_claim_at
+
+ async def record_no_interim_webhook() -> None:
+ await app.DATABASE.workflow_run_attempts.claim_attempt_webhook(
+ workflow_run.workflow_run_id,
+ attempt_number,
+ **marker_kwargs,
+ )
+
+ effect_result = await run_effect_once(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ effect_name="interim webhook completion marker",
+ effect=record_no_interim_webhook,
+ completion_kind="interim",
+ heartbeat=heartbeat,
+ )
+ effect_outcome = await handle_fenced_effect_result(effect_result, "interim")
+ if effect_outcome is not None:
+ return effect_outcome
+ else:
+ # Preserve the no-policy release sequence, including its fire-and-forget terminal
+ # hook and fallback scheduling behavior.
+ if is_final_decision or not attempt_rows:
+ await self._apply_completion_run_tags_best_effort(workflow_run)
+ self._schedule_workflow_run_terminal_hooks(
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=workflow_run.organization_id,
+ workflow_id=workflow_run.workflow_id,
+ status=workflow_run.status,
+ workflow_run=workflow_run,
+ )
+ if is_final_decision:
+ await self.execute_workflow_webhook(workflow_run, api_key, claim_kind=None)
+ elif decision is not None and decision.send_webhook_now:
+ await self.execute_workflow_webhook(workflow_run, api_key, claim_kind="interim")
+
+ # The legacy path sends an every-attempt webhook even though a retry decision does not claim
+ # terminal side effects. Keep that behavior outside the release claim gate.
+ if not policy_attempt and decision is not None and decision.retry and decision.send_webhook_now:
+ await self.execute_workflow_webhook(workflow_run, api_key, claim_kind="interim")
+
+ if claimed_terminal_side_effects and not policy_attempt:
+ self._schedule_credential_fallback_retry(workflow_run)
+ return "released"
+
+ async def _update_workflow_run_status(
+ self,
+ workflow_run_id: str,
+ status: WorkflowRunStatus,
+ failure_reason: str | None = None,
+ run_with: str | None = None,
+ ai_fallback: bool | None = None,
+ failure_category: list[dict] | None = None,
+ ) -> WorkflowRun:
+ flipped_to_final = False
+ workflow_run: WorkflowRun | None = None
+ if status.is_final():
+ 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,
+ run_with=run_with,
+ ai_fallback=ai_fallback,
+ failure_category=failure_category,
+ )
+ flipped_to_final = workflow_run is not None
+ if workflow_run is not None:
+ # The terminal row is committed; its bookkeeping runs even when decision recording fails.
+ try:
+ await on_terminal_transition(
+ workflow_run,
+ status,
+ failure_reason,
+ failure_category,
+ )
+ finally:
+ await self._after_workflow_run_status_write(workflow_run, status, emit_run_minutes=True)
+ return workflow_run
+ if await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id):
+ # Policy runs keep the winning terminal status and its frozen retry decision.
+ return await self.get_workflow_run(workflow_run_id)
+ if workflow_run is None:
+ workflow_run = await app.DATABASE.workflow_runs.update_workflow_run(
+ workflow_run_id=workflow_run_id,
+ status=status,
+ failure_reason=failure_reason,
+ run_with=run_with,
+ ai_fallback=ai_fallback,
+ failure_category=failure_category,
+ )
+ await self._after_workflow_run_status_write(workflow_run, status, emit_run_minutes=flipped_to_final)
+ return workflow_run
+
+ async def _update_workflow_run_status_if_not_final(
+ self,
+ workflow_run_id: str,
+ status: WorkflowRunStatus,
+ failure_reason: str | None = None,
+ run_with: str | None = None,
+ failure_category: list[dict] | None = None,
+ finalized_by: str | None = None,
+ run_minutes_recorded_through: datetime | 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(
@@ -9813,12 +11790,20 @@ class WorkflowService:
)
if workflow_run is None:
return None
- await self._after_workflow_run_status_write(
- workflow_run,
- status,
- finalized_by=finalized_by,
- run_minutes_recorded_through=run_minutes_recorded_through,
- )
+ try:
+ await on_terminal_transition(
+ workflow_run,
+ status,
+ failure_reason,
+ failure_category,
+ )
+ finally:
+ await self._after_workflow_run_status_write(
+ workflow_run,
+ status,
+ finalized_by=finalized_by,
+ run_minutes_recorded_through=run_minutes_recorded_through,
+ )
return workflow_run
async def _finish_preexisting_timed_out_workflow_run(
@@ -9839,9 +11824,17 @@ class WorkflowService:
return None
# Bulk stuck-run cleanup writes only the status. Complete that deferred
# terminal transition exactly once, when ``finished_at`` is still null.
- await self._after_workflow_run_status_write(
- workflow_run, WorkflowRunStatus.timed_out, finalized_by=finalized_by
- )
+ try:
+ await on_terminal_transition(
+ workflow_run,
+ WorkflowRunStatus.timed_out,
+ failure_reason,
+ failure_category,
+ )
+ finally:
+ await self._after_workflow_run_status_write(
+ workflow_run, WorkflowRunStatus.timed_out, finalized_by=finalized_by
+ )
return workflow_run
async def _after_workflow_run_status_write(
@@ -9862,8 +11855,21 @@ class WorkflowService:
if workflow_run.started_at
else workflow_run.created_at.replace(tzinfo=UTC)
)
- queued_seconds = (start_time - workflow_run.created_at.replace(tzinfo=UTC)).total_seconds()
+ queued_seconds = _queued_seconds(workflow_run)
duration_seconds = (now - start_time).total_seconds()
+ attempt_lookup_failed = False
+ try:
+ attempt_rows = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ except Exception:
+ # The status row is committed; the task_runs mirror below must still be scheduled.
+ attempt_lookup_failed = True
+ attempt_rows = []
+ LOG.warning(
+ "Failed to load workflow retry attempts for terminal bookkeeping",
+ workflow_run_id=workflow_run_id,
+ exc_info=True,
+ )
+ latest_attempt = max(attempt_rows, key=lambda row: row.attempt_number, default=None)
# A run can reach a terminal status twice: the finally-block path terminalizes,
# re-opens the row to `running` so the block can execute, then terminalizes again.
# Both writes are real non-terminal -> terminal flips, so the second one records
@@ -9881,6 +11887,14 @@ class WorkflowService:
duration_seconds=duration_seconds,
recorded_seconds=recorded_seconds,
workflow_run_status=workflow_run.status,
+ # A run with a retry policy reaches a terminal status once per attempt. Consumers that
+ # derive one outcome per run keep only the events without a pending retry.
+ attempt_number=latest_attempt.attempt_number if latest_attempt is not None else None,
+ retry_pending=(
+ None
+ if attempt_lookup_failed
+ else latest_attempt is not None and is_retry_pending(status, now, latest_attempt)
+ ),
organization_id=workflow_run.organization_id,
run_with=workflow_run.run_with,
ai_fallback=workflow_run.ai_fallback,
@@ -9902,14 +11916,15 @@ class WorkflowService:
excluded_reason=None if workflow_run.started_at else "never_started",
finalized_by=finalized_by,
)
- await self._apply_completion_run_tags_best_effort(workflow_run)
- self._schedule_workflow_run_terminal_hooks(
- workflow_run_id=workflow_run_id,
- organization_id=workflow_run.organization_id,
- workflow_id=workflow_run.workflow_id,
- status=status,
- workflow_run=workflow_run,
- )
+ if not attempt_rows and not attempt_lookup_failed:
+ await self._apply_completion_run_tags_best_effort(workflow_run)
+ self._schedule_workflow_run_terminal_hooks(
+ workflow_run_id=workflow_run_id,
+ organization_id=workflow_run.organization_id,
+ workflow_id=workflow_run.workflow_id,
+ status=status,
+ workflow_run=workflow_run,
+ )
# Best-effort fire-and-forget write-through to task_runs table.
# Runs off the hot path so workflow status transitions stay fast.
bg = asyncio.create_task(
@@ -9932,6 +11947,7 @@ class WorkflowService:
status=status.value,
started_at=workflow_run.started_at,
finished_at=workflow_run.finished_at,
+ source_workflow_run_id=workflow_run_id,
)
# Also sync task_v2 if this workflow_run backs an observer_cruise
task_v2 = await app.DATABASE.observer.get_task_v2_by_workflow_run_id(
@@ -9945,6 +11961,7 @@ class WorkflowService:
status=status.value,
started_at=workflow_run.started_at,
finished_at=workflow_run.finished_at,
+ source_workflow_run_id=workflow_run_id,
)
except Exception:
LOG.warning(
@@ -9978,6 +11995,7 @@ class WorkflowService:
is_partial_run: bool = False,
requested_completion_contract: dict[str, Any] | None = None,
run_minutes_recorded_through: datetime | None = None,
+ workflow: Workflow | None = None,
) -> WorkflowRun:
"""
Set final workflow run status based on pre-finally state.
@@ -9998,6 +12016,7 @@ class WorkflowService:
workflow_run,
is_partial_run=is_partial_run,
requested_completion_contract=requested_completion_contract,
+ workflow=workflow,
)
if contract_verdict is not None and not contract_verdict.satisfied:
updated = await self._update_workflow_run_status_if_not_final(
@@ -10034,7 +12053,12 @@ class WorkflowService:
return workflow_run
async def _session_download_artifact_ids(
- self, workflow_run: WorkflowRun, context: SkyvernContext | None, download_run_id: str | None
+ self,
+ workflow_run: WorkflowRun,
+ context: SkyvernContext | None,
+ download_run_id: str | None,
+ attempt_rows: Sequence[Any] | None = None,
+ attempt_number: int | None = None,
) -> set[str]:
"""This run's downloads still scoped to the browser session, whether the watcher already
bound them to it or cleanup has yet to. Failure-tolerant: an unavailable read must not
@@ -10042,6 +12066,13 @@ class WorkflowService:
browser_session_id = context.browser_session_id if context else None
if not browser_session_id or not download_run_id:
return set()
+ run_started_at: datetime | None = workflow_run.created_at
+ if attempt_rows and attempt_number is not None:
+ run_started_at = self._attempt_started_at(attempt_rows, attempt_number)
+ if run_started_at is None:
+ return set()
+ if run_started_at is None:
+ return set()
try:
# This run as producer plus still-unbound rows in its window: a reused session's
# earlier downloads would otherwise satisfy a run that produced nothing.
@@ -10049,7 +12080,8 @@ class WorkflowService:
run_id=download_run_id,
browser_session_id=browser_session_id,
organization_id=workflow_run.organization_id,
- run_started_at=workflow_run.created_at,
+ run_started_at=run_started_at,
+ attempt_number=attempt_number if attempt_rows and attempt_number is not None else None,
)
except Exception:
LOG.warning(
@@ -10065,6 +12097,7 @@ class WorkflowService:
*,
is_partial_run: bool = False,
requested_completion_contract: dict[str, Any] | None = None,
+ workflow: Workflow | None = None,
) -> ContractVerdict | None:
"""Grade the workflow's declared completion contract, or None when it declares nothing.
@@ -10077,11 +12110,13 @@ class WorkflowService:
try:
# The run is pinned to one workflow version; grading the permanent id would read
# whatever version exists now, so an edit mid-run could judge this run by a contract
- # it never executed.
- workflow = await self.get_workflow(
- workflow_id=workflow_run.workflow_id,
- organization_id=workflow_run.organization_id,
- )
+ # it never executed. Execution hands over the version it loaded because this active-only
+ # lookup cannot see that version once it is soft-deleted.
+ if workflow is None:
+ workflow = await self.get_workflow(
+ workflow_id=workflow_run.workflow_id,
+ organization_id=workflow_run.organization_id,
+ )
criteria = parse_completion_contract(workflow.workflow_definition if workflow else None)
if not criteria and requested_completion_contract is not None:
# A copilot test run executes a version the request's obligation has not been
@@ -10090,16 +12125,51 @@ class WorkflowService:
if not criteria:
return None
context = skyvern_context.current()
+ attempt_rows: Sequence[Any] = []
+ attempt_repository = getattr(app.DATABASE, "workflow_run_attempts", None)
+ get_attempts = getattr(attempt_repository, "get_attempts", None)
+ if get_attempts is not None:
+ try:
+ attempt_rows = await get_attempts(workflow_run.workflow_run_id)
+ except Exception:
+ LOG.warning(
+ "Attempt read failed while grading completion contract; using legacy download scope",
+ workflow_run_id=workflow_run.workflow_run_id,
+ exc_info=True,
+ )
+ attempt_number = compute_attempt_view(workflow_run, attempt_rows).attempt if attempt_rows else None
# Producer and consumer must resolve the same download key: a sub-workflow registers
# files under the parent's run id, so the raw workflow_run_id would read an empty dir.
download_run_id = resolve_run_download_id(context, fallback_run_id=workflow_run.workflow_run_id)
+ if download_run_id is None:
+ download_run_id = workflow_run.workflow_run_id
+ artifact_ids: set[str] | None = None
+ if attempt_rows and attempt_number is not None:
+ artifact_ids = await self._download_artifact_ids_for_attempt(
+ run_id=download_run_id,
+ organization_id=workflow_run.organization_id,
+ attempt_rows=attempt_rows,
+ attempt_number=attempt_number,
+ )
files = await app.STORAGE.get_downloaded_files(
organization_id=workflow_run.organization_id,
run_id=download_run_id,
)
+ files = self._filter_downloaded_files_to_attempt(
+ files or [],
+ attempt_rows=attempt_rows,
+ attempt_number=attempt_number,
+ artifact_ids=artifact_ids,
+ )
# Session-scoped downloads may not be registered under the run dir; including them
# keeps a real download from reading as zero.
- session_download_ids = await self._session_download_artifact_ids(workflow_run, context, download_run_id)
+ session_download_ids = await self._session_download_artifact_ids(
+ workflow_run,
+ context,
+ download_run_id,
+ attempt_rows=attempt_rows,
+ attempt_number=attempt_number,
+ )
registered = files or []
# The sources overlap on the same resolved run key once rows carry ids, so subtracting
# the ids already present in `registered` counts a stamped file once. Without ids the
@@ -10262,17 +12332,11 @@ class WorkflowService:
)
self._background_tasks.add(bg)
bg.add_done_callback(self._background_tasks.discard)
- start_time = (
- workflow_run.started_at.replace(tzinfo=UTC)
- if workflow_run.started_at
- else workflow_run.created_at.replace(tzinfo=UTC)
- )
- queued_seconds = (start_time - workflow_run.created_at.replace(tzinfo=UTC)).total_seconds()
LOG.info(
f"Marked workflow run {workflow_run_id} as running",
workflow_run_id=workflow_run_id,
run_with=run_with,
- queued_seconds=queued_seconds,
+ queued_seconds=_queued_seconds(workflow_run),
)
return workflow_run
@@ -10374,6 +12438,43 @@ class WorkflowService:
)
if current is None:
raise WorkflowRunNotFound(workflow_run_id)
+
+ if current.status.is_final():
+ attempt_rows = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ if attempt_rows:
+ latest_attempt = max(attempt_rows, key=lambda attempt: attempt.attempt_number)
+ revoked = await app.DATABASE.workflow_run_attempts.revoke_or_abandon_attempt(
+ workflow_run_id=workflow_run_id,
+ attempt_number=latest_attempt.attempt_number,
+ decision="revoked",
+ reason="cancel",
+ )
+ refreshed_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=workflow_run_id,
+ )
+ if refreshed_run is not None:
+ current = refreshed_run
+ refreshed_attempts = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ latest_attempt = max(refreshed_attempts or attempt_rows, key=lambda attempt: attempt.attempt_number)
+ if revoked or latest_attempt.retry_decision in {"final", "revoked", "abandoned"}:
+ return current
+ if not current.status.is_final():
+ # Atomic preparation commits the next attempt with the queued run. Re-read and
+ # cancel that queued/running row.
+ updated = await self.mark_workflow_run_as_canceled_if_not_final(
+ workflow_run_id=workflow_run_id,
+ )
+ if updated is not None:
+ return updated
+ current = (
+ await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=workflow_run_id,
+ )
+ or current
+ )
+ if not current.status.is_final():
+ return current
+
LOG.info(
"Rejecting cancel: workflow run already in terminal state",
workflow_run_id=workflow_run_id,
@@ -10404,61 +12505,16 @@ class WorkflowService:
workflow_run_id=workflow_run_id,
)
otel_trace.get_current_span().set_attribute("task.completion_status", WorkflowRunStatus.canceled)
-
- # Mirror ``_update_workflow_run_status`` side effects on a terminal transition:
- # extraction-cache clear, duration-metrics log, and task_runs write-through.
- extraction_cache.clear_workflow_run(workflow_run_id)
-
- start_time = (
- updated.started_at.replace(tzinfo=UTC) if updated.started_at else updated.created_at.replace(tzinfo=UTC)
- )
- queued_seconds = (start_time - updated.created_at.replace(tzinfo=UTC)).total_seconds()
- duration_seconds = (datetime.now(UTC) - start_time).total_seconds()
- # This path finalizes once and never re-opens the run, so the recorded sample is
- # the whole duration. It is logged anyway so every emission site carries the field.
- LOG.info(
- "Workflow run duration metrics",
- workflow_run_id=workflow_run_id,
- workflow_id=updated.workflow_id,
- queued_seconds=queued_seconds,
- duration_seconds=duration_seconds,
- recorded_seconds=duration_seconds,
- workflow_run_status=updated.status,
- organization_id=updated.organization_id,
- run_with=updated.run_with,
- ai_fallback=updated.ai_fallback,
- trigger_type=updated.trigger_type,
- workflow_schedule_id=updated.workflow_schedule_id,
- task_v3_ab_arm=_task_v3_ab_arm_for_duration_log(workflow_run_id),
- )
- # Same compute gate as ``_after_workflow_run_status_write``: cancelling a run
- # that never started bills queue age, not compute, so it records as a tagged
- # zero-minute exclusion instead.
- if updated.parent_workflow_run_id is None:
- await app.AGENT_FUNCTION.record_run_duration(
- run_type="workflow_run",
- status=str(WorkflowRunStatus.canceled),
- duration_seconds=duration_seconds,
- workflow_run_id=workflow_run_id,
- organization_id=updated.organization_id,
- excluded_reason=None if updated.started_at else "never_started",
+ # The terminal row is committed; its bookkeeping runs even when decision recording fails.
+ try:
+ await on_terminal_transition(
+ updated,
+ WorkflowRunStatus.canceled,
+ failure_reason,
+ None,
)
- await self._apply_completion_run_tags_best_effort(updated)
-
- self._schedule_workflow_run_terminal_hooks(
- workflow_run_id=workflow_run_id,
- organization_id=updated.organization_id,
- workflow_id=updated.workflow_id,
- status=WorkflowRunStatus.canceled,
- workflow_run=updated,
- )
-
- bg = asyncio.create_task(
- self._sync_task_run_from_workflow_run(updated, workflow_run_id, WorkflowRunStatus.canceled),
- )
- self._background_tasks.add(bg)
- bg.add_done_callback(self._background_tasks.discard)
-
+ finally:
+ await self._after_workflow_run_status_write(updated, WorkflowRunStatus.canceled)
return updated
async def mark_workflow_run_as_timed_out(
@@ -10538,7 +12594,7 @@ class WorkflowService:
workflow_id: str,
workflow_parameter_type: WorkflowParameterType,
key: str,
- default_value: bool | int | float | str | dict | list | None = None,
+ default_value: bool | float | str | dict | list | None = None,
description: str | None = None,
) -> WorkflowParameter:
return await app.DATABASE.workflow_params.create_workflow_parameter(
@@ -10622,10 +12678,12 @@ class WorkflowService:
workflow_id: str,
workflow_run_id: str,
workflow: Workflow | None = None,
+ workflow_run_output_parameters: list[WorkflowRunOutputParameter] | None = None,
) -> list[tuple[OutputParameter, WorkflowRunOutputParameter]]:
- workflow_run_output_parameters = await app.DATABASE.workflow_runs.get_workflow_run_output_parameters(
- workflow_run_id=workflow_run_id
- )
+ if workflow_run_output_parameters is None:
+ workflow_run_output_parameters = await app.DATABASE.workflow_runs.get_workflow_run_output_parameters(
+ workflow_run_id=workflow_run_id
+ )
output_parameters = await app.DATABASE.workflow_params.get_workflow_output_parameters_by_ids(
output_parameter_ids=[
workflow_run_output_parameter.output_parameter_id
@@ -10723,9 +12781,21 @@ class WorkflowService:
organization_id: str | None = None,
limit: int = 3,
workflow_run_tasks: list[Task] | None = None,
+ historical_artifacts: list[Artifact] | None = None,
) -> list[Artifact]:
"""Return latest screenshot artifacts across recent tasks in a workflow run."""
+ if historical_artifacts is not None:
+ return sorted(
+ [
+ artifact
+ for artifact in historical_artifacts
+ if artifact.artifact_type in (ArtifactType.SCREENSHOT_ACTION, ArtifactType.SCREENSHOT_FINAL)
+ ],
+ key=lambda artifact: artifact.created_at,
+ reverse=True,
+ )[:limit]
+
if workflow_run_tasks is None:
workflow_run_tasks = await app.DATABASE.tasks.get_tasks_by_workflow_run_id(workflow_run_id=workflow_run_id)
@@ -10779,6 +12849,7 @@ class WorkflowService:
organization_id: str | None = None,
limit: int = 3,
workflow_run_tasks: list[Task] | None = None,
+ historical_artifacts: list[Artifact] | None = None,
) -> list[str]:
"""Return latest screenshot URLs across recent tasks in a workflow run."""
artifacts = await self.get_recent_workflow_screenshot_artifacts(
@@ -10786,6 +12857,7 @@ class WorkflowService:
organization_id=organization_id,
limit=limit,
workflow_run_tasks=workflow_run_tasks,
+ historical_artifacts=historical_artifacts,
)
if not artifacts:
return []
@@ -10856,6 +12928,8 @@ class WorkflowService:
workflow_run: WorkflowRun,
task_v2: Any | None,
organization_id: str | None,
+ historical_artifacts: list[Artifact] | None = None,
+ current_attempt_artifacts: list[Artifact] | None = None,
) -> tuple[list[str], bool]:
"""Fetch recording URLs, preferring precise run-scoped recordings over the shared
browser-session recording.
@@ -10870,11 +12944,26 @@ class WorkflowService:
# non-clip run recording may be an in-progress per-step snapshot, so it does NOT pre-empt
# the finalized session recording below — only run_recordings/ clips do.
run_id = task_v2.observer_cruise_id if task_v2 else workflow_run.workflow_run_id
- run_recording_artifacts = await app.DATABASE.artifacts.list_artifacts_for_run_by_type(
- run_id=run_id,
- artifact_type=ArtifactType.RECORDING,
- organization_id=workflow_run.organization_id,
+ # A current retry is scoped to its own attempt's artifacts but still needs the clip, shared-session,
+ # and closes-on-completion checks below; only a finished historical attempt returns its recording as is.
+ scoped_artifacts = historical_artifacts if historical_artifacts is not None else current_attempt_artifacts
+ run_recording_artifacts = (
+ [artifact for artifact in scoped_artifacts if artifact.artifact_type == ArtifactType.RECORDING]
+ if scoped_artifacts is not None
+ else await app.DATABASE.artifacts.list_artifacts_for_run_by_type(
+ run_id=run_id,
+ artifact_type=ArtifactType.RECORDING,
+ organization_id=workflow_run.organization_id,
+ )
)
+ if historical_artifacts is not None and run_recording_artifacts:
+ archived = await app.ARTIFACT_MANAGER.is_recording_archived(run_recording_artifacts[0])
+ urls = (
+ []
+ if archived
+ else await app.ARTIFACT_MANAGER.get_share_links_with_bundle_support(run_recording_artifacts)
+ )
+ return [url for url in urls if url is not None], archived
# "/run_recordings/" mirrors run_recording_clips.RUN_RECORDING_PATH_SEGMENT.
clip_artifacts = [a for a in run_recording_artifacts if a.uri and "/run_recordings/" in a.uri]
if clip_artifacts:
@@ -10885,6 +12974,7 @@ class WorkflowService:
# Fall back to the shared browser-session recording (windowed, then unbounded for a
# persistent session whose continuous recording finalizes long after the run ends).
+ # A continuous browser-session recording is shared across attempts when no attributable recording exists.
if not recording_urls and not recording_archived and workflow_run.browser_session_id:
if workflow_run.started_at is None:
LOG.warning(
@@ -10908,7 +12998,7 @@ class WorkflowService:
# close, often long after run_end, so it never lands in the bounded
# window. Drop the upper bound rather than show "no recording".
recording_urls = _select_recording_urls_in_window(recordings, lower_bound)
- except asyncio.TimeoutError:
+ except TimeoutError:
LOG.warning("Timeout getting recordings", browser_session_id=workflow_run.browser_session_id)
# Last resort: a run's own recording, only when its browser closes on completion. A run that
@@ -10934,6 +13024,9 @@ class WorkflowService:
self,
workflow_run: WorkflowRun,
task_v2: Any | None,
+ attempt_rows: Sequence[Any] | None = None,
+ attempt_number: int | None = None,
+ historical_artifacts: list[Artifact] | None = None,
) -> tuple[list[FileInfo], list[str] | None]:
"""Fetch downloaded files for a workflow run, including task_v2 files when present."""
downloaded_files: list[FileInfo] = []
@@ -10941,9 +13034,30 @@ class WorkflowService:
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
context = skyvern_context.current()
+ download_run_id = (
+ context.run_id if context and context.run_id else None
+ ) or workflow_run.workflow_run_id
downloaded_files = await app.STORAGE.get_downloaded_files(
organization_id=workflow_run.organization_id,
- run_id=context.run_id if context and context.run_id else workflow_run.workflow_run_id,
+ run_id=download_run_id,
+ )
+ artifact_ids: set[str] | None = None
+ if attempt_rows and attempt_number is not None:
+ artifact_ids = await self._download_artifact_ids_for_attempt(
+ run_id=download_run_id,
+ organization_id=workflow_run.organization_id,
+ attempt_rows=attempt_rows,
+ attempt_number=attempt_number,
+ attribution_workflow_run_id=workflow_run.workflow_run_id,
+ historical_artifacts=historical_artifacts
+ if download_run_id == workflow_run.workflow_run_id
+ else None,
+ )
+ downloaded_files = self._filter_downloaded_files_to_attempt(
+ downloaded_files,
+ attempt_rows=attempt_rows,
+ attempt_number=attempt_number,
+ artifact_ids=artifact_ids,
)
if task_v2:
task_v2_downloaded_files = await app.STORAGE.get_downloaded_files(
@@ -10951,10 +13065,35 @@ class WorkflowService:
run_id=task_v2.observer_cruise_id,
)
if task_v2_downloaded_files:
- downloaded_files.extend(task_v2_downloaded_files)
+ task_v2_artifact_ids = None
+ if (
+ attempt_rows
+ and attempt_number is not None
+ and any(row.attempt_number > attempt_number for row in attempt_rows)
+ ):
+ task_v2_artifact_ids = await self._download_artifact_ids_for_attempt(
+ run_id=task_v2.observer_cruise_id,
+ organization_id=workflow_run.organization_id,
+ attempt_rows=attempt_rows,
+ attempt_number=attempt_number,
+ attribution_workflow_run_id=workflow_run.workflow_run_id,
+ historical_artifacts=(
+ historical_artifacts
+ if task_v2.observer_cruise_id == workflow_run.workflow_run_id
+ else None
+ ),
+ )
+ downloaded_files.extend(
+ self._filter_downloaded_files_to_attempt(
+ task_v2_downloaded_files,
+ attempt_rows=attempt_rows,
+ attempt_number=attempt_number,
+ artifact_ids=task_v2_artifact_ids,
+ )
+ )
if downloaded_files:
downloaded_file_urls = [file_info.url for file_info in downloaded_files]
- except asyncio.TimeoutError:
+ except TimeoutError:
LOG.warning(
"Timeout to get downloaded files",
workflow_run_id=workflow_run.workflow_run_id,
@@ -10976,6 +13115,7 @@ class WorkflowService:
include_step_count: bool = False,
allow_deleted: bool = False,
cap_output_values: bool = False,
+ target_attempt_number: int | None = None,
) -> WorkflowRunResponseBase:
# ``cap_output_values`` defaults off so webhook delivery and replay keep full
# fidelity; only the interactive read surfaces that must fit in one JSON
@@ -10994,7 +13134,7 @@ class WorkflowService:
task_v2,
workflow_run_tasks,
workflow_parameter_tuples,
- block_errors,
+ attempt_rows,
) = await self._gather_with_max_in_flight(
(
lambda: app.DATABASE.workflows.get_workflow_for_workflow_run(
@@ -11009,9 +13149,7 @@ class WorkflowService:
),
lambda: app.DATABASE.tasks.get_tasks_by_workflow_run_id(workflow_run_id=workflow_run_id),
lambda: app.DATABASE.workflow_runs.get_workflow_run_parameters(workflow_run_id=workflow_run_id),
- lambda: app.DATABASE.workflow_runs.get_workflow_run_block_errors(
- workflow_run_id=workflow_run_id, organization_id=organization_id
- ),
+ lambda: app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id),
)
)
@@ -11019,6 +13157,74 @@ class WorkflowService:
LOG.error(f"Workflow {workflow_permanent_id} not found")
raise WorkflowNotFound(workflow_permanent_id=workflow_permanent_id)
+ attempt_view = compute_attempt_view(
+ workflow_run,
+ attempt_rows,
+ resolve_workflow_retry_policy(workflow),
+ target_attempt_number=target_attempt_number,
+ )
+ historical_attempt = (
+ attempt_view.attempts[-1]
+ if target_attempt_number is not None
+ and any(row.attempt_number > target_attempt_number for row in attempt_rows)
+ else None
+ )
+ if cap_output_values:
+ for attempt in attempt_view.attempts:
+ attempt.failure_reason = truncate_oversized_response_text(attempt.failure_reason)
+ current_attempt = attempt_view.attempt
+ block_errors = await app.DATABASE.workflow_runs.get_workflow_run_block_errors(
+ workflow_run_id=workflow_run_id, organization_id=organization_id, attempt_number=current_attempt
+ )
+ historical_outputs: list[WorkflowRunOutputParameter] | None = None
+ omitted_output_count = 0
+ historical_artifacts: list[Artifact] | None = None
+ if historical_attempt is not None:
+ attempt_row = next(row for row in attempt_rows if row.attempt_number == current_attempt)
+ snapshot = await app.DATABASE.workflow_run_attempts.get_interim_payload_snapshot(
+ workflow_run_id, current_attempt
+ )
+ omitted_output_count = snapshot.get("omitted_output_count") or 0
+ historical_outputs = [
+ WorkflowRunOutputParameter(workflow_run_id=workflow_run_id, **output)
+ for output in snapshot.get("output_parameters", [])
+ ]
+ workflow_run = workflow_run.model_copy(
+ update={
+ "status": WorkflowRunStatus(historical_attempt.status),
+ "failure_reason": historical_attempt.failure_reason,
+ "failure_category": attempt_row.failure_category,
+ "queued_at": datetime.fromisoformat(snapshot["queued_at"]) if snapshot.get("queued_at") else None,
+ "browser_session_id": snapshot.get("browser_session_id", attempt_row.pinned_browser_session_id),
+ "started_at": historical_attempt.started_at,
+ "finished_at": historical_attempt.finished_at,
+ "credits_used": snapshot.get("credits_used") or 0,
+ "cached_credits_used": snapshot.get("cached_credits_used") or 0,
+ }
+ )
+ workflow_run_tasks = [task for task in workflow_run_tasks if (task.attempt_number or 1) == current_attempt]
+ historical_artifacts = await app.DATABASE.workflow_runs.get_artifacts_for_attempt(
+ workflow_run_id,
+ workflow_run.organization_id,
+ current_attempt,
+ historical_attempt.started_at,
+ self._successor_attempt_boundary(attempt_rows, current_attempt),
+ )
+
+ screenshot_tasks = workflow_run_tasks
+ current_attempt_artifacts = historical_artifacts
+ if current_attempt > 1:
+ screenshot_tasks = [task for task in workflow_run_tasks if (task.attempt_number or 1) == current_attempt]
+ if current_attempt_artifacts is None:
+ attempt_row = next(row for row in attempt_rows if row.attempt_number == current_attempt)
+ current_attempt_artifacts = await app.DATABASE.workflow_runs.get_artifacts_for_attempt(
+ workflow_run_id,
+ workflow_run.organization_id,
+ current_attempt,
+ attempt_row.started_at or attempt_row.created_at,
+ self._successor_attempt_boundary(attempt_rows, current_attempt),
+ )
+
# Batch 2: fetches that depend on batch 1 results, all run concurrently.
(
screenshot_urls_raw,
@@ -11030,15 +13236,29 @@ class WorkflowService:
self.get_recent_workflow_screenshot_urls(
workflow_run_id=workflow_run_id,
organization_id=organization_id,
- workflow_run_tasks=workflow_run_tasks,
+ workflow_run_tasks=screenshot_tasks,
+ historical_artifacts=current_attempt_artifacts,
),
self.get_output_parameter_workflow_run_output_parameter_tuples(
workflow_id=workflow_run.workflow_id,
workflow_run_id=workflow_run_id,
workflow=workflow,
+ workflow_run_output_parameters=historical_outputs,
+ ),
+ self._fetch_recording_urls(
+ workflow_run,
+ task_v2,
+ organization_id,
+ historical_artifacts=historical_artifacts,
+ current_attempt_artifacts=current_attempt_artifacts,
+ ),
+ self._fetch_downloaded_files(
+ workflow_run,
+ task_v2,
+ attempt_rows=attempt_rows,
+ attempt_number=current_attempt,
+ historical_artifacts=historical_artifacts,
),
- self._fetch_recording_urls(workflow_run, task_v2, organization_id),
- self._fetch_downloaded_files(workflow_run, task_v2),
app.DATABASE.workflow_runs.get_workflow_run_retried_by(
workflow_run_id=workflow_run_id,
organization_id=workflow_run.organization_id,
@@ -11072,7 +13292,13 @@ class WorkflowService:
outputs[EXTRACTED_INFORMATION_KEY] = _cap(extracted_information, EXTRACTED_INFORMATION_KEY)
# Refresh any expired presigned screenshot URLs in the outputs
outputs = await self._refresh_output_urls(
- outputs, organization_id=organization_id, workflow_run_id=workflow_run_id
+ outputs,
+ historical_artifacts=historical_artifacts,
+ current_attempt_artifacts=current_attempt_artifacts,
+ organization_id=organization_id,
+ workflow_run_id=workflow_run_id,
+ attempt_rows=attempt_rows,
+ attempt_number=current_attempt,
)
# The refresh expands artifact IDs into presigned URLs and FileInfo objects —
# ~25x on an ID-dense value — so a value that fit before it can exceed the cap
@@ -11082,8 +13308,21 @@ class WorkflowService:
if cap_output_values:
outputs = {key: _cap(value, key) for key, value in outputs.items()}
+ if omitted_output_count:
+ outputs = outputs or {}
+ outputs["_interim_output_snapshot"] = {
+ "truncated": True,
+ "reason": "interim_output_snapshot_budget_exceeded",
+ "omitted_output_count": omitted_output_count,
+ }
+
+ scoped_tasks = [
+ task
+ for task in workflow_run_tasks
+ if (task.attempt_number is None and current_attempt == 1) or task.attempt_number == current_attempt
+ ]
task_errors: list[dict[str, Any]] = []
- for task in workflow_run_tasks:
+ for task in scoped_tasks:
task_errors.extend(task.errors)
# Also collect block-level error codes (e.g. FILE_PARSER_ERROR) into the
@@ -11114,7 +13353,7 @@ class WorkflowService:
total_cost: float | None = None
if include_step_count or include_cost:
step_count, _ = await app.DATABASE.tasks.get_step_counts_by_task_ids(
- task_ids=[task.task_id for task in workflow_run_tasks], organization_id=organization_id
+ task_ids=[task.task_id for task in scoped_tasks], organization_id=organization_id
)
total_steps = step_count
@@ -11128,6 +13367,10 @@ class WorkflowService:
workflow_id=workflow.workflow_permanent_id,
workflow_run_id=workflow_run_id,
status=workflow_run.status,
+ attempt=attempt_view.attempt,
+ retry_pending=attempt_view.retry_pending,
+ next_attempt_at=attempt_view.next_attempt_at,
+ attempts=attempt_view.attempts,
failure_reason=(
truncate_oversized_response_text(workflow_run.failure_reason)
if cap_output_values
@@ -11607,12 +13850,81 @@ class WorkflowService:
browser_persistence_status: WorkflowRunStatus | None = None,
skip_browser_session_write_back: bool = False,
schedule_credential_fallback_retry: bool = True,
+ attempt_number: int = 1,
) -> None:
# Direct cleanup callers can enter with a terminal row. When browser cleanup is still
# pending, install the tombstone before the first awaited terminal hook. A pre-finalization
# cleanup result has already reached complete_stream_teardown and must not be tombstoned again.
if browser_cleanup_result is None:
mark_stream_closing(workflow_run.workflow_run_id)
+ policy_run: bool | None
+ try:
+ policy_run = await is_retry_eligible_run(
+ workflow_run,
+ workflow_run.organization_id,
+ workflow,
+ )
+ except Exception:
+ # Browser teardown must still run; ownership is derived from the attempt rows below.
+ policy_run = None
+ LOG.warning(
+ "Failed to evaluate retry eligibility during cleanup",
+ workflow_run_id=workflow_run.workflow_run_id,
+ exc_info=True,
+ )
+ attempt_lookup_failed = False
+ try:
+ attempt_rows = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run.workflow_run_id)
+ except Exception:
+ attempt_lookup_failed = True
+ LOG.warning(
+ "Failed to load workflow retry attempts during cleanup",
+ workflow_run_id=workflow_run.workflow_run_id,
+ policy_run=policy_run,
+ exc_info=True,
+ )
+ attempt_rows = []
+ if policy_run is None or not (attempt_lookup_failed or attempt_rows):
+ # Enrollment is the attempt row: with none readable, leave terminal effects to recovery;
+ # with none at all, the run took the ordinary path and keeps its cleanup-time effects.
+ policy_run = attempt_lookup_failed or bool(attempt_rows)
+ current_attempt = next(
+ (attempt for attempt in attempt_rows if attempt.attempt_number == attempt_number),
+ None,
+ )
+ terminal_decision: RetryDecision | None = None
+ if (
+ policy_run
+ and not attempt_lookup_failed
+ and attempt_rows
+ and need_call_webhook
+ and current_attempt is not None
+ ):
+ terminal_decision = await get_recorded_decision(
+ workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ )
+ if terminal_decision is None:
+ terminal_decision = await on_terminal_transition(
+ workflow_run,
+ workflow_run.status,
+ workflow_run.failure_reason,
+ workflow_run.failure_category,
+ attempt_number=attempt_number,
+ )
+ if terminal_decision.retry:
+ terminal_decision = await finalize_abandoned_attempt(
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=workflow_run.organization_id,
+ reason="caller_not_retry_aware",
+ status=workflow_run.status,
+ failure_reason=workflow_run.failure_reason,
+ finished_at=workflow_run.finished_at,
+ attempt_number=attempt_number,
+ )
+ elif policy_run and not attempt_lookup_failed and attempt_rows and need_call_webhook:
+ # Never fall back to a newer attempt if a late cleanup cannot find its own row.
+ terminal_decision = RetryDecision(False, attempt_number, 0, True, "attempt_not_found")
analytics.capture("skyvern-oss-agent-workflow-status", {"status": workflow_run.status})
capture_workflow_run_ids = [workflow_run.workflow_run_id]
caller_cancelled = False
@@ -11637,6 +13949,7 @@ class WorkflowService:
workflow_run_id=workflow_run.workflow_run_id,
organization_id=workflow_run.organization_id,
status=workflow_run.status,
+ is_final_attempt=not policy_run,
)
if browser_cleanup_result is None:
browser_cleanup_result = await self._clean_up_workflow_browser(
@@ -11676,10 +13989,17 @@ class WorkflowService:
context = skyvern_context.current()
finalization_run_id = resolve_run_download_id(context, fallback_run_id=workflow_run.workflow_run_id)
try:
- await app.STORAGE.save_downloaded_files(
- organization_id=workflow_run.organization_id,
- run_id=finalization_run_id,
- )
+ if attempt_rows:
+ await app.STORAGE.save_downloaded_files(
+ organization_id=workflow_run.organization_id,
+ run_id=finalization_run_id,
+ attempt_number=attempt_number,
+ )
+ else:
+ await app.STORAGE.save_downloaded_files(
+ organization_id=workflow_run.organization_id,
+ run_id=finalization_run_id,
+ )
except DownloadSaveIncompleteError as exc:
# Session-artifact claiming below must still run for the files that saved.
LOG.warning(
@@ -11691,28 +14011,32 @@ class WorkflowService:
# 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",
+ run_started_at: datetime | None = workflow_run.created_at
+ if attempt_number > 1:
+ run_started_at = current_attempt.started_at if current_attempt is not None else None
+ if run_started_at is not None:
+ 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=run_started_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:
+ except TimeoutError:
LOG.warning(
"Timeout to save downloaded files",
workflow_run_id=workflow_run.workflow_run_id,
@@ -11724,12 +14048,18 @@ class WorkflowService:
workflow_run_id=workflow_run.workflow_run_id,
)
- # Before the webhook, so a caller acting on the run's completion already sees the
- # attached files gone.
- await uploaded_file_service.delete_files_attached_to_run(run_id=workflow_run.workflow_run_id)
+ # No-policy runs retain the historical cleanup-time deletion. Policy-run deletion is
+ # claimed with the final decision in run_terminal_side_effects below; if the attempt
+ # lookup failed, leave this logical-run effect for recovery.
+ if not policy_run:
+ await uploaded_file_service.delete_files_attached_to_run(run_id=workflow_run.workflow_run_id)
if need_call_webhook:
- await self.execute_workflow_webhook(workflow_run, api_key)
+ if policy_run and not attempt_lookup_failed and attempt_rows:
+ assert terminal_decision is not None
+ await self._run_terminal_side_effects_with_retries(workflow_run, terminal_decision, api_key=api_key)
+ elif not policy_run:
+ await self.execute_workflow_webhook(workflow_run, api_key)
finally:
# Run contexts hold parameters/secrets/outputs and are keyed per
# run; without eviction they accumulate for the process lifetime.
@@ -11744,7 +14074,7 @@ class WorkflowService:
# it; scheduling was removed from the status markers, which fired before cleanup and for
# cascade/reaper failures that never reach cleanup. Finally-only failures explicitly
# suppress it because replaying the workflow cannot repair post-run cleanup.
- if schedule_credential_fallback_retry:
+ if schedule_credential_fallback_retry and not policy_run:
self._schedule_credential_fallback_retry(workflow_run)
if caller_cancelled:
raise asyncio.CancelledError
@@ -11753,6 +14083,8 @@ class WorkflowService:
self,
workflow_run: WorkflowRun,
api_key: str | None = None,
+ *,
+ target_attempt_number: int | None = None,
) -> PreparedWorkflowWebhook | None:
workflow_id = workflow_run.workflow_id
# Cleanup path: tolerate soft-deleted workflows. If the workflow row
@@ -11766,6 +14098,7 @@ class WorkflowService:
organization_id=workflow_run.organization_id,
include_step_count=True,
allow_deleted=True,
+ target_attempt_number=target_attempt_number,
)
except WorkflowNotFound:
LOG.warning(
@@ -11811,6 +14144,10 @@ class WorkflowService:
run_id=workflow_run.workflow_run_id,
run_type=RunType.workflow_run,
status=RunStatus(workflow_run_status_response.status),
+ attempt=workflow_run_status_response.attempt,
+ retry_pending=workflow_run_status_response.retry_pending,
+ next_attempt_at=workflow_run_status_response.next_attempt_at,
+ attempts=workflow_run_status_response.attempts,
output=workflow_run_status_response.outputs,
downloaded_files=workflow_run_status_response.downloaded_files,
recording_url=workflow_run_status_response.recording_url,
@@ -11863,7 +14200,7 @@ class WorkflowService:
headers=signed_data.headers,
)
- async def deliver_prepared_workflow_webhook(self, webhook: PreparedWorkflowWebhook) -> None:
+ async def deliver_prepared_workflow_webhook(self, webhook: PreparedWorkflowWebhook) -> bool:
LOG.info(
"Sending webhook run status to webhook callback url",
sampling=True,
@@ -11877,7 +14214,7 @@ class WorkflowService:
url=webhook.webhook_callback_url,
payload=webhook.signed_payload,
headers=webhook.headers,
- timeout_seconds=30.0,
+ timeout_seconds=WORKFLOW_WEBHOOK_HTTP_TIMEOUT_SECONDS,
organization_id=webhook.organization_id,
run_id=webhook.workflow_run_id,
)
@@ -11902,7 +14239,7 @@ class WorkflowService:
workflow_run_id=webhook.workflow_run_id,
exc_info=True,
)
- return
+ return False
if resp.status_code >= 200 and resp.status_code < 300:
LOG.info(
@@ -11925,6 +14262,7 @@ class WorkflowService:
workflow_run_id=webhook.workflow_run_id,
exc_info=True,
)
+ return True
else:
LOG.info(
"Webhook failed",
@@ -11945,16 +14283,132 @@ class WorkflowService:
workflow_run_id=webhook.workflow_run_id,
exc_info=True,
)
+ return False
async def execute_workflow_webhook(
self,
workflow_run: WorkflowRun,
api_key: str | None = None,
+ claim_kind: Literal["interim", "final"] | None = "final",
+ *,
+ side_effects_claim_at: datetime | None = None,
+ attempt_number: int | None = None,
+ skip_side_effects_lease_check: bool = False,
) -> None:
- webhook = await self.prepare_workflow_webhook(workflow_run, api_key)
+ webhook = await self.prepare_workflow_webhook(
+ workflow_run,
+ api_key,
+ target_attempt_number=attempt_number if claim_kind == "interim" else None,
+ )
+ selected_attempt: Any | None = None
+ if claim_kind is not None:
+ attempt_rows = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run.workflow_run_id)
+ if attempt_rows:
+ selected_attempt = (
+ next((row for row in attempt_rows if row.attempt_number == attempt_number), None)
+ if attempt_number is not None
+ else max(attempt_rows, key=lambda row: row.attempt_number)
+ )
+ if selected_attempt is None and side_effects_claim_at is not None:
+ LOG.info(
+ "Skipping workflow webhook after attempt lease row disappeared",
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_kind=claim_kind,
+ )
+ return
+ if selected_attempt is None:
+ selected_attempt = max(attempt_rows, key=lambda row: row.attempt_number)
+ attempt_number = selected_attempt.attempt_number
+ claim_timestamp = (
+ selected_attempt.interim_webhook_sent_at
+ if claim_kind == "interim"
+ else selected_attempt.webhook_sent_at
+ )
+ if claim_timestamp is not None:
+ LOG.info(
+ "Skipping workflow webhook after attempt claim was already recorded",
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_kind=claim_kind,
+ )
+ return
if webhook is None:
+ if claim_kind is not None and attempt_number is not None:
+ marker_kwargs: dict[str, Any] = {"kind": claim_kind}
+ if side_effects_claim_at is not None:
+ marker_kwargs["expected_claim_at"] = side_effects_claim_at
+ await app.DATABASE.workflow_run_attempts.claim_attempt_webhook(
+ workflow_run.workflow_run_id,
+ attempt_number,
+ **marker_kwargs,
+ )
return
- await self.deliver_prepared_workflow_webhook(webhook)
+ if side_effects_claim_at is not None and not skip_side_effects_lease_check:
+ if attempt_number is None:
+ return
+ if not await self._side_effects_lease_is_current(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_at=side_effects_claim_at,
+ completion_kind=claim_kind or "final",
+ effect_bound_seconds=WEBHOOK_FALLBACK_GRACE_SECONDS,
+ ):
+ return
+ elif claim_kind is not None and attempt_number is not None and not skip_side_effects_lease_check:
+ if selected_attempt is None:
+ return
+ selected_claim_at = getattr(selected_attempt, "side_effects_released_at", None)
+ if not await self._workflow_webhook_fallback_is_current(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ expected_claim_at=selected_claim_at,
+ ):
+ return
+ delivery_attempt = None
+ if selected_attempt is not None and claim_kind is not None and attempt_number is not None:
+ delivery_attempt = await app.DATABASE.workflow_run_attempts.reserve_attempt_webhook_delivery(
+ workflow_run.workflow_run_id,
+ attempt_number,
+ kind=claim_kind,
+ expected_claim_at=side_effects_claim_at or getattr(selected_attempt, "side_effects_released_at", None),
+ max_attempts=WORKFLOW_WEBHOOK_DELIVERY_MAX_ATTEMPTS,
+ )
+ if not delivery_attempt:
+ return
+ delivered = await self.deliver_prepared_workflow_webhook(webhook)
+ if not delivered:
+ if delivery_attempt == WORKFLOW_WEBHOOK_DELIVERY_MAX_ATTEMPTS:
+ assert attempt_number is not None and claim_kind is not None
+ exhausted = await app.DATABASE.workflow_run_attempts.claim_attempt_webhook(
+ workflow_run.workflow_run_id,
+ attempt_number,
+ kind=claim_kind,
+ expected_claim_at=side_effects_claim_at
+ or getattr(selected_attempt, "side_effects_released_at", None),
+ delivery_exhausted=True,
+ )
+ if exhausted:
+ return
+ if selected_attempt is not None:
+ raise RuntimeError("Workflow webhook delivery failed; attempt delivery remains pending")
+ return
+ if claim_kind is not None and attempt_number is not None:
+ marker_kwargs = {"kind": claim_kind, "delivery_attempted": True}
+ if side_effects_claim_at is not None:
+ marker_kwargs["expected_claim_at"] = side_effects_claim_at
+ claimed = await app.DATABASE.workflow_run_attempts.claim_attempt_webhook(
+ workflow_run.workflow_run_id,
+ attempt_number,
+ **marker_kwargs,
+ )
+ if not claimed:
+ LOG.info(
+ "Workflow webhook delivery completed after attempt claim was recorded",
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=attempt_number,
+ claim_kind=claim_kind,
+ )
async def persist_video_data(
self,
@@ -12950,6 +15404,7 @@ class WorkflowService:
)
block_map[block.workflow_run_block_id] = WorkflowRunTimeline(
type=WorkflowRunTimelineType.block,
+ attempt=block.attempt_number or 1,
block=block,
created_at=block.created_at,
modified_at=block.modified_at,
@@ -13037,7 +15492,7 @@ class WorkflowService:
if block_labels and not code_gen:
# Do not generate script if block_labels is provided, and an explicit code_gen
# request is not made
- return None
+ return
existing_script, rendered_cache_key_value, _is_pinned = await workflow_script_service.get_workflow_script(
workflow,
@@ -13058,7 +15513,7 @@ class WorkflowService:
script_id=existing_script.script_id,
workflow_run_id=workflow_run.workflow_run_id,
)
- return None
+ return
cached_block_labels: set[str] = set()
script_blocks = await app.DATABASE.scripts.get_script_blocks_by_script_revision_id(
@@ -13713,17 +16168,6 @@ class WorkflowService:
historical_episodes: list | None = None,
) -> None:
"""Run the AI Script Reviewer and create a new script version if successful."""
- # Imports are method-local to defer the script_reviewer module load to
- # the rare path where the reviewer is actually triggered (most workflow
- # runs never invoke it). Pre-existing convention in this method.
- from skyvern.services.script_reviewer import (
- BlockReviewResult,
- ScriptReviewer,
- load_filtered_run_param_values,
- store_review_artifacts,
- )
- from skyvern.services.workflow_script_service import create_script_version_from_review
-
LOG.info(
"Script reviewer async task starting",
workflow_permanent_id=workflow.workflow_permanent_id,
diff --git a/skyvern/forge/sdk/workflow/workflow_definition_converter.py b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
index 79f4e4961..a5e4ac5d0 100644
--- a/skyvern/forge/sdk/workflow/workflow_definition_converter.py
+++ b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
@@ -346,6 +346,7 @@ def convert_workflow_definition(
version=dag_version,
finally_block_label=workflow_definition_yaml.finally_block_label,
error_code_mapping=workflow_definition_yaml.error_code_mapping,
+ retry_policy=workflow_definition_yaml.retry_policy,
workflow_system_prompt=workflow_definition_yaml.workflow_system_prompt,
completion_contract=workflow_definition_yaml.completion_contract,
)
diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.py
index 9594cc98f..4200316c6 100644
--- a/skyvern/forge/taskv3/tools.py
+++ b/skyvern/forge/taskv3/tools.py
@@ -25,6 +25,7 @@ import unicodedata
import weakref
from collections import Counter, defaultdict, deque
from contextvars import ContextVar
+from datetime import datetime
from enum import Enum
from typing import TYPE_CHECKING, Any, Awaitable, Callable, NamedTuple
@@ -38,6 +39,9 @@ from skyvern.core.script_generations.fuzzy_matcher import (
match_option_exact_or_stem_with_tier,
normalize_option_label,
)
+from skyvern.forge.sdk.api.files import resolve_run_download_id
+from skyvern.forge.sdk.artifact.storage.base import get_download_retry_started_at, is_file_from_retry_attempt
+from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import URL_IN_TEXT, canonical_url, opaque_url_echo_window
from skyvern.forge.taskv3.frame_perception import frame_perception_enabled
from skyvern.forge.taskv3.loop import (
@@ -12355,10 +12359,17 @@ def _apply_download_signal(tools: list[ToolSpec], downloads_dir: str | None) ->
seen_started: set[str] = set()
pending: list[str] = []
baseline = {"done": False}
+ baseline_lock = asyncio.Lock()
+ attempt_started_at: datetime | None = None
def _list_split() -> tuple[list[str], list[str]]:
try:
- names = sorted(os.listdir(downloads_dir))
+ names = sorted(
+ name
+ for name in os.listdir(downloads_dir)
+ if attempt_started_at is None
+ or is_file_from_retry_attempt(os.path.join(downloads_dir, name), attempt_started_at)
+ )
except OSError:
return [], []
completed = [n for n in names if not n.endswith(BROWSER_DOWNLOADING_SUFFIX)]
@@ -12373,16 +12384,22 @@ def _apply_download_signal(tools: list[ToolSpec], downloads_dir: str | None) ->
_compactable: bool = tool_spec.compactable,
_tool_name: str = tool_spec.name,
) -> ToolResult:
- if not baseline["done"]:
- baseline["done"] = True
- try:
- # Snapshot BEFORE the first handler runs, so a download triggered by the very
- # first tool call is reported rather than absorbed into the baseline.
- completed0, in_progress0 = _list_split()
- seen_completed.update(completed0)
- seen_started.update(_download_signal_identity(n) for n in in_progress0)
- except Exception:
- LOG.warning("taskv3 download signal baseline snapshot failed", tool=_tool_name, exc_info=True)
+ nonlocal attempt_started_at
+ async with baseline_lock:
+ if not baseline["done"]:
+ try:
+ context = skyvern_context.current()
+ attempt_started_at = await get_download_retry_started_at(
+ context.organization_id if context else None, resolve_run_download_id(context)
+ )
+ # Snapshot BEFORE the first handler runs, so a download triggered by the very
+ # first tool call is reported rather than absorbed into the baseline.
+ completed0, in_progress0 = _list_split()
+ seen_completed.update(completed0)
+ seen_started.update(_download_signal_identity(n) for n in in_progress0)
+ except Exception:
+ LOG.warning("taskv3 download signal baseline snapshot failed", tool=_tool_name, exc_info=True)
+ baseline["done"] = True
result = await _handler(args)
try:
# A tool that stages its own file into downloads_dir (file_upload) names it in
diff --git a/skyvern/library/embedded_server_factory.py b/skyvern/library/embedded_server_factory.py
index 8f8d053ae..2e6c942ee 100644
--- a/skyvern/library/embedded_server_factory.py
+++ b/skyvern/library/embedded_server_factory.py
@@ -9,7 +9,7 @@ import httpx
from httpx import ASGITransport
from skyvern.config import settings
-from skyvern.forge.api_app import create_api_app
+from skyvern.forge.api_app import create_api_app, ensure_sqlite_schema
from skyvern.forge.sdk.api.llm.config_registry import LLMConfigRegistry
from skyvern.schemas.llm import LLMConfig, LLMRouterConfig
@@ -168,6 +168,13 @@ def create_embedded_server(
if use_in_memory_db:
self._api_key = await self._bootstrap_in_memory_db()
+ else:
+ # ASGITransport never runs the FastAPI lifespan, so a persistent local SQLite
+ # database gets the server's schema bootstrap here instead.
+ from skyvern.forge import app as forge_app # noqa: PLC0415
+
+ if forge_app.DATABASE.engine.dialect.name == "sqlite":
+ await ensure_sqlite_schema(forge_app.DATABASE)
self._transport = ASGITransport(app=api_app)
@@ -179,7 +186,6 @@ def create_embedded_server(
from skyvern.forge.sdk.core.security import create_access_token # noqa: PLC0415
from skyvern.forge.sdk.db.agent_db import AgentDB # noqa: PLC0415
from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType # noqa: PLC0415
- from skyvern.forge.sdk.db.models import Base # noqa: PLC0415
# Only replace the engine if cloud/__init__.py swapped it to Postgres.
# When _apply_sqlite_overrides() runs before create_api_app(), the engine
@@ -201,8 +207,7 @@ def create_embedded_server(
forge_app.STORAGE = StorageFactory.get_storage()
db = forge_app.DATABASE
- async with db.engine.begin() as conn:
- await conn.run_sync(Base.metadata.create_all)
+ await ensure_sqlite_schema(db)
org = await db.organizations.create_organization(organization_name="local")
token = create_access_token(org.organization_id, expires_delta=timedelta(days=365 * 10))
diff --git a/skyvern/library/skyvern.py b/skyvern/library/skyvern.py
index 79d96b1d3..4f119e254 100644
--- a/skyvern/library/skyvern.py
+++ b/skyvern/library/skyvern.py
@@ -417,7 +417,7 @@ class Skyvern(AsyncSkyvern):
async with asyncio.timeout(timeout):
while True:
workflow_run = await super().get_run(workflow_run.run_id)
- if RunStatus(workflow_run.status).is_final():
+ if RunStatus(workflow_run.status).is_final() and not getattr(workflow_run, "retry_pending", False):
break
await asyncio.sleep(DEFAULT_AGENT_HEARTBEAT_INTERVAL)
return WorkflowRunResponse.model_validate(workflow_run.model_dump())
@@ -476,7 +476,7 @@ class Skyvern(AsyncSkyvern):
async with asyncio.timeout(timeout):
while True:
workflow_run = await super().get_run(workflow_run.run_id)
- if RunStatus(workflow_run.status).is_final():
+ if RunStatus(workflow_run.status).is_final() and not getattr(workflow_run, "retry_pending", False):
break
await asyncio.sleep(DEFAULT_AGENT_HEARTBEAT_INTERVAL)
return WorkflowRunResponse.model_validate(workflow_run.model_dump())
diff --git a/skyvern/library/skyvern_browser_page.py b/skyvern/library/skyvern_browser_page.py
index a54992e71..0ff566a53 100644
--- a/skyvern/library/skyvern_browser_page.py
+++ b/skyvern/library/skyvern_browser_page.py
@@ -1,4 +1,6 @@
# ruff: noqa: E402
+import asyncio
+from contextvars import Context
from typing import TYPE_CHECKING, Any
from skyvern.exceptions import require_local_extra_modules
@@ -8,6 +10,7 @@ require_local_extra_modules("skyvern.library.skyvern_browser_page")
from playwright.async_api import Frame, Page
from skyvern.core.script_generations.skyvern_page import SkyvernPage
+from skyvern.forge.sdk.api.files import local_file_requires_organization
from skyvern.library.skyvern_browser_page_agent import SkyvernBrowserPageAgent
from skyvern.library.skyvern_browser_page_ai import SdkSkyvernPageAi
@@ -41,8 +44,32 @@ class SkyvernBrowserPage(SkyvernPage):
def __init__(self, browser: "SkyvernBrowser", page: Page):
super().__init__(page, SdkSkyvernPageAi(browser, page))
self._browser = browser
+ self._file_organization_id: str | None = None
self.agent = SkyvernBrowserPageAgent(browser, page)
+ async def _get_file_organization_id(self, file_url: str) -> str | None:
+ organization_id = await super()._get_file_organization_id(file_url)
+ if organization_id:
+ return organization_id
+ if not local_file_requires_organization(file_url):
+ return None
+ if self._file_organization_id is not None:
+ return self._file_organization_id
+ client = self._browser.skyvern
+ if not client._api_key and client._embedded_client is None:
+ return None
+ # Embedded middleware must not inherit or mutate the caller's context object.
+ response = await asyncio.create_task(
+ client._client_wrapper.httpx_client.request("api/v1/organizations/me", method="GET"),
+ context=Context(),
+ )
+ response.raise_for_status()
+ organization_id = response.json().get("organization_id")
+ if not isinstance(organization_id, str) or not organization_id:
+ raise PermissionError("Authenticated organization response has no organization ID")
+ self._file_organization_id = organization_id
+ return organization_id
+
async def frame_switch(
self,
*,
diff --git a/skyvern/library/skyvern_browser_page_agent.py b/skyvern/library/skyvern_browser_page_agent.py
index 5fa9ebe37..e9568ecb2 100644
--- a/skyvern/library/skyvern_browser_page_agent.py
+++ b/skyvern/library/skyvern_browser_page_agent.py
@@ -400,7 +400,7 @@ class SkyvernBrowserPageAgent:
async with asyncio.timeout(timeout):
while True:
task_run = await self._browser.skyvern.get_run(run_id)
- if RunStatus(task_run.status).is_final():
+ if RunStatus(task_run.status).is_final() and not getattr(task_run, "retry_pending", False):
break
await asyncio.sleep(DEFAULT_AGENT_HEARTBEAT_INTERVAL)
return task_run
diff --git a/skyvern/schemas/runs.py b/skyvern/schemas/runs.py
index bdaf0dc50..059c65a27 100644
--- a/skyvern/schemas/runs.py
+++ b/skyvern/schemas/runs.py
@@ -764,6 +764,25 @@ class BaseRunResponse(BaseModel):
)
+class WorkflowRunAttempt(BaseModel):
+ attempt_number: int = Field(description="One-based number of this workflow run attempt")
+ status: RunStatus = Field(description="Status of this workflow run attempt")
+ failure_reason: str | None = Field(default=None, description="Reason for failure, if the attempt failed")
+ error_codes: list[str] = Field(default_factory=list, description="Error codes reported by this attempt")
+ started_at: datetime | None = Field(default=None, description="Timestamp when this attempt started")
+ finished_at: datetime | None = Field(default=None, description="Timestamp when this attempt finished")
+ retry_decision: str | None = Field(default=None, description="Retry decision recorded for this attempt")
+ decision_reason: str | None = Field(default=None, description="Reason recorded for the retry decision")
+ next_attempt_at: datetime | None = Field(
+ default=None,
+ description="Timestamp when the next attempt is scheduled",
+ )
+ webhook_sent_at: datetime | None = Field(
+ default=None,
+ description="Timestamp when the webhook for this attempt was sent",
+ )
+
+
class TaskRunResponse(BaseRunResponse):
run_type: TaskRunTypeField = Field(
description="Types of a task run - task_v1, task_v2, openai_cua, anthropic_cua, ui_tars"
@@ -775,6 +794,19 @@ class TaskRunResponse(BaseRunResponse):
class WorkflowRunResponse(BaseRunResponse):
run_type: WorkflowRunTypeField = Field(description="Type of run - always workflow_run for workflow runs")
+ attempt: int = Field(default=1, description="One-based number of the current workflow run attempt")
+ retry_pending: bool = Field(
+ default=False,
+ description="Whether another attempt is scheduled for this workflow run",
+ )
+ next_attempt_at: datetime | None = Field(
+ default=None,
+ description="Timestamp when the next workflow run attempt is scheduled",
+ )
+ attempts: list[WorkflowRunAttempt] = Field(
+ default_factory=list,
+ description="Attempts recorded for this workflow run",
+ )
run_with: str = Field(
default="agent",
description="Whether the workflow run was executed with agent or code",
diff --git a/skyvern/schemas/workflows.py b/skyvern/schemas/workflows.py
index 50a4f2d9f..840e8c25f 100644
--- a/skyvern/schemas/workflows.py
+++ b/skyvern/schemas/workflows.py
@@ -9,7 +9,7 @@ from enum import StrEnum
from typing import Annotated, Any, Literal, Protocol, TypeVar
import structlog
-from pydantic import BaseModel, Field, field_serializer, field_validator, model_validator
+from pydantic import BaseModel, Field, StrictInt, field_serializer, field_validator, model_validator
from skyvern.config import settings
from skyvern.constants import ERROR_CODE_REASONING_MAX_LENGTH
@@ -1589,12 +1589,67 @@ def workflow_definition_has_v2_graph_constructs(blocks: list[BLOCK_YAML_SUBCLASS
return any(isinstance(block, ConditionalBlockYAML) or block.next_block_label is not None for block in blocks)
+class WorkflowRetryRule(BaseModel):
+ status: Literal["completed", "failed", "terminated", "canceled", "timed_out"] = Field(
+ description=(
+ "Terminal status that triggers a retry rule; canceled is accepted for forward compatibility, "
+ "but a canceled run never retries in the current runtime, including explicit API/UI cancels."
+ )
+ )
+ error_codes: list[Annotated[str, Field(min_length=1)]] | None = Field(
+ default=None,
+ description="Optional error codes. The rule matches when any listed code is present.",
+ )
+
+ @field_validator("error_codes")
+ @classmethod
+ def deduplicate_error_codes(cls, error_codes: list[str] | None) -> list[str] | None:
+ if error_codes is None:
+ return None
+ return list(dict.fromkeys(error_codes))
+
+
+class WorkflowRetryPolicy(BaseModel):
+ max_retries: StrictInt = Field(
+ default=1,
+ ge=1,
+ le=5,
+ description="Maximum number of retries after the initial attempt",
+ )
+ delay_seconds: StrictInt = Field(
+ default=0,
+ ge=0,
+ le=3600,
+ description="Fixed delay before the next attempt, in seconds",
+ )
+ webhook_on_retry: Literal["final_only", "every_attempt"] = Field(
+ default="final_only",
+ description="Whether to send a webhook for every attempt or only the final attempt",
+ )
+ retry_on: list[WorkflowRetryRule] = Field(
+ min_length=1,
+ description="Terminal status rules that enable retries",
+ )
+
+ @field_validator("retry_on")
+ @classmethod
+ def validate_unique_statuses(cls, retry_on: list[WorkflowRetryRule]) -> list[WorkflowRetryRule]:
+ statuses = [rule.status for rule in retry_on]
+ if len(statuses) != len(set(statuses)):
+ raise ValueError("retry_on must contain each status at most once")
+ return retry_on
+
+
class WorkflowDefinitionYAML(BaseModel):
version: int | None = None
parameters: list[PARAMETER_YAML_TYPES]
blocks: list[BLOCK_YAML_TYPES]
finally_block_label: str | None = None
error_code_mapping: dict[str, str] | None = None
+ retry_policy: WorkflowRetryPolicy | None = Field(
+ default=None,
+ description="Optional policy for retrying eligible terminal workflow runs",
+ )
workflow_system_prompt: str | None = None
completion_contract: dict[str, Any] | None = Field(
default=None,
diff --git a/skyvern/services/block_service.py b/skyvern/services/block_service.py
index 9d5469ee9..ab8168295 100644
--- a/skyvern/services/block_service.py
+++ b/skyvern/services/block_service.py
@@ -92,6 +92,7 @@ async def ensure_workflow_run(
debug_session_id=block_run_request.debug_session_id,
code_gen=block_run_request.code_gen,
trigger_type=trigger_type,
+ block_scoped=True,
)
return workflow_run
diff --git a/skyvern/services/cleanup_service.py b/skyvern/services/cleanup_service.py
index 2655cb0a6..d2e6f2f7f 100644
--- a/skyvern/services/cleanup_service.py
+++ b/skyvern/services/cleanup_service.py
@@ -136,9 +136,10 @@ def sweep_stale_temp_artifacts(max_age_hours: float | None = None) -> int:
DOWNLOAD_PATH is swept only when the active storage backend uploads run downloads
elsewhere (S3/Azure/GCS), leaving the local copy as scratch. On the local backend
- LocalStorage.save_downloaded_files is a no-op and get_downloaded_files serves the files
- in place via file:// URIs, so DOWNLOAD_PATH/<run_id> is the run's permanent artifact
- record — sweeping it would silently delete user data — and it is left untouched.
+ LocalStorage.save_downloaded_files copies each file into the artifact path, but a file it
+ skips (an upload failure, an older-attempt file) is still served only from
+ DOWNLOAD_PATH/<run_id> via file:// URIs, so that directory stays the fallback record and
+ is left untouched.
Returns:
Number of entries removed.
diff --git a/skyvern/services/run_service.py b/skyvern/services/run_service.py
index 91a6221f8..e50a02da3 100644
--- a/skyvern/services/run_service.py
+++ b/skyvern/services/run_service.py
@@ -1,4 +1,5 @@
import asyncio
+from datetime import datetime, timedelta
import structlog
from fastapi import HTTPException, status
@@ -6,8 +7,10 @@ from fastapi import HTTPException, status
from skyvern.config import settings
from skyvern.exceptions import OrganizationNotFound, TaskNotFound, WorkflowRunNotFound
from skyvern.forge import app
+from skyvern.forge.sdk.db.datetime_utils import naive_utc_now
from skyvern.forge.sdk.schemas.tasks import TaskStatus
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
+from skyvern.forge.sdk.workflow.retry_policy import LEASE_TAKEOVER_SECONDS, RetryDecision, get_recorded_decision
from skyvern.forge.sdk.workflow.service import (
truncate_oversized_response_text,
truncate_oversized_response_value,
@@ -171,9 +174,50 @@ async def cancel_workflow_run(
]:
continue
await app.WORKFLOW_SERVICE.mark_workflow_run_as_canceled(child_workflow_run.workflow_run_id)
- await app.WORKFLOW_SERVICE.mark_workflow_run_as_canceled(workflow_run_id)
- await uploaded_file_service.delete_files_attached_to_run(run_id=workflow_run_id)
- await app.WORKFLOW_SERVICE.execute_workflow_webhook(workflow_run, api_key=api_key)
+
+ attempt_rows = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ if workflow_run.status.is_final() and attempt_rows:
+ latest_attempt = max(attempt_rows, key=lambda attempt: attempt.attempt_number)
+ await app.DATABASE.workflow_run_attempts.revoke_or_abandon_attempt(
+ workflow_run_id=workflow_run_id,
+ attempt_number=latest_attempt.attempt_number,
+ decision="revoked",
+ reason="cancel",
+ )
+ workflow_run = (
+ await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ )
+ or workflow_run
+ )
+
+ workflow_run = await app.WORKFLOW_SERVICE.mark_workflow_run_as_canceled(workflow_run_id)
+ attempt_rows = await app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ if attempt_rows:
+ decision = await get_recorded_decision(workflow_run_id)
+ if decision is None:
+ attempt_number = max(attempt_rows, key=lambda attempt: attempt.attempt_number).attempt_number
+ decision = RetryDecision(False, attempt_number, 0, True, "cancel")
+ attempt = next((row for row in attempt_rows if row.attempt_number == decision.attempt_number), None)
+ side_effects_claim_at = getattr(attempt, "side_effects_released_at", None)
+ if isinstance(side_effects_claim_at, datetime):
+ await app.WORKFLOW_SERVICE._run_terminal_side_effects_with_retries(
+ workflow_run,
+ decision,
+ api_key=api_key,
+ side_effects_claim_at=side_effects_claim_at,
+ side_effects_stale_before=naive_utc_now() - timedelta(seconds=LEASE_TAKEOVER_SECONDS),
+ )
+ else:
+ await app.WORKFLOW_SERVICE._run_terminal_side_effects_with_retries(
+ workflow_run,
+ decision,
+ api_key=api_key,
+ )
+ else:
+ await uploaded_file_service.delete_files_attached_to_run(run_id=workflow_run_id)
+ await app.WORKFLOW_SERVICE.execute_workflow_webhook(workflow_run, api_key=api_key)
async def cancel_run(run_id: str, organization_id: str | None = None, api_key: str | None = None) -> None:
diff --git a/skyvern/services/script_service.py b/skyvern/services/script_service.py
index 614d5efd7..d24af8cf1 100644
--- a/skyvern/services/script_service.py
+++ b/skyvern/services/script_service.py
@@ -52,6 +52,7 @@ from skyvern.forge.sdk.api.llm.api_handler_factory import (
get_org_aware_secondary_llm_api_handler,
)
from skyvern.forge.sdk.artifact.models import ArtifactType
+from skyvern.forge.sdk.artifact.storage.base import get_download_retry_started_at, is_file_from_retry_attempt
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.hashing import diagnostic_fingerprint
from skyvern.forge.sdk.db.enums import TaskType, is_job_recipe_workflow_run_trigger_type
@@ -654,6 +655,7 @@ async def _create_workflow_block_run_and_task(
workflow_run_block = await app.DATABASE.observer.create_workflow_run_block(
workflow_run_id=workflow_run_id,
+ attempt_number=app.WORKFLOW_CONTEXT_MANAGER.get_attempt_number(workflow_run_id),
parent_workflow_run_block_id=context.parent_workflow_run_block_id,
organization_id=organization_id,
block_type=block_type,
@@ -704,6 +706,7 @@ async def _create_workflow_block_run_and_task(
status="running",
organization_id=organization_id,
workflow_run_id=workflow_run_id,
+ attempt_number=app.WORKFLOW_CONTEXT_MANAGER.get_attempt_number(workflow_run_id),
model=model,
# always use the action history for validation in caching/script run
include_action_history_in_verification=True,
@@ -1000,7 +1003,7 @@ async def _update_workflow_block(
downloaded_files: list[FileInfo] = []
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
- downloaded_files = await app.STORAGE.get_downloaded_files(
+ downloaded_files = await app.STORAGE.get_current_attempt_downloaded_files(
organization_id=context.organization_id,
run_id=context.workflow_run_id,
)
@@ -1009,6 +1012,7 @@ async def _update_workflow_block(
downloaded_files = _filter_downloaded_files_for_current_iteration(
downloaded_files,
context.loop_internal_state,
+ aliases=app.STORAGE.get_downloaded_file_signature_aliases,
)
task_screenshot_artifacts = await app.WORKFLOW_SERVICE.get_recent_task_screenshot_artifacts(
@@ -2502,6 +2506,17 @@ async def download(
context.workflow_run_id or ""
)
+ attempt_started_at = await get_download_retry_started_at(context.organization_id, download_run_id)
+
+ def current_attempt_local_files(directory: Path) -> list[str]:
+ if not directory.exists():
+ return []
+ return [
+ file_path
+ for file_path in list_files_in_directory(directory)
+ if attempt_started_at is None or is_file_from_retry_attempt(file_path, attempt_started_at)
+ ]
+
try:
await _prepare_cached_block_inputs(cache_key, navigation_prompt)
@@ -2529,7 +2544,7 @@ async def download(
# Track local files before download for renaming with download_suffix
local_download_dir = get_path_for_workflow_download_directory(download_run_id)
- local_files_before = list_files_in_directory(local_download_dir) if local_download_dir.exists() else []
+ local_files_before = current_attempt_local_files(local_download_dir)
local_file_signatures_before: dict[str, tuple[int, int]] = {}
for file_path in local_files_before:
try:
@@ -2550,6 +2565,7 @@ async def download(
download_dir=local_download_dir,
organization_id=org_id,
browser_session_id=context.browser_session_id,
+ attempt_started_at=attempt_started_at,
)
# Poll local filesystem for newly downloaded files.
@@ -2582,7 +2598,7 @@ async def download(
while True:
_now = _loop.time()
_elapsed = _now - _poll_start
- _local_files_now = list_files_in_directory(local_download_dir) if local_download_dir.exists() else []
+ _local_files_now = current_attempt_local_files(local_download_dir)
_new_files = [file_path for file_path in _local_files_now if file_path not in local_files_before]
_changed_files = []
for file_path in _local_files_now:
@@ -2659,7 +2675,7 @@ async def download(
# correctly-named file and subsequent blocks get the right URLs.
# This matches the agent path ordering in agent.py.
if download_suffix and local_download_dir.exists():
- local_files_after = list_files_in_directory(local_download_dir)
+ local_files_after = current_attempt_local_files(local_download_dir)
files_to_rename = [file_path for file_path in newly_downloaded_files if file_path in local_files_after]
newly_downloaded_files = []
for file_path in files_to_rename:
@@ -2809,9 +2825,7 @@ async def download(
LOG.warning("Failed to run download block. Falling back to AI run.", exc_info=True)
fallback_download_dir = get_path_for_workflow_download_directory(download_run_id)
- fallback_files_before = (
- list_files_in_directory(fallback_download_dir) if fallback_download_dir.exists() else []
- )
+ fallback_files_before = current_attempt_local_files(fallback_download_dir)
fallback_file_signatures_before: dict[str, tuple[int, int]] = {}
for file_path in fallback_files_before:
try:
@@ -2832,9 +2846,7 @@ async def download(
error_code_mapping=error_code_mapping,
)
if file_download_block is not None and storage_type is not None:
- fallback_files_after = (
- list_files_in_directory(fallback_download_dir) if fallback_download_dir.exists() else []
- )
+ fallback_files_after = current_attempt_local_files(fallback_download_dir)
fallback_downloaded_files = []
for file_path in fallback_files_after:
signature_before = fallback_file_signatures_before.get(file_path)
@@ -4067,7 +4079,7 @@ async def loop(
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
downloaded_file_signatures_before_iteration = [
_to_downloaded_file_signature(file_info)
- for file_info in await app.STORAGE.get_downloaded_files(
+ for file_info in await app.STORAGE.get_current_attempt_downloaded_files(
organization_id=organization_id or "",
run_id=workflow_run_id,
)
@@ -4218,7 +4230,7 @@ async def while_loop(
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
downloaded_file_signatures_before_iteration = [
_to_downloaded_file_signature(file_info)
- for file_info in await app.STORAGE.get_downloaded_files(
+ for file_info in await app.STORAGE.get_current_attempt_downloaded_files(
organization_id=organization_id or "",
run_id=workflow_run_id,
)
diff --git a/skyvern/services/uploaded_file_service.py b/skyvern/services/uploaded_file_service.py
index af4892221..e42277679 100644
--- a/skyvern/services/uploaded_file_service.py
+++ b/skyvern/services/uploaded_file_service.py
@@ -8,6 +8,7 @@ caller's organization prefix by the storage layer before the object is removed.
from __future__ import annotations
+import asyncio
import os
from datetime import datetime, timedelta, timezone
@@ -21,6 +22,8 @@ from skyvern.forge.sdk.schemas.files import UploadedFile
LOG = structlog.get_logger()
+DEFAULT_TERMINAL_SIDE_EFFECT_TIMEOUT_SECONDS = 30.0
+
class InvalidRetentionPeriod(ValueError):
pass
@@ -229,7 +232,27 @@ async def attach_files_to_run(*, file_ids: list[str], organization_id: str, run_
return attached
-async def delete_files_attached_to_run(*, run_id: str) -> int:
+async def delete_files_attached_to_run(
+ *,
+ run_id: str,
+ timeout_seconds: float | None = None,
+) -> int:
+ try:
+ async with asyncio.timeout(timeout_seconds):
+ return await _delete_files_attached_to_run(run_id=run_id)
+ except TimeoutError:
+ LOG.warning(
+ "Timed out while deleting files attached to run",
+ run_id=run_id,
+ timeout_seconds=timeout_seconds,
+ )
+ return 0
+ except Exception:
+ LOG.exception("Failed to delete files attached to run", run_id=run_id)
+ return 0
+
+
+async def _delete_files_attached_to_run(*, run_id: str) -> int:
"""Delete every file attached to a run. Safe to call for runs that have no attachments.
Never raises. This runs inside run teardown, where an exception would cost the run its
diff --git a/skyvern/services/webhook_service.py b/skyvern/services/webhook_service.py
index 7aa1aecfc..c78a94dee 100644
--- a/skyvern/services/webhook_service.py
+++ b/skyvern/services/webhook_service.py
@@ -30,6 +30,12 @@ from skyvern.forge.sdk.workflow.models.workflow import (
WorkflowRunResponseBase,
WorkflowRunStatus,
)
+from skyvern.forge.sdk.workflow.retry_policy import (
+ RETRY_DECISION_ABANDONED,
+ RETRY_DECISION_FINAL,
+ RETRY_DECISION_REVOKED,
+ compute_attempt_view,
+)
from skyvern.schemas.runs import (
ProxyLocation,
RunStatus,
@@ -239,6 +245,25 @@ async def replay_run_webhook(
API key from the database. This is useful for endpoints that authenticate with an API key and want the replay
signature to match the caller-provided key.
"""
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=run_id,
+ organization_id=organization_id,
+ )
+ if workflow_run is not None:
+ attempt_rows = await app.DATABASE.workflow_run_attempts.get_attempts(run_id)
+ attempt_view = compute_attempt_view(workflow_run, attempt_rows)
+ # A run without attempt rows replays at any status, as before retry policies existed.
+ if attempt_rows and (
+ not workflow_run.status.is_final()
+ or attempt_view.retry_pending
+ or attempt_view.attempts[-1].retry_decision
+ not in {RETRY_DECISION_FINAL, RETRY_DECISION_REVOKED, RETRY_DECISION_ABANDONED}
+ ):
+ raise SkyvernHTTPException(
+ f"Run {run_id} is not final; webhook replay is unavailable until it is final.",
+ status_code=status.HTTP_409_CONFLICT,
+ )
+
payload = await _build_webhook_payload(organization_id=organization_id, run_id=run_id)
signing_key = api_key if api_key else await _get_api_key(organization_id=organization_id)
signed_data = generate_skyvern_webhook_signature(payload=payload.payload, api_key=signing_key)
@@ -427,6 +452,10 @@ async def _build_workflow_payload(
run_id=workflow_run.workflow_run_id,
run_type=RunType.workflow_run,
status=RunStatus(status_response.status),
+ attempt=status_response.attempt,
+ retry_pending=status_response.retry_pending,
+ next_attempt_at=status_response.next_attempt_at,
+ attempts=status_response.attempts,
output=status_response.outputs,
downloaded_files=status_response.downloaded_files,
recording_url=status_response.recording_url,
diff --git a/skyvern/services/workflow_schedule_service.py b/skyvern/services/workflow_schedule_service.py
index 5bddcae8e..4050c737f 100644
--- a/skyvern/services/workflow_schedule_service.py
+++ b/skyvern/services/workflow_schedule_service.py
@@ -18,9 +18,11 @@ from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from skyvern.config import settings
from skyvern.forge import app
+from skyvern.forge.sdk.api.llm.custom_llm_registry import prepare_org_llm_runtime
from skyvern.forge.sdk.db.enums import WorkflowRunTriggerType
from skyvern.forge.sdk.schemas.workflow_schedules import WorkflowSchedule
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRequestBody
+from skyvern.forge.sdk.workflow.retry_policy import queue_initial_attempt
from skyvern.forge.sdk.workflow.schedules import compute_previous_fire_time
from skyvern.services.workflow_service import prepare_workflow
from skyvern.utils.files import initialize_skyvern_state_file
@@ -220,15 +222,24 @@ class LocalWorkflowScheduleScheduler:
return
raise
+ # A persisted run counts as a delivered fire, so the attempt must be recoverable by the dispatch
+ # sweep before the initializers below can fail.
+ if not await queue_initial_attempt(workflow_run.workflow_run_id, 1):
+ return
await initialize_skyvern_state_file(
workflow_run_id=workflow_run.workflow_run_id,
organization_id=organization.organization_id,
)
- await app.WORKFLOW_SERVICE.execute_workflow(
+ await prepare_org_llm_runtime(app.DATABASE, organization.organization_id, organization)
+ await app.WORKFLOW_SERVICE.execute_workflow_with_retries(
workflow_run_id=workflow_run.workflow_run_id,
api_key=None,
organization=organization,
browser_session_id=workflow_run.browser_session_id,
+ block_labels=None,
+ block_outputs=None,
+ need_call_webhook=True,
+ claim_initial_attempt=True,
)
diff --git a/skyvern/services/workflow_service.py b/skyvern/services/workflow_service.py
index 9d92535fa..bc0005418 100644
--- a/skyvern/services/workflow_service.py
+++ b/skyvern/services/workflow_service.py
@@ -104,6 +104,7 @@ async def prepare_workflow(
copilot_session_id: str | None = None,
resolved_workflow_id: str | None = None,
tag_write_context: TagWriteContext | None = None,
+ block_scoped: bool = False,
) -> WorkflowRun:
"""
Prepare a workflow to be run.
@@ -135,6 +136,7 @@ async def prepare_workflow(
copilot_session_id=copilot_session_id,
resolved_workflow_id=resolved_workflow_id,
tag_write_context=tag_write_context,
+ block_scoped=block_scoped,
)
if resolved_workflow_id is not None:
@@ -248,6 +250,10 @@ async def get_workflow_run_response(
run_id=workflow_run_id,
run_type=RunType.workflow_run,
status=RunStatus(workflow_run.status),
+ attempt=workflow_run_resp.attempt,
+ retry_pending=workflow_run_resp.retry_pending,
+ next_attempt_at=workflow_run_resp.next_attempt_at,
+ attempts=workflow_run_resp.attempts,
output=workflow_run_resp.outputs,
downloaded_files=workflow_run_resp.downloaded_files,
recording_url=workflow_run_resp.recording_url,
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index 4300f4afd..fc4ba0b2b 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -115,6 +115,7 @@ from skyvern.forge.sdk.api.llm.api_handler_factory import (
)
from skyvern.forge.sdk.api.llm.exceptions import LLMProviderError
from skyvern.forge.sdk.api.llm.schema_validator import extraction_shape_matches, validate_and_fill_extraction_result
+from skyvern.forge.sdk.artifact.storage.base import get_download_retry_started_at, is_file_from_retry_attempt
from skyvern.forge.sdk.browser_action_preflight import preflight_action, preflight_derived_action
from skyvern.forge.sdk.cache import extraction_cache, extraction_shadow
from skyvern.forge.sdk.copilot.block_goal_wrapping import unwrap_goal_fields
@@ -1645,13 +1646,16 @@ def _normalize_download_identity(file: str) -> str:
return _INTERCEPTOR_TEMP_IDENTITY_RE.sub("", file.removesuffix(BROWSER_DOWNLOADING_SUFFIX))
-def _local_download_signal_identities(download_dir: Path) -> set[str]:
+def _local_download_signal_identities(download_dir: Path, *, attempt_started_at: datetime | None = None) -> set[str]:
"""Task-local download-signal identities from the local run directory only (no remote-storage
enumeration). Each name is normalized so both in-flight temp shapes -- Chrome-native ``<final>.crdownload``
and the interceptor's ``<final>.<32-lowercase-hex>.crdownload`` -- collapse to the same ``<final>`` identity
as the settled file, so a download counted mid-flight and again once settled is never seen as new against
its own baseline. Incomplete temp files are included so a pre-existing partial is part of the baseline."""
- return {_normalize_download_identity(file) for file in list_files_in_directory(download_dir)}
+ return {
+ _normalize_download_identity(file)
+ for file in list_files_in_directory(download_dir, attempt_started_at=attempt_started_at)
+ }
async def _settle_and_close_false_click_download(
@@ -1665,6 +1669,7 @@ async def _settle_and_close_false_click_download(
baseline: _PageDeltaBaseline | None,
download_dir: Path,
signal_before: set[str],
+ attempt_started_at: datetime | None = None,
) -> None:
"""Synchronous FileDownloadBlock lifecycle for a non-download click/select, entered only when the action
left an immediate same-context Page delta (the caller gates on it). With a Page present but no file signal
@@ -1681,7 +1686,11 @@ async def _settle_and_close_false_click_download(
return
def _list_local_final_files() -> list[str]:
- return [file for file in list_files_in_directory(download_dir) if not file.endswith(BROWSER_DOWNLOADING_SUFFIX)]
+ return [
+ file
+ for file in list_files_in_directory(download_dir, attempt_started_at=attempt_started_at)
+ if not file.endswith(BROWSER_DOWNLOADING_SUFFIX)
+ ]
async def _list_final() -> list[str]:
return _list_local_final_files()
@@ -1724,7 +1733,7 @@ async def _settle_and_close_false_click_download(
observed_delta_pages.append(candidate)
if owning_context is not None:
owning_context.record_download_popup_claim(task.task_id, candidate)
- if _local_download_signal_identities(download_dir) - signal_before:
+ if _local_download_signal_identities(download_dir, attempt_started_at=attempt_started_at) - signal_before:
file_signal_observed = True
if observed_delta_pages and file_signal_observed:
break
@@ -1742,10 +1751,12 @@ async def _settle_and_close_false_click_download(
# whose normalized identity appeared since the pre-action baseline. Unrelated pre-existing partials in
# the shared download dir are excluded, so a stalled older download cannot extend this action for
# minutes. An already-settled new file leaves this set empty, so finalization returns without waiting.
- new_identities = _local_download_signal_identities(download_dir) - signal_before
+ new_identities = (
+ _local_download_signal_identities(download_dir, attempt_started_at=attempt_started_at) - signal_before
+ )
attributable_downloading = [
path
- for path in list_downloading_files_in_directory(download_dir)
+ for path in list_downloading_files_in_directory(download_dir, attempt_started_at=attempt_started_at)
if _normalize_download_identity(path) in new_identities
]
downloaded_file_names, _ = await _finalize_download_artifacts(
@@ -1755,6 +1766,7 @@ async def _settle_and_close_false_click_download(
list_observed_download_files=_list_final,
timeout_seconds=max(0.0, overall_deadline_seconds - (time.monotonic() - started_at)),
downloading_files=attributable_downloading,
+ attempt_started_at=attempt_started_at,
)
# Durable completion is what authorizes the close: an observed signal that never finalizes (e.g. a
# stalled ``.crdownload``) leaves the page open and the claim intact for the late-credit backstop
@@ -1856,6 +1868,7 @@ async def _finalize_download_artifacts(
task: Task,
list_files_before: list[str],
list_observed_download_files: Callable[[], Awaitable[list[str]]],
+ attempt_started_at: datetime | None = None,
timeout_seconds: float | None = None,
downloading_files: list[str] | None = None,
) -> tuple[list[str], set[str]]:
@@ -1872,6 +1885,7 @@ async def _finalize_download_artifacts(
organization_id=task.organization_id,
browser_session_id=task.browser_session_id,
timeout=settle_timeout,
+ attempt_started_at=attempt_started_at,
)
elif downloading_files:
try:
@@ -4643,6 +4657,12 @@ class ActionHandler:
# Capture the owning context in the action coroutine so the popup callback never reads a
# possibly empty/stale skyvern_context.current() at dispatch.
false_click_owning_context = skyvern_context.current()
+ false_click_run_id = resolve_run_download_id(
+ false_click_owning_context, task.workflow_run_id or task.task_id
+ )
+ false_click_attempt_started_at = await get_download_retry_started_at(
+ task.organization_id, false_click_run_id
+ )
# Retain the initiating BrowserContext, run the bounded pre-action quiescence gate, THEN
# snapshot the delta baseline: a Page/file a previous action's in-flight browser/CDP handler
# produced during the admission window is pre-existing, not this click's. Prove quiescence
@@ -4665,11 +4685,10 @@ class ActionHandler:
false_click_quiescent = False
# Task/run download baseline captured BEFORE the inner action (contract requirement) so a file
# landing during it counts as new. Local run dir only, including in-flight ``.crdownload``.
- false_click_run_id = resolve_run_download_id(
- false_click_owning_context, task.workflow_run_id or task.task_id
- )
false_click_download_dir = Path(get_download_dir(run_id=false_click_run_id))
- false_click_signal_before = _local_download_signal_identities(false_click_download_dir)
+ false_click_signal_before = _local_download_signal_identities(
+ false_click_download_dir, attempt_started_at=false_click_attempt_started_at
+ )
false_click_popup_event_count = 0
with traced_span(_tracer, "skyvern.agent.action.false_click_download"):
false_click_download_event: asyncio.Future[tuple[Download, Page]] = (
@@ -4723,15 +4742,23 @@ class ActionHandler:
context = skyvern_context.current()
run_id = resolve_run_download_id(context, task.workflow_run_id or task.task_id)
download_dir = Path(get_download_dir(run_id=run_id))
+ attempt_started_at = await get_download_retry_started_at(task.organization_id, run_id)
async def list_false_click_files(extra: Path | None = None) -> list[str]:
- files = list_files_in_directory(download_dir)
+ files = list_files_in_directory(download_dir, attempt_started_at=attempt_started_at)
if task.browser_session_id:
files += await app.STORAGE.list_downloaded_files_in_browser_session(
organization_id=task.organization_id,
browser_session_id=task.browser_session_id,
)
- if extra and extra.is_file():
+ if (
+ extra
+ and extra.is_file()
+ and (
+ attempt_started_at is None
+ or is_file_from_retry_attempt(str(extra), attempt_started_at)
+ )
+ ):
files.append(str(extra))
return files
@@ -4761,6 +4788,7 @@ class ActionHandler:
task=task,
list_files_before=baseline,
list_observed_download_files=lambda: list_false_click_files(persisted.path),
+ attempt_started_at=attempt_started_at,
)
try:
persisted_artifact_qualified = (
@@ -4871,6 +4899,7 @@ class ActionHandler:
baseline=false_click_baseline,
download_dir=false_click_download_dir,
signal_before=false_click_signal_before,
+ attempt_started_at=false_click_attempt_started_at,
)
action.finished_at = naive_utc_now()
persisted_action = await app.DATABASE.workflow_params.create_action(
@@ -4882,6 +4911,7 @@ class ActionHandler:
context = skyvern_context.current()
run_id = resolve_run_download_id(context, fallback_run_id=task.workflow_run_id or task.task_id)
download_dir = Path(get_download_dir(run_id=run_id))
+ attempt_started_at = await get_download_retry_started_at(task.organization_id, run_id)
download_event: asyncio.Future[Download] = asyncio.get_running_loop().create_future()
eager_blob_capture = _EagerAdoptedBlobCapture(
enabled=bool(task.browser_session_id),
@@ -4915,7 +4945,7 @@ class ActionHandler:
return _normalize_download_identity(file)
async def _list_download_signal_files() -> list[str]:
- files = list_files_in_directory(download_dir)
+ files = list_files_in_directory(download_dir, attempt_started_at=attempt_started_at)
if task.browser_session_id:
downloading_files_in_browser_session = await app.STORAGE.list_downloading_files_in_browser_session(
organization_id=task.organization_id, browser_session_id=task.browser_session_id
@@ -4928,7 +4958,9 @@ class ActionHandler:
async def _list_final_download_files() -> list[str]:
files = [
- file for file in list_files_in_directory(download_dir) if not file.endswith(BROWSER_DOWNLOADING_SUFFIX)
+ file
+ for file in list_files_in_directory(download_dir, attempt_started_at=attempt_started_at)
+ if not file.endswith(BROWSER_DOWNLOADING_SUFFIX)
]
if task.browser_session_id:
files += await app.STORAGE.list_downloaded_files_in_browser_session(
@@ -5473,6 +5505,7 @@ class ActionHandler:
task=task,
list_files_before=list_files_before,
list_observed_download_files=_list_final_download_files,
+ attempt_started_at=attempt_started_at,
)
if downloaded_file_names:
results[-1].downloaded_files = action.downloaded_files = downloaded_file_names
diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py
index b9db14f01..f9599224e 100644
--- a/tests/unit/conftest.py
+++ b/tests/unit/conftest.py
@@ -13,7 +13,7 @@ from contextlib import AbstractAsyncContextManager, asynccontextmanager
from dataclasses import dataclass
from pathlib import Path
from types import SimpleNamespace
-from typing import TypeVar
+from typing import Any, TypeVar
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -42,6 +42,26 @@ from tests.unit.force_stub_app import start_forge_stub_app
LEGACY_DOWNLOAD_ESCAPE_CASES = ("parent_traversal", "encoded_dot_dot", "sibling_prefix", "symlink_escape")
+class FakeWorkflowRunAttemptsRepository:
+ """Small in-memory repository for tests that need durable attempt resolution."""
+
+ def __init__(self, attempts: list[Any] | None = None) -> None:
+ self.attempts = list(attempts or [])
+ self.requested_workflow_run_ids: list[str] = []
+
+ async def get_attempts(self, workflow_run_id: str) -> list[Any]:
+ self.requested_workflow_run_ids.append(workflow_run_id)
+ return list(self.attempts)
+
+ async def refresh_attempt_finished_at(self, workflow_run_id: str, attempt_number: int, *, finished_at: Any) -> Any:
+ for attempt in self.attempts:
+ if attempt.workflow_run_id == workflow_run_id and attempt.attempt_number == attempt_number:
+ if getattr(attempt, "retry_decision", None) is not None:
+ attempt.finished_at = finished_at
+ return attempt
+ return None
+
+
@pytest.fixture
def legacy_download_uris(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict[str, str]:
"""file:// URIs into a synthetic legacy repo root: one canonical file plus every escape class.
@@ -90,12 +110,14 @@ def workflow_context_manager_factory() -> Callable[..., WorkflowContextManager]:
mask_secrets: bool = True,
secrets: dict[str, str] | None = None,
runtime_otp_values: set[str] | None = None,
+ attempt_number: int = 1,
) -> WorkflowContextManager:
manager = WorkflowContextManager()
manager.workflow_run_contexts[workflow_run_id] = SimpleNamespace(
mask_secrets=mask_secrets,
secrets=dict(secrets or {}),
runtime_otp_values=set(runtime_otp_values or set()),
+ attempt_number=attempt_number,
)
return manager
diff --git a/tests/unit/embedded/test_sqlite_server_mode.py b/tests/unit/embedded/test_sqlite_server_mode.py
index 92ffa537a..0e0c5d4f0 100644
--- a/tests/unit/embedded/test_sqlite_server_mode.py
+++ b/tests/unit/embedded/test_sqlite_server_mode.py
@@ -188,6 +188,30 @@ async def test_sqlite_bootstrap_upgrades_legacy_organization_table(
assert "uq_organizations_slug" in indexes
+async def test_sqlite_bootstrap_adds_attempt_columns_to_existing_tables(
+ sqlite_bootstrap_db,
+ patched_env_writes,
+) -> None:
+ """Bootstrap adds the retry attempt columns to a database created before them, so ORM reads work again."""
+ from sqlalchemy import select
+
+ from skyvern.forge.api_app import _bootstrap_sqlite
+ from skyvern.forge.sdk.db.models import Base, TaskModel, WorkflowRunBlockModel
+
+ async with sqlite_bootstrap_db.engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+ await conn.exec_driver_sql("ALTER TABLE tasks DROP COLUMN attempt_number")
+ await conn.exec_driver_sql("ALTER TABLE workflow_run_blocks DROP COLUMN attempt_number")
+
+ await _bootstrap_sqlite()
+ await _bootstrap_sqlite()
+
+ async with sqlite_bootstrap_db.Session() as session:
+ assert (await session.execute(select(TaskModel))).scalars().all() == []
+ assert (await session.execute(select(WorkflowRunBlockModel))).scalars().all() == []
+
+
@pytest.mark.asyncio
async def test_sqlite_bootstrap_syncs_existing_env_api_key(
monkeypatch: pytest.MonkeyPatch,
@@ -352,6 +376,43 @@ async def test_local_persistent_mode_accepts_settings_without_dotenv(
await skyvern.aclose()
+async def test_persistent_embedded_mode_upgrades_an_existing_sqlite_schema(tmp_path: Path) -> None:
+ """Persistent embedded mode never runs the server lifespan, so it must bootstrap the SQLite schema itself."""
+ from sqlalchemy import select
+
+ from skyvern.forge import app as forge_app
+ from skyvern.forge.sdk.db.agent_db import AgentDB
+ from skyvern.forge.sdk.db.models import Base, TaskModel, WorkflowRunBlockModel
+ from skyvern.library.embedded_server_factory import create_embedded_server
+
+ db = AgentDB(f"sqlite+aiosqlite:///{tmp_path / 'existing.db'}")
+ async with db.engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+ await conn.exec_driver_sql("ALTER TABLE tasks DROP COLUMN attempt_number")
+ await conn.exec_driver_sql("ALTER TABLE workflow_run_blocks DROP COLUMN attempt_number")
+
+ async def fake_app(scope, receive, send): # type: ignore[no-untyped-def]
+ await send({"type": "http.response.start", "status": 200, "headers": []})
+ await send({"type": "http.response.body", "body": b"[]"})
+
+ original_db = forge_app.DATABASE
+ forge_app.DATABASE = db # type: ignore[assignment]
+ client = create_embedded_server(settings_overrides={"SKYVERN_API_KEY": "dummy-key"}, use_in_memory_db=False)
+ try:
+ with patch("skyvern.library.embedded_server_factory.create_api_app", return_value=fake_app):
+ response = await client.get("/")
+ assert response.status_code == 200
+ # The mapped models select every column; a missing one fails here with "no such column".
+ async with db.Session() as session:
+ assert (await session.execute(select(TaskModel))).scalars().all() == []
+ assert (await session.execute(select(WorkflowRunBlockModel))).scalars().all() == []
+ finally:
+ await client.aclose()
+ forge_app.DATABASE = original_db # type: ignore[assignment]
+ await db.engine.dispose()
+
+
@pytest.mark.asyncio
async def test_create_embedded_server_uses_settings_api_key_in_persistent_mode() -> None:
"""Persistent embedded bootstrap should read SKYVERN_API_KEY from settings overrides."""
diff --git a/tests/unit/force_stub_app.py b/tests/unit/force_stub_app.py
index ea2a28459..6ac91e8d3 100644
--- a/tests/unit/force_stub_app.py
+++ b/tests/unit/force_stub_app.py
@@ -24,13 +24,20 @@ def create_forge_stub_app() -> ForgeApp:
fake_app_module = ForgeApp()
fake_app_module.DATABASE = _LazyNamespace()
+ # Retry-policy-aware production paths query the attempt repository even for legacy runs.
+ # Keep the shared stub's no-policy behavior explicit instead of letting _LazyNamespace
+ # manufacture truthy AsyncMocks for these reads.
+ fake_app_module.DATABASE.workflow_run_attempts = make_workflow_run_attempts_fake()
+ fake_app_module.DATABASE.debug = SimpleNamespace(has_block_run_for_workflow_run=AsyncMock(return_value=False))
fake_app_module.WORKFLOW_CONTEXT_MANAGER = _LazyNamespace()
+ fake_app_module.WORKFLOW_CONTEXT_MANAGER.workflow_run_contexts = {}
fake_app_module.WORKFLOW_CONTEXT_MANAGER.mask_secrets_enabled_for_run = MagicMock(return_value=False)
fake_app_module.WORKFLOW_CONTEXT_MANAGER.secret_redaction_enabled_for_run = MagicMock(return_value=False)
fake_app_module.WORKFLOW_CONTEXT_MANAGER.artifact_redaction_enabled = MagicMock(return_value=False)
fake_app_module.WORKFLOW_CONTEXT_MANAGER.get_secret_values_for_run = MagicMock(return_value=set())
fake_app_module.WORKFLOW_CONTEXT_MANAGER.runtime_secret_values_for_artifacts = MagicMock(return_value=set())
fake_app_module.WORKFLOW_CONTEXT_MANAGER.secret_values_for_drop_check = MagicMock(return_value=set())
+ fake_app_module.WORKFLOW_CONTEXT_MANAGER.get_attempt_number = MagicMock(return_value=1)
# Sync liveness predicate — _LazyNamespace would auto-mock it as a truthy (never-awaited) AsyncMock,
# making every wr_ alias read as a live sharer. Default to "no run is live" so tests must opt a run
# into liveness explicitly (non-PBS ownership signal).
@@ -43,6 +50,7 @@ def create_forge_stub_app() -> ForgeApp:
fake_app_module.PERSISTENT_SESSIONS_MANAGER = _LazyNamespace()
fake_app_module.ARTIFACT_MANAGER = _LazyNamespace()
fake_app_module.AGENT_FUNCTION = _LazyNamespace()
+ fake_app_module.AGENT_FUNCTION.is_block_scoped_workflow_run = AsyncMock(return_value=False)
fake_app_module.AGENT_FUNCTION.validate_block_execution = AsyncMock()
fake_app_module.AGENT_FUNCTION.validate_code_block = AsyncMock()
# Secure CodeBlock runner gating — _LazyNamespace would auto-mock these as
@@ -129,6 +137,40 @@ def create_forge_stub_app() -> ForgeApp:
return fake_app_module
+def make_workflow_run_attempts_fake() -> SimpleNamespace:
+ """Return the no-policy attempt repository used by isolated database fakes."""
+ session = AsyncMock()
+ session.execute = AsyncMock(return_value=SimpleNamespace(rowcount=0))
+ session.commit = AsyncMock()
+ session_context = MagicMock()
+ session_context.__aenter__ = AsyncMock(return_value=session)
+ session_context.__aexit__ = AsyncMock(return_value=None)
+ return SimpleNamespace(
+ Session=MagicMock(return_value=session_context),
+ create_attempt=AsyncMock(return_value=SimpleNamespace(attempt_number=1)),
+ pin_first_attempt_browser_session_if_unset=AsyncMock(),
+ get_attempts=AsyncMock(return_value=[]),
+ get_interim_payload_snapshot=AsyncMock(return_value={}),
+ get_latest_attempts_for_runs=AsyncMock(return_value={}),
+ list_stale_pending_retries=AsyncMock(return_value=[]),
+ list_attempts_needing_recovery=AsyncMock(return_value=[]),
+ list_stale_dispatch_claims=AsyncMock(return_value=[]),
+ release_stale_dispatch_claim=AsyncMock(return_value=False),
+ mark_attempt_inputs_unrecoverable=AsyncMock(),
+ refresh_attempt_finished_at=AsyncMock(return_value=None),
+ fail_prepared_workflow_run=AsyncMock(return_value=False),
+ claim_prepared_attempt_execution=AsyncMock(return_value=None),
+ finalize_attempt=AsyncMock(return_value=SimpleNamespace(attempt_number=1)),
+ revoke_or_abandon_attempt=AsyncMock(return_value=False),
+ reserve_attempt_webhook_delivery=AsyncMock(return_value=None),
+ claim_attempt_webhook=AsyncMock(return_value=False),
+ claim_attempt_side_effects=AsyncMock(return_value=False),
+ save_side_effect_progress=AsyncMock(return_value=False),
+ clear_failed_interim_side_effect_lease=AsyncMock(return_value=False),
+ delete_attempts_for_run=AsyncMock(),
+ )
+
+
def start_forge_stub_app() -> ForgeApp:
force_app_instance = create_forge_stub_app()
set_force_app_instance(force_app_instance)
diff --git a/tests/unit/forge/sdk/artifact/storage/test_azure_storage.py b/tests/unit/forge/sdk/artifact/storage/test_azure_storage.py
index cea84e9ec..5744ba7cd 100644
--- a/tests/unit/forge/sdk/artifact/storage/test_azure_storage.py
+++ b/tests/unit/forge/sdk/artifact/storage/test_azure_storage.py
@@ -1,10 +1,15 @@
-from datetime import datetime
+import hashlib
+import os
+from datetime import UTC, datetime, timedelta
from pathlib import Path
+from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+import skyvern.forge.sdk.artifact.storage.azure as azure_module
+import skyvern.forge.sdk.artifact.storage.base as base_module
from skyvern.config import settings
from skyvern.exceptions import DownloadSaveIncompleteError
from skyvern.forge.sdk.api.azure import StandardBlobTier
@@ -13,6 +18,9 @@ from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType
from skyvern.forge.sdk.artifact.storage.azure import AzureStorage
from skyvern.forge.sdk.artifact.storage.base import SENSITIVE_SHARE_URL_EXPIRY_HOURS
from skyvern.forge.sdk.artifact.storage.recording_test_helpers import fake_prepared_recording
+from skyvern.forge.sdk.workflow.context_manager import WorkflowContextManager
+from skyvern.forge.sdk.workflow.service import WorkflowService
+from tests.unit.conftest import FakeWorkflowRunAttemptsRepository
# Test constants
TEST_CONTAINER = "test-azure-container"
@@ -52,12 +60,13 @@ def mock_browser_session_artifact_create(monkeypatch: pytest.MonkeyPatch) -> Non
app isn't initialized in these storage-only tests. Covers both
download and recording artifact creators.
"""
- import skyvern.forge.sdk.artifact.storage.azure as azure_module
fake_app = MagicMock()
fake_app.ARTIFACT_MANAGER.create_browser_session_download_artifact = AsyncMock(return_value="a_test")
fake_app.ARTIFACT_MANAGER.create_browser_session_recording_artifact = AsyncMock(return_value="a_test")
fake_app.ARTIFACT_MANAGER.create_download_artifact = AsyncMock(return_value="a_test")
+ fake_app.WORKFLOW_CONTEXT_MANAGER = WorkflowContextManager()
+ fake_app.DATABASE.workflow_run_attempts = FakeWorkflowRunAttemptsRepository()
monkeypatch.setattr(azure_module, "app", fake_app)
@@ -276,6 +285,69 @@ class TestAzureStorageBuildUri:
assert uri == expected
+async def test_get_downloaded_files_legacy_listing_attributes_and_scopes_attempt_files(
+ azure_storage: AzureStorageForTests, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ run_id = "wr_retry"
+ attempt_one_modified_at = datetime(2026, 9, 7, 11, 0, tzinfo=UTC)
+ attempt_two_started_at = datetime(2026, 9, 7, 12, 0, tzinfo=UTC)
+ blob_modified_at = datetime(2026, 9, 7, 12, 1, tzinfo=UTC)
+ old_key = f"downloads/local/{settings.ENV}/{TEST_ORGANIZATION_ID}/{run_id}/old.pdf"
+ current_key = f"downloads/local/{settings.ENV}/{TEST_ORGANIZATION_ID}/{run_id}/current.pdf"
+ old_uri = f"azure://{settings.AZURE_STORAGE_CONTAINER_UPLOADS}/{old_key}"
+ old_artifact = Artifact(
+ artifact_id="a_old",
+ artifact_type=ArtifactType.DOWNLOAD,
+ uri=old_uri,
+ organization_id=TEST_ORGANIZATION_ID,
+ run_id=run_id,
+ workflow_run_id=run_id,
+ created_at=attempt_one_modified_at,
+ modified_at=attempt_one_modified_at,
+ )
+
+ async def get_object_info(uri: str) -> dict[str, Any]:
+ return {
+ "Metadata": {"sha256_checksum": f"sha-{uri.rsplit('/', 1)[-1]}"},
+ "ContentLength": 10,
+ "LastModified": blob_modified_at,
+ }
+
+ azure_storage.async_client.list_files = AsyncMock(return_value=[old_key, current_key])
+ azure_storage.async_client.get_object_info = AsyncMock(side_effect=get_object_info)
+ azure_storage.async_client.create_sas_urls = AsyncMock(
+ side_effect=lambda uris: [f"https://signed.test/{uri.rsplit('/', 1)[-1]}" for uri in uris]
+ )
+ rows = AsyncMock(return_value=[old_artifact])
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.artifact.storage.azure.app.DATABASE.artifacts.list_artifacts_for_run_by_type", rows
+ )
+
+ with patch.object(settings, "ARTIFACT_CONTENT_HMAC_KEYRING", None):
+ files = await azure_storage.get_downloaded_files(TEST_ORGANIZATION_ID, run_id)
+
+ assert len(files) == 2
+ old_file, current_file = files
+ assert old_file.artifact_id == "a_old"
+ assert old_file.modified_at == attempt_one_modified_at
+ assert current_file.artifact_id is None
+ assert current_file.modified_at == blob_modified_at
+ rows.assert_awaited_once_with(
+ run_id=run_id,
+ organization_id=TEST_ORGANIZATION_ID,
+ artifact_type=ArtifactType.DOWNLOAD,
+ )
+
+ scoped = WorkflowService()._filter_downloaded_files_to_attempt(
+ files,
+ attempt_rows=[SimpleNamespace(attempt_number=2, started_at=attempt_two_started_at)],
+ attempt_number=2,
+ artifact_ids=set(),
+ )
+ assert [file_info.filename for file_info in scoped] == ["current.pdf"]
+
+
AZURE_CONTENT_TYPE_TEST_CASES = [
# (filename, expected_content_type, artifact_type, date)
("video.webm", "video/webm", "videos", "2025-01-15"),
@@ -381,8 +453,89 @@ async def test_save_downloaded_files_partial_upload_failure_raises_after_saving_
monkeypatch.setattr(azure_storage.async_client, "upload_file_from_path", _upload)
+ monkeypatch.setattr(base_module.app.DATABASE.workflow_runs, "get_workflow_run", AsyncMock(return_value=None))
+
with pytest.raises(DownloadSaveIncompleteError) as raised:
await azure_storage.save_downloaded_files(organization_id=TEST_ORGANIZATION_ID, run_id="wr_partial")
assert raised.value.skipped_files == ["a.pdf"]
assert [uri.rsplit("/", 1)[-1] for uri in uploaded] == ["b.pdf"]
+
+
+async def test_save_downloaded_files_retry_skips_stale_files_and_versions_fresh_redownloads(
+ azure_storage: AzureStorageForTests, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ run_id = "wr_retry"
+ run_dir = tmp_path / "downloads" / run_id
+ run_dir.mkdir(parents=True)
+ stale_file = run_dir / "only-attempt-1.pdf"
+ fresh_file = run_dir / "report.pdf"
+ stale_file.write_bytes(b"same bytes")
+ fresh_file.write_bytes(b"same bytes")
+ monkeypatch.setattr("skyvern.forge.sdk.api.files.settings.DOWNLOAD_PATH", str(tmp_path / "downloads"))
+
+ attempt_started_at = datetime.now(UTC) - timedelta(seconds=1)
+ os.utime(stale_file, (attempt_started_at.timestamp() - 60, attempt_started_at.timestamp() - 60))
+ os.utime(fresh_file, (attempt_started_at.timestamp() + 1, attempt_started_at.timestamp() + 1))
+ checksum = hashlib.sha256(b"same bytes").hexdigest()
+ base_uri = (
+ f"azure://{settings.AZURE_STORAGE_CONTAINER_UPLOADS}/downloads/{settings.ENV}/{TEST_ORGANIZATION_ID}/{run_id}"
+ )
+ rows = [
+ make_artifact(f"{base_uri}/{stale_file.name}", artifact_type=ArtifactType.DOWNLOAD).model_copy(
+ update={"checksum": checksum, "modified_at": attempt_started_at - timedelta(seconds=60)}
+ ),
+ make_artifact(f"{base_uri}/{fresh_file.name}", artifact_type=ArtifactType.DOWNLOAD).model_copy(
+ update={"checksum": checksum, "modified_at": attempt_started_at - timedelta(seconds=60)}
+ ),
+ ]
+
+ async def _list_rows(**kwargs: object) -> list[Artifact]:
+ return rows
+
+ async def _save_row(*, uri: str, **kwargs: object) -> str:
+ for row_index, row in enumerate(rows):
+ if row.uri == uri:
+ rows[row_index] = row.model_copy(update={"modified_at": datetime.now(UTC)})
+ return row.artifact_id
+ rows.append(
+ make_artifact(uri, artifact_type=ArtifactType.DOWNLOAD).model_copy(
+ update={"artifact_id": "a_retry", "modified_at": datetime.now(UTC)}
+ )
+ )
+ return rows[-1].artifact_id
+
+ attempts_repository = FakeWorkflowRunAttemptsRepository(
+ [SimpleNamespace(attempt_number=2, started_at=attempt_started_at)]
+ )
+ monkeypatch.setattr(azure_storage.async_client, "upload_file_from_path", AsyncMock())
+ monkeypatch.setattr(
+ azure_module,
+ "app",
+ fake_app := SimpleNamespace(
+ ARTIFACT_MANAGER=SimpleNamespace(create_download_artifact=AsyncMock(side_effect=_save_row)),
+ WORKFLOW_CONTEXT_MANAGER=WorkflowContextManager(),
+ DATABASE=SimpleNamespace(
+ artifacts=SimpleNamespace(list_artifacts_for_run_by_type=_list_rows),
+ workflow_run_attempts=attempts_repository,
+ workflow_runs=SimpleNamespace(get_workflow_run=AsyncMock(return_value=None)),
+ ),
+ ),
+ )
+ monkeypatch.setattr(base_module, "app", fake_app)
+
+ await azure_storage.save_downloaded_files(organization_id=TEST_ORGANIZATION_ID, run_id=run_id)
+
+ assert attempts_repository.requested_workflow_run_ids == [run_id]
+ assert azure_storage.async_client.upload_file_from_path.await_args.kwargs["uri"] == (
+ f"{base_uri}/attempts/2/{fresh_file.name}"
+ )
+ assert len(rows) == 3
+ assert all(row.modified_at < attempt_started_at for row in rows[:2])
+ registered = [
+ call.kwargs["filename"] for call in azure_module.app.ARTIFACT_MANAGER.create_download_artifact.await_args_list
+ ]
+ assert registered == [fresh_file.name]
+ attempt_two_listing = [row.uri.rsplit("/", 1)[-1] for row in rows if row.modified_at >= attempt_started_at]
+ assert attempt_two_listing == [fresh_file.name]
diff --git a/tests/unit/forge/sdk/artifact/storage/test_gcs_storage.py b/tests/unit/forge/sdk/artifact/storage/test_gcs_storage.py
index 407585708..6b4fa08d9 100644
--- a/tests/unit/forge/sdk/artifact/storage/test_gcs_storage.py
+++ b/tests/unit/forge/sdk/artifact/storage/test_gcs_storage.py
@@ -1,11 +1,16 @@
-from datetime import datetime
+import hashlib
+import os
+from datetime import UTC, datetime, timedelta
from pathlib import Path
+from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
import skyvern.forge.sdk.api.real_gcp as real_gcp_module
+import skyvern.forge.sdk.artifact.storage.base as base_module
+import skyvern.forge.sdk.artifact.storage.gcs as gcs_module
from skyvern.config import settings
from skyvern.exceptions import DownloadSaveIncompleteError
from skyvern.forge.sdk.api.gcp import STORAGE_CLASS_STANDARD
@@ -14,6 +19,9 @@ from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType
from skyvern.forge.sdk.artifact.storage.base import SENSITIVE_SHARE_URL_EXPIRY_HOURS
from skyvern.forge.sdk.artifact.storage.gcs import GcsStorage
from skyvern.forge.sdk.artifact.storage.recording_test_helpers import fake_prepared_recording
+from skyvern.forge.sdk.workflow.context_manager import WorkflowContextManager
+from skyvern.forge.sdk.workflow.service import WorkflowService
+from tests.unit.conftest import FakeWorkflowRunAttemptsRepository
TEST_BUCKET = "test-gcs-bucket"
TEST_ORGANIZATION_ID = "test-org-123"
@@ -56,12 +64,13 @@ def mock_browser_session_artifact_create(monkeypatch: pytest.MonkeyPatch) -> Non
Mirrors the azure/s3 storage test fixtures — the forge app isn't initialized
in these storage-only tests, so patch the module-level ``app`` reference.
"""
- import skyvern.forge.sdk.artifact.storage.gcs as gcs_module
fake_app = MagicMock()
fake_app.ARTIFACT_MANAGER.create_browser_session_download_artifact = AsyncMock(return_value="a_test")
fake_app.ARTIFACT_MANAGER.create_browser_session_recording_artifact = AsyncMock(return_value="a_test")
fake_app.ARTIFACT_MANAGER.create_download_artifact = AsyncMock(return_value="a_test")
+ fake_app.WORKFLOW_CONTEXT_MANAGER = WorkflowContextManager()
+ fake_app.DATABASE.workflow_run_attempts = FakeWorkflowRunAttemptsRepository()
monkeypatch.setattr(gcs_module, "app", fake_app)
@@ -279,6 +288,69 @@ class TestGcsStorageBuildUri:
assert uri == expected
+async def test_get_downloaded_files_legacy_listing_attributes_and_scopes_attempt_files(
+ gcs_storage: GcsStorageForTests, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ run_id = "wr_retry"
+ attempt_one_modified_at = datetime(2026, 9, 7, 11, 0, tzinfo=UTC)
+ attempt_two_started_at = datetime(2026, 9, 7, 12, 0, tzinfo=UTC)
+ blob_modified_at = datetime(2026, 9, 7, 12, 1, tzinfo=UTC)
+ old_key = f"downloads/local/{settings.ENV}/{TEST_ORGANIZATION_ID}/{run_id}/old.pdf"
+ current_key = f"downloads/local/{settings.ENV}/{TEST_ORGANIZATION_ID}/{run_id}/current.pdf"
+ old_uri = f"gs://{settings.GCS_BUCKET_UPLOADS}/{old_key}"
+ old_artifact = Artifact(
+ artifact_id="a_old",
+ artifact_type=ArtifactType.DOWNLOAD,
+ uri=old_uri,
+ organization_id=TEST_ORGANIZATION_ID,
+ run_id=run_id,
+ workflow_run_id=run_id,
+ created_at=attempt_one_modified_at,
+ modified_at=attempt_one_modified_at,
+ )
+
+ async def get_object_info(uri: str) -> dict[str, Any]:
+ return {
+ "Metadata": {"sha256_checksum": f"sha-{uri.rsplit('/', 1)[-1]}"},
+ "ContentLength": 10,
+ "LastModified": blob_modified_at,
+ }
+
+ gcs_storage.async_client.list_files = AsyncMock(return_value=[old_key, current_key])
+ gcs_storage.async_client.get_object_info = AsyncMock(side_effect=get_object_info)
+ gcs_storage.async_client.create_signed_urls = AsyncMock(
+ side_effect=lambda uris: [f"https://signed.test/{uri.rsplit('/', 1)[-1]}" for uri in uris]
+ )
+ rows = AsyncMock(return_value=[old_artifact])
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.artifact.storage.gcs.app.DATABASE.artifacts.list_artifacts_for_run_by_type", rows
+ )
+
+ with patch.object(settings, "ARTIFACT_CONTENT_HMAC_KEYRING", None):
+ files = await gcs_storage.get_downloaded_files(TEST_ORGANIZATION_ID, run_id)
+
+ assert len(files) == 2
+ old_file, current_file = files
+ assert old_file.artifact_id == "a_old"
+ assert old_file.modified_at == attempt_one_modified_at
+ assert current_file.artifact_id is None
+ assert current_file.modified_at == blob_modified_at
+ rows.assert_awaited_once_with(
+ run_id=run_id,
+ organization_id=TEST_ORGANIZATION_ID,
+ artifact_type=ArtifactType.DOWNLOAD,
+ )
+
+ scoped = WorkflowService()._filter_downloaded_files_to_attempt(
+ files,
+ attempt_rows=[SimpleNamespace(attempt_number=2, started_at=attempt_two_started_at)],
+ attempt_number=2,
+ artifact_ids=set(),
+ )
+ assert [file_info.filename for file_info in scoped] == ["current.pdf"]
+
+
GCS_CONTENT_TYPE_TEST_CASES = [
("video.webm", "video/webm"),
("data.json", "application/json"),
@@ -417,8 +489,89 @@ async def test_save_downloaded_files_partial_upload_failure_raises_after_saving_
monkeypatch.setattr(gcs_storage.async_client, "upload_file_from_path", _upload)
+ monkeypatch.setattr(base_module.app.DATABASE.workflow_runs, "get_workflow_run", AsyncMock(return_value=None))
+
with pytest.raises(DownloadSaveIncompleteError) as raised:
await gcs_storage.save_downloaded_files(organization_id=TEST_ORGANIZATION_ID, run_id="wr_partial")
assert raised.value.skipped_files == ["a.pdf"]
assert [uri.rsplit("/", 1)[-1] for uri in uploaded] == ["b.pdf"]
+
+
+async def test_save_downloaded_files_retry_skips_stale_files_and_versions_fresh_redownloads(
+ gcs_storage: GcsStorageForTests, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ run_id = "wr_retry"
+ run_dir = tmp_path / "downloads" / run_id
+ run_dir.mkdir(parents=True)
+ stale_file = run_dir / "only-attempt-1.pdf"
+ fresh_file = run_dir / "report.pdf"
+ stale_file.write_bytes(b"same bytes")
+ fresh_file.write_bytes(b"same bytes")
+ monkeypatch.setattr("skyvern.forge.sdk.api.files.settings.DOWNLOAD_PATH", str(tmp_path / "downloads"))
+
+ attempt_started_at = datetime.now(UTC) - timedelta(seconds=1)
+ os.utime(stale_file, (attempt_started_at.timestamp() - 60, attempt_started_at.timestamp() - 60))
+ os.utime(fresh_file, (attempt_started_at.timestamp() + 1, attempt_started_at.timestamp() + 1))
+ checksum = hashlib.sha256(b"same bytes").hexdigest()
+ base_uri = f"gs://{settings.GCS_BUCKET_UPLOADS}/downloads/{settings.ENV}/{TEST_ORGANIZATION_ID}/{run_id}"
+ rows = [
+ make_artifact(
+ f"{base_uri}/{stale_file.name}", artifact_id="a_stale", artifact_type=ArtifactType.DOWNLOAD
+ ).model_copy(update={"checksum": checksum, "modified_at": attempt_started_at - timedelta(seconds=60)}),
+ make_artifact(
+ f"{base_uri}/{fresh_file.name}", artifact_id="a_fresh", artifact_type=ArtifactType.DOWNLOAD
+ ).model_copy(update={"checksum": checksum, "modified_at": attempt_started_at - timedelta(seconds=60)}),
+ ]
+
+ async def _list_rows(**kwargs: object) -> list[Artifact]:
+ return rows
+
+ async def _save_row(*, uri: str, **kwargs: object) -> str:
+ for row_index, row in enumerate(rows):
+ if row.uri == uri:
+ rows[row_index] = row.model_copy(update={"modified_at": datetime.now(UTC)})
+ return row.artifact_id
+ rows.append(
+ make_artifact(uri, artifact_id="a_retry", artifact_type=ArtifactType.DOWNLOAD).model_copy(
+ update={"modified_at": datetime.now(UTC)}
+ )
+ )
+ return rows[-1].artifact_id
+
+ attempts_repository = FakeWorkflowRunAttemptsRepository(
+ [SimpleNamespace(attempt_number=2, started_at=attempt_started_at)]
+ )
+ monkeypatch.setattr(gcs_storage.async_client, "upload_file_from_path", AsyncMock())
+ monkeypatch.setattr(gcs_storage, "_get_storage_class_for_org", AsyncMock(return_value="STANDARD"))
+ monkeypatch.setattr(gcs_storage, "_get_tags_for_org", AsyncMock(return_value=None))
+ monkeypatch.setattr(
+ gcs_module,
+ "app",
+ fake_app := SimpleNamespace(
+ ARTIFACT_MANAGER=SimpleNamespace(create_download_artifact=AsyncMock(side_effect=_save_row)),
+ WORKFLOW_CONTEXT_MANAGER=WorkflowContextManager(),
+ DATABASE=SimpleNamespace(
+ artifacts=SimpleNamespace(list_artifacts_for_run_by_type=_list_rows),
+ workflow_run_attempts=attempts_repository,
+ workflow_runs=SimpleNamespace(get_workflow_run=AsyncMock(return_value=None)),
+ ),
+ ),
+ )
+ monkeypatch.setattr(base_module, "app", fake_app)
+
+ await gcs_storage.save_downloaded_files(organization_id=TEST_ORGANIZATION_ID, run_id=run_id)
+
+ assert attempts_repository.requested_workflow_run_ids == [run_id]
+ assert gcs_storage.async_client.upload_file_from_path.await_args.kwargs["uri"] == (
+ f"{base_uri}/attempts/2/{fresh_file.name}"
+ )
+ assert len(rows) == 3
+ assert all(row.modified_at < attempt_started_at for row in rows[:2])
+ registered = [
+ call.kwargs["filename"] for call in gcs_module.app.ARTIFACT_MANAGER.create_download_artifact.await_args_list
+ ]
+ assert registered == [fresh_file.name]
+ attempt_two_listing = [row.uri.rsplit("/", 1)[-1] for row in rows if row.modified_at >= attempt_started_at]
+ assert attempt_two_listing == [fresh_file.name]
diff --git a/tests/unit/forge/sdk/artifact/storage/test_local_storage.py b/tests/unit/forge/sdk/artifact/storage/test_local_storage.py
index 4e2e79944..b2d9c274c 100644
--- a/tests/unit/forge/sdk/artifact/storage/test_local_storage.py
+++ b/tests/unit/forge/sdk/artifact/storage/test_local_storage.py
@@ -1,5 +1,6 @@
from pathlib import Path
-from unittest.mock import patch
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
import pytest
from freezegun import freeze_time
@@ -151,3 +152,35 @@ async def test_delete_legacy_file_rejects_other_organization_path(tmp_path: Path
await storage.delete_legacy_file(organization_id=TEST_ORGANIZATION_ID, uri=f"file://{artifact_path}")
assert artifact_path.exists()
+
+
+async def test_get_downloaded_files_carries_local_artifact_attribution(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ run_id = TEST_WORKFLOW_RUN_ID
+ download_path = tmp_path / run_id / "report.pdf"
+ download_path.parent.mkdir(parents=True)
+ download_path.write_bytes(b"report")
+ uri = f"file://{download_path}"
+ artifact = SimpleNamespace(
+ artifact_id="artifact_download_1",
+ uri=uri,
+ modified_at=None,
+ )
+ list_artifacts = AsyncMock(return_value=[artifact])
+ monkeypatch.setattr(settings, "DOWNLOAD_PATH", str(tmp_path))
+
+ with patch("skyvern.forge.sdk.artifact.storage.local.app") as mock_app:
+ mock_app.DATABASE.artifacts.list_artifacts_for_run_by_type = list_artifacts
+ files = await LocalStorage().get_downloaded_files(TEST_ORGANIZATION_ID, run_id)
+
+ assert len(files) == 1
+ assert files[0].artifact_id == "artifact_download_1"
+ assert files[0].modified_at is not None
+ list_artifacts.assert_awaited_once_with(
+ run_id=run_id,
+ organization_id=TEST_ORGANIZATION_ID,
+ artifact_type=ArtifactType.DOWNLOAD,
+ )
diff --git a/tests/unit/forge/sdk/artifact/storage/test_s3_storage.py b/tests/unit/forge/sdk/artifact/storage/test_s3_storage.py
index 54501c8bb..19ee13e1e 100644
--- a/tests/unit/forge/sdk/artifact/storage/test_s3_storage.py
+++ b/tests/unit/forge/sdk/artifact/storage/test_s3_storage.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import hashlib
import io
import os
import shutil
@@ -15,6 +16,8 @@ import pytest
import zstandard as zstd
from freezegun import freeze_time
+import skyvern.forge.sdk.artifact.storage.base as base_module
+import skyvern.forge.sdk.artifact.storage.s3 as s3_module
from skyvern.config import settings
from skyvern.exceptions import DownloadSaveIncompleteError
from skyvern.forge.sdk.api.aws import _STREAM_UPLOAD_IO_QUEUE_DEPTH, S3StorageClass, S3Uri
@@ -24,6 +27,8 @@ from skyvern.forge.sdk.artifact.signing import SENSITIVE_ARTIFACT_URL_EXPIRY_SEC
from skyvern.forge.sdk.artifact.storage.s3 import S3Storage
from skyvern.forge.sdk.db.id import generate_artifact_id
from skyvern.forge.sdk.models import Step
+from skyvern.forge.sdk.workflow.context_manager import WorkflowContextManager
+from tests.unit.conftest import FakeWorkflowRunAttemptsRepository
from tests.unit.forge.sdk.artifact.storage.test_helpers import (
create_fake_for_ai_suggestion,
create_fake_step,
@@ -1419,8 +1424,6 @@ class TestS3SaveDownloadedFiles:
async def test_partial_upload_failure_raises_after_saving_the_rest(
self, s3_storage: S3Storage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
- import skyvern.forge.sdk.artifact.storage.s3 as s3_module
-
self._seed_run_dir(tmp_path, monkeypatch)
uploaded: list[str] = []
@@ -1434,9 +1437,17 @@ class TestS3SaveDownloadedFiles:
monkeypatch.setattr(
s3_module,
"app",
- SimpleNamespace(ARTIFACT_MANAGER=SimpleNamespace(create_download_artifact=create_download_artifact)),
+ SimpleNamespace(
+ ARTIFACT_MANAGER=SimpleNamespace(create_download_artifact=create_download_artifact),
+ WORKFLOW_CONTEXT_MANAGER=WorkflowContextManager(),
+ DATABASE=SimpleNamespace(
+ workflow_run_attempts=FakeWorkflowRunAttemptsRepository(),
+ workflow_runs=SimpleNamespace(get_workflow_run=AsyncMock(return_value=None)),
+ ),
+ ),
)
+ monkeypatch.setattr(base_module, "app", s3_module.app)
with pytest.raises(DownloadSaveIncompleteError) as raised:
await s3_storage.save_downloaded_files(organization_id=TEST_ORGANIZATION_ID, run_id="wr_partial")
@@ -1448,8 +1459,6 @@ class TestS3SaveDownloadedFiles:
async def test_artifact_row_failure_counts_as_skipped(
self, s3_storage: S3Storage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
- import skyvern.forge.sdk.artifact.storage.s3 as s3_module
-
self._seed_run_dir(tmp_path, monkeypatch)
monkeypatch.setattr(s3_storage.async_client, "upload_file_from_path", AsyncMock())
@@ -1461,10 +1470,16 @@ class TestS3SaveDownloadedFiles:
s3_module,
"app",
SimpleNamespace(
- ARTIFACT_MANAGER=SimpleNamespace(create_download_artifact=AsyncMock(side_effect=_create_row))
+ ARTIFACT_MANAGER=SimpleNamespace(create_download_artifact=AsyncMock(side_effect=_create_row)),
+ WORKFLOW_CONTEXT_MANAGER=WorkflowContextManager(),
+ DATABASE=SimpleNamespace(
+ workflow_run_attempts=FakeWorkflowRunAttemptsRepository(),
+ workflow_runs=SimpleNamespace(get_workflow_run=AsyncMock(return_value=None)),
+ ),
),
)
+ monkeypatch.setattr(base_module, "app", s3_module.app)
with pytest.raises(DownloadSaveIncompleteError) as raised:
await s3_storage.save_downloaded_files(organization_id=TEST_ORGANIZATION_ID, run_id="wr_partial")
@@ -1474,7 +1489,6 @@ class TestS3SaveDownloadedFiles:
self, s3_storage: S3Storage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A run's second cleanup must cost only its new files, not the whole download dir (SKY-14752)."""
- import skyvern.forge.sdk.artifact.storage.s3 as s3_module
self._seed_run_dir(tmp_path, monkeypatch)
run_dir = tmp_path / "downloads" / "wr_partial"
@@ -1500,10 +1514,16 @@ class TestS3SaveDownloadedFiles:
"app",
SimpleNamespace(
ARTIFACT_MANAGER=SimpleNamespace(create_download_artifact=_create_row),
- DATABASE=SimpleNamespace(artifacts=SimpleNamespace(list_artifacts_for_run_by_type=_list_rows)),
+ WORKFLOW_CONTEXT_MANAGER=WorkflowContextManager(),
+ DATABASE=SimpleNamespace(
+ artifacts=SimpleNamespace(list_artifacts_for_run_by_type=_list_rows),
+ workflow_run_attempts=FakeWorkflowRunAttemptsRepository(),
+ workflow_runs=SimpleNamespace(get_workflow_run=AsyncMock(return_value=None)),
+ ),
),
)
+ monkeypatch.setattr(base_module, "app", s3_module.app)
await s3_storage.save_downloaded_files(organization_id=TEST_ORGANIZATION_ID, run_id="wr_partial")
assert sorted(uploaded) == ["a.pdf", "b.pdf"]
@@ -1516,6 +1536,113 @@ class TestS3SaveDownloadedFiles:
assert sorted(uploaded) == ["b.pdf", "c.pdf"]
assert len(rows) == 3
+ uploaded.clear()
+ monkeypatch.setattr(base_module, "app", s3_module.app)
+ s3_module.app.DATABASE.workflow_run_attempts.attempts = [
+ SimpleNamespace(attempt_number=2, started_at=datetime.now(UTC) - timedelta(seconds=1))
+ ]
+ await s3_storage.save_downloaded_files(organization_id=TEST_ORGANIZATION_ID, run_id="wr_partial")
+
+ assert sorted(uploaded) == ["a.pdf", "b.pdf", "c.pdf"]
+ assert len(rows) == 6
+
+ async def test_retry_save_skips_stale_files_and_versions_fresh_redownloads(
+ self, s3_storage: S3Storage, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ run_id = "wr_retry"
+ run_dir = tmp_path / "downloads" / run_id
+ run_dir.mkdir(parents=True)
+ stale_file = run_dir / "only-attempt-1.pdf"
+ fresh_file = run_dir / "report.pdf"
+ late_attempt_one_file = run_dir / "late-attempt-1.pdf"
+ stale_file.write_bytes(b"same bytes")
+ fresh_file.write_bytes(b"same bytes")
+ late_attempt_one_file.write_bytes(b"new attempt-one bytes")
+ monkeypatch.setattr("skyvern.forge.sdk.api.files.settings.DOWNLOAD_PATH", str(tmp_path / "downloads"))
+
+ attempt_started_at = datetime.now(UTC) - timedelta(seconds=1)
+ attempt_one_started_at = attempt_started_at - timedelta(minutes=2)
+ os.utime(stale_file, (attempt_started_at.timestamp() - 60, attempt_started_at.timestamp() - 60))
+ os.utime(fresh_file, (attempt_started_at.timestamp() + 1, attempt_started_at.timestamp() + 1))
+ os.utime(late_attempt_one_file, (attempt_started_at.timestamp() - 30, attempt_started_at.timestamp() - 30))
+ checksum = hashlib.sha256(b"same bytes").hexdigest()
+ base_uri = f"s3://{settings.AWS_S3_BUCKET_UPLOADS}/downloads/{settings.ENV}/{TEST_ORGANIZATION_ID}/{run_id}"
+ rows = [
+ _share_artifact(ArtifactType.DOWNLOAD, f"{base_uri}/{stale_file.name}").model_copy(
+ update={"checksum": checksum, "modified_at": attempt_started_at - timedelta(seconds=60)}
+ ),
+ _share_artifact(ArtifactType.DOWNLOAD, f"{base_uri}/{fresh_file.name}").model_copy(
+ update={"checksum": checksum, "modified_at": attempt_started_at - timedelta(seconds=60)}
+ ),
+ ]
+
+ async def _list_rows(**kwargs: object) -> list[Artifact]:
+ return rows
+
+ uploaded: list[str] = []
+
+ async def _upload(*, uri: str, **kwargs: object) -> None:
+ uploaded.append(uri.rsplit("/", 1)[-1])
+
+ async def _save_row(*, uri: str, checksum: str | None = None, **kwargs: object) -> str:
+ for row_index, row in enumerate(rows):
+ if row.uri == uri:
+ rows[row_index] = row.model_copy(update={"modified_at": datetime.now(UTC)})
+ return row.artifact_id
+ rows.append(
+ _share_artifact(ArtifactType.DOWNLOAD, uri).model_copy(
+ update={"checksum": checksum, "modified_at": datetime.now(UTC)}
+ )
+ )
+ return rows[-1].artifact_id
+
+ attempts_repository = FakeWorkflowRunAttemptsRepository(
+ [
+ SimpleNamespace(attempt_number=1, started_at=attempt_one_started_at),
+ SimpleNamespace(attempt_number=2, started_at=attempt_started_at),
+ ]
+ )
+ upload_mock = AsyncMock(side_effect=_upload)
+ monkeypatch.setattr(s3_storage.async_client, "upload_file_from_path", upload_mock)
+ monkeypatch.setattr(
+ s3_module,
+ "app",
+ fake_app := SimpleNamespace(
+ ARTIFACT_MANAGER=SimpleNamespace(create_download_artifact=AsyncMock(side_effect=_save_row)),
+ WORKFLOW_CONTEXT_MANAGER=WorkflowContextManager(),
+ DATABASE=SimpleNamespace(
+ artifacts=SimpleNamespace(list_artifacts_for_run_by_type=_list_rows),
+ workflow_run_attempts=attempts_repository,
+ workflow_runs=SimpleNamespace(get_workflow_run=AsyncMock(return_value=None)),
+ ),
+ ),
+ )
+ monkeypatch.setattr(base_module, "app", fake_app)
+
+ await s3_storage.save_downloaded_files(organization_id=TEST_ORGANIZATION_ID, run_id=run_id)
+
+ assert attempts_repository.requested_workflow_run_ids == [run_id]
+ assert uploaded == [fresh_file.name]
+ assert upload_mock.await_args.kwargs["uri"] == f"{base_uri}/attempts/2/{fresh_file.name}"
+ assert len(rows) == 3
+ assert all(row.modified_at < attempt_started_at for row in rows[:2])
+ registered = [
+ call.kwargs["filename"] for call in s3_module.app.ARTIFACT_MANAGER.create_download_artifact.await_args_list
+ ]
+ assert registered == [fresh_file.name]
+ attempt_two_listing = [row.uri.rsplit("/", 1)[-1] for row in rows if row.modified_at >= attempt_started_at]
+ assert attempt_two_listing == [fresh_file.name]
+
+ uploaded.clear()
+ await s3_storage.save_downloaded_files(
+ organization_id=TEST_ORGANIZATION_ID,
+ run_id=run_id,
+ attempt_number=1,
+ )
+
+ assert attempts_repository.requested_workflow_run_ids == [run_id, run_id]
+ assert uploaded == [late_attempt_one_file.name]
+
async def _settle(iterations: int = 100) -> None:
"""Drain the event loop's ready queue deterministically so create_task'd writes reach their
diff --git a/tests/unit/forge/sdk/db/test_tasks_repository.py b/tests/unit/forge/sdk/db/test_tasks_repository.py
index 567d80786..6a74f1d09 100644
--- a/tests/unit/forge/sdk/db/test_tasks_repository.py
+++ b/tests/unit/forge/sdk/db/test_tasks_repository.py
@@ -1,6 +1,12 @@
+from decimal import Decimal
+
import pytest
+from sqlalchemy import select
+from skyvern.forge import app
+from skyvern.forge.agent import ForgeAgent
from skyvern.forge.sdk.db.enums import TaskType
+from skyvern.forge.sdk.db.models import TaskRunModel, WorkflowRunAttemptModel
@pytest.mark.asyncio
@@ -66,3 +72,81 @@ async def test_internal_synthetic_sdk_task_round_trips_through_repository(agent_
persisted = await agent_db.tasks.get_task(task.task_id, organization.organization_id)
assert persisted is not None
assert persisted.task_type == TaskType.synthetic_sdk_action
+
+
+async def test_workflow_step_budget_starts_fresh_on_retry(agent_db, monkeypatch: pytest.MonkeyPatch) -> None:
+ organization = await agent_db.organizations.create_organization(
+ organization_name="Test organization", organization_id="o_attempt_budget"
+ )
+ organization.max_steps_per_workflow_run = 2
+ tasks = []
+ for attempt in (None, 1, 2):
+ task = await agent_db.tasks.create_task(
+ url="https://example.com",
+ title=None,
+ navigation_goal=None,
+ data_extraction_goal=None,
+ navigation_payload=None,
+ organization_id=organization.organization_id,
+ workflow_run_id="wr_budget",
+ attempt_number=attempt,
+ )
+ tasks.append(task)
+ await agent_db.tasks.create_step(
+ task.task_id, order=0, retry_index=0, organization_id=organization.organization_id
+ )
+ monkeypatch.setattr(app, "DATABASE", agent_db)
+ agent = ForgeAgent()
+ assert await agent._check_workflow_run_step_budget(organization, tasks[0]) == (2, 2)
+ assert await agent._check_workflow_run_step_budget(organization, tasks[1]) == (2, 2)
+ assert await agent._check_workflow_run_step_budget(organization, tasks[2]) == (1, 2)
+ assert len(await agent_db.tasks.get_tasks_by_workflow_run_id("wr_budget")) == 3
+
+
[email protected]("first_attempt", [None, 1])
+async def test_compute_cost_preserves_first_attempt_assignment_and_adds_retries(agent_db, first_attempt) -> None:
+ async with agent_db.Session() as session:
+ session.add(
+ TaskRunModel(
+ organization_id="o_cost",
+ run_id="wr_cost",
+ task_run_type="workflow_run",
+ duration_ms=999,
+ compute_cost=Decimal(9),
+ )
+ )
+ if first_attempt is not None:
+ session.add(
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_cost", organization_id="o_cost", attempt_number=1, status="failed"
+ )
+ )
+ await session.commit()
+ await agent_db.tasks.update_job_run_compute_cost(
+ organization_id="o_cost",
+ run_id="wr_cost",
+ duration_ms=1000,
+ compute_cost=Decimal("0.10"),
+ llm_cost=Decimal("0.20"),
+ )
+ async with agent_db.Session() as session:
+ row = await session.scalar(select(TaskRunModel).where(TaskRunModel.run_id == "wr_cost"))
+ assert (row.duration_ms, row.compute_cost) == (1000, Decimal("0.10"))
+ session.add(
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_cost", organization_id="o_cost", attempt_number=2, status="completed"
+ )
+ )
+ await session.commit()
+ await agent_db.tasks.update_job_run_compute_cost(
+ organization_id="o_cost",
+ run_id="wr_cost",
+ duration_ms=2000,
+ compute_cost=Decimal("0.30"),
+ llm_cost=Decimal("0.50"),
+ )
+ async with agent_db.Session() as session:
+ row = await session.scalar(select(TaskRunModel).where(TaskRunModel.run_id == "wr_cost"))
+ assert (row.duration_ms, row.compute_cost, row.llm_cost) == (3000, Decimal("0.40"), Decimal("0.50"))
diff --git a/tests/unit/forge/sdk/db/test_workflow_runs_repository.py b/tests/unit/forge/sdk/db/test_workflow_runs_repository.py
index 19b62ae0e..cfb6fa0ab 100644
--- a/tests/unit/forge/sdk/db/test_workflow_runs_repository.py
+++ b/tests/unit/forge/sdk/db/test_workflow_runs_repository.py
@@ -4,7 +4,8 @@ from __future__ import annotations
import asyncio
import re
-from datetime import datetime, timezone
+from datetime import UTC, datetime, timedelta, timezone
+from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock
@@ -14,20 +15,35 @@ from sqlalchemy import event
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncEngine
+from skyvern.forge import app
+from skyvern.forge.sdk.artifact.models import ArtifactType
from skyvern.forge.sdk.db.agent_db import AgentDB, _build_engine
+from skyvern.forge.sdk.db.enums import BrowserSeedSource
from skyvern.forge.sdk.db.models import (
+ ArtifactModel,
Base,
+ CredentialModel,
+ OrganizationModel,
PersistentBrowserSessionModel,
+ TaskModel,
TaskRunModel,
WorkflowModel,
+ WorkflowRunAttemptModel,
+ WorkflowRunBlockModel,
+ WorkflowRunCredentialSelectionModel,
WorkflowRunModel,
)
+from skyvern.forge.sdk.db.repositories import workflow_run_attempts as attempts_repository_module
+from skyvern.forge.sdk.db.repositories.workflow_run_attempts import TerminalSideEffectCheckpoint
from skyvern.forge.sdk.db.repositories.workflow_runs import WorkflowRunsRepository
from skyvern.forge.sdk.schemas.persistent_browser_sessions import FORCED_WORKFLOW_SESSION_RUNNABLE_TYPE
+from skyvern.forge.sdk.workflow import service as workflow_service_module
from skyvern.forge.sdk.workflow.models.parameter import WorkflowParameter, WorkflowParameterType
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
+from skyvern.forge.sdk.workflow.retry_policy import LEASE_TAKEOVER_SECONDS, is_retry_eligible_run
from skyvern.schemas.run_enums import RunType
from skyvern.schemas.runs import MAX_SEARCH_FETCH_LIMIT
+from skyvern.schemas.workflows import WorkflowRetryPolicy
def _make_workflow_parameter(
@@ -147,6 +163,423 @@ def _credential_run(
)
+ "clear_browser_address, replacement_browser_address, expected_browser_address",
+ [
+ (False, None, "caller-cdp.example.test"),
+ (False, "healthy-cdp.example.test", "healthy-cdp.example.test"),
+ (True, None, None),
+ ],
+)
+async def test_prepare_next_attempt_clears_only_server_assigned_browser_address(
+ sqlite_db: AgentDB,
+ clear_browser_address: bool,
+ replacement_browser_address: str | None,
+ expected_browser_address: str | None,
+) -> None:
+ now = datetime(2026, 7, 22, 12, 0, tzinfo=UTC)
+ workflow_run_id = "wr_prepare_address"
+ workflow_run = _workflow_run_model(
+ workflow_run_id=workflow_run_id,
+ queued_at=now,
+ status=WorkflowRunStatus.failed.value,
+ )
+ workflow_run.browser_address = "caller-cdp.example.test"
+ attempt = WorkflowRunAttemptModel(
+ workflow_run_id=workflow_run.workflow_run_id,
+ attempt_number=1,
+ organization_id="org_test",
+ status=WorkflowRunStatus.failed.value,
+ retry_decision="retry",
+ next_attempt_at=now,
+ )
+ async with sqlite_db.Session() as session:
+ session.add_all([workflow_run, attempt])
+ await session.commit()
+
+ preparation = await sqlite_db.workflow_runs.prepare_next_attempt_atomic(
+ workflow_run_id=workflow_run_id,
+ organization_id="org_test",
+ from_attempt=1,
+ expected_status=WorkflowRunStatus.failed,
+ browser_session_id=None,
+ clear_browser_address=clear_browser_address,
+ replacement_browser_address=replacement_browser_address,
+ )
+
+ assert preparation.status == "inserted"
+ async with sqlite_db.Session() as session:
+ reopened = await session.get(WorkflowRunModel, workflow_run_id)
+ assert reopened is not None
+ assert reopened.browser_address == expected_browser_address
+ assert reopened.status == WorkflowRunStatus.queued.value
+
+
+async def test_prepare_next_attempt_reopens_the_task_run_mirror(sqlite_db: AgentDB) -> None:
+ now = datetime(2026, 7, 22, 12, 0, tzinfo=UTC)
+ workflow_run_id = "wr_prepare_task_run"
+ workflow_run = _workflow_run_model(
+ workflow_run_id=workflow_run_id,
+ queued_at=now,
+ status=WorkflowRunStatus.failed.value,
+ )
+ attempt = WorkflowRunAttemptModel(
+ workflow_run_id=workflow_run_id,
+ attempt_number=1,
+ organization_id="org_test",
+ status=WorkflowRunStatus.failed.value,
+ retry_decision="retry",
+ next_attempt_at=now,
+ )
+ task_run = _task_run_model(
+ run_id=workflow_run_id,
+ created_at=now,
+ workflow_permanent_id="wpid_test",
+ status=WorkflowRunStatus.failed.value,
+ )
+ task_run.started_at = now.replace(tzinfo=None)
+ task_run.finished_at = (now + timedelta(minutes=5)).replace(tzinfo=None)
+ async with sqlite_db.Session() as session:
+ session.add_all([workflow_run, attempt, task_run])
+ await session.commit()
+
+ preparation = await sqlite_db.workflow_runs.prepare_next_attempt_atomic(
+ workflow_run_id=workflow_run_id,
+ organization_id="org_test",
+ from_attempt=1,
+ expected_status=WorkflowRunStatus.failed,
+ browser_session_id=None,
+ )
+
+ assert preparation.status == "inserted"
+ async with sqlite_db.Session() as session:
+ mirrored = await session.get(TaskRunModel, f"tr_{workflow_run_id}")
+ assert mirrored is not None
+ assert (mirrored.status, mirrored.started_at, mirrored.finished_at) == (
+ WorkflowRunStatus.queued.value,
+ None,
+ None,
+ )
+
+
[email protected]("strategy", ["round_robin", "random"])
+ "seed_source, pool_size, sequential, retained_session, retained_address, replacement_address, resets_seed",
+ [
+ (BrowserSeedSource.credential, 2, False, None, None, None, True),
+ (BrowserSeedSource.own_memory, 2, False, None, None, None, True),
+ (BrowserSeedSource.credential, 1, False, None, None, None, False),
+ (BrowserSeedSource.own_memory, 1, False, None, None, None, False),
+ (BrowserSeedSource.credential, 2, True, None, None, None, False),
+ (BrowserSeedSource.override, 2, False, None, None, None, False),
+ (BrowserSeedSource.picked, 2, False, None, None, None, False),
+ (BrowserSeedSource.fresh, 2, False, None, None, None, False),
+ (BrowserSeedSource.credential, 2, False, "explicit", None, None, False),
+ (BrowserSeedSource.own_memory, 2, False, "explicit", None, None, False),
+ (BrowserSeedSource.credential, 2, False, "forced", None, None, False),
+ (BrowserSeedSource.own_memory, 2, False, "forced", None, None, False),
+ (BrowserSeedSource.credential, 2, False, None, "retained-cdp.example.test", None, False),
+ (BrowserSeedSource.own_memory, 2, False, None, "retained-cdp.example.test", None, False),
+ (BrowserSeedSource.credential, 2, False, None, "retained-cdp.example.test", "healthy-cdp.example.test", True),
+ (BrowserSeedSource.own_memory, 2, False, None, "retained-cdp.example.test", "healthy-cdp.example.test", True),
+ ],
+)
+async def test_prepare_next_attempt_invalidates_only_rotated_credential_seed(
+ sqlite_db: AgentDB,
+ monkeypatch: pytest.MonkeyPatch,
+ strategy: str,
+ seed_source: BrowserSeedSource,
+ pool_size: int,
+ sequential: bool,
+ retained_session: str | None,
+ retained_address: str | None,
+ replacement_address: str | None,
+ resets_seed: bool,
+) -> None:
+ monkeypatch.setattr(app, "DATABASE", sqlite_db)
+ now = datetime.now(UTC)
+ retained_session_id = "pbs_retained" if retained_session else None
+ run = _workflow_run_model(
+ workflow_run_id="wr_seed",
+ queued_at=now,
+ status="failed",
+ browser_session_id=None if retained_address else retained_session_id or "pbs_unpinned",
+ )
+ run.browser_address = retained_address
+ run.browser_profile_id = "bp_a"
+ run.browser_seed_source = seed_source
+ run.browser_sink_profile_id = "bp_sink_a"
+ credential_ids = ["cred_a", "cred_b"][:pool_size]
+ async with sqlite_db.Session() as session:
+ session.add(OrganizationModel(organization_id="org_test", organization_name="Test Organization"))
+ await session.flush()
+ session.add_all(
+ [
+ run,
+ WorkflowModel(
+ workflow_id="wf_test",
+ workflow_permanent_id="wpid_test",
+ organization_id="org_test",
+ title="Workflow",
+ workflow_definition={
+ "blocks": [],
+ "parameters": [
+ {
+ "parameter_type": "credential",
+ "key": "login",
+ "credential_parameter_id": "cp_login",
+ "workflow_id": "wf_test",
+ "created_at": now.isoformat(),
+ "modified_at": now.isoformat(),
+ "credential_id": "cred_a",
+ "credential_ids": credential_ids,
+ "selection_strategy": strategy,
+ }
+ ],
+ },
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_seed",
+ organization_id="org_test",
+ attempt_number=1,
+ status="failed",
+ retry_decision="retry",
+ pinned_browser_session_id=retained_session_id if retained_session == "explicit" else None,
+ ),
+ WorkflowRunCredentialSelectionModel(
+ workflow_run_id="wr_seed",
+ organization_id="org_test",
+ workflow_permanent_id="wpid_test",
+ parameter_key="login",
+ credential_id="cred_a",
+ ),
+ *[
+ CredentialModel(
+ credential_id=credential_id,
+ organization_id="org_test",
+ name=credential_id,
+ credential_type="password",
+ run_sequentially=sequential,
+ )
+ for credential_id in credential_ids
+ ],
+ ]
+ )
+ await session.commit()
+
+ if retained_session == "forced":
+ await sqlite_db.workflow_run_attempts.pin_first_attempt_browser_session_if_unset(
+ workflow_run_id="wr_seed",
+ organization_id="org_test",
+ browser_session_id="pbs_retained",
+ )
+ attempts = await sqlite_db.workflow_run_attempts.get_attempts("wr_seed")
+ preparation = await sqlite_db.workflow_runs.prepare_next_attempt_atomic(
+ workflow_run_id="wr_seed",
+ organization_id="org_test",
+ from_attempt=1,
+ expected_status=WorkflowRunStatus.failed,
+ browser_session_id=attempts[0].pinned_browser_session_id,
+ clear_browser_address=False,
+ replacement_browser_address=replacement_address,
+ )
+
+ assert preparation.status == "inserted"
+ assert preparation.pinned_browser_session_id == retained_session_id
+ reopened = await sqlite_db.workflow_runs.get_workflow_run("wr_seed", "org_test")
+ assert reopened is not None
+ assert reopened.browser_session_id == retained_session_id
+ assert reopened.browser_address == (replacement_address or retained_address)
+ # A retry that moved to another host has no cookies to keep paired, so it rotates like an unpinned retry.
+ rotates = (
+ pool_size == 2 and not sequential and not retained_session and (not retained_address or replacement_address)
+ )
+ selected = await sqlite_db.workflow_run_credential_selections.get_selection("wr_seed", "login")
+ assert selected == ("cred_b" if rotates else "cred_a")
+ actual_seed = (reopened.browser_profile_id, reopened.browser_seed_source, reopened.browser_sink_profile_id)
+ assert actual_seed == ((None, None, None) if resets_seed else ("bp_a", seed_source, "bp_sink_a"))
+
+
+async def test_list_stale_pending_retries_leaves_fresh_and_prepared_attempts_untouched(
+ sqlite_db: AgentDB,
+) -> None:
+ now = datetime(2026, 7, 22, 12, 0, tzinfo=UTC)
+ stale = WorkflowRunAttemptModel(
+ workflow_run_id="wr_stale_retry",
+ attempt_number=1,
+ organization_id="org_test",
+ status=WorkflowRunStatus.failed.value,
+ retry_decision="retry",
+ next_attempt_at=now - timedelta(seconds=601),
+ )
+ fresh = WorkflowRunAttemptModel(
+ workflow_run_id="wr_fresh_retry",
+ attempt_number=1,
+ organization_id="org_test",
+ status=WorkflowRunStatus.failed.value,
+ retry_decision="retry",
+ next_attempt_at=now - timedelta(seconds=599),
+ )
+ prepared = WorkflowRunAttemptModel(
+ workflow_run_id="wr_prepared_retry",
+ attempt_number=1,
+ organization_id="org_test",
+ status=WorkflowRunStatus.failed.value,
+ retry_decision="retry",
+ next_attempt_at=now - timedelta(seconds=601),
+ next_attempt_prepared_at=now - timedelta(seconds=600),
+ )
+ async with sqlite_db.Session() as session:
+ session.add_all([stale, fresh, prepared])
+ await session.commit()
+
+ attempts = await sqlite_db.workflow_run_attempts.list_stale_pending_retries(
+ now - timedelta(seconds=600),
+ )
+
+ assert [attempt.workflow_run_id for attempt in attempts] == ["wr_stale_retry"]
+
+
+async def test_abandonment_skips_a_pending_retry_with_a_young_side_effects_lease(
+ sqlite_db: AgentDB,
+) -> None:
+ now = datetime.now(UTC).replace(tzinfo=None)
+ young_claim = now - timedelta(seconds=LEASE_TAKEOVER_SECONDS - 1)
+ old_claim = now - timedelta(seconds=LEASE_TAKEOVER_SECONDS + 1)
+ young = WorkflowRunAttemptModel(
+ workflow_run_id="wr_young_lease",
+ attempt_number=1,
+ organization_id="org_test",
+ status=WorkflowRunStatus.failed.value,
+ retry_decision="retry",
+ next_attempt_at=now - timedelta(seconds=LEASE_TAKEOVER_SECONDS + 1),
+ side_effects_released_at=young_claim,
+ )
+ old = WorkflowRunAttemptModel(
+ workflow_run_id="wr_old_lease",
+ attempt_number=1,
+ organization_id="org_test",
+ status=WorkflowRunStatus.failed.value,
+ retry_decision="retry",
+ next_attempt_at=now - timedelta(seconds=LEASE_TAKEOVER_SECONDS + 1),
+ side_effects_released_at=old_claim,
+ )
+ async with sqlite_db.Session() as session:
+ session.add_all([young, old])
+ await session.commit()
+
+ skipped = await sqlite_db.workflow_run_attempts.revoke_or_abandon_attempt(
+ workflow_run_id="wr_young_lease",
+ attempt_number=1,
+ decision="abandoned",
+ reason="stale_retry",
+ lease_takeover_seconds=LEASE_TAKEOVER_SECONDS,
+ )
+ abandoned = await sqlite_db.workflow_run_attempts.revoke_or_abandon_attempt(
+ workflow_run_id="wr_old_lease",
+ attempt_number=1,
+ decision="abandoned",
+ reason="stale_retry",
+ lease_takeover_seconds=LEASE_TAKEOVER_SECONDS,
+ )
+
+ assert skipped is None
+ assert abandoned is not None
+ assert abandoned.retry_decision == "abandoned"
+ assert abandoned.side_effects_released_at is None
+ async with sqlite_db.Session() as session:
+ unchanged = await session.get(WorkflowRunAttemptModel, ("wr_young_lease", 1))
+ assert unchanged is not None
+ assert unchanged.retry_decision == "retry"
+ assert unchanged.side_effects_released_at == young_claim
+
+
+async def test_side_effect_claim_after_abandonment_requires_the_expected_retry_decision(
+ sqlite_db: AgentDB,
+) -> None:
+ attempt = WorkflowRunAttemptModel(
+ workflow_run_id="wr_claim_after_abandonment",
+ attempt_number=1,
+ organization_id="org_test",
+ status=WorkflowRunStatus.failed.value,
+ retry_decision="retry",
+ )
+ async with sqlite_db.Session() as session:
+ session.add(attempt)
+ await session.commit()
+
+ abandoned = await sqlite_db.workflow_run_attempts.revoke_or_abandon_attempt(
+ workflow_run_id="wr_claim_after_abandonment",
+ attempt_number=1,
+ decision="abandoned",
+ reason="stale_retry",
+ lease_takeover_seconds=LEASE_TAKEOVER_SECONDS,
+ )
+ claim = await sqlite_db.workflow_run_attempts.claim_attempt_side_effects(
+ workflow_run_id="wr_claim_after_abandonment",
+ attempt_number=1,
+ kind="interim",
+ expected_retry_decision="retry",
+ )
+
+ assert abandoned is not None
+ assert claim is None
+
+
+async def test_reopened_retry_is_ordered_after_delay_admitted_lane_occupant(sqlite_db: AgentDB) -> None:
+ now = datetime.now(UTC)
+ occupant_queued_at = now + timedelta(hours=1)
+ retry_run = _workflow_run_model(
+ workflow_run_id="wr_retry_lane",
+ queued_at=now - timedelta(hours=2),
+ browser_session_id="pbs_shared",
+ status=WorkflowRunStatus.failed.value,
+ )
+ delay_occupant = _workflow_run_model(
+ workflow_run_id="wr_delay_occupant",
+ queued_at=occupant_queued_at,
+ browser_session_id="pbs_shared",
+ )
+ attempt = WorkflowRunAttemptModel(
+ workflow_run_id="wr_retry_lane",
+ attempt_number=1,
+ organization_id="org_test",
+ status=WorkflowRunStatus.failed.value,
+ retry_decision="retry",
+ next_attempt_at=now,
+ )
+ async with sqlite_db.Session() as session:
+ session.add_all([retry_run, delay_occupant, attempt])
+ await session.commit()
+
+ preparation = await sqlite_db.workflow_runs.prepare_next_attempt_atomic(
+ workflow_run_id="wr_retry_lane",
+ organization_id="org_test",
+ from_attempt=1,
+ expected_status=WorkflowRunStatus.failed,
+ browser_session_id="pbs_shared",
+ clear_browser_address=False,
+ )
+
+ assert preparation.status == "inserted"
+ assert preparation.serialized_identity is True
+ async with sqlite_db.Session() as session:
+ reopened = await session.get(WorkflowRunModel, "wr_retry_lane")
+ assert reopened is not None
+ assert reopened.queued_at is not None
+ assert reopened.queued_at > occupant_queued_at.replace(tzinfo=None)
+ blocker = await sqlite_db.workflow_runs.get_blocking_sequential_workflow_run("wr_retry_lane")
+ assert blocker is not None
+ assert blocker.workflow_run_id == "wr_delay_occupant"
+
+
@pytest.mark.asyncio
async def test_credential_gate_crosses_workflows_and_respects_scope_and_status(sqlite_db: AgentDB) -> None:
# The three excluded peers (other-org / completed / disjoint-credential) are stamped strictly
@@ -1133,7 +1566,9 @@ async def test_get_workflow_runs_for_workflow_permanent_id_keeps_child_runs_by_d
@pytest.mark.asyncio
-async def test_get_workflow_runs_for_browser_session_filters_and_excludes() -> None:
+async def test_get_workflow_runs_for_browser_session_filters_and_excludes(
+ sqlite_db: AgentDB, sqlite_engine: AsyncEngine, monkeypatch: pytest.MonkeyPatch
+) -> None:
captured: dict[str, Any] = {}
async def _execute(query):
@@ -1164,6 +1599,56 @@ async def test_get_workflow_runs_for_browser_session_filters_and_excludes() -> N
assert "LIMIT 5" in rendered
assert "OFFSET 5" in rendered
+ now = datetime(2026, 7, 22, 12, 0, tzinfo=UTC).replace(tzinfo=None)
+ runs = [
+ _workflow_run_model(
+ workflow_run_id=f"wr_session_{i}", queued_at=now + timedelta(seconds=i), browser_session_id="pbs_test"
+ )
+ for i in range(4)
+ ]
+ foreign = _workflow_run_model(
+ workflow_run_id="wr_foreign", queued_at=now, browser_session_id="pbs_test", organization_id="org_other"
+ )
+ child = _workflow_run_model(workflow_run_id="wr_child", queued_at=now, browser_session_id="pbs_test")
+ child.parent_workflow_run_id = runs[0].workflow_run_id
+ copilot = _workflow_run_model(workflow_run_id="wr_copilot", queued_at=now, browser_session_id="pbs_test")
+ copilot.copilot_session_id = "cps_test"
+ other_session = _workflow_run_model(
+ workflow_run_id="wr_other_session", queued_at=now, browser_session_id="pbs_other"
+ )
+ async with sqlite_db.Session() as session:
+ session.add(
+ WorkflowModel(
+ workflow_id="wf_test", workflow_permanent_id="wpid_test", title="test", workflow_definition={}
+ )
+ )
+ session.add_all([*runs, foreign, child, copilot, other_session])
+ session.add_all(
+ [
+ WorkflowRunAttemptModel(
+ workflow_run_id=run.workflow_run_id,
+ organization_id="org_test",
+ attempt_number=number,
+ status="queued" if number == 2 else "failed",
+ )
+ for run in runs
+ for number in (1, 2)
+ ]
+ )
+ await session.commit()
+ monkeypatch.setattr(app, "DATABASE", sqlite_db)
+ statements, listener = _capture_sql(sqlite_engine)
+ try:
+ page = await workflow_service_module.WorkflowService().get_workflow_runs_for_browser_session(
+ browser_session_id="pbs_test", organization_id="org_test", page=2, page_size=2
+ )
+ finally:
+ event.remove(sqlite_engine.sync_engine, "before_cursor_execute", listener)
+
+ assert [run.workflow_run_id for run in page] == ["wr_session_1", "wr_session_0"]
+ assert [run.attempt for run in page] == [2, 2]
+ assert len([statement for statement in statements if "FROM workflow_run_attempts" in statement]) == 1
+
@pytest.mark.asyncio
async def test_get_last_queued_workflow_run_can_include_browser_session_rows(sqlite_db: AgentDB) -> None:
@@ -1885,3 +2370,512 @@ async def test_wake_candidates_signal_every_lane_head(sqlite_db: AgentDB) -> Non
waiters = await sqlite_db.workflow_runs.get_queued_runs_sharing_sequential_lanes("wr_tri_done")
assert [w.workflow_run_id for w in waiters] == ["wr_tri_key", "wr_tri_cred", "wr_tri_sess"]
+
+
+ "scenario",
+ [
+ "stale",
+ "young",
+ "boundary",
+ "running_run",
+ "terminal_run",
+ "unstarted_run",
+ "queued_attempt",
+ "unstarted_attempt",
+ "decided_attempt",
+ "wrong_organization",
+ "wrong_attempt",
+ "mismatched_organization",
+ "missing_run",
+ ],
+)
+async def test_stale_dispatch_claim_release_is_conditional_and_reclaimable(
+ sqlite_db: AgentDB, monkeypatch: pytest.MonkeyPatch, scenario: str
+) -> None:
+ now = datetime.now(UTC).replace(tzinfo=None)
+ monkeypatch.setattr(attempts_repository_module, "naive_utc_now", lambda: now)
+ cutoff = now - timedelta(seconds=max(600, LEASE_TAKEOVER_SECONDS))
+ old = cutoff - timedelta(seconds=1)
+ run = _workflow_run_model(workflow_run_id="wr_dispatch", queued_at=old)
+ run.started_at = old
+ run.modified_at = old
+ attempt = WorkflowRunAttemptModel(
+ workflow_run_id=run.workflow_run_id,
+ organization_id=run.organization_id,
+ attempt_number=2,
+ status="running",
+ started_at=old,
+ modified_at=old,
+ )
+ if scenario in {"young", "boundary"}:
+ attempt.modified_at = cutoff + timedelta(seconds=1 if scenario == "young" else 0)
+ elif scenario == "running_run":
+ run.status = "running"
+ elif scenario == "terminal_run":
+ run.status = "failed"
+ elif scenario == "unstarted_run":
+ run.started_at = None
+ elif scenario == "queued_attempt":
+ attempt.status = "queued"
+ elif scenario == "unstarted_attempt":
+ attempt.started_at = None
+ elif scenario == "decided_attempt":
+ attempt.retry_decision = "final"
+ elif scenario == "mismatched_organization":
+ attempt.organization_id = "org_other"
+ async with sqlite_db.Session() as session:
+ if scenario != "missing_run":
+ session.add(run)
+ session.add(attempt)
+ await session.commit()
+
+ async def snapshot() -> tuple[object, ...]:
+ async with sqlite_db.Session() as session:
+ current_run = await session.get(WorkflowRunModel, "wr_dispatch")
+ current_attempt = await session.get(WorkflowRunAttemptModel, ("wr_dispatch", 2))
+ assert current_attempt is not None
+ return (
+ (current_run.status, current_run.started_at, current_run.modified_at) if current_run else None,
+ current_attempt.status,
+ current_attempt.started_at,
+ current_attempt.modified_at,
+ current_attempt.retry_decision,
+ )
+
+ before = await snapshot()
+ candidates = await sqlite_db.workflow_run_attempts.list_stale_dispatch_claims(cutoff.replace(tzinfo=UTC))
+ assert bool(candidates) == (scenario in {"stale", "wrong_organization", "wrong_attempt"})
+ released = await sqlite_db.workflow_run_attempts.release_stale_dispatch_claim(
+ "wr_dispatch",
+ "org_other" if scenario == "wrong_organization" else "org_test",
+ 3 if scenario == "wrong_attempt" else 2,
+ stale_before=cutoff.replace(tzinfo=UTC),
+ )
+ assert released is (scenario == "stale")
+ if not released:
+ assert await snapshot() == before
+ return
+ assert await snapshot() == (("queued", None, now), "queued", None, now, None)
+ assert not await sqlite_db.workflow_run_attempts.release_stale_dispatch_claim(
+ "wr_dispatch", "org_test", 2, stale_before=cutoff
+ )
+ stamp = await sqlite_db.workflow_run_attempts.claim_prepared_attempt_execution("wr_dispatch", "org_test", 2)
+ assert stamp == now
+ assert await snapshot() == (("queued", now, now), "running", now, now, None)
+ assert await sqlite_db.workflow_run_attempts.claim_prepared_attempt_execution("wr_dispatch", "org_test", 2) is None
+
+
[email protected]("run_status", [WorkflowRunStatus.canceled.value, WorkflowRunStatus.queued.value])
+async def test_recovery_selects_never_started_attempts_of_terminal_runs(sqlite_db: AgentDB, run_status: str) -> None:
+ # A cancel that lands before mark_attempt_started leaves a created row with no started_at; the
+ # terminal run still owes its cleanup and webhook, so recovery must see the row.
+ old = datetime.now(UTC).replace(tzinfo=None) - timedelta(seconds=LEASE_TAKEOVER_SECONDS + 1)
+ run = _workflow_run_model(workflow_run_id="wr_never_started", queued_at=old, status=run_status)
+ attempt = WorkflowRunAttemptModel(
+ workflow_run_id=run.workflow_run_id,
+ organization_id=run.organization_id,
+ attempt_number=1,
+ status="created",
+ modified_at=old,
+ )
+ async with sqlite_db.Session() as session:
+ session.add_all([run, attempt])
+ await session.commit()
+
+ candidates = await sqlite_db.workflow_run_attempts.list_attempts_needing_recovery(
+ datetime.now(UTC) - timedelta(seconds=LEASE_TAKEOVER_SECONDS)
+ )
+
+ expected = ["wr_never_started"] if run_status == WorkflowRunStatus.canceled.value else []
+ assert [candidate.workflow_run_id for candidate in candidates] == expected
+
+
[email protected]("started_after_selection", [False, True])
+async def test_prepared_recovery_failure_is_conditional_on_unstarted_queued_run(
+ sqlite_db: AgentDB, started_after_selection: bool
+) -> None:
+ old = datetime.now(UTC).replace(tzinfo=None) - timedelta(seconds=LEASE_TAKEOVER_SECONDS + 1)
+ run = _workflow_run_model(workflow_run_id="wr_prepared_recovery", queued_at=old)
+ attempt = WorkflowRunAttemptModel(
+ workflow_run_id=run.workflow_run_id,
+ organization_id=run.organization_id,
+ attempt_number=2,
+ status="queued",
+ modified_at=old,
+ )
+ task_run = _task_run_model(
+ run_id=run.workflow_run_id,
+ created_at=old.replace(tzinfo=UTC),
+ workflow_permanent_id="wpid_test",
+ status=WorkflowRunStatus.queued.value,
+ )
+ async with sqlite_db.Session() as session:
+ session.add_all([run, attempt, task_run])
+ await session.commit()
+ candidates = await sqlite_db.workflow_run_attempts.list_attempts_needing_recovery(
+ datetime.now(UTC) - timedelta(seconds=LEASE_TAKEOVER_SECONDS)
+ )
+ assert [candidate.workflow_run_id for candidate in candidates] == ["wr_prepared_recovery"]
+ if started_after_selection:
+ async with sqlite_db.Session() as session:
+ current = await session.get(WorkflowRunModel, "wr_prepared_recovery")
+ assert current is not None
+ # Keep queued to prove started_at independently fences the failure UPDATE.
+ current.started_at = datetime.now(UTC).replace(tzinfo=None)
+ await session.commit()
+ claimed = await sqlite_db.workflow_run_attempts.fail_prepared_workflow_run(
+ "wr_prepared_recovery", "org_test", 2, "execution absent"
+ )
+ assert claimed is not started_after_selection
+ assert not await sqlite_db.workflow_run_attempts.fail_prepared_workflow_run(
+ "wr_prepared_recovery", "org_test", 2, "execution absent"
+ )
+ async with sqlite_db.Session() as session:
+ current = await session.get(WorkflowRunModel, "wr_prepared_recovery")
+ assert current is not None
+ assert current.status == ("queued" if started_after_selection else "failed")
+ mirrored = await session.get(TaskRunModel, "tr_wr_prepared_recovery")
+ assert mirrored is not None
+ # The runs list reads finished_at from this mirror; the abandon must write it in the same transaction.
+ assert (mirrored.status, mirrored.finished_at is not None) == (
+ ("queued", False) if started_after_selection else ("failed", True)
+ )
+
+
[email protected]("labels_only", [False, True])
+async def test_oss_run_with_unpersisted_block_outputs_abandons_retry(
+ sqlite_db: AgentDB, monkeypatch: pytest.MonkeyPatch, labels_only: bool
+) -> None:
+ now = datetime.now(UTC).replace(tzinfo=None)
+ run_model = _workflow_run_model(workflow_run_id="wr_scoped_inputs", queued_at=now, status="failed")
+ async with sqlite_db.Session() as session:
+ session.add(run_model)
+ await session.commit()
+ await sqlite_db.workflow_run_attempts.create_attempt("wr_scoped_inputs", "org_test", 1, "queued")
+ run = await sqlite_db.workflow_runs.get_workflow_run("wr_scoped_inputs", organization_id="org_test")
+ assert run is not None
+ workflow = SimpleNamespace(
+ workflow_definition=SimpleNamespace(
+ retry_policy=WorkflowRetryPolicy.model_validate({"retry_on": [{"status": "failed"}]})
+ )
+ )
+ svc = workflow_service_module.WorkflowService()
+ monkeypatch.setattr(app, "DATABASE", sqlite_db)
+ monkeypatch.setattr(app, "WORKFLOW_SERVICE", svc)
+ monkeypatch.setattr(svc, "get_workflow", AsyncMock(return_value=workflow))
+ monkeypatch.setattr(svc, "get_workflow_by_workflow_run_id", AsyncMock(return_value=workflow))
+ monkeypatch.setattr(app.AGENT_FUNCTION, "is_block_scoped_workflow_run", AsyncMock(return_value=False))
+ assert await is_retry_eligible_run(run, "org_test")
+ execute = AsyncMock(return_value=run)
+ monkeypatch.setattr(svc, "execute_workflow", execute)
+ release = AsyncMock(return_value="released")
+ monkeypatch.setattr(svc, "_run_terminal_side_effects_with_retries", release)
+ prepare = AsyncMock()
+ monkeypatch.setattr(workflow_service_module, "prepare_next_attempt_result", prepare)
+
+ await svc.execute_workflow_with_retries(
+ workflow_run_id=run.workflow_run_id,
+ api_key=None,
+ organization=SimpleNamespace(organization_id="org_test"),
+ block_labels=["selected"] if labels_only else None,
+ block_outputs=None if labels_only else {"caller_output": {"value": "original"}},
+ )
+
+ execute.assert_awaited_once()
+ assert execute.await_args.kwargs["block_labels"] == (["selected"] if labels_only else None)
+ assert execute.await_args.kwargs["block_outputs"] == (
+ None if labels_only else {"caller_output": {"value": "original"}}
+ )
+ prepare.assert_not_awaited()
+ attempts = await sqlite_db.workflow_run_attempts.get_attempts(run.workflow_run_id)
+ assert len(attempts) == 1
+ assert attempts[0].retry_decision == "abandoned"
+ assert attempts[0].decision_reason == "unrecoverable_block_outputs"
+ assert attempts[0].finished_at is not None
+ release.assert_awaited_once()
+ assert release.await_args.args[1].retry is False
+
+
[email protected]("ownership", ["running", "unknown", "absent", "terminal", "error"])
[email protected]("prepared_during_check", [False, True])
+async def test_stale_retry_recovery_checks_ownership_and_decision_cas(
+ sqlite_db: AgentDB, monkeypatch: pytest.MonkeyPatch, ownership: str, prepared_during_check: bool
+) -> None:
+ old = datetime.now(UTC).replace(tzinfo=None) - timedelta(seconds=LEASE_TAKEOVER_SECONDS + 1)
+ run = _workflow_run_model(workflow_run_id="wr_stale_owned", queued_at=old, status="failed")
+ attempt = WorkflowRunAttemptModel(
+ workflow_run_id="wr_stale_owned",
+ organization_id=run.organization_id,
+ attempt_number=1,
+ status="failed",
+ retry_decision="retry",
+ next_attempt_at=old,
+ finished_at=old,
+ )
+ async with sqlite_db.Session() as session:
+ session.add_all([run, attempt])
+ await session.commit()
+ monkeypatch.setattr(app, "DATABASE", sqlite_db)
+ svc = workflow_service_module.WorkflowService()
+ monkeypatch.setattr(app, "WORKFLOW_SERVICE", svc)
+ release = AsyncMock()
+ monkeypatch.setattr(svc, "_run_terminal_side_effects_with_retries", release)
+ monkeypatch.setattr(workflow_service_module, "_get_recovery_api_key", AsyncMock(return_value=None))
+
+ async def execution_status(_run: Any) -> str:
+ if prepared_during_check:
+ async with sqlite_db.Session() as session:
+ current = await session.get(WorkflowRunAttemptModel, ("wr_stale_owned", 1))
+ current.next_attempt_prepared_at = datetime.now(UTC).replace(tzinfo=None)
+ await session.commit()
+ if ownership == "error":
+ raise RuntimeError("description unavailable")
+ return ownership
+
+ describe = AsyncMock(side_effect=execution_status)
+ monkeypatch.setattr(app.AGENT_FUNCTION, "get_workflow_run_execution_status", describe)
+ await workflow_service_module.recover_pending_workflow_attempts(release_only=True)
+ current = (await sqlite_db.workflow_run_attempts.get_attempts("wr_stale_owned"))[0]
+ won = ownership in {"absent", "terminal"} and not prepared_during_check
+ assert current.retry_decision == ("abandoned" if won else "retry")
+ assert release.await_count == int(won)
+ describe.assert_awaited_once()
+
+
+async def test_terminal_progress_fences_stale_writers_and_separates_release_kinds(sqlite_db: AgentDB) -> None:
+ repo = sqlite_db.workflow_run_attempts
+ await repo.create_attempt("wr_progress", "org_test", 1, "failed")
+ async with sqlite_db.Session() as session:
+ row = await session.get(WorkflowRunAttemptModel, ("wr_progress", 1))
+ row.retry_decision = "retry"
+ await session.commit()
+ first_token = await repo.claim_attempt_side_effects("wr_progress", 1, kind="interim")
+ assert first_token is not None
+ interim: TerminalSideEffectCheckpoint = {
+ "completed_effects": ["interim workflow webhook"],
+ "final_hook_invoked": False,
+ }
+ assert await repo.save_side_effect_progress(
+ "wr_progress", 1, kind="interim", expected_claim_at=first_token, progress=interim
+ )
+ second_token = await repo.claim_attempt_side_effects(
+ "wr_progress",
+ 1,
+ kind="interim",
+ expected_claim_at=first_token,
+ stale_before=first_token + timedelta(seconds=1),
+ )
+ assert second_token is not None and second_token != first_token
+ assert not await repo.save_side_effect_progress(
+ "wr_progress",
+ 1,
+ kind="interim",
+ expected_claim_at=first_token,
+ progress={"completed_effects": [], "final_hook_invoked": False},
+ )
+ assert await repo.revoke_or_abandon_attempt("wr_progress", 1, "revoked", "cancel") is not None
+ final_token = await repo.claim_attempt_side_effects("wr_progress", 1, kind="final")
+ assert final_token is not None
+ final: TerminalSideEffectCheckpoint = {"completed_effects": ["workflow final hook"], "final_hook_invoked": True}
+ assert await repo.save_side_effect_progress(
+ "wr_progress", 1, kind="final", expected_claim_at=final_token, progress=final
+ )
+ assert not await repo.save_side_effect_progress(
+ "wr_progress", 1, kind="interim", expected_claim_at=second_token, progress=interim
+ )
+ row = (await repo.get_attempts("wr_progress"))[0]
+ assert row.interim_side_effects_progress == interim
+ assert row.final_side_effects_progress == final
+
+
[email protected]("unrelated_count, unrelated_parent_links", [(0, False), (1000, False), (1000, True)])
+async def test_attempt_artifact_ancestry_ignores_unrelated_history(
+ sqlite_db: AgentDB, sqlite_engine: AsyncEngine, unrelated_count: int, unrelated_parent_links: bool
+) -> None:
+ start = datetime(2026, 7, 22, 12, tzinfo=UTC)
+ successor = start + timedelta(minutes=10)
+ root = "wr_ancestry"
+ runs = {
+ name: _workflow_run_model(workflow_run_id=name, queued_at=start)
+ for name in (root, "wr_block_child", "wr_parent_child", "wr_grandchild", "wr_next_child")
+ }
+ runs["wr_parent_child"].parent_workflow_run_id = root
+ runs["wr_grandchild"].parent_workflow_run_id = "wr_block_child"
+ runs["wr_next_child"].parent_workflow_run_id = root
+ async with sqlite_db.Session() as session:
+ session.add(OrganizationModel(organization_id="org_test", organization_name="Test Organization"))
+ await session.flush()
+ session.add_all(list(runs.values()))
+ for name, number in [("wr_block_child", 1), ("wr_next_child", 2)]:
+ session.add(
+ WorkflowRunBlockModel(
+ workflow_run_block_id=f"spawn_{name}",
+ workflow_run_id=root,
+ block_workflow_run_id=name,
+ organization_id="org_test",
+ block_type="task_v2",
+ status="completed",
+ attempt_number=number,
+ )
+ )
+ await session.flush()
+ for name in runs:
+ session.add(
+ TaskModel(
+ task_id=f"task_{name}",
+ workflow_run_id=name,
+ organization_id="org_test",
+ status="completed",
+ url="https://example.com",
+ attempt_number=7,
+ )
+ )
+ await session.flush()
+ for name in list(runs)[1:]:
+ session.add(
+ ArtifactModel(
+ artifact_id=f"artifact_{name}",
+ organization_id="org_test",
+ run_id=root,
+ workflow_run_id=name,
+ task_id=f"task_{name}",
+ artifact_type=ArtifactType.DOWNLOAD,
+ uri=f"https://example.com/{name}",
+ created_at=start if name == "wr_parent_child" else successor + timedelta(minutes=1),
+ )
+ )
+ for name, when in [("in_window", start), ("outside_window", successor)]:
+ session.add(
+ ArtifactModel(
+ artifact_id=name,
+ organization_id="org_test",
+ run_id=root,
+ artifact_type=ArtifactType.DOWNLOAD,
+ uri=f"https://example.com/{name}",
+ created_at=when,
+ )
+ )
+ for i in range(unrelated_count):
+ unrelated_id = f"wr_unrelated_{i}"
+ unrelated_run = _workflow_run_model(workflow_run_id=unrelated_id, queued_at=start)
+ unrelated_run.parent_workflow_run_id = f"wr_unrelated_{i - 1}" if i and unrelated_parent_links else None
+ session.add(unrelated_run)
+ session.add(
+ WorkflowRunBlockModel(
+ workflow_run_block_id=f"unrelated_block_{i}",
+ workflow_run_id=f"wr_unrelated_{i - 1}" if i else unrelated_id,
+ block_workflow_run_id=unrelated_id if i else None,
+ organization_id="org_test",
+ block_type="task_v2",
+ status="completed",
+ attempt_number=2,
+ )
+ )
+ await session.commit()
+
+ async with sqlite_engine.begin() as connection:
+ await connection.exec_driver_sql("ANALYZE")
+ statements, listener = _capture_sql(sqlite_engine)
+ plans: list[str] = []
+
+ def explain(conn: Any, cursor: Any, statement: str, parameters: Any, *args: Any) -> None:
+ if statement.startswith("WITH RECURSIVE"):
+ plan_cursor = conn.connection.cursor()
+ try:
+ plan_cursor.execute("EXPLAIN QUERY PLAN " + statement, parameters)
+ plans.extend(row[3] for row in plan_cursor.fetchall())
+ finally:
+ plan_cursor.close()
+
+ event.listen(sqlite_engine.sync_engine, "before_cursor_execute", explain)
+ try:
+ first = await sqlite_db.workflow_runs.get_artifacts_for_attempt(root, "org_test", 1, start, successor)
+ second = await sqlite_db.workflow_runs.get_artifacts_for_attempt(root, "org_test", 2, successor, None)
+ finally:
+ event.remove(sqlite_engine.sync_engine, "before_cursor_execute", listener)
+ event.remove(sqlite_engine.sync_engine, "before_cursor_execute", explain)
+
+ assert {artifact.artifact_id for artifact in first} == {
+ "artifact_wr_block_child",
+ "artifact_wr_parent_child",
+ "artifact_wr_grandchild",
+ "in_window",
+ }
+ assert {artifact.artifact_id for artifact in second} == {"artifact_wr_next_child", "outside_window"}
+ assert len(statements) == 2
+ if unrelated_count:
+ assert any("parent_workflow_run_id=?" in plan for plan in plans), plans
+ block_plans = [plan for plan in plans if "attempt_spawning_block" in plan]
+ assert block_plans and all("organization_id=? AND workflow_run_id=?" in plan for plan in block_plans), plans
+ assert not any(plan.startswith("SCAN attempt_child") for plan in plans), plans
+
+
+async def test_recovery_paginates_stale_undecided_terminal_runs(sqlite_db: AgentDB) -> None:
+ now = datetime.now(UTC).replace(tzinfo=None)
+ cutoff = now - timedelta(seconds=LEASE_TAKEOVER_SECONDS)
+ old = cutoff - timedelta(seconds=1)
+ terminal_statuses = ["completed", "failed", "terminated", "canceled", "timed_out"]
+ async with sqlite_db.Session() as session:
+ for index, status in enumerate(terminal_statuses + ["running", "failed", "failed"]):
+ run_id = f"wr_undecided_{index}"
+ session.add(_workflow_run_model(workflow_run_id=run_id, queued_at=old, status=status))
+ session.add(
+ WorkflowRunAttemptModel(
+ workflow_run_id=run_id,
+ organization_id="org_test",
+ attempt_number=1,
+ status="running",
+ started_at=None if index == 7 else old,
+ modified_at=now if index == 6 else old,
+ )
+ )
+ session.add(
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_undecided_0",
+ organization_id="org_test",
+ attempt_number=2,
+ status="running",
+ started_at=old,
+ modified_at=old,
+ )
+ )
+ session.add(_workflow_run_model(workflow_run_id="wr_retry_decided", queued_at=old, status="failed"))
+ session.add(
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_retry_decided",
+ organization_id="org_test",
+ attempt_number=1,
+ status="failed",
+ retry_decision="retry",
+ next_attempt_at=old - timedelta(seconds=1),
+ modified_at=now,
+ )
+ )
+ await session.commit()
+
+ recovered: list[tuple[str, int]] = []
+ cursor = None
+ for _ in range(5):
+ page = await sqlite_db.workflow_run_attempts.list_attempts_needing_recovery(cutoff, cursor=cursor, limit=2)
+ if not page:
+ break
+ recovered.extend((attempt.workflow_run_id, attempt.attempt_number) for attempt in page)
+ last = page[-1]
+ cursor = (last.next_attempt_at or last.modified_at, last.workflow_run_id, last.attempt_number)
+ # Index 7 never started but its run is terminal, so recovery still owes it the terminal effects.
+ assert recovered == [
+ ("wr_retry_decided", 1),
+ ("wr_undecided_0", 1),
+ ("wr_undecided_0", 2),
+ *((f"wr_undecided_{index}", 1) for index in range(1, 5)),
+ ("wr_undecided_7", 1),
+ ]
diff --git a/tests/unit/forge/sdk/routes/test_agent_protocol_run_block.py b/tests/unit/forge/sdk/routes/test_agent_protocol_run_block.py
index ff9e55e2c..6944618d2 100644
--- a/tests/unit/forge/sdk/routes/test_agent_protocol_run_block.py
+++ b/tests/unit/forge/sdk/routes/test_agent_protocol_run_block.py
@@ -49,3 +49,21 @@ async def test_run_block_response_includes_resolved_browser_session(
assert response.browser_session_id == resolved_browser_session_id
assert execute_blocks.await_args.kwargs["browser_session_id"] == resolved_browser_session_id
+
+
+async def test_ensure_workflow_run_marks_block_runs_as_block_scoped(monkeypatch: pytest.MonkeyPatch) -> None:
+ prepare = AsyncMock(return_value=SimpleNamespace(workflow_run_id="wr_123"))
+ monkeypatch.setattr(agent_protocol.block_service.workflow_service, "prepare_workflow", prepare)
+ monkeypatch.setattr(
+ agent_protocol.block_service.skyvern_context, "ensure_context", lambda: SimpleNamespace(request_id="req_1")
+ )
+
+ await agent_protocol.block_service.ensure_workflow_run(
+ organization=SimpleNamespace(organization_id="org_123"),
+ template=False,
+ workflow_permanent_id="wpid_123",
+ block_run_request=BlockRunRequest(workflow_id="wpid_123", block_labels=["block_1"]),
+ )
+
+ assert prepare.await_args.kwargs["block_scoped"] is True
diff --git a/tests/unit/submission/test_shadow.py b/tests/unit/submission/test_shadow.py
index 8c5dc903c..3772d52d7 100644
--- a/tests/unit/submission/test_shadow.py
+++ b/tests/unit/submission/test_shadow.py
@@ -629,6 +629,54 @@ async def test_cua_run_and_coordinate_click_overrides_are_applied_end_to_end(
database.tasks.get_run.assert_awaited_once_with(run_id="task-1", organization_id="org-1")
+ ("last_step_task_id", "expected_task_id"),
+ [("task-b", "task-b"), ("task-a", "task-a"), ("task-missing", "task-b")],
+)
+async def test_workflow_context_only_loads_current_attempt(
+ monkeypatch: pytest.MonkeyPatch, last_step_task_id: str, expected_task_id: str
+) -> None:
+ first_task = _task("task-a", workflow_run_id="workflow-run-1")
+ first_task.attempt_number = None
+ retry_task = _task("task-b", workflow_run_id="workflow-run-1")
+ retry_task.attempt_number = 2
+ tasks = {item.task_id: item for item in [first_task, retry_task]}
+ actions = {task_id: _submit_action(task_id=task_id, step_id=f"step-{task_id}") for task_id in tasks}
+ steps = {task_id: _step(f"step-{task_id}", 1, task_id=task_id, action=actions[task_id]) for task_id in tasks}
+
+ async def get_steps(task_id: str, organization_id: str) -> list[Step]:
+ assert organization_id == "org-1"
+ return [steps[task_id]]
+
+ async def get_actions(task_id: str, organization_id: str | None = None) -> list[ClickAction]:
+ assert organization_id == "org-1"
+ return [actions[task_id]]
+
+ tasks_repo = SimpleNamespace(
+ get_tasks_by_workflow_run_id=AsyncMock(return_value=[retry_task, first_task]),
+ get_task_steps=AsyncMock(side_effect=get_steps),
+ get_task_actions_hydrated=AsyncMock(side_effect=get_actions),
+ )
+ monkeypatch.setattr(
+ shadow.app,
+ "DATABASE",
+ SimpleNamespace(
+ tasks=tasks_repo,
+ workflow_runs=SimpleNamespace(get_workflow_run_output_parameters=AsyncMock(return_value=[])),
+ ),
+ )
+ last_step = steps.get(last_step_task_id) or _step("step-missing", 2, task_id=last_step_task_id)
+
+ context = await shadow._load_context(task=None, workflow_run=_workflow_run(), last_step=last_step)
+
+ assert context.tasks == [tasks[expected_task_id]]
+ assert context.steps == [steps[expected_task_id]]
+ assert context.actions == [actions[expected_task_id]]
+ tasks_repo.get_task_steps.assert_awaited_once_with(expected_task_id, "org-1")
+ tasks_repo.get_task_actions_hydrated.assert_awaited_once_with(expected_task_id, organization_id="org-1")
+
+
@pytest.mark.asyncio
async def test_workflow_uses_all_tasks_and_block_engine_for_cua_detection(monkeypatch: pytest.MonkeyPatch) -> None:
first_task = _task("task-a", workflow_run_id="workflow-run-1")
diff --git a/tests/unit/test_agent_cleanup_download_suffix.py b/tests/unit/test_agent_cleanup_download_suffix.py
index 6e9abc9a7..5ae739d8b 100644
--- a/tests/unit/test_agent_cleanup_download_suffix.py
+++ b/tests/unit/test_agent_cleanup_download_suffix.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import os
import time
+from datetime import UTC, datetime
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -11,6 +12,8 @@ from structlog.testing import capture_logs
from skyvern.exceptions import DownloadFileMaxWaitingTime, TaskNotFound
from skyvern.forge.agent import ForgeAgent
+from skyvern.forge.sdk.api.files import check_downloading_files_and_wait_for_download_to_complete
+from skyvern.forge.sdk.artifact.storage.base import get_download_retry_started_at
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.schemas.runs import RunEngine
from skyvern.webeye.actions.models import DetailedAgentStepOutput
@@ -1836,3 +1839,73 @@ async def test_late_cleanup_skips_popup_already_closed_by_in_seam_cleanup() -> N
popup.close.assert_awaited_once() # only the in-seam close; late cleanup did not re-close
assert task.task_id not in ctx.download_popup_claims
+
+
+async def test_retry_waits_ignore_retained_partial_files(tmp_path) -> None:
+ cutoff = datetime.fromtimestamp(200, tz=UTC)
+ stale = tmp_path / "previous.pdf.crdownload"
+ stale.write_bytes(b"old partial")
+ os.utime(stale, (100, 100))
+ (tmp_path / "current.pdf").write_bytes(b"complete")
+ task = _make_task(workflow_run_id="wr_retry")
+ exhausted: set[str] = set()
+ with (
+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=tmp_path),
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=None),
+ capture_logs() as logs,
+ ):
+ async with asyncio.timeout(0.5):
+ await check_downloading_files_and_wait_for_download_to_complete(
+ tmp_path, task.organization_id, timeout=5, attempt_started_at=cutoff
+ )
+ await ForgeAgent()._wait_for_in_flight_downloads(
+ task,
+ SimpleNamespace(download_timeout=5),
+ task.organization_id,
+ attempt_started_at=cutoff,
+ exhausted=exhausted,
+ )
+ assert exhausted == set()
+ assert not any("long-time downloading" in row["event"] for row in logs)
+ assert stale.read_bytes() == b"old partial"
+
+
[email protected]("attempt", [1, None, "lookup_error"])
+async def test_retry_waits_keep_unfiltered_fallback(tmp_path, attempt) -> None:
+ stale = tmp_path / "previous.pdf.crdownload"
+ stale.write_bytes(b"old partial")
+ os.utime(stale, (100, 100))
+ result = ("wr_retry", 1, datetime.fromtimestamp(200, tz=UTC)) if attempt == 1 else ("wr_retry", 1, None)
+ task = _make_task(workflow_run_id="wr_retry")
+ exhausted: set[str] = set()
+ with (
+ patch(
+ "skyvern.forge.sdk.artifact.storage.base.resolve_download_attempt",
+ new=AsyncMock(
+ return_value=result,
+ side_effect=RuntimeError("lookup unavailable") if attempt == "lookup_error" else None,
+ ),
+ ),
+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=tmp_path),
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=None),
+ capture_logs() as logs,
+ ):
+ cutoff = await get_download_retry_started_at(task.organization_id, task.workflow_run_id)
+ await check_downloading_files_and_wait_for_download_to_complete(
+ tmp_path, task.organization_id, timeout=0.01, attempt_started_at=cutoff
+ )
+ await ForgeAgent()._wait_for_in_flight_downloads(
+ task,
+ SimpleNamespace(download_timeout=0.01),
+ task.organization_id,
+ attempt_started_at=cutoff,
+ exhausted=exhausted,
+ )
+ assert cutoff is None
+ assert exhausted == {str(stale)}
+ assert any("long-time downloading" in row["event"] for row in logs)
+ if attempt == "lookup_error":
+ assert any("Failed to resolve download attempt" in row["event"] for row in logs)
+ assert stale.exists()
diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.py
index fb92eb9db..b32113305 100644
--- a/tests/unit/test_agent_task_v3.py
+++ b/tests/unit/test_agent_task_v3.py
@@ -4126,6 +4126,49 @@ async def test_execute_task_v3_handoff_flag_on_renders_predecessor_into_goal(mon
assert goal.index(framing_marker) < goal.index("Workflow context")
+async def test_execute_task_v3_handoff_ignores_blocks_from_prior_attempt(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr("skyvern.forge.agent.settings.TASK_V3_BLOCK_HANDOFF", True)
+ monkeypatch.setattr("skyvern.forge.agent.app.WORKFLOW_CONTEXT_MANAGER.get_attempt_number", lambda _run_id: 2)
+ previous_attempt_row = _make_predecessor_run_block(
+ workflow_run_block_id="wrb_attempt_1",
+ attempt_number=1,
+ created_at=datetime.now(UTC) - timedelta(minutes=5),
+ label="old_shipping",
+ status=BlockStatus.failed,
+ finish_reason="prior attempt failure",
+ )
+ current_attempt_row = _make_predecessor_run_block(
+ workflow_run_block_id="wrb_attempt_2",
+ attempt_number=2,
+ task_id="task-123",
+ created_at=datetime.now(UTC),
+ label="shipping",
+ status=BlockStatus.running,
+ finish_reason=None,
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.agent.app.DATABASE.observer.get_workflow_run_blocks",
+ AsyncMock(return_value=[previous_attempt_row, current_attempt_row]),
+ )
+ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.observer.update_workflow_run_block", AsyncMock())
+
+ outcome = LoopOutcome(status="completed", reason="done", billable_actions=["click"])
+ block = _make_block(TaskBlock, label="shipping")
+ _step, _task, loop_mock, _post = await _run_execute_task_v3(
+ monkeypatch,
+ outcome,
+ task_block=block,
+ workflow_run_id="wr_handoff",
+ data_extraction_goal=None,
+ extracted_information_schema=None,
+ )
+
+ goal = loop_mock.await_args.kwargs["goal"]
+ assert "Workflow context" not in goal
+ assert "prior attempt failure" not in goal
+
+
@pytest.mark.asyncio
async def test_execute_task_v3_handoff_flag_off_skips_lookup_and_goal_unchanged(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/test_api_app.py b/tests/unit/test_api_app.py
index ce779ff9c..cce7be3aa 100644
--- a/tests/unit/test_api_app.py
+++ b/tests/unit/test_api_app.py
@@ -4,7 +4,10 @@ Handlers are registered through the app's own registrar so a type the real app c
cannot be missing here, or vice versa.
"""
+import asyncio
import sqlite3
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
import httpx
import psycopg
@@ -13,6 +16,7 @@ import pytest
from fastapi import FastAPI
from sqlalchemy.exc import OperationalError
+from skyvern.forge import api_app
from skyvern.forge.api_app import register_db_unavailable_handlers
from skyvern.forge.sdk.db.exceptions import DatabaseConnectionUnavailableError
@@ -88,3 +92,70 @@ async def test_a_read_that_exhausted_its_reconnects_answers_like_the_driver_erro
assert response.status_code == 503
assert response.headers["Retry-After"] == "1"
+
+
[email protected]("recovery_fails", [False, True])
+async def test_retry_recovery_never_blocks_startup_or_requests(monkeypatch, recovery_fails, caplog) -> None:
+ entered = asyncio.Event()
+ exited = asyncio.Event()
+
+ async def recover() -> None:
+ entered.set()
+ try:
+ if recovery_fails:
+ raise RuntimeError("recovery unavailable")
+ await asyncio.Event().wait()
+ finally:
+ exited.set()
+
+ monkeypatch.setattr(api_app, "ensure_tracing_initialized", lambda: None)
+ monkeypatch.setattr(type(api_app.settings), "is_sqlite", lambda _self: False)
+ stop_retry_recovery = AsyncMock()
+ monkeypatch.setattr(
+ api_app.AsyncExecutorFactory,
+ "get_executor",
+ lambda: SimpleNamespace(recover_pending_retries=recover, stop_retry_recovery=stop_retry_recovery),
+ )
+ monkeypatch.setattr(
+ api_app,
+ "forge_app",
+ SimpleNamespace(
+ DATABASE=api_app.forge_app.DATABASE,
+ api_app_startup_event=None,
+ api_app_shutdown_event=None,
+ PERSISTENT_SESSIONS_MANAGER=SimpleNamespace(cleanup_stale_sessions=AsyncMock(), start_reaper=lambda: None),
+ ),
+ )
+ for name in ("start_cleanup_scheduler", "start_temp_artifact_sweep", "start_workflow_schedule_scheduler"):
+ monkeypatch.setattr(api_app, name, lambda: None)
+ for name in (
+ "load_custom_llm_configs_from_database",
+ "stop_workflow_schedule_scheduler",
+ "stop_cleanup_scheduler",
+ "stop_temp_artifact_sweep",
+ ):
+ monkeypatch.setattr(api_app, name, AsyncMock())
+ monkeypatch.setattr(api_app.interpretation_registry, "stop_all", AsyncMock())
+ server = FastAPI()
+
+ @server.get("/health")
+ async def health() -> dict:
+ return {"ready": True}
+
+ context = api_app.lifespan(server)
+ await asyncio.wait_for(context.__aenter__(), timeout=1)
+ try:
+ await asyncio.wait_for(entered.wait(), timeout=1)
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=server), base_url="http://testserver") as client:
+ response = await client.get("/health")
+ assert response.status_code == 200
+ assert response.json() == {"ready": True}
+ if recovery_fails:
+ assert "Failed to recover pending workflow retries" in caplog.text
+ else:
+ assert not exited.is_set()
+ finally:
+ await asyncio.wait_for(context.__aexit__(None, None, None), timeout=1)
+ stop_retry_recovery.assert_awaited_once()
+ assert exited.is_set()
diff --git a/tests/unit/test_background_task_executor.py b/tests/unit/test_background_task_executor.py
index 0ddb26226..5ec5bb43d 100644
--- a/tests/unit/test_background_task_executor.py
+++ b/tests/unit/test_background_task_executor.py
@@ -1,17 +1,1760 @@
import asyncio
+import json
+from collections.abc import AsyncIterator
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock
+from typing import Any
+from unittest.mock import ANY, AsyncMock, MagicMock, Mock
+import httpx
import pytest
+import pytest_asyncio
from fastapi import BackgroundTasks
+from sqlalchemy import insert, literal, select, update
-from skyvern.exceptions import SkyvernException
+from skyvern.config import settings
+from skyvern.exceptions import SkyvernException, WorkflowRetryAttemptLookupError
from skyvern.forge import app
+from skyvern.forge.agent_functions import AgentFunction
+from skyvern.forge.sdk.artifact.models import ArtifactType
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
+from skyvern.forge.sdk.db.agent_db import AgentDB, _build_engine
+from skyvern.forge.sdk.db.models import (
+ ArtifactModel,
+ Base,
+ OrganizationModel,
+ OutputParameterModel,
+ StepModel,
+ TaskModel,
+ WorkflowModel,
+ WorkflowRunAttemptModel,
+ WorkflowRunBlockModel,
+ WorkflowRunModel,
+ WorkflowRunOutputParameterModel,
+)
+from skyvern.forge.sdk.db.repositories import workflow_run_attempts as attempts_repository_module
+from skyvern.forge.sdk.db.repositories import workflow_runs as workflow_runs_repository_module
+from skyvern.forge.sdk.db.repositories.workflow_runs import PrepareNextAttemptResult
+from skyvern.forge.sdk.executor import background_task_executor as background_task_executor_module
from skyvern.forge.sdk.executor.background_task_executor import BackgroundTaskExecutor
+from skyvern.forge.sdk.schemas.files import FileInfo
from skyvern.forge.sdk.schemas.persistent_browser_sessions import FORCED_WORKFLOW_SESSION_RUNNABLE_TYPE
+from skyvern.forge.sdk.workflow import retry_policy as retry_policy_module
+from skyvern.forge.sdk.workflow import service as service_module
+from skyvern.forge.sdk.workflow.constants import INTERIM_OUTPUT_SNAPSHOT_MAX_BYTES
+from skyvern.forge.sdk.workflow.models.workflow import WorkflowRun, WorkflowRunStatus
+from skyvern.forge.sdk.workflow.retry_policy import RETRY_DECISION_GRACE_SECONDS, RetryDecision, mark_attempt_started
+from skyvern.forge.sdk.workflow.service import WorkflowService
from skyvern.schemas.browser_session_close import BrowserSessionCloseReason
+from skyvern.services import workflow_schedule_service as schedule_service_module
+from tests.unit.scoped_asyncio import ScopedAsyncio
+
+
[email protected](autouse=True)
+def workflow_service(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(app, "WORKFLOW_SERVICE", WorkflowService())
+ monkeypatch.setattr(
+ app.DATABASE.workflow_run_attempts, "list_stale_dispatch_claims", AsyncMock(return_value=[]), raising=False
+ )
+ monkeypatch.setattr(app.AGENT_FUNCTION, "get_workflow_run_execution_status", AsyncMock(return_value="absent"))
+
+
+@pytest_asyncio.fixture
+async def sqlite_db(tmp_path: Path) -> AsyncIterator[AgentDB]:
+ url = f"sqlite+aiosqlite:///{tmp_path / 'recovery.db'}"
+ engine = _build_engine(url)
+ async with engine.begin() as connection:
+ await connection.run_sync(Base.metadata.create_all)
+ try:
+ yield AgentDB(url, db_engine=engine)
+ finally:
+ await engine.dispose()
+
+
+@pytest_asyncio.fixture
+async def interim_retry_db(sqlite_db: AgentDB, monkeypatch: pytest.MonkeyPatch) -> AgentDB:
+ monkeypatch.setattr(app, "DATABASE", sqlite_db)
+ now = datetime.now(UTC).replace(tzinfo=None)
+ async with sqlite_db.Session() as session:
+ session.add(OrganizationModel(organization_id="org_test", organization_name="Test Organization"))
+ await session.commit()
+ session.add_all(
+ [
+ WorkflowModel(
+ workflow_id="wf_retry",
+ workflow_permanent_id="wpid_retry",
+ organization_id="org_test",
+ title="Retry delivery",
+ version=1,
+ workflow_definition={
+ "blocks": [],
+ "parameters": [],
+ "retry_policy": {
+ "max_retries": 1,
+ "delay_seconds": 5,
+ "retry_on": [{"status": "failed"}],
+ "webhook_on_retry": "every_attempt",
+ },
+ },
+ ),
+ WorkflowRunModel(
+ workflow_run_id="wr_retry",
+ workflow_id="wf_retry",
+ workflow_permanent_id="wpid_retry",
+ organization_id="org_test",
+ status="failed",
+ finished_at=now,
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_retry",
+ organization_id="org_test",
+ attempt_number=1,
+ status="failed",
+ retry_decision="retry",
+ finished_at=now,
+ next_attempt_at=now + timedelta(seconds=5),
+ ),
+ ]
+ )
+ await session.commit()
+ svc = app.WORKFLOW_SERVICE
+ monkeypatch.setattr(svc, "prepare_workflow_webhook", AsyncMock(return_value=object()))
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", AsyncMock())
+ monkeypatch.setattr(app.AGENT_FUNCTION, "on_workflow_run_final", AsyncMock())
+ monkeypatch.setattr(svc, "_start_credential_fallback_retry_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "_apply_completion_run_tags_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "_run_workflow_run_terminal_hooks", AsyncMock())
+ monkeypatch.setattr(app.WORKFLOW_CONTEXT_MANAGER, "remove_workflow_run_context", MagicMock())
+ monkeypatch.setattr(sqlite_db.tasks, "get_tasks_by_workflow_run_id", AsyncMock(return_value=[]))
+ monkeypatch.setattr(sqlite_db.observer, "get_workflow_run_blocks", AsyncMock(return_value=[]))
+ return sqlite_db
+
+
+@pytest_asyncio.fixture
+async def prepared_dispatch_db(interim_retry_db: AgentDB, monkeypatch: pytest.MonkeyPatch) -> AgentDB:
+ database = interim_retry_db
+ monkeypatch.setattr(settings, "RETRY_DISPATCH_GRACE_SECONDS", 600)
+ async with database.Session() as session:
+ previous = await session.get(WorkflowRunAttemptModel, ("wr_retry", 1))
+ assert previous is not None
+ previous.interim_webhook_sent_at = datetime.now(UTC).replace(tzinfo=None)
+ await session.commit()
+ preparation = await database.workflow_runs.prepare_next_attempt_atomic("wr_retry", "org_test", 1, "failed", None)
+ assert preparation.status == "inserted"
+ monkeypatch.setattr(
+ database.organizations, "get_valid_org_auth_token", AsyncMock(return_value=SimpleNamespace(token="api-token"))
+ )
+ monkeypatch.setattr(background_task_executor_module, "initialize_skyvern_state_file", AsyncMock())
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ return database
+
+
[email protected]("resume_fresh", [True, False], ids=["startup", "periodic"])
[email protected]("configured_grace", [0, 600, 2 * service_module.LEASE_TAKEOVER_SECONDS])
[email protected]("scenario", ["stale", "young", "boundary", "running"])
+async def test_claimed_undispatched_retry_recovers_after_process_loss(
+ prepared_dispatch_db: AgentDB,
+ monkeypatch: pytest.MonkeyPatch,
+ scenario: str,
+ resume_fresh: bool,
+ configured_grace: int,
+) -> None:
+ database = prepared_dispatch_db
+ assert await database.workflow_run_attempts.claim_prepared_attempt_execution("wr_retry", "org_test", 2)
+ attempt = (await database.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ original_stamp = attempt.started_at
+ assert original_stamp is not None
+ monkeypatch.setattr(settings, "RETRY_DISPATCH_GRACE_SECONDS", configured_grace)
+ grace = max(600, service_module.LEASE_TAKEOVER_SECONDS, configured_grace)
+ age = grace + {"stale": 1, "young": -1, "boundary": 0, "running": 1}[scenario]
+ recovery_time = attempt.modified_at + timedelta(seconds=age)
+ for module in (service_module, background_task_executor_module, attempts_repository_module):
+ monkeypatch.setattr(module, "naive_utc_now", lambda: recovery_time)
+ if scenario == "running":
+ async with database.Session() as session:
+ run_model = await session.get(WorkflowRunModel, "wr_retry")
+ assert run_model is not None
+ run_model.status = "running"
+ await session.commit()
+ execute = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)
+ run = await database.workflow_runs.get_workflow_run("wr_retry", "org_test")
+ assert run is not None and run.started_at is not None
+ assert attempt.status == "running" and attempt.retry_decision is None
+ assert await AgentFunction.get_workflow_run_execution_status(app.AGENT_FUNCTION, run) == "absent"
+ # Cloud/Temporal's existing recovery query must continue to exclude dispatch claims.
+ assert (
+ await database.workflow_run_attempts.list_attempts_needing_recovery(
+ recovery_time - timedelta(seconds=service_module.LEASE_TAKEOVER_SECONDS)
+ )
+ == []
+ )
+ executor = BackgroundTaskExecutor()
+ assert not executor._retry_dispatches_needing_recovery
+ if resume_fresh:
+ monkeypatch.setattr(executor, "_start_retry_recovery_sweep", MagicMock())
+ await executor.recover_pending_retries()
+ else:
+ await executor._recover_pending_retries_once(resume_fresh=False)
+ if executor._background_tasks:
+ await asyncio.gather(*executor._background_tasks)
+ current = (await database.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ if scenario == "stale":
+ execute.assert_awaited_once()
+ assert execute.await_args is not None
+ assert execute.await_args.kwargs["attempt_number"] == 2
+ assert execute.await_args.kwargs["prepared_attempt_claimed"] is True
+ assert current.started_at == recovery_time != original_stamp
+ assert current.status == "running" and current.retry_decision is None
+ else:
+ execute.assert_not_awaited()
+ assert current.started_at == original_stamp
+ assert current.modified_at == attempt.modified_at
+
+
+def _hold_after_dispatch_claim(
+ database: AgentDB, monkeypatch: pytest.MonkeyPatch
+) -> tuple[asyncio.Event, asyncio.Event]:
+ """Pause a prepared resume right after it claims the dispatch, before execution starts."""
+ claimed = asyncio.Event()
+ resume = asyncio.Event()
+ claim = database.workflow_run_attempts.claim_prepared_attempt_execution
+
+ async def claim_and_wait(*args: object, **kwargs: object) -> datetime | None:
+ stamp = await claim(*args, **kwargs)
+ claimed.set()
+ await resume.wait()
+ return stamp
+
+ monkeypatch.setattr(database.workflow_run_attempts, "claim_prepared_attempt_execution", claim_and_wait)
+ return claimed, resume
+
+
+async def test_retry_dispatch_fences_claim_replaced_before_dispatch(
+ prepared_dispatch_db: AgentDB, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ database = prepared_dispatch_db
+ entered, resume = _hold_after_dispatch_claim(database, monkeypatch)
+ execute = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)
+ pending = (await database.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ executor = BackgroundTaskExecutor()
+ executor._schedule_retry_resume(pending)
+ tasks = list(executor._background_tasks)
+ try:
+ await asyncio.wait_for(entered.wait(), timeout=5)
+ claimed = (await database.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ assert claimed.started_at is not None
+ # Emulate the durable result of a competing recovery release/reclaim before this dispatch runs.
+ replacement_stamp = claimed.started_at + timedelta(seconds=2 * service_module.LEASE_TAKEOVER_SECONDS)
+ async with database.Session() as session:
+ await session.execute(
+ update(WorkflowRunAttemptModel)
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == "wr_retry", WorkflowRunAttemptModel.attempt_number == 2
+ )
+ .values(started_at=replacement_stamp, modified_at=replacement_stamp)
+ )
+ await session.execute(
+ update(WorkflowRunModel)
+ .where(WorkflowRunModel.workflow_run_id == "wr_retry")
+ .values(started_at=replacement_stamp, modified_at=replacement_stamp)
+ )
+ await session.commit()
+ finally:
+ resume.set()
+ await asyncio.gather(*tasks)
+ execute.assert_not_awaited()
+ current = (await database.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ assert current.started_at == replacement_stamp
+ assert current.retry_decision is None
+ assert not executor._retry_dispatches_needing_recovery
+ assert not executor._scheduled_retry_resumes
+
+
[email protected]("initializer", ["state_file", "llm_runtime"])
[email protected]("recovers", [True, False], ids=["transient", "persistent"])
+async def test_prepared_retry_initializer_failure_keeps_the_attempt_recoverable(
+ prepared_dispatch_db: AgentDB, monkeypatch: pytest.MonkeyPatch, initializer: str, recovers: bool
+) -> None:
+ database = prepared_dispatch_db
+ error = RuntimeError("initializer unavailable")
+ failing = AsyncMock(side_effect=[error, None, None] if recovers else error)
+ monkeypatch.setattr(
+ background_task_executor_module,
+ "initialize_skyvern_state_file" if initializer == "state_file" else "prepare_org_llm_runtime",
+ failing,
+ )
+ real_now = background_task_executor_module.naive_utc_now
+ clock_offset = timedelta()
+
+ async def sleep(seconds: float) -> None:
+ nonlocal clock_offset
+ assert 0 < seconds <= background_task_executor_module.LEASE_TAKEOVER_SECONDS
+ if not recovers:
+ clock_offset += timedelta(seconds=background_task_executor_module.LEASE_TAKEOVER_SECONDS + 1)
+
+ monkeypatch.setattr(background_task_executor_module, "naive_utc_now", lambda: real_now() + clock_offset)
+ monkeypatch.setattr(background_task_executor_module, "asyncio", ScopedAsyncio(sleep=sleep))
+ execute = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)
+ pending = (await database.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ executor = BackgroundTaskExecutor()
+ executor._schedule_retry_resume(pending)
+ await asyncio.gather(*executor._background_tasks)
+
+ current = (await database.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ workflow_run = await database.workflow_runs.get_workflow_run(workflow_run_id="wr_retry", organization_id="org_test")
+ assert workflow_run is not None
+ assert current.retry_decision is None
+ assert not executor._scheduled_retry_resumes
+ if recovers:
+ execute.assert_awaited_once()
+ assert execute.await_args is not None
+ assert execute.await_args.kwargs["attempt_number"] == 2
+ assert execute.await_args.kwargs["prepared_attempt_claimed"] is True
+ assert current.started_at is not None
+ else:
+ execute.assert_not_awaited()
+ assert current.status == "queued" and current.started_at is None
+ assert workflow_run.status == WorkflowRunStatus.queued
+ assert ("wr_retry", 2) in executor._retry_resumes_needing_recovery
+
+
+async def test_periodic_recovery_skips_its_own_stale_dispatch(
+ prepared_dispatch_db: AgentDB, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ database = prepared_dispatch_db
+ entered, resume = _hold_after_dispatch_claim(database, monkeypatch)
+ execute = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)
+ pending = (await database.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ executor = BackgroundTaskExecutor()
+ executor._schedule_retry_resume(pending)
+ tasks = list(executor._background_tasks)
+ try:
+ await asyncio.wait_for(entered.wait(), timeout=5)
+ claimed = (await database.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ assert claimed.started_at is not None
+ recovery_time = claimed.modified_at + timedelta(seconds=2 * service_module.LEASE_TAKEOVER_SECONDS)
+ for module in (service_module, background_task_executor_module, attempts_repository_module):
+ monkeypatch.setattr(module, "naive_utc_now", lambda: recovery_time)
+ await executor._recover_pending_retries_once(resume_fresh=False)
+ current = (await database.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ assert current.started_at == claimed.started_at
+ assert current.modified_at == claimed.modified_at
+ execute.assert_not_awaited()
+ finally:
+ resume.set()
+ await asyncio.gather(*tasks)
+ execute.assert_awaited_once()
+
+
+async def test_recovery_skips_dispatch_if_release_cas_loses(
+ prepared_dispatch_db: AgentDB, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ database = prepared_dispatch_db
+ assert await database.workflow_run_attempts.claim_prepared_attempt_execution("wr_retry", "org_test", 2)
+ claimed = (await database.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ recovery_time = claimed.modified_at + timedelta(seconds=2 * service_module.LEASE_TAKEOVER_SECONDS)
+ for module in (service_module, background_task_executor_module, attempts_repository_module):
+ monkeypatch.setattr(module, "naive_utc_now", lambda: recovery_time)
+ release = database.workflow_run_attempts.release_stale_dispatch_claim
+
+ async def lose_release(*args: object, **kwargs: object) -> bool:
+ async with database.Session() as session:
+ await session.execute(
+ update(WorkflowRunModel).where(WorkflowRunModel.workflow_run_id == "wr_retry").values(status="running")
+ )
+ await session.commit()
+ return await release(*args, **kwargs)
+
+ monkeypatch.setattr(database.workflow_run_attempts, "release_stale_dispatch_claim", lose_release)
+ execute = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)
+ executor = BackgroundTaskExecutor()
+ await executor._recover_pending_retries_once(resume_fresh=False)
+ if executor._background_tasks:
+ await asyncio.gather(*executor._background_tasks)
+ execute.assert_not_awaited()
+ current = (await database.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ assert current.started_at == claimed.started_at
+ assert not executor._scheduled_retry_resumes
+
+
+@pytest_asyncio.fixture
+async def undecided_terminal_db(interim_retry_db: AgentDB) -> AgentDB:
+ old = datetime.now(UTC).replace(tzinfo=None) - timedelta(seconds=service_module.LEASE_TAKEOVER_SECONDS + 1)
+ async with interim_retry_db.Session() as session:
+ run = await session.get(WorkflowRunModel, "wr_retry")
+ run.started_at = old - timedelta(seconds=10)
+ run.finished_at = old
+ run.failure_reason = "persisted terminal failure"
+ run.failure_category = [{"category": "navigation"}]
+ attempt = await session.get(WorkflowRunAttemptModel, ("wr_retry", 1))
+ attempt.status = "running"
+ attempt.retry_decision = None
+ attempt.started_at = run.started_at
+ attempt.finished_at = None
+ attempt.next_attempt_at = None
+ attempt.modified_at = old
+ await session.commit()
+ return interim_retry_db
+
+
[email protected]("sweep", ["startup", "periodic", "release_only"])
[email protected]("status", ["failed", "terminated"])
+async def test_recovery_reconstructs_undecided_terminal_attempt(
+ undecided_terminal_db: AgentDB, monkeypatch: pytest.MonkeyPatch, sweep: str, status: str
+) -> None:
+ database = undecided_terminal_db
+ svc = app.WORKFLOW_SERVICE
+ async with database.Session() as session:
+ run = await session.get(WorkflowRunModel, "wr_retry")
+ run.status = status
+ await session.commit()
+
+ deliver = AsyncMock(return_value=True)
+ execute = AsyncMock()
+ monkeypatch.setattr(svc, "deliver_prepared_workflow_webhook", deliver)
+ monkeypatch.setattr(svc, "execute_workflow_with_retries", execute)
+ monkeypatch.setattr(service_module, "_get_recovery_api_key", AsyncMock(return_value="test-key"))
+ monkeypatch.setattr(BackgroundTaskExecutor, "_get_valid_api_key", AsyncMock(return_value="test-key"))
+ monkeypatch.setattr(background_task_executor_module, "initialize_skyvern_state_file", AsyncMock())
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ monkeypatch.setattr(background_task_executor_module, "asyncio", ScopedAsyncio(sleep=AsyncMock()))
+ executor = BackgroundTaskExecutor()
+ if sweep == "release_only":
+ await svc.recover_pending_workflow_attempts(release_only=True)
+ else:
+ await executor._recover_pending_retries_once(resume_fresh=sweep == "startup")
+ await asyncio.gather(*executor._background_tasks)
+
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ first = attempts[0]
+ assert first.status == status
+ assert first.retry_decision == ("retry" if status == "failed" else "final")
+ assert first.failure_reason == "persisted terminal failure"
+ assert first.failure_category == [{"category": "navigation"}]
+ assert first.finished_at is not None
+ deliver.assert_awaited_once()
+ if status == "failed":
+ assert first.next_attempt_at is not None
+ assert first.interim_webhook_sent_at is not None
+ assert first.webhook_sent_at is None
+ if sweep == "release_only":
+ assert len(attempts) == 1
+ execute.assert_not_awaited()
+ else:
+ assert first.next_attempt_prepared_at is not None
+ assert len(attempts) == 2
+ assert attempts[1].status == "queued"
+ assert execute.await_args.kwargs["attempt_number"] == 2
+ else:
+ assert len(attempts) == 1
+ assert first.webhook_sent_at is not None
+ assert first.next_attempt_at is None
+ execute.assert_not_awaited()
+
+
[email protected]("sweep", ["background", "release_only"])
[email protected]("ownership", ["absent", "running", "unknown"])
+async def test_recovery_leaves_concurrent_terminal_decision_and_live_owner_alone(
+ undecided_terminal_db: AgentDB, monkeypatch: pytest.MonkeyPatch, sweep: str, ownership: str
+) -> None:
+ database = undecided_terminal_db
+ svc = app.WORKFLOW_SERVICE
+
+ async def execution_status(run: WorkflowRun) -> str:
+ if ownership == "absent":
+ await service_module.on_terminal_transition(
+ run, run.status, run.failure_reason, run.failure_category, attempt_number=1
+ )
+ return ownership
+
+ monkeypatch.setattr(app.AGENT_FUNCTION, "get_workflow_run_execution_status", execution_status)
+ deliver = AsyncMock(return_value=True)
+ monkeypatch.setattr(svc, "deliver_prepared_workflow_webhook", deliver)
+ executor = BackgroundTaskExecutor()
+ if sweep == "release_only":
+ await svc.recover_pending_workflow_attempts(release_only=True)
+ else:
+ await executor._recover_pending_retries_once(resume_fresh=False)
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ assert len(attempts) == 1
+ assert attempts[0].retry_decision == ("retry" if ownership == "absent" else None)
+ assert attempts[0].side_effects_released_at is None
+ assert attempts[0].interim_webhook_sent_at is None
+ assert attempts[0].webhook_sent_at is None
+ assert not executor._scheduled_retry_resumes
+ deliver.assert_not_awaited()
+
+
[email protected]("race_stage", ["read", "write"])
+async def test_undecided_recovery_is_noop_when_live_finalizer_wins(
+ undecided_terminal_db: AgentDB, monkeypatch: pytest.MonkeyPatch, race_stage: str
+) -> None:
+ database = undecided_terminal_db
+ svc = app.WORKFLOW_SERVICE
+ read_attempts = database.workflow_run_attempts.get_attempts
+ transition = service_module.on_terminal_transition
+ winning_attempt: WorkflowRunAttemptModel | None = None
+ finalize_ready = asyncio.Event()
+
+ async def finalize_live() -> None:
+ nonlocal winning_attempt
+ await finalize_ready.wait()
+ winning_attempt = await database.workflow_run_attempts.finalize_attempt(
+ "wr_retry",
+ 1,
+ status="failed",
+ failure_reason="live finalizer failure",
+ failure_category=None,
+ error_codes=[],
+ finished_at=datetime.now(UTC),
+ retry_decision="final",
+ decision_reason="live finalizer decision",
+ next_attempt_at=None,
+ )
+
+ live_finalizer = asyncio.create_task(finalize_live())
+
+ async def transition_after_live(*args: object, **kwargs: object) -> object:
+ finalize_ready.set()
+ await live_finalizer
+ return await transition(*args, **kwargs)
+
+ async def tasks_after_live(*args: object, **kwargs: object) -> list:
+ finalize_ready.set()
+ await live_finalizer
+ return []
+
+ if race_stage == "read":
+ monkeypatch.setattr(service_module, "on_terminal_transition", transition_after_live)
+ else:
+ monkeypatch.setattr(database.tasks, "get_tasks_by_workflow_run_id", tasks_after_live)
+ deliver = AsyncMock(return_value=True)
+ monkeypatch.setattr(svc, "deliver_prepared_workflow_webhook", deliver)
+ executor = BackgroundTaskExecutor()
+ try:
+ await executor._recover_pending_retries_once(resume_fresh=False)
+ finally:
+ live_finalizer.cancel()
+ await asyncio.gather(live_finalizer, return_exceptions=True)
+ assert winning_attempt is not None
+ attempts = await read_attempts("wr_retry")
+ assert len(attempts) == 1
+ current = attempts[0]
+ assert current.retry_decision == "final"
+ assert current.failure_reason == "live finalizer failure"
+ assert current.decision_reason == "live finalizer decision"
+ assert current.modified_at == winning_attempt.modified_at
+ assert current.side_effects_released_at is None
+ assert current.webhook_sent_at is None
+ assert not executor._scheduled_retry_resumes
+ deliver.assert_not_awaited()
+
+
+async def test_recovery_sweep_paginates_undecided_attempts_after_finalizing_each_page(
+ undecided_terminal_db: AgentDB, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ database = undecided_terminal_db
+ svc = app.WORKFLOW_SERVICE
+ old = datetime.now(UTC).replace(tzinfo=None) - timedelta(seconds=service_module.LEASE_TAKEOVER_SECONDS + 1)
+ async with database.Session() as session:
+ run = await session.get(WorkflowRunModel, "wr_retry")
+ run.status = "terminated"
+ for index in range(4):
+ run_id = f"wr_page_{index}"
+ session.add(
+ WorkflowRunModel(
+ workflow_run_id=run_id,
+ organization_id="org_test",
+ workflow_id="wf_retry",
+ workflow_permanent_id="wpid_retry",
+ status="terminated",
+ started_at=old,
+ finished_at=old,
+ )
+ )
+ session.add(
+ WorkflowRunAttemptModel(
+ workflow_run_id=run_id,
+ organization_id="org_test",
+ attempt_number=1,
+ status="running",
+ started_at=old,
+ modified_at=old,
+ )
+ )
+ await session.commit()
+
+ read_page = database.workflow_run_attempts.list_attempts_needing_recovery
+ cursors: list[tuple[datetime, str, int] | None] = []
+
+ async def small_page(
+ cutoff: datetime, *, cursor: tuple[datetime, str, int] | None = None
+ ) -> list[WorkflowRunAttemptModel]:
+ cursors.append(cursor)
+ return await read_page(cutoff, cursor=cursor, limit=2)
+
+ monkeypatch.setattr(database.workflow_run_attempts, "list_attempts_needing_recovery", small_page)
+ monkeypatch.setattr(service_module, "ATTEMPT_RECOVERY_BATCH_SIZE", 2)
+ monkeypatch.setattr(service_module, "_get_recovery_api_key", AsyncMock(return_value="test-key"))
+ deliver = AsyncMock(return_value=True)
+ monkeypatch.setattr(svc, "deliver_prepared_workflow_webhook", deliver)
+ await svc.recover_pending_workflow_attempts(release_only=True)
+ assert len(cursors) == 3
+ for run_id in ["wr_retry", *(f"wr_page_{index}" for index in range(4))]:
+ attempt = (await database.workflow_run_attempts.get_attempts(run_id))[0]
+ assert attempt.retry_decision == "final"
+ assert attempt.webhook_sent_at is not None
+ assert await read_page(datetime.now(UTC)) == []
+ assert deliver.await_count == 5
+
+
+async def test_policy_terminal_winner_survives_late_failed_writer(
+ interim_retry_db: AgentDB, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ database = interim_retry_db
+ svc = app.WORKFLOW_SERVICE
+ async with database.Session() as session:
+ run = await session.get(WorkflowRunModel, "wr_retry")
+ run.status = "running"
+ run.finished_at = None
+ attempt = await session.get(WorkflowRunAttemptModel, ("wr_retry", 1))
+ attempt.status = "running"
+ attempt.retry_decision = None
+ attempt.finished_at = None
+ attempt.next_attempt_at = None
+ await session.commit()
+
+ finalize_attempt = AsyncMock(wraps=database.workflow_run_attempts.finalize_attempt)
+ monkeypatch.setattr(database.workflow_run_attempts, "finalize_attempt", finalize_attempt)
+ sync_status = AsyncMock()
+ monkeypatch.setattr(svc, "_sync_task_run_from_workflow_run", sync_status)
+
+ before = set(svc._background_tasks)
+ completed = await svc.mark_workflow_run_as_completed("wr_retry")
+ late_failure = await svc.mark_workflow_run_as_failed("wr_retry", failure_reason="late failure")
+ stored = await svc.get_workflow_run("wr_retry", "org_test")
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ await asyncio.gather(*(svc._background_tasks - before))
+
+ assert completed.status == late_failure.status == stored.status == WorkflowRunStatus.completed
+ assert late_failure.failure_reason == stored.failure_reason is None
+ assert late_failure.failure_category == stored.failure_category is None
+ assert late_failure.finished_at == stored.finished_at == completed.finished_at
+ assert len(attempts) == 1
+ assert attempts[0].status == "completed"
+ assert attempts[0].retry_decision == "final"
+ assert attempts[0].finished_at is not None
+ assert attempts[0].failure_reason is None
+ assert attempts[0].next_attempt_at is None
+ assert attempts[0].next_attempt_prepared_at is None
+ finalize_attempt.assert_awaited_once()
+ sync_status.assert_awaited_once()
+ assert sync_status.await_args.args[2] == WorkflowRunStatus.completed
+
+
[email protected]("escaped_exception", [False, True])
[email protected]("final_delivery_succeeds", [False, True])
+async def test_in_process_retry_continues_after_interim_delivery_exhaustion(
+ interim_retry_db: AgentDB,
+ monkeypatch: pytest.MonkeyPatch,
+ escaped_exception: bool,
+ final_delivery_succeeds: bool,
+) -> None:
+ database = interim_retry_db
+ svc = app.WORKFLOW_SERVICE
+ events: list[str] = []
+ deliveries: list[int] = []
+
+ async def deliver(_webhook: object) -> bool:
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ number = attempts[-1].attempt_number
+ deliveries.append(number)
+ return number == 2 and final_delivery_succeeds
+
+ async def execute(**kwargs: object) -> WorkflowRun:
+ number = kwargs["attempt_number"]
+ events.append(f"execute:{number}")
+ if number == 1:
+ if escaped_exception:
+ raise RuntimeError("attempt failed")
+ return await svc.get_workflow_run("wr_retry", "org_test")
+ assert number == 2
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ assert attempts[0].interim_webhook_sent_at is not None
+ assert attempts[0].next_attempt_prepared_at is not None
+ completed = await database.workflow_runs.update_workflow_run_if_not_final(
+ workflow_run_id="wr_retry", status=WorkflowRunStatus.completed
+ )
+ assert completed is not None
+ await service_module.on_terminal_transition(completed, completed.status, None, None, attempt_number=2)
+ return completed
+
+ async def sleep(seconds: float) -> None:
+ # The owner sleeps only what is left of the 5 s delay after the interim effects ran.
+ assert 0 <= seconds <= 5
+ assert deliveries == [1] * service_module.TERMINAL_RELEASE_RETRY_MAX_ATTEMPTS
+ events.append("sleep")
+
+ monkeypatch.setattr(svc, "execute_workflow", execute)
+ monkeypatch.setattr(svc, "deliver_prepared_workflow_webhook", deliver)
+ monkeypatch.setattr(service_module, "asyncio", ScopedAsyncio(sleep=sleep))
+ result = await svc.execute_workflow_with_retries(
+ "wr_retry", api_key="test-key", organization=SimpleNamespace(organization_id="org_test")
+ )
+
+ assert result.status == WorkflowRunStatus.completed
+ assert events == ["execute:1", "sleep", "execute:2"]
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ assert len(attempts) == 2
+ assert attempts[0].interim_webhook_sent_at is not None
+ assert attempts[0].side_effects_released_at is not None
+ assert attempts[0].interim_side_effects_progress["webhook_delivery_exhausted_at"]
+ assert not attempts[0].interim_side_effects_progress.get("webhook_delivery_attempted")
+ assert attempts[0].retry_decision == "retry"
+ assert attempts[1].retry_decision == "final"
+ assert attempts[1].webhook_sent_at is not None
+ assert bool(attempts[1].final_side_effects_progress.get("webhook_delivery_attempted")) == final_delivery_succeeds
+ assert bool(attempts[1].final_side_effects_progress.get("webhook_delivery_exhausted_at")) != final_delivery_succeeds
+ assert deliveries.count(2) == (1 if final_delivery_succeeds else service_module.TERMINAL_RELEASE_RETRY_MAX_ATTEMPTS)
+
+
[email protected]("escaped_exception", [False, True])
+async def test_in_process_retry_continues_after_interim_payload_failure(
+ interim_retry_db: AgentDB, monkeypatch: pytest.MonkeyPatch, escaped_exception: bool
+) -> None:
+ database = interim_retry_db
+ svc = app.WORKFLOW_SERVICE
+ events: list[str] = []
+ release_outcomes: list[str] = []
+ release = svc._run_terminal_side_effects_with_retries
+
+ async def record_release(*args: object, **kwargs: object) -> str:
+ outcome = await release(*args, **kwargs)
+ release_outcomes.append(outcome)
+ return outcome
+
+ async def prepare(run: WorkflowRun, *args: object, **kwargs: object) -> object:
+ if run.status == WorkflowRunStatus.failed:
+ raise RuntimeError("payload unavailable")
+ return object()
+
+ async def execute(**kwargs: object) -> WorkflowRun:
+ number = kwargs["attempt_number"]
+ events.append(f"execute:{number}")
+ if number == 1:
+ if escaped_exception:
+ raise RuntimeError("attempt failed")
+ return await svc.get_workflow_run("wr_retry", "org_test")
+ assert number == 2
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ assert attempts[0].next_attempt_prepared_at is not None
+ completed = await database.workflow_runs.update_workflow_run_if_not_final(
+ workflow_run_id="wr_retry", status=WorkflowRunStatus.completed
+ )
+ assert completed is not None
+ await service_module.on_terminal_transition(completed, completed.status, None, None, attempt_number=2)
+ return completed
+
+ async def sleep(seconds: float) -> None:
+ # The owner sleeps only what is left of the 5 s delay after the interim effects ran.
+ assert 0 <= seconds <= 5
+ assert release_outcomes == ["effect_failed"]
+ attempt = (await database.workflow_run_attempts.get_attempts("wr_retry"))[0]
+ assert attempt.interim_webhook_sent_at is None
+ assert attempt.side_effects_released_at is None
+ assert (attempt.interim_side_effects_progress or {}).get("webhook_delivery_attempts", 0) == 0
+ events.append("sleep")
+
+ monkeypatch.setattr(svc, "_run_terminal_side_effects_with_retries", record_release)
+ monkeypatch.setattr(svc, "prepare_workflow_webhook", prepare)
+ monkeypatch.setattr(svc, "deliver_prepared_workflow_webhook", AsyncMock(return_value=True))
+ monkeypatch.setattr(svc, "execute_workflow", execute)
+ monkeypatch.setattr(service_module, "asyncio", ScopedAsyncio(sleep=sleep))
+ result = await svc.execute_workflow_with_retries(
+ "wr_retry", api_key="test-key", organization=SimpleNamespace(organization_id="org_test")
+ )
+ assert result.status == WorkflowRunStatus.completed
+ assert events == ["execute:1", "sleep", "execute:2"]
+ assert release_outcomes == ["effect_failed", "released"]
+
+
[email protected]("sweep", ["background", "cloud"])
[email protected]("current_status", ["running", "completed"])
[email protected]("artifact_link", ["task", "step", "block", "time"])
[email protected]("latest_has_screenshot", [False, True])
[email protected]("latest_has_recording", [False, True])
+async def test_recovered_interim_payload_describes_target_attempt(
+ interim_retry_db: AgentDB,
+ monkeypatch: pytest.MonkeyPatch,
+ sweep: str,
+ current_status: str,
+ artifact_link: str,
+ latest_has_screenshot: bool,
+ latest_has_recording: bool,
+) -> None:
+ database = interim_retry_db
+ svc = app.WORKFLOW_SERVICE
+ monkeypatch.setattr(svc, "prepare_workflow_webhook", WorkflowService.prepare_workflow_webhook.__get__(svc))
+ monkeypatch.setattr(
+ database.tasks,
+ "get_tasks_by_workflow_run_id",
+ type(database.tasks).get_tasks_by_workflow_run_id.__get__(database.tasks),
+ )
+
+ async def links(artifacts: list) -> list[str]:
+ return [artifact.uri for artifact in artifacts]
+
+ monkeypatch.setattr(app.ARTIFACT_MANAGER, "get_share_links_with_bundle_support", links)
+ monkeypatch.setattr(app.ARTIFACT_MANAGER, "is_recording_archived", AsyncMock(return_value=False))
+
+ def attribution(number: str) -> dict[str, str]:
+ return {
+ "task": {"task_id": f"task_{number}"},
+ "step": {"step_id": f"step_{number}"},
+ "block": {"workflow_run_block_id": f"block_{number}"},
+ "time": {},
+ }[artifact_link]
+
+ downloads: list[FileInfo] = []
+ monkeypatch.setattr(app.STORAGE, "get_downloaded_files", AsyncMock(side_effect=lambda **kwargs: list(downloads)))
+ monkeypatch.setattr(service_module, "_get_recovery_api_key", AsyncMock(return_value="test-key"))
+ deliver = AsyncMock(return_value=httpx.Response(200))
+ monkeypatch.setattr(app.AGENT_FUNCTION, "deliver_webhook", deliver)
+ async with database.Session() as session:
+ run = await session.get(WorkflowRunModel, "wr_retry")
+ run.webhook_callback_url = "https://example.com/hook"
+ run.failure_reason = "first attempt failed"
+ run.started_at = run.finished_at - timedelta(seconds=10)
+ run.queued_at = run.started_at - timedelta(seconds=1)
+ run.failure_category = [{"category": "navigation"}]
+ run.credits_used = 10
+ run.cached_credits_used = 2
+ first = await session.get(WorkflowRunAttemptModel, ("wr_retry", 1))
+ first.failure_category = run.failure_category
+ first.failure_reason = run.failure_reason
+ first.error_codes = ["FIRST_ERROR"]
+ first.started_at = run.started_at
+ session.add(OutputParameterModel(output_parameter_id="op_retry", workflow_id="wf_retry", key="result"))
+ session.add(
+ WorkflowRunOutputParameterModel(
+ workflow_run_id="wr_retry",
+ output_parameter_id="op_retry",
+ value={
+ "value": "first",
+ "legacy": {
+ "task_id": "task_first",
+ "workflow_screenshots": ["old-url"],
+ },
+ },
+ )
+ )
+ session.add(
+ TaskModel(
+ task_id="task_first",
+ organization_id="org_test",
+ workflow_run_id="wr_retry",
+ status="failed",
+ url="https://example.com",
+ attempt_number=None,
+ )
+ )
+ await session.flush()
+ session.add(
+ StepModel(
+ step_id="step_first", task_id="task_first", organization_id="org_test", status="completed", order=0
+ )
+ )
+ session.add(
+ WorkflowRunBlockModel(
+ workflow_run_block_id="block_first",
+ workflow_run_id="wr_retry",
+ organization_id="org_test",
+ status="failed",
+ block_type="task",
+ attempt_number=None,
+ )
+ )
+ for kind, suffix in [
+ (ArtifactType.SCREENSHOT_FINAL, "png"),
+ (ArtifactType.DOWNLOAD, "pdf"),
+ (ArtifactType.RECORDING, "webm"),
+ ]:
+ session.add(
+ ArtifactModel(
+ artifact_id=f"first_{suffix}",
+ organization_id="org_test",
+ run_id="wr_retry",
+ workflow_run_id="wr_retry",
+ **attribution("first"),
+ artifact_type=kind,
+ uri=(
+ "https://example.com/run_recordings/attempt1.webm"
+ if kind == ArtifactType.RECORDING
+ else f"https://example.com/attempt1.{suffix}"
+ ),
+ created_at=run.started_at,
+ modified_at=run.started_at,
+ )
+ )
+ downloads.append(
+ FileInfo(
+ url="https://example.com/attempt1.pdf",
+ filename="attempt1.pdf",
+ artifact_id="first_pdf",
+ modified_at=run.started_at,
+ )
+ )
+ await session.commit()
+ run = await svc.get_workflow_run("wr_retry", "org_test")
+ original = await svc.prepare_workflow_webhook(run, "test-key")
+ assert original is not None
+ expected = json.loads(original.signed_payload)
+ assert expected["retry_pending"] is True
+ preparation = await database.workflow_runs.prepare_next_attempt_atomic("wr_retry", "org_test", 1, "failed", None)
+ assert preparation.status == "inserted"
+ assert await database.workflow_runs.get_workflow_run_output_parameters("wr_retry") == []
+ await database.workflow_runs.create_or_update_workflow_run_output_parameter(
+ "wr_retry", "op_retry", {"value": "second"}
+ )
+ async with database.Session() as session:
+ run_row = await session.get(WorkflowRunModel, "wr_retry")
+ run_row.status = current_status
+ run_row.credits_used = 30
+ run_row.cached_credits_used = 6
+ run_row.started_at = datetime.now(UTC).replace(tzinfo=None)
+ run_row.finished_at = run_row.started_at if current_status == "completed" else None
+ second = await session.get(WorkflowRunAttemptModel, ("wr_retry", 2))
+ second.status = current_status
+ second.started_at = run_row.started_at
+ second.finished_at = run_row.finished_at
+ second.retry_decision = "final" if current_status == "completed" else None
+ second.side_effects_released_at = run_row.started_at if current_status == "completed" else None
+ session.add(
+ TaskModel(
+ task_id="task_second",
+ organization_id="org_test",
+ workflow_run_id="wr_retry",
+ status=current_status,
+ url="https://example.com",
+ attempt_number=2,
+ )
+ )
+ await session.flush()
+ session.add(
+ StepModel(
+ step_id="step_second", task_id="task_second", organization_id="org_test", status="completed", order=0
+ )
+ )
+ session.add(
+ WorkflowRunBlockModel(
+ workflow_run_block_id="block_second",
+ workflow_run_id="wr_retry",
+ organization_id="org_test",
+ status="failed",
+ block_type="task",
+ attempt_number=2,
+ )
+ )
+ for kind, suffix in [
+ (ArtifactType.SCREENSHOT_FINAL, "png"),
+ (ArtifactType.DOWNLOAD, "pdf"),
+ (ArtifactType.RECORDING, "webm"),
+ ]:
+ session.add(
+ ArtifactModel(
+ artifact_id=f"second_{suffix}",
+ organization_id="org_test",
+ run_id="wr_retry",
+ workflow_run_id="wr_retry",
+ **attribution("second"),
+ artifact_type=kind,
+ uri=(
+ "https://example.com/run_recordings/attempt2.webm"
+ if kind == ArtifactType.RECORDING
+ else f"https://example.com/attempt2.{suffix}"
+ ),
+ created_at=run_row.started_at,
+ modified_at=run_row.started_at,
+ )
+ )
+ if not latest_has_recording:
+ await session.flush()
+ recording = await session.get(ArtifactModel, "second_webm")
+ await session.delete(recording)
+ if not latest_has_screenshot:
+ await session.flush()
+ screenshot = await session.get(ArtifactModel, "second_png")
+ await session.delete(screenshot)
+ downloads.extend(
+ [
+ FileInfo(
+ url="https://example.com/attempt2.pdf",
+ filename="attempt2.pdf",
+ artifact_id="second_pdf",
+ modified_at=downloads[0].modified_at,
+ ),
+ FileInfo(
+ url="https://example.com/unattributed2.pdf",
+ filename="unattributed2.pdf",
+ modified_at=run_row.started_at,
+ ),
+ ]
+ )
+ await session.commit()
+ if sweep == "background":
+ await BackgroundTaskExecutor()._recover_pending_retries_once(resume_fresh=False)
+ else:
+ await svc.recover_pending_workflow_attempts(release_only=True)
+ assert deliver.await_count == 1
+ payload = json.loads(deliver.call_args.kwargs["payload"])
+ compared_fields = [
+ "attempt",
+ "status",
+ "failure_reason",
+ "failure_category",
+ "queued_at",
+ "credits_used",
+ "cached_credits_used",
+ "screenshot_urls",
+ "recording_url",
+ "recording_urls",
+ "downloaded_files",
+ "downloaded_file_urls",
+ "total_steps",
+ "step_count",
+ "started_at",
+ "finished_at",
+ "attempts",
+ "retry_pending",
+ "next_attempt_at",
+ "outputs",
+ "output",
+ ]
+ mismatched_fields = [field for field in compared_fields if payload[field] != expected[field]]
+ assert not mismatched_fields, mismatched_fields
+ assert payload["attempts"][0]["error_codes"] == ["FIRST_ERROR"]
+ assert payload["screenshot_urls"] == ["https://example.com/attempt1.png"]
+ assert payload["recording_url"] == "https://example.com/run_recordings/attempt1.webm"
+ assert payload["step_count"] == 1
+ assert payload["credits_used"] == 10
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION,
+ "calculate_workflow_run_total_cost",
+ AsyncMock(side_effect=lambda **kwargs: kwargs["credits_used"] + kwargs["cached_credits_used"]),
+ )
+ response = await svc.build_workflow_run_status_response(
+ "wpid_retry",
+ "wr_retry",
+ organization_id="org_test",
+ target_attempt_number=1,
+ include_cost=True,
+ )
+ assert response.total_cost == 12
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ assert attempts[0].interim_webhook_sent_at is not None
+ assert attempts[0].webhook_sent_at is None
+ assert attempts[1].interim_webhook_sent_at is None
+ assert attempts[1].webhook_sent_at is None
+ assert "output_parameters" not in attempts[0].interim_side_effects_progress
+ historical = (await database.workflow_run_attempts.get_interim_payload_snapshot("wr_retry", 1))["output_parameters"]
+ assert historical[0]["value"]["value"] == "first"
+ assert payload["output"]["result"]["legacy"]["workflow_screenshots"] == ["https://example.com/attempt1.png"]
+ current = await database.workflow_runs.get_workflow_run_output_parameters("wr_retry")
+ assert [output.value for output in current] == [{"value": "second"}]
+ async with database.Session() as session:
+ run_row = await session.get(WorkflowRunModel, "wr_retry")
+ run_row.status = "completed"
+ run_row.finished_at = datetime.now(UTC).replace(tzinfo=None)
+ second = await session.get(WorkflowRunAttemptModel, ("wr_retry", 2))
+ second.status = "completed"
+ second.finished_at = run_row.finished_at
+ second.retry_decision = "final"
+ second.side_effects_released_at = None
+ await session.commit()
+ run = await svc.get_workflow_run("wr_retry", "org_test")
+ ordinary = await svc.prepare_workflow_webhook(run, "test-key")
+ targeted = await svc.prepare_workflow_webhook(run, "test-key", target_attempt_number=2)
+ assert json.loads(ordinary.signed_payload) == json.loads(targeted.signed_payload)
+ latest = json.loads(ordinary.signed_payload)
+ expected_screenshots = ["https://example.com/attempt2.png"] if latest_has_screenshot else None
+ assert latest["screenshot_urls"] == expected_screenshots
+ response = await svc.build_workflow_run_status_response("wpid_retry", "wr_retry", organization_id="org_test")
+ assert response.screenshot_urls == expected_screenshots
+ expected_recordings = ["https://example.com/run_recordings/attempt2.webm"] if latest_has_recording else None
+ assert response.recording_urls == expected_recordings
+ assert latest["recording_urls"] == expected_recordings
+ assert response.recording_url == (expected_recordings[-1] if expected_recordings else None)
+ assert latest["recording_url"] == response.recording_url
+ # Steps are attempt-scoped like errors and screenshots; credits accumulate across attempts.
+ assert latest["step_count"] == 1
+ assert latest["credits_used"] == 30
+ decision = RetryDecision(False, 2, 0, True, "no_match")
+ for expected_outcome in ["released", "already_released"]:
+ assert await svc._run_terminal_side_effects_with_retries(run, decision, api_key="test-key") == expected_outcome
+ payloads = [json.loads(call.kwargs["payload"]) for call in deliver.call_args_list]
+ assert [(item["attempt"], item["status"]) for item in payloads] == [(1, "failed"), (2, "completed")]
+ assert payloads[1]["output"]["result"] == {"value": "second"}
+ assert payloads[1]["screenshot_urls"] == expected_screenshots
+ assert payloads[1]["recording_urls"] == expected_recordings
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ assert attempts[1].webhook_sent_at is not None
+
+
[email protected]("has_attempt_row", [False, True])
+async def test_single_attempt_preserves_screenshots_and_recordings(
+ interim_retry_db: AgentDB, monkeypatch: pytest.MonkeyPatch, has_attempt_row: bool
+) -> None:
+ database = interim_retry_db
+ svc = app.WORKFLOW_SERVICE
+ start = datetime.now(UTC).replace(tzinfo=None) - timedelta(minutes=10)
+ async with database.Session() as session:
+ workflow = await session.get(WorkflowModel, "wf_retry")
+ workflow.workflow_definition = {"blocks": [], "parameters": []}
+ run = await session.get(WorkflowRunModel, "wr_retry")
+ run.webhook_callback_url = "https://example.com/hook"
+ if not has_attempt_row:
+ attempt = await session.get(WorkflowRunAttemptModel, ("wr_retry", 1))
+ await session.delete(attempt)
+ for index in range(2):
+ session.add(
+ TaskModel(
+ task_id=f"legacy_task_{index}",
+ organization_id="org_test",
+ workflow_run_id="wr_retry",
+ status="failed",
+ url="https://example.com",
+ attempt_number=None,
+ created_at=start + timedelta(minutes=index),
+ )
+ )
+ await session.flush()
+ for index in range(3):
+ session.add(
+ ArtifactModel(
+ artifact_id=f"legacy_png_{index}",
+ organization_id="org_test",
+ run_id="wr_retry",
+ workflow_run_id="wr_retry",
+ task_id=f"legacy_task_{index}" if index < 2 else None,
+ artifact_type=ArtifactType.SCREENSHOT_FINAL,
+ uri=f"https://example.com/legacy{index}.png",
+ created_at=start + timedelta(minutes=index),
+ )
+ )
+ session.add(
+ ArtifactModel(
+ artifact_id="legacy_webm",
+ organization_id="org_test",
+ run_id="wr_retry",
+ workflow_run_id="wr_retry",
+ artifact_type=ArtifactType.RECORDING,
+ uri="https://example.com/run_recordings/legacy.webm",
+ created_at=start,
+ )
+ )
+ await session.commit()
+ monkeypatch.setattr(
+ database.tasks,
+ "get_tasks_by_workflow_run_id",
+ type(database.tasks).get_tasks_by_workflow_run_id.__get__(database.tasks),
+ )
+ monkeypatch.setattr(app.STORAGE, "get_downloaded_files", AsyncMock(return_value=[]))
+ monkeypatch.setattr(
+ app.ARTIFACT_MANAGER,
+ "get_share_links_with_bundle_support",
+ AsyncMock(side_effect=lambda artifacts: [artifact.uri for artifact in artifacts]),
+ )
+ monkeypatch.setattr(app.ARTIFACT_MANAGER, "is_recording_archived", AsyncMock(return_value=False))
+ expected = [f"https://example.com/legacy{index}.png" for index in (1, 0, 2)]
+ response = await svc.build_workflow_run_status_response("wpid_retry", "wr_retry", organization_id="org_test")
+ assert response.screenshot_urls == expected
+ assert response.recording_urls == ["https://example.com/run_recordings/legacy.webm"]
+ payload = await WorkflowService.prepare_workflow_webhook(
+ svc, await svc.get_workflow_run("wr_retry", "org_test"), "test-key"
+ )
+ assert json.loads(payload.signed_payload)["screenshot_urls"] == expected
+ assert json.loads(payload.signed_payload)["recording_urls"] == response.recording_urls
+
+
[email protected]("interim_complete", [False, True])
[email protected]("null_progress", [False, True])
+async def test_interim_snapshot_is_bounded_and_survives_completed_delivery(
+ interim_retry_db: AgentDB,
+ interim_complete: bool,
+ null_progress: bool,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ database = interim_retry_db
+ async with database.Session() as session:
+ attempt = await session.get(WorkflowRunAttemptModel, ("wr_retry", 1))
+ attempt.interim_webhook_sent_at = datetime.now(UTC).replace(tzinfo=None) if interim_complete else None
+ attempt.interim_side_effects_progress = (
+ None
+ if null_progress
+ else {
+ "completed_effects": ["cleanup"],
+ "webhook_delivery_attempts": 1,
+ }
+ )
+ for index in range(3):
+ session.add(
+ OutputParameterModel(output_parameter_id=f"large_{index}", workflow_id="wf_retry", key=f"large_{index}")
+ )
+ session.add(
+ WorkflowRunOutputParameterModel(
+ workflow_run_id="wr_retry",
+ output_parameter_id=f"large_{index}",
+ value="x" * (INTERIM_OUTPUT_SNAPSHOT_MAX_BYTES // 2 + index),
+ )
+ )
+ await session.flush()
+ if null_progress:
+ await session.execute(
+ update(WorkflowRunAttemptModel)
+ .where(
+ WorkflowRunAttemptModel.workflow_run_id == "wr_retry",
+ )
+ .values(interim_side_effects_progress=literal("null"))
+ )
+ await session.commit()
+ result = await database.workflow_runs.prepare_next_attempt_atomic("wr_retry", "org_test", 1, "failed", None)
+ assert result.status == "inserted"
+ async with database.Session() as session:
+ attempt = await session.get(WorkflowRunAttemptModel, ("wr_retry", 1))
+ progress = attempt.interim_side_effects_progress or {}
+ if not null_progress:
+ assert progress["completed_effects"] == ["cleanup"]
+ assert progress["webhook_delivery_attempts"] == 1
+ # A completed interim delivery no longer skips the snapshot: the historical response needs it.
+ entries = progress["output_parameters"]
+ assert len(json.dumps(entries).encode("utf-8")) <= INTERIM_OUTPUT_SNAPSHOT_MAX_BYTES
+ assert [entry["output_parameter_id"] for entry in entries] == [f"large_{index}" for index in range(3)]
+ assert all(entry["created_at"] for entry in entries)
+ assert entries[1]["value"]["truncated"] is True
+ assert entries[2]["value"]["truncated"] is True
+ metadata = await database.workflow_run_attempts.get_attempts("wr_retry")
+ assert "output_parameters" not in metadata[0].interim_side_effects_progress
+ monkeypatch.setattr(app.STORAGE, "get_downloaded_files", AsyncMock(return_value=[]))
+ response = await app.WORKFLOW_SERVICE.build_workflow_run_status_response(
+ "wpid_retry",
+ "wr_retry",
+ organization_id="org_test",
+ target_attempt_number=1,
+ )
+ assert response.outputs["large_2"]["truncated"] is True
+
+
[email protected]("artifact_link", ["task", "step", "block"])
[email protected]("ancestry", ["block", "chain", "fallback"])
[email protected]("child_attempt", [None, 1])
+async def test_historical_child_artifacts_use_parent_attempt(
+ interim_retry_db: AgentDB,
+ monkeypatch: pytest.MonkeyPatch,
+ artifact_link: str,
+ ancestry: str,
+ child_attempt: int | None,
+) -> None:
+ database = interim_retry_db
+ svc = app.WORKFLOW_SERVICE
+ start = datetime.now(UTC).replace(tzinfo=None) - timedelta(minutes=30)
+ downloads = []
+ async with database.Session() as session:
+ run = await session.get(WorkflowRunModel, "wr_retry")
+ run.webhook_callback_url = "https://example.com/hook"
+ for number in (1, 2):
+ when = start + timedelta(minutes=10 * (number - 1))
+ attempt = await session.get(WorkflowRunAttemptModel, ("wr_retry", number))
+ if attempt is None:
+ attempt = WorkflowRunAttemptModel(
+ workflow_run_id="wr_retry", organization_id="org_test", attempt_number=number
+ )
+ session.add(attempt)
+ attempt.status = "failed"
+ attempt.started_at = when
+ attempt.finished_at = when + timedelta(minutes=1)
+ attempt.retry_decision = "retry"
+ attempt.interim_side_effects_progress = {
+ "credits_used": 0,
+ "cached_credits_used": 0,
+ "output_parameters": [
+ {
+ "output_parameter_id": "op_children",
+ "created_at": when.isoformat(),
+ "value": {
+ "workflow_screenshot_artifact_ids": ["child_1_png", "child_2_png"],
+ "downloaded_file_artifact_ids": ["child_1_pdf", "child_2_pdf"],
+ },
+ }
+ ],
+ }
+ enclosing_id = f"wr_enclosing_{number}"
+ child_id = f"wr_child_{number}"
+ if ancestry == "chain":
+ session.add(
+ WorkflowRunModel(
+ workflow_run_id=enclosing_id,
+ workflow_permanent_id="wpid_retry",
+ workflow_id="wf_retry",
+ organization_id="org_test",
+ parent_workflow_run_id="wr_retry",
+ status="completed",
+ )
+ )
+ session.add(
+ WorkflowRunModel(
+ workflow_run_id=child_id,
+ workflow_permanent_id="wpid_retry",
+ workflow_id="wf_retry",
+ organization_id="org_test",
+ parent_workflow_run_id=enclosing_id if ancestry == "chain" else "wr_retry",
+ status="completed",
+ )
+ )
+ if ancestry != "fallback":
+ session.add(
+ WorkflowRunBlockModel(
+ workflow_run_block_id=f"spawn_{number}",
+ workflow_run_id="wr_retry",
+ block_workflow_run_id=enclosing_id if ancestry == "chain" else child_id,
+ organization_id="org_test",
+ block_type="task_v2",
+ status="completed",
+ attempt_number=number,
+ )
+ )
+ await session.flush()
+ session.add(
+ TaskModel(
+ task_id=f"child_task_{number}",
+ workflow_run_id=child_id,
+ organization_id="org_test",
+ status="completed",
+ url="https://example.com",
+ attempt_number=child_attempt,
+ )
+ )
+ await session.flush()
+ session.add(
+ StepModel(
+ step_id=f"child_step_{number}",
+ task_id=f"child_task_{number}",
+ organization_id="org_test",
+ status="completed",
+ order=0,
+ )
+ )
+ session.add(
+ WorkflowRunBlockModel(
+ workflow_run_block_id=f"child_block_{number}",
+ workflow_run_id=child_id,
+ organization_id="org_test",
+ block_type="task",
+ status="completed",
+ attempt_number=child_attempt,
+ )
+ )
+ link = {
+ "task": {"task_id": f"child_task_{number}"},
+ "step": {"step_id": f"child_step_{number}"},
+ "block": {"workflow_run_block_id": f"child_block_{number}"},
+ }[artifact_link]
+ # Late uploads retain the spawning attempt when an ancestor block is available.
+ uploaded_at = when if ancestry == "fallback" else start + timedelta(minutes=25)
+ for kind, suffix in [
+ (ArtifactType.DOWNLOAD, "pdf"),
+ (ArtifactType.SCREENSHOT_FINAL, "png"),
+ (ArtifactType.RECORDING, "webm"),
+ ]:
+ artifact_id = f"child_{number}_{suffix}"
+ url = f"https://example.com/{artifact_id}"
+ session.add(
+ ArtifactModel(
+ artifact_id=artifact_id,
+ organization_id="org_test",
+ run_id="wr_retry",
+ workflow_run_id=child_id,
+ artifact_type=kind,
+ uri=url,
+ created_at=uploaded_at,
+ modified_at=uploaded_at,
+ **link,
+ )
+ )
+ if suffix == "pdf":
+ downloads.append(
+ FileInfo(url=url, filename=artifact_id, artifact_id=artifact_id, modified_at=uploaded_at)
+ )
+ session.add(OutputParameterModel(output_parameter_id="op_children", workflow_id="wf_retry", key="children"))
+ session.add(
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_retry",
+ organization_id="org_test",
+ attempt_number=3,
+ status="running",
+ started_at=start + timedelta(minutes=20),
+ )
+ )
+ await session.commit()
+ monkeypatch.setattr(app.STORAGE, "get_downloaded_files", AsyncMock(return_value=downloads))
+ monkeypatch.setattr(
+ app.ARTIFACT_MANAGER,
+ "get_share_links_with_bundle_support",
+ AsyncMock(side_effect=lambda artifacts: [a.uri for a in artifacts]),
+ )
+ monkeypatch.setattr(
+ app.ARTIFACT_MANAGER, "resolve_share_url", AsyncMock(side_effect=lambda artifact, **kwargs: artifact.uri)
+ )
+ monkeypatch.setattr(app.ARTIFACT_MANAGER, "resolve_artifact_url_expiry_seconds", AsyncMock(return_value=3600))
+ monkeypatch.setattr(app.ARTIFACT_MANAGER, "is_recording_archived", AsyncMock(return_value=False))
+ lookup = AsyncMock(wraps=database.workflow_runs.get_artifacts_for_attempt)
+ monkeypatch.setattr(database.workflow_runs, "get_artifacts_for_attempt", lookup)
+ for number in (1, 2):
+ payload = await WorkflowService.prepare_workflow_webhook(
+ svc, await svc.get_workflow_run("wr_retry", "org_test"), "test-key", target_attempt_number=number
+ )
+ body = json.loads(payload.signed_payload)
+ assert body["screenshot_urls"] == [f"https://example.com/child_{number}_png"]
+ assert body["recording_url"] == f"https://example.com/child_{number}_webm"
+ assert body["downloaded_file_urls"] == [f"https://example.com/child_{number}_pdf"]
+ assert body["outputs"]["children"]["downloaded_file_urls"] == [f"https://example.com/child_{number}_pdf"]
+ assert lookup.await_count == number
+ artifacts = await database.workflow_runs.get_artifacts_for_attempt(
+ "wr_retry", "org_test", 1, start, start + timedelta(minutes=10)
+ )
+ legacy = await svc._refresh_output_urls(
+ {
+ "workflow_screenshot_artifact_ids": [],
+ "downloaded_files": [
+ {"filename": "child_1_pdf"},
+ {"filename": "child_2_pdf"},
+ ],
+ },
+ "org_test",
+ "wr_retry",
+ attempt_rows=await database.workflow_run_attempts.get_attempts("wr_retry"),
+ attempt_number=1,
+ historical_artifacts=artifacts,
+ )
+ assert legacy["downloaded_file_urls"] == ["https://example.com/child_1_pdf"]
+ assert lookup.await_count == 3
+ async with database.Session() as session:
+ await session.execute(
+ update(ArtifactModel)
+ .where(ArtifactModel.artifact_type == ArtifactType.DOWNLOAD)
+ .values(run_id="observer_storage")
+ )
+ await session.commit()
+ monkeypatch.setattr(
+ app.STORAGE,
+ "get_downloaded_files",
+ AsyncMock(side_effect=lambda **kwargs: downloads if kwargs["run_id"] == "observer_storage" else []),
+ )
+ files, urls = await svc._fetch_downloaded_files(
+ await svc.get_workflow_run("wr_retry", "org_test"),
+ SimpleNamespace(observer_cruise_id="observer_storage"),
+ attempt_rows=await database.workflow_run_attempts.get_attempts("wr_retry"),
+ attempt_number=1,
+ historical_artifacts=[],
+ )
+ assert [file.artifact_id for file in files] == ["child_1_pdf"]
+ assert urls == ["https://example.com/child_1_pdf"]
+ assert lookup.await_count == 4
+ assert lookup.call_args.args[0] == "wr_retry"
+ assert lookup.call_args.kwargs == {"artifact_run_id": "observer_storage"}
+
+
[email protected]("usage", ["null_columns", "missing_keys", "null_keys"])
+async def test_historical_usage_defaults_to_zero(
+ interim_retry_db: AgentDB, monkeypatch: pytest.MonkeyPatch, usage: str
+) -> None:
+ database = interim_retry_db
+ async with database.Session() as session:
+ run = await session.get(WorkflowRunModel, "wr_retry")
+ run.credits_used = None
+ run.cached_credits_used = None
+ run.webhook_callback_url = "https://example.com/hook"
+ await session.commit()
+ result = await database.workflow_runs.prepare_next_attempt_atomic("wr_retry", "org_test", 1, "failed", None)
+ assert result.status == "inserted"
+ async with database.Session() as session:
+ run = await session.get(WorkflowRunModel, "wr_retry")
+ run.credits_used = 91
+ run.cached_credits_used = 17
+ if usage != "null_columns":
+ attempt = await session.get(WorkflowRunAttemptModel, ("wr_retry", 1))
+ attempt.interim_side_effects_progress = (
+ {"output_parameters": []}
+ if usage == "missing_keys"
+ else {"output_parameters": [], "credits_used": None, "cached_credits_used": None}
+ )
+ await session.commit()
+ monkeypatch.setattr(app.STORAGE, "get_downloaded_files", AsyncMock(return_value=[]))
+ payload = await WorkflowService.prepare_workflow_webhook(
+ app.WORKFLOW_SERVICE,
+ await app.WORKFLOW_SERVICE.get_workflow_run("wr_retry", "org_test"),
+ "test-key",
+ target_attempt_number=1,
+ )
+ body = json.loads(payload.signed_payload)
+ assert (body["credits_used"], body["cached_credits_used"]) == (0, 0)
+ if usage == "null_columns":
+ snapshot = await database.workflow_run_attempts.get_interim_payload_snapshot("wr_retry", 1)
+ assert (snapshot["credits_used"], snapshot["cached_credits_used"]) == (0, 0)
+
+
+async def test_interim_snapshot_metadata_overflow_keeps_retry_and_reports_omission(
+ interim_retry_db: AgentDB, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ database = interim_retry_db
+ count = 10000
+ created_at = datetime.now(UTC).replace(tzinfo=None)
+ ids = [f"op_metadata_overflow_{index:08d}" for index in range(count)]
+ async with database.Session() as session:
+ await session.execute(
+ insert(OutputParameterModel),
+ [{"output_parameter_id": output_id, "workflow_id": "wf_retry", "key": output_id} for output_id in ids],
+ )
+ await session.execute(
+ insert(WorkflowRunOutputParameterModel),
+ [
+ {
+ "workflow_run_id": "wr_retry",
+ "output_parameter_id": output_id,
+ "value": None,
+ "created_at": created_at + timedelta(microseconds=index),
+ }
+ for index, output_id in enumerate(ids)
+ ],
+ )
+ run = await session.get(WorkflowRunModel, "wr_retry")
+ run.webhook_callback_url = "https://example.com/hook"
+ await session.commit()
+ result = await database.workflow_runs.prepare_next_attempt_atomic("wr_retry", "org_test", 1, "failed", None)
+ assert result.status == "inserted"
+ assert len(await database.workflow_run_attempts.get_attempts("wr_retry")) == 2
+ snapshot = await database.workflow_run_attempts.get_interim_payload_snapshot("wr_retry", 1)
+ entries = snapshot["output_parameters"]
+ assert 0 < len(entries) < count
+ assert snapshot["omitted_output_count"] == count - len(entries)
+ assert (
+ len(json.dumps({key: snapshot[key] for key in ("output_parameters", "omitted_output_count")}).encode())
+ <= INTERIM_OUTPUT_SNAPSHOT_MAX_BYTES
+ )
+ assert [entry["output_parameter_id"] for entry in entries] == ids[: len(entries)]
+ monkeypatch.setattr(app.STORAGE, "get_downloaded_files", AsyncMock(return_value=[]))
+ payload = await WorkflowService.prepare_workflow_webhook(
+ app.WORKFLOW_SERVICE,
+ await app.WORKFLOW_SERVICE.get_workflow_run("wr_retry", "org_test"),
+ "test-key",
+ target_attempt_number=1,
+ )
+ body = json.loads(payload.signed_payload)
+ assert body["outputs"]["_interim_output_snapshot"] == {
+ "truncated": True,
+ "reason": "interim_output_snapshot_budget_exceeded",
+ "omitted_output_count": count - len(entries),
+ }
+ assert body["output"] == body["outputs"]
+
+
[email protected]("target_attempt_number", [1, None])
+async def test_attempt_recording_uses_its_shared_session(
+ interim_retry_db: AgentDB,
+ monkeypatch: pytest.MonkeyPatch,
+ target_attempt_number: int | None,
+) -> None:
+ database = interim_retry_db
+ now = datetime.now(UTC).replace(tzinfo=None)
+ async with database.Session() as session:
+ run = await session.get(WorkflowRunModel, "wr_retry")
+ run.browser_session_id = "session_first"
+ run.started_at = now - timedelta(seconds=30)
+ first = await session.get(WorkflowRunAttemptModel, ("wr_retry", 1))
+ first.started_at = run.started_at
+ await session.commit()
+ result = await database.workflow_runs.prepare_next_attempt_atomic(
+ "wr_retry",
+ "org_test",
+ 1,
+ "failed",
+ "session_second",
+ )
+ assert result.status == "inserted"
+ async with database.Session() as session:
+ run = await session.get(WorkflowRunModel, "wr_retry")
+ run.started_at = now
+ second = await session.get(WorkflowRunAttemptModel, ("wr_retry", 2))
+ second.started_at = now
+ await session.commit()
+ expected_session = "session_first" if target_attempt_number == 1 else "session_second"
+
+ async def shared_recordings(*, organization_id: str, browser_session_id: str) -> list[FileInfo]:
+ assert browser_session_id == expected_session
+ return [
+ FileInfo(
+ url="https://example.com/shared.webm", filename="shared.webm", modified_at=now + timedelta(hours=1)
+ )
+ ]
+
+ monkeypatch.setattr(app.STORAGE, "get_shared_recordings_in_browser_session", shared_recordings)
+ monkeypatch.setattr(app.STORAGE, "get_downloaded_files", AsyncMock(return_value=[]))
+ response = await app.WORKFLOW_SERVICE.build_workflow_run_status_response(
+ "wpid_retry",
+ "wr_retry",
+ organization_id="org_test",
+ target_attempt_number=target_attempt_number,
+ )
+ assert response.recording_url == "https://example.com/shared.webm"
+ assert response.browser_session_id == expected_session
+
+
[email protected]("sweep", ["background", "cloud"])
[email protected]("lease", ["none", "stale", "young"])
+async def test_recovery_releases_earlier_interim_without_abandoning_retry(
+ interim_retry_db: AgentDB, monkeypatch: pytest.MonkeyPatch, sweep: str, lease: str
+) -> None:
+ database = interim_retry_db
+ svc = app.WORKFLOW_SERVICE
+ now = datetime.now(UTC).replace(tzinfo=None)
+ cutoff = now - timedelta(seconds=service_module.LEASE_TAKEOVER_SECONDS)
+ old = cutoff - timedelta(seconds=1)
+ preparation = await database.workflow_runs.prepare_next_attempt_atomic("wr_retry", "org_test", 1, "failed", None)
+ assert preparation.status == "inserted"
+ async with database.Session() as session:
+ attempt = await session.scalar(
+ select(WorkflowRunAttemptModel).where(WorkflowRunAttemptModel.attempt_number == 1)
+ )
+ attempt.next_attempt_at = old
+ attempt.side_effects_released_at = {"none": None, "stale": old, "young": now}[lease]
+ await session.commit()
+ assert [a.attempt_number for a in await database.workflow_run_attempts.list_attempts_needing_recovery(cutoff)] == (
+ [] if lease == "young" else [1]
+ )
+ delivery = AsyncMock(return_value=False)
+ monkeypatch.setattr(svc, "deliver_prepared_workflow_webhook", delivery)
+ monkeypatch.setattr(service_module, "_get_recovery_api_key", AsyncMock(return_value="test-key"))
+ for succeeds in [False, True]:
+ delivery.return_value = succeeds
+ if sweep == "background":
+ await BackgroundTaskExecutor()._recover_pending_retries_once(resume_fresh=False)
+ else:
+ await svc.recover_pending_workflow_attempts(release_only=True)
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ assert [a.retry_decision for a in attempts] == ["retry", None]
+ assert (attempts[0].interim_webhook_sent_at is not None) == (lease != "young")
+ if lease != "young":
+ assert attempts[0].interim_side_effects_progress["webhook_delivery_exhausted_at"]
+ assert not attempts[0].interim_side_effects_progress.get("webhook_delivery_attempted")
+ assert attempts[0].webhook_sent_at is None
+ assert attempts[1].started_at is None
+ assert delivery.await_count == (0 if lease == "young" else service_module.WORKFLOW_WEBHOOK_DELIVERY_MAX_ATTEMPTS)
+ assert await database.workflow_run_attempts.list_attempts_needing_recovery(cutoff) == []
+
+
[email protected]("sweep", ["background", "cloud"])
[email protected]("run_terminal", [True, False])
+async def test_recovery_finalizes_never_started_attempts_of_terminal_runs(
+ monkeypatch: pytest.MonkeyPatch, sweep: str, run_terminal: bool
+) -> None:
+ # A cancel before mark_attempt_started leaves a created row with no started_at; the terminal run
+ # still owes its cleanup and webhook. A queued run with the same row is not terminal and stays put.
+ old = datetime.now(UTC).replace(tzinfo=None) - timedelta(seconds=service_module.LEASE_TAKEOVER_SECONDS + 1)
+ attempt = SimpleNamespace(
+ workflow_run_id="wr_never_started",
+ organization_id="org_test",
+ attempt_number=1,
+ status="created",
+ retry_decision=None,
+ started_at=None,
+ next_attempt_at=None,
+ next_attempt_prepared_at=None,
+ modified_at=old,
+ )
+ run = SimpleNamespace(
+ workflow_run_id="wr_never_started",
+ organization_id="org_test",
+ status=WorkflowRunStatus.canceled if run_terminal else WorkflowRunStatus.queued,
+ )
+ monkeypatch.setattr(
+ app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(
+ list_attempts_needing_recovery=AsyncMock(side_effect=[[attempt], []]),
+ list_stale_dispatch_claims=AsyncMock(return_value=[]),
+ ),
+ workflow_runs=SimpleNamespace(get_workflow_run=AsyncMock(return_value=run)),
+ ),
+ )
+ recover = AsyncMock(return_value=None)
+ monkeypatch.setattr(service_module, "_recover_undecided_terminal_attempt", recover)
+ schedule_resume = MagicMock()
+
+ if sweep == "background":
+ executor = BackgroundTaskExecutor()
+ executor._schedule_retry_resume = schedule_resume # type: ignore[method-assign]
+ await executor._recover_pending_retries_once(resume_fresh=False)
+ else:
+ await app.WORKFLOW_SERVICE.recover_pending_workflow_attempts(release_only=True)
+
+ if run_terminal:
+ recover.assert_awaited_once_with(attempt, workflow_run=run)
+ else:
+ recover.assert_not_awaited()
+ schedule_resume.assert_not_called()
+
+
+async def test_undecided_recovery_reuses_the_run_the_sweep_loaded(monkeypatch: pytest.MonkeyPatch) -> None:
+ # workflow_runs is high-traffic: the sweep's finality read is the only read per candidate.
+ attempt = SimpleNamespace(workflow_run_id="wr_loaded", organization_id="org_test", attempt_number=1)
+ run = SimpleNamespace(
+ workflow_run_id="wr_loaded",
+ organization_id="org_test",
+ status=WorkflowRunStatus.canceled,
+ failure_reason=None,
+ failure_category=None,
+ )
+ monkeypatch.setattr(
+ app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_runs=SimpleNamespace(get_workflow_run=AsyncMock(side_effect=AssertionError("re-read"))),
+ ),
+ )
+ monkeypatch.setattr(
+ app, "AGENT_FUNCTION", SimpleNamespace(get_workflow_run_execution_status=AsyncMock(return_value="running"))
+ )
+
+ assert await service_module._recover_undecided_terminal_attempt(attempt, workflow_run=run) is None
@pytest.mark.asyncio
@@ -24,25 +1767,978 @@ async def test_schedule_runs_work_without_background_tasks() -> None:
assert keyword == "keyword"
ran.set()
- BackgroundTaskExecutor()._schedule(None, work, "positional", keyword="keyword")
+ BackgroundTaskExecutor()._schedule(None, work, "positional", keyword="keyword")
+
+ await asyncio.wait_for(ran.wait(), timeout=1)
+
+
+async def test_schedule_defers_to_background_tasks_when_present() -> None:
+ calls: list[tuple[str, str]] = []
+
+ async def work(value: str, *, keyword: str) -> None:
+ calls.append((value, keyword))
+
+ background_tasks = BackgroundTasks()
+ BackgroundTaskExecutor()._schedule(background_tasks, work, "positional", keyword="keyword")
+
+ # Queued on the request's BackgroundTasks rather than started eagerly.
+ assert calls == []
+ await background_tasks()
+ assert calls == [("positional", "keyword")]
+
+
+async def test_recover_pending_retries_abandons_only_stale_attempts(monkeypatch: pytest.MonkeyPatch) -> None:
+ stale_attempt = SimpleNamespace(
+ workflow_run_id="wr_stale",
+ organization_id="org_test",
+ attempt_number=1,
+ retry_decision="retry",
+ next_attempt_at=datetime.now(UTC) - timedelta(seconds=RETRY_DECISION_GRACE_SECONDS + 1),
+ next_attempt_prepared_at=None,
+ )
+ fresh_attempt = SimpleNamespace(workflow_run_id="wr_fresh", organization_id="org_test", attempt_number=1)
+ stale_run = SimpleNamespace(
+ workflow_run_id="wr_stale",
+ organization_id="org_test",
+ status=WorkflowRunStatus.failed,
+ failure_reason="failed",
+ finished_at=SimpleNamespace(),
+ )
+ list_recovery = AsyncMock(return_value=[stale_attempt])
+ get_workflow_run = AsyncMock(return_value=stale_run)
+ monkeypatch.setattr(
+ app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(
+ list_attempts_needing_recovery=list_recovery, list_stale_dispatch_claims=AsyncMock(return_value=[])
+ ),
+ workflow_runs=SimpleNamespace(get_workflow_run=get_workflow_run),
+ ),
+ )
+ abandoned_decision = RetryDecision(False, 1, 0, True, "process_restart")
+ finalize_abandoned = AsyncMock(return_value=abandoned_decision)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.executor.background_task_executor.finalize_abandoned_attempt",
+ finalize_abandoned,
+ )
+ side_effects = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "_run_terminal_side_effects_with_retries", side_effects)
+ monkeypatch.setattr(BackgroundTaskExecutor, "_start_retry_recovery_sweep", MagicMock())
+
+ await BackgroundTaskExecutor().recover_pending_retries()
+
+ list_recovery.assert_awaited_once()
+ assert get_workflow_run.await_args.kwargs["workflow_run_id"] == stale_attempt.workflow_run_id
+ assert fresh_attempt.workflow_run_id not in {
+ call.kwargs["workflow_run_id"] for call in get_workflow_run.await_args_list
+ }
+ finalize_abandoned.assert_awaited_once_with(
+ workflow_run_id="wr_stale",
+ organization_id="org_test",
+ reason="process_restart",
+ status=WorkflowRunStatus.failed,
+ failure_reason="failed",
+ finished_at=stale_run.finished_at,
+ attempt_number=1,
+ )
+ side_effects.assert_awaited_once_with(stale_run, abandoned_decision)
+
+
+async def test_recovery_sweep_does_not_start_final_effects_for_a_young_retry_lease(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ stale_attempt = SimpleNamespace(
+ workflow_run_id="wr_young_lease",
+ organization_id="org_test",
+ attempt_number=1,
+ retry_decision="retry",
+ next_attempt_at=datetime.now(UTC) - timedelta(seconds=RETRY_DECISION_GRACE_SECONDS + 1),
+ next_attempt_prepared_at=None,
+ side_effects_released_at=datetime.now(UTC),
+ )
+ stale_run = SimpleNamespace(
+ workflow_run_id="wr_young_lease",
+ organization_id="org_test",
+ status=WorkflowRunStatus.failed,
+ failure_reason="failed",
+ finished_at=SimpleNamespace(),
+ )
+ monkeypatch.setattr(
+ app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(
+ list_attempts_needing_recovery=AsyncMock(return_value=[stale_attempt]),
+ list_stale_dispatch_claims=AsyncMock(return_value=[]),
+ ),
+ workflow_runs=SimpleNamespace(get_workflow_run=AsyncMock(return_value=stale_run)),
+ ),
+ )
+ skipped_decision = RetryDecision(True, 1, 0, True, "stale_retry_lease_active")
+ finalize_abandoned = AsyncMock(return_value=skipped_decision)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.executor.background_task_executor.finalize_abandoned_attempt",
+ finalize_abandoned,
+ )
+ side_effects = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "_run_terminal_side_effects_with_retries", side_effects)
+
+ await BackgroundTaskExecutor()._recover_pending_retries_once(resume_fresh=False)
+
+ finalize_abandoned.assert_awaited_once()
+ side_effects.assert_not_awaited()
+
+
+async def test_recover_pending_retries_starts_the_sweep_when_the_initial_pass_raises(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ executor = BackgroundTaskExecutor()
+ passes: list[bool] = []
+ outcomes = iter([RuntimeError("database unavailable"), RuntimeError("database unavailable"), None, None])
+
+ async def recover_once(*, resume_fresh: bool) -> None:
+ passes.append(resume_fresh)
+ outcome = next(outcomes)
+ if outcome is not None:
+ raise outcome
+
+ ticks = asyncio.Semaphore(0)
+
+ async def controlled_sleep(_seconds: float) -> None:
+ await ticks.acquire()
+
+ async def wait_for_pass(count: int) -> None:
+ while len(passes) < count:
+ await asyncio.sleep(0)
+
+ monkeypatch.setattr(executor, "_recover_pending_retries_once", recover_once)
+ monkeypatch.setattr(background_task_executor_module, "asyncio", ScopedAsyncio(sleep=controlled_sleep))
+
+ with pytest.raises(RuntimeError, match="database unavailable"):
+ await executor.recover_pending_retries()
+
+ sweep_task = executor._retry_recovery_sweep_task
+ assert sweep_task is not None and not sweep_task.done()
+ try:
+ for count in range(2, 5):
+ ticks.release()
+ await asyncio.wait_for(wait_for_pass(count), timeout=1)
+ finally:
+ await executor.stop_retry_recovery()
+
+ # The sweep keeps resuming fresh rows until one pass succeeds, then leaves them to in-process owners.
+ assert passes == [True, True, True, False]
+
+
+async def test_stop_retry_recovery_cancels_the_sweep_and_scheduled_resumes(monkeypatch: pytest.MonkeyPatch) -> None:
+ executor = BackgroundTaskExecutor()
+ monkeypatch.setattr(executor, "_recover_pending_retries_once", AsyncMock())
+
+ async def wait_for_next_attempt(_attempt: object) -> None:
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr(executor, "_resume_pending_retry", wait_for_next_attempt)
+
+ await executor.recover_pending_retries()
+ executor._schedule_retry_resume(SimpleNamespace(workflow_run_id="wr_retry", attempt_number=1))
+ sweep_task = executor._retry_recovery_sweep_task
+ assert sweep_task is not None and not sweep_task.done()
+ (resume_task,) = executor._retry_resume_tasks
+ assert not resume_task.done()
+
+ await executor.stop_retry_recovery()
+
+ assert sweep_task.cancelled()
+ assert resume_task.cancelled()
+ assert executor._retry_recovery_sweep_task is None
+ assert not executor._retry_resume_tasks
+ await executor.stop_retry_recovery()
+
+
+async def test_recover_pending_retries_resumes_fresh_attempt_after_delay(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ now = datetime.now(UTC)
+ pending_attempt = SimpleNamespace(
+ workflow_run_id="wr_fresh",
+ organization_id="org_test",
+ attempt_number=1,
+ retry_decision="retry",
+ next_attempt_at=now + timedelta(seconds=5),
+ next_attempt_prepared_at=None,
+ )
+ organization = SimpleNamespace(organization_id="org_test")
+ sleep_started = asyncio.Event()
+ release_sleep = asyncio.Event()
+ execution_done = asyncio.Event()
+
+ async def controlled_sleep(delay_seconds: float) -> None:
+ assert delay_seconds > 0
+ sleep_started.set()
+ await release_sleep.wait()
+
+ async def execute_workflow_with_retries(**kwargs: object) -> None:
+ assert kwargs["attempt_number"] == 2
+ assert kwargs["browser_session_id"] == "pinned-session"
+ assert kwargs["api_key"] == "api-token"
+ execution_done.set()
+
+ prepare = AsyncMock(
+ return_value=PrepareNextAttemptResult(
+ status="inserted",
+ pinned_browser_session_id="pinned-session",
+ )
+ )
+ get_valid_org_auth_token = AsyncMock(return_value=SimpleNamespace(token="api-token"))
+ monkeypatch.setattr(
+ app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(
+ list_attempts_needing_recovery=AsyncMock(return_value=[pending_attempt]),
+ list_stale_dispatch_claims=AsyncMock(return_value=[]),
+ ),
+ organizations=SimpleNamespace(
+ get_organization=AsyncMock(return_value=organization),
+ get_valid_org_auth_token=get_valid_org_auth_token,
+ ),
+ ),
+ )
+ monkeypatch.setattr(background_task_executor_module, "asyncio", ScopedAsyncio(sleep=controlled_sleep))
+ monkeypatch.setattr(background_task_executor_module, "prepare_next_attempt_result", prepare)
+ monkeypatch.setattr(background_task_executor_module, "initialize_skyvern_state_file", AsyncMock())
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ monkeypatch.setattr(
+ app.WORKFLOW_SERVICE,
+ "execute_workflow_with_retries",
+ execute_workflow_with_retries,
+ )
+ monkeypatch.setattr(BackgroundTaskExecutor, "_start_retry_recovery_sweep", MagicMock())
+
+ executor = BackgroundTaskExecutor()
+ await executor.recover_pending_retries()
+
+ await asyncio.wait_for(sleep_started.wait(), timeout=1)
+ prepare.assert_not_awaited()
+ release_sleep.set()
+ await asyncio.wait_for(execution_done.wait(), timeout=1)
+ get_valid_org_auth_token.assert_awaited_once_with(
+ organization_id="org_test",
+ token_type="api",
+ )
+ prepare.assert_awaited_once_with(
+ workflow_run_id="wr_fresh",
+ organization_id="org_test",
+ from_attempt=1,
+ clear_browser_address=False,
+ )
+
+
+ "lookup, failure",
+ [
+ ("token", "exception"),
+ ("token", "none"),
+ ("organization", "exception"),
+ ("organization", "none"),
+ ("initialization", "exception"),
+ ],
+)
+async def test_startup_retry_recovers_transient_initialization_failure_without_another_sweep(
+ interim_retry_db: AgentDB, monkeypatch: pytest.MonkeyPatch, lookup: str, failure: str
+) -> None:
+ database = interim_retry_db
+ now = datetime.now(UTC).replace(tzinfo=None)
+ async with database.Session() as session:
+ attempt = await session.get(WorkflowRunAttemptModel, ("wr_retry", 1))
+ attempt.next_attempt_at = now
+ attempt.interim_webhook_sent_at = now
+ await session.commit()
+ organization = await database.organizations.get_organization("org_test")
+ token = SimpleNamespace(token="api-token")
+ error = RuntimeError("temporary lookup failure") if failure == "exception" else None
+ monkeypatch.setattr(
+ database.organizations,
+ "get_organization",
+ AsyncMock(side_effect=[error, organization] if lookup == "organization" else None, return_value=organization),
+ )
+ monkeypatch.setattr(
+ database.organizations,
+ "get_valid_org_auth_token",
+ AsyncMock(side_effect=[error, token] if lookup == "token" else None, return_value=token),
+ )
+ monkeypatch.setattr(
+ background_task_executor_module,
+ "initialize_skyvern_state_file",
+ AsyncMock(side_effect=[error, None, None] if lookup == "initialization" else None),
+ )
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ sleeps: list[float] = []
+
+ async def sleep(seconds: float) -> None:
+ sleeps.append(seconds)
+ assert 0 < seconds <= background_task_executor_module.LEASE_TAKEOVER_SECONDS
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ assert len(attempts) == 1
+ assert attempts[0].next_attempt_prepared_at is None
+
+ monkeypatch.setattr(background_task_executor_module, "asyncio", ScopedAsyncio(sleep=sleep))
+ execute = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)
+ executor = BackgroundTaskExecutor()
+ await executor._recover_pending_retries_once(resume_fresh=True)
+ await asyncio.gather(*executor._background_tasks)
+
+ assert sleeps
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ assert [row.attempt_number for row in attempts] == [1, 2]
+ assert attempts[0].next_attempt_prepared_at is not None
+ execute.assert_awaited_once()
+ assert execute.await_args.kwargs["attempt_number"] == 2
+ assert execute.await_args.kwargs["api_key"] == "api-token"
+ assert not executor._scheduled_retry_resumes
+
+
[email protected]("cancelled", [False, True])
+async def test_startup_retry_backoff_preserves_sweep_recovery_or_cancellation(
+ interim_retry_db: AgentDB, monkeypatch: pytest.MonkeyPatch, cancelled: bool
+) -> None:
+ database = interim_retry_db
+ now = datetime.now(UTC).replace(tzinfo=None)
+ async with database.Session() as session:
+ attempt = await session.get(WorkflowRunAttemptModel, ("wr_retry", 1))
+ attempt.next_attempt_at = now
+ attempt.interim_webhook_sent_at = now
+ await session.commit()
+ monkeypatch.setattr(background_task_executor_module, "naive_utc_now", lambda: now)
+ token = AsyncMock(side_effect=RuntimeError("database unavailable"))
+ monkeypatch.setattr(database.organizations, "get_valid_org_auth_token", token)
+ monkeypatch.setattr(background_task_executor_module, "initialize_skyvern_state_file", AsyncMock())
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ execute = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)
+ executor = BackgroundTaskExecutor()
+ sleeps: list[float] = []
+
+ async def sleep(seconds: float) -> None:
+ nonlocal now
+ sleeps.append(seconds)
+ if cancelled:
+ raise asyncio.CancelledError
+ now += timedelta(seconds=seconds)
+ await executor._recover_pending_retries_once(resume_fresh=False)
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ assert len(attempts) == 1
+ assert attempts[0].retry_decision == "retry"
+
+ monkeypatch.setattr(background_task_executor_module, "asyncio", ScopedAsyncio(sleep=sleep))
+ await executor._recover_pending_retries_once(resume_fresh=True)
+ if cancelled:
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.gather(*executor._background_tasks)
+ else:
+ await asyncio.gather(*executor._background_tasks)
+ execute.assert_not_awaited()
+ assert not executor._scheduled_retry_resumes
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ assert len(attempts) == 1
+ assert attempts[0].retry_decision == "retry"
+ if cancelled:
+ assert not executor._retry_resumes_needing_recovery
+ return
+
+ assert sum(sleeps) == background_task_executor_module.LEASE_TAKEOVER_SECONDS
+ assert max(sleeps) <= 30
+ assert ("wr_retry", 1) in executor._retry_resumes_needing_recovery
+ now += timedelta(seconds=1)
+ token.side_effect = None
+ token.return_value = SimpleNamespace(token="api-token")
+ await executor._recover_pending_retries_once(resume_fresh=False)
+ await asyncio.gather(*executor._background_tasks)
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ assert [row.attempt_number for row in attempts] == [1, 2]
+ execute.assert_awaited_once()
+ assert execute.await_args.kwargs["attempt_number"] == 2
+ assert not executor._retry_resumes_needing_recovery
+
+
+async def test_startup_retry_with_definitively_missing_token_remains_abandonable(
+ interim_retry_db: AgentDB, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ database = interim_retry_db
+ now = datetime.now(UTC).replace(tzinfo=None)
+ async with database.Session() as session:
+ attempt = await session.get(WorkflowRunAttemptModel, ("wr_retry", 1))
+ attempt.next_attempt_at = now
+ await session.commit()
+ monkeypatch.setattr(background_task_executor_module, "asyncio", ScopedAsyncio(sleep=AsyncMock()))
+ execute = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)
+ executor = BackgroundTaskExecutor()
+ await executor._recover_pending_retries_once(resume_fresh=True)
+ await asyncio.gather(*executor._background_tasks)
+ assert not executor._scheduled_retry_resumes
+ execute.assert_not_awaited()
+
+ async with database.Session() as session:
+ attempt = await session.get(WorkflowRunAttemptModel, ("wr_retry", 1))
+ attempt.next_attempt_at = now - timedelta(seconds=background_task_executor_module.LEASE_TAKEOVER_SECONDS + 1)
+ await session.commit()
+ await executor._recover_pending_retries_once(resume_fresh=False)
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ assert len(attempts) == 1
+ assert attempts[0].retry_decision == "abandoned"
+ execute.assert_not_awaited()
+
+
[email protected]("dependency", ["token", "organization"])
[email protected]("transient", [False, True])
+async def test_prepared_retry_missing_dependency_abandons_or_recovers_on_next_sweep(
+ interim_retry_db: AgentDB, monkeypatch: pytest.MonkeyPatch, dependency: str, transient: bool
+) -> None:
+ database = interim_retry_db
+ now = datetime.now(UTC).replace(tzinfo=None)
+ async with database.Session() as session:
+ attempt = await session.get(WorkflowRunAttemptModel, ("wr_retry", 1))
+ attempt.interim_webhook_sent_at = now
+ await session.commit()
+ preparation = await database.workflow_runs.prepare_next_attempt_atomic("wr_retry", "org_test", 1, "failed", None)
+ assert preparation.status == "inserted"
+ async with database.Session() as session:
+ attempt = await session.get(WorkflowRunAttemptModel, ("wr_retry", 2))
+ attempt.modified_at = now - timedelta(seconds=background_task_executor_module.LEASE_TAKEOVER_SECONDS + 1)
+ await session.commit()
+ monkeypatch.setattr(background_task_executor_module, "LEASE_TAKEOVER_SECONDS", 3)
+ monkeypatch.setattr(background_task_executor_module, "naive_utc_now", lambda: now)
+ organization = await database.organizations.get_organization("org_test")
+ lookup = AsyncMock(side_effect=RuntimeError("database unavailable") if transient else None, return_value=None)
+ monkeypatch.setattr(
+ database.organizations,
+ "get_valid_org_auth_token" if dependency == "token" else "get_organization",
+ lookup,
+ )
+ monkeypatch.setattr(background_task_executor_module, "initialize_skyvern_state_file", AsyncMock())
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "prepare_workflow_webhook", AsyncMock(return_value=None))
+ execute = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)
+ executor = BackgroundTaskExecutor()
+
+ async def sleep(seconds: float) -> None:
+ nonlocal now
+ current = (await database.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ assert current.status == "queued"
+ assert current.retry_decision is None
+ now += timedelta(seconds=seconds)
+
+ monkeypatch.setattr(background_task_executor_module, "asyncio", ScopedAsyncio(sleep=sleep))
+ await executor._recover_pending_retries_once(resume_fresh=True)
+ await asyncio.gather(*executor._background_tasks)
+ execute.assert_not_awaited()
+ assert not executor._scheduled_retry_resumes
+ current = (await database.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ run = await database.workflow_runs.get_workflow_run("wr_retry", "org_test")
+ assert run is not None
+ if transient:
+ assert current.status == "queued"
+ assert current.retry_decision is None
+ assert current.started_at is None
+ assert run.status == WorkflowRunStatus.queued
+ assert ("wr_retry", 2) in executor._retry_resumes_needing_recovery
+ lookup.side_effect = None
+ lookup.return_value = SimpleNamespace(token="api-token") if dependency == "token" else organization
+ if dependency == "organization":
+ monkeypatch.setattr(
+ database.organizations,
+ "get_valid_org_auth_token",
+ AsyncMock(return_value=SimpleNamespace(token="api-token")),
+ )
+ await executor._recover_pending_retries_once(resume_fresh=False)
+ await asyncio.gather(*executor._background_tasks)
+ current = (await database.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ assert current.started_at is not None
+ execute.assert_awaited_once()
+ assert execute.await_args.kwargs["attempt_number"] == 2
+ assert not executor._retry_resumes_needing_recovery
+ else:
+ assert current.status == "failed"
+ assert current.retry_decision == "abandoned"
+ assert current.decision_reason == "prepared_attempt_never_started"
+ assert run.status == WorkflowRunStatus.failed
+ assert ("API token" if dependency == "token" else "organization") in run.failure_reason
+ assert current.webhook_sent_at is not None
+ assert current.final_side_effects_progress["completed_effects"]
+ assert not executor._retry_resumes_needing_recovery
+ schedule = MagicMock()
+ monkeypatch.setattr(executor, "_schedule_retry_resume", schedule)
+ await executor._recover_pending_retries_once(resume_fresh=False)
+ schedule.assert_not_called()
+ execute.assert_not_awaited()
+
+
+async def test_retry_recovery_sweep_never_resumes_a_retry_while_its_loop_is_sleeping(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ pending_attempt = SimpleNamespace(
+ workflow_run_id="wr_sleeping",
+ organization_id="org_test",
+ attempt_number=1,
+ retry_decision="retry",
+ next_attempt_at=datetime.now(UTC) + timedelta(seconds=30),
+ next_attempt_prepared_at=None,
+ )
+ sweep_sleep_started = asyncio.Event()
+ release_sweep = asyncio.Event()
+ recovery_finished = asyncio.Event()
+
+ async def controlled_sleep(_delay_seconds: float) -> None:
+ sweep_sleep_started.set()
+ await release_sweep.wait()
+ await asyncio.sleep(0)
+
+ async def list_recovery(_cutoff: datetime) -> list[SimpleNamespace]:
+ recovery_finished.set()
+ return [pending_attempt]
+
+ monkeypatch.setattr(
+ app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(
+ list_attempts_needing_recovery=list_recovery, list_stale_dispatch_claims=AsyncMock(return_value=[])
+ ),
+ ),
+ )
+ monkeypatch.setattr(background_task_executor_module, "asyncio", ScopedAsyncio(sleep=controlled_sleep))
+ schedule_resume = MagicMock()
+ executor = BackgroundTaskExecutor()
+ executor._fresh_retries_recovered = True
+ executor._schedule_retry_resume = schedule_resume # type: ignore[method-assign]
+
+ sweep_task = asyncio.create_task(executor._retry_recovery_sweep())
+ await asyncio.wait_for(sweep_sleep_started.wait(), timeout=1)
+ release_sweep.set()
+ await asyncio.wait_for(recovery_finished.wait(), timeout=1)
+ sweep_task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await sweep_task
+
+ schedule_resume.assert_not_called()
+
+
+async def test_two_retry_resumers_only_the_inserting_preparer_executes_the_next_attempt(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ pending_attempt = SimpleNamespace(
+ workflow_run_id="wr_two_callers",
+ organization_id="org_test",
+ attempt_number=1,
+ next_attempt_at=datetime.now(UTC) - timedelta(seconds=1),
+ )
+ organization = SimpleNamespace(organization_id="org_test")
+ prepare = AsyncMock(
+ side_effect=[
+ PrepareNextAttemptResult(status="inserted", pinned_browser_session_id="pinned-session"),
+ PrepareNextAttemptResult(status="already_prepared", pinned_browser_session_id="pinned-session"),
+ ]
+ )
+ execute = AsyncMock()
+ monkeypatch.setattr(background_task_executor_module, "prepare_next_attempt_result", prepare)
+ monkeypatch.setattr(background_task_executor_module, "initialize_skyvern_state_file", AsyncMock())
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ monkeypatch.setattr(
+ app,
+ "DATABASE",
+ SimpleNamespace(
+ organizations=SimpleNamespace(
+ get_organization=AsyncMock(return_value=organization),
+ get_valid_org_auth_token=AsyncMock(return_value=SimpleNamespace(token="api-token")),
+ ),
+ ),
+ )
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)
+
+ executor = BackgroundTaskExecutor()
+ await asyncio.gather(
+ executor._resume_pending_retry(pending_attempt),
+ executor._resume_pending_retry(pending_attempt),
+ )
+
+ assert prepare.await_count == 2
+ execute.assert_awaited_once()
+ assert execute.await_args.kwargs["attempt_number"] == 2
+
+
[email protected]("persistent", [False, True])
+async def test_retry_entry_preserves_policy_when_attempt_lookup_fails(
+ interim_retry_db: AgentDB, monkeypatch: pytest.MonkeyPatch, persistent: bool
+) -> None:
+ database = interim_retry_db
+ svc = app.WORKFLOW_SERVICE
+ organization = await database.organizations.get_organization("org_test")
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ lookup = AsyncMock(
+ side_effect=RuntimeError("attempt lookup failed")
+ if persistent
+ else [RuntimeError("temporary failure"), attempts]
+ )
+ monkeypatch.setattr(database.workflow_run_attempts, "get_attempts", lookup)
+ sleep = AsyncMock()
+ monkeypatch.setattr(service_module, "asyncio", ScopedAsyncio(sleep=sleep))
+ run = await svc.get_workflow_run("wr_retry", "org_test")
+ execute = AsyncMock(return_value=run)
+ monkeypatch.setattr(svc, "execute_workflow", execute)
+ decision = RetryDecision(False, 1, 0, True, "budget_exhausted")
+ monkeypatch.setattr(service_module, "get_recorded_decision", AsyncMock(return_value=decision))
+ release = AsyncMock(return_value="released")
+ monkeypatch.setattr(svc, "_run_terminal_side_effects_with_retries", release)
+
+ if persistent:
+ with pytest.raises(WorkflowRetryAttemptLookupError) as raised:
+ await svc.execute_workflow_with_retries("wr_retry", api_key="api-token", organization=organization)
+ assert raised.value.__cause__ is lookup.side_effect
+ assert lookup.await_count == 3
+ assert [call.args[0] for call in sleep.await_args_list] == [0.1, 0.2]
+ execute.assert_not_awaited()
+ release.assert_not_awaited()
+ else:
+ await svc.execute_workflow_with_retries("wr_retry", api_key="api-token", organization=organization)
+ assert lookup.await_count == 2
+ sleep.assert_awaited_once_with(0.1)
+ execute.assert_awaited_once()
+ assert execute.await_args.kwargs["need_call_webhook"] is False
+ release.assert_awaited_once()
+ assert release.await_args.args[1] == decision
+
+
[email protected]("outage", ["transient", "persistent"])
+async def test_retry_owner_retries_next_attempt_preparation_until_the_sweep_cutoff(
+ monkeypatch: pytest.MonkeyPatch, outage: str
+) -> None:
+ svc = app.WORKFLOW_SERVICE
+ decision = RetryDecision(True, 1, 5, False, "retry_on_failed")
+ error = RuntimeError("database unavailable")
+ read = AsyncMock(side_effect=error if outage == "persistent" else [error, decision])
+ monkeypatch.setattr(service_module, "get_recorded_decision", read)
+ prepared = SimpleNamespace(status="inserted", pinned_browser_session_id=None, serialized_identity=False)
+ prepare = AsyncMock(return_value=prepared)
+ monkeypatch.setattr(service_module, "prepare_next_attempt_result", prepare)
+ sleep = AsyncMock()
+ monkeypatch.setattr(service_module, "asyncio", ScopedAsyncio(sleep=sleep))
+ # Each clock read advances two thirds of the takeover window, so the second failure is past the deadline.
+ clock = datetime.now(UTC).replace(tzinfo=None)
+ step = timedelta(seconds=service_module.LEASE_TAKEOVER_SECONDS * 2 / 3)
+
+ def now() -> datetime:
+ nonlocal clock
+ clock += step
+ return clock - step
+
+ monkeypatch.setattr(service_module, "naive_utc_now", now)
+
+ if outage == "persistent":
+ with pytest.raises(RuntimeError, match="database unavailable"):
+ await svc._prepare_recorded_retry("wr_retry", "org_test", decision)
+ prepare.assert_not_awaited()
+ else:
+ assert await svc._prepare_recorded_retry("wr_retry", "org_test", decision) is prepared
+ prepare.assert_awaited_once()
+ assert prepare.await_args.kwargs["from_attempt"] == 1
+ assert prepare.await_args.kwargs["clear_browser_address"] is False
+ assert read.await_count == 2
+ sleep.assert_awaited_once_with(1.0)
+
+
+ "failure_phase",
+ [
+ "preparation",
+ "entry",
+ "prepared_entry",
+ "prepared_run_lookup",
+ "transient_entry",
+ "execution",
+ "prepared_execution",
+ ],
+)
+async def test_retry_resumer_recovers_attempt_lookup_failure_on_next_sweep(
+ interim_retry_db: AgentDB, monkeypatch: pytest.MonkeyPatch, failure_phase: str
+) -> None:
+ database = interim_retry_db
+ svc = app.WORKFLOW_SERVICE
+ now = datetime.now(UTC).replace(tzinfo=None)
+ async with database.Session() as session:
+ attempt = await session.get(WorkflowRunAttemptModel, ("wr_retry", 1))
+ attempt.next_attempt_at = now - timedelta(seconds=1)
+ attempt.interim_webhook_sent_at = now
+ await session.commit()
+ if failure_phase.startswith("prepared_"):
+ preparation = await database.workflow_runs.prepare_next_attempt_atomic(
+ "wr_retry", "org_test", 1, "failed", None
+ )
+ assert preparation.status == "inserted"
+ read_attempts = database.workflow_run_attempts.get_attempts
+ pending = (await read_attempts("wr_retry"))[-1]
+ monkeypatch.setattr(
+ database.organizations, "get_valid_org_auth_token", AsyncMock(return_value=SimpleNamespace(token="api-token"))
+ )
+ monkeypatch.setattr(background_task_executor_module, "initialize_skyvern_state_file", AsyncMock())
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ monkeypatch.setattr(service_module, "asyncio", ScopedAsyncio(sleep=AsyncMock()))
+ lookup = AsyncMock(wraps=read_attempts)
+ monkeypatch.setattr(database.workflow_run_attempts, "get_attempts", lookup)
+ claim = AsyncMock(wraps=database.workflow_run_attempts.claim_prepared_attempt_execution)
+ monkeypatch.setattr(database.workflow_run_attempts, "claim_prepared_attempt_execution", claim)
+ abandon = AsyncMock()
+ executor = BackgroundTaskExecutor()
+ monkeypatch.setattr(executor, "_abandon_retry", abandon)
+ release = AsyncMock(return_value="released")
+ monkeypatch.setattr(svc, "_run_terminal_side_effects_with_retries", release)
+ decision = RetryDecision(False, 2, 0, True, "budget_exhausted")
+ monkeypatch.setattr(service_module, "get_recorded_decision", AsyncMock(return_value=decision))
+ execute = AsyncMock(return_value=await svc.get_workflow_run("wr_retry", "org_test"))
+ monkeypatch.setattr(svc, "execute_workflow", execute)
+ read_run = AsyncMock(wraps=svc.get_workflow_run)
+ monkeypatch.setattr(svc, "get_workflow_run", read_run)
+ real_entry = svc.execute_workflow_with_retries
+ before_failure: list[dict[str, object]] = []
+
+ async def snapshot() -> list[dict[str, object]]:
+ return [
+ {column.name: getattr(row, column.name) for column in WorkflowRunAttemptModel.__table__.columns}
+ for row in await read_attempts("wr_retry")
+ ]
+
+ async def entry(**kwargs: object) -> WorkflowRun:
+ nonlocal before_failure
+ before_failure = await snapshot()
+ if failure_phase in {"entry", "prepared_entry"}:
+ lookup.side_effect = RuntimeError("attempt lookup failed")
+ elif failure_phase == "prepared_run_lookup":
+ read_run.side_effect = RuntimeError("workflow run lookup failed before execution")
+ elif failure_phase == "transient_entry":
+ lookup.side_effect = [RuntimeError("temporary failure"), await read_attempts("wr_retry")]
+ return await real_entry(**kwargs)
+
+ if failure_phase == "preparation":
+ before_failure = await snapshot()
+ lookup.side_effect = RuntimeError("attempt lookup failed")
+ if failure_phase in {"execution", "prepared_execution"}:
+ release.side_effect = RuntimeError("terminal effects failed after execution")
+ if failure_phase == "prepared_execution":
+ execute.side_effect = RuntimeError("workflow execution failed")
+ dispatch = AsyncMock(side_effect=entry)
+ monkeypatch.setattr(svc, "execute_workflow_with_retries", dispatch)
+ executor._schedule_retry_resume(pending)
+ await asyncio.gather(*executor._background_tasks)
+ key = ("wr_retry", pending.attempt_number)
+ assert not executor._scheduled_retry_resumes
+ abandon.assert_not_awaited()
+
+ if failure_phase.startswith("prepared_"):
+ claimed_attempt = (await read_attempts("wr_retry"))[-1]
+ assert claimed_attempt.started_at is not None
+ assert claim.await_count == 1
+
+ if failure_phase in {"transient_entry", "execution", "prepared_execution"}:
+ execute.assert_awaited_once()
+ assert execute.await_args.kwargs["need_call_webhook"] is False
+ assert key not in executor._retry_resumes_needing_recovery
+ assert key not in executor._retry_dispatches_needing_recovery
+ lookup.side_effect = None
+ await executor._recover_pending_retries_once(resume_fresh=False)
+ assert not executor._scheduled_retry_resumes
+ return
+
+ execute.assert_not_awaited()
+ assert await snapshot() == before_failure
+ assert (await read_attempts("wr_retry"))[0].retry_decision == "retry"
+ assert key in executor._retry_resumes_needing_recovery
+ if failure_phase != "preparation":
+ assert key in executor._retry_dispatches_needing_recovery
+ if failure_phase in {"entry", "prepared_entry"}:
+ assert lookup.await_count >= 3
+ lookup.side_effect = None
+ read_run.side_effect = None
+ dispatch.side_effect = real_entry
+ await executor._recover_pending_retries_once(resume_fresh=False)
+ assert key in executor._scheduled_retry_resumes
+ await asyncio.gather(*executor._background_tasks)
+ execute.assert_awaited_once()
+ assert execute.await_args.kwargs["attempt_number"] == 2
+ assert execute.await_args.kwargs["need_call_webhook"] is False
+ assert claim.await_count == 1
+ assert key not in executor._retry_resumes_needing_recovery
+ assert key not in executor._retry_dispatches_needing_recovery
+ assert not executor._scheduled_retry_resumes
+ assert (await read_attempts("wr_retry"))[0].retry_decision == "retry"
+ abandon.assert_not_awaited()
+
+
+async def test_periodic_recovery_leaves_a_fresh_prepared_queued_attempt_alone(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ prepared_attempt = SimpleNamespace(
+ workflow_run_id="wr_prepared_queued",
+ organization_id="org_test",
+ attempt_number=2,
+ retry_decision=None,
+ status=WorkflowRunStatus.queued.value,
+ started_at=None,
+ modified_at=datetime.now(UTC),
+ )
+ failed_run = SimpleNamespace(
+ workflow_run_id="wr_prepared_queued",
+ organization_id="org_test",
+ status=WorkflowRunStatus.failed,
+ failure_reason="Workflow retry attempt was prepared but never started before recovery.",
+ finished_at=datetime.now(UTC),
+ )
+ mark_failed = AsyncMock()
+ mark_failed.return_value = failed_run
+ finalize_abandoned = AsyncMock(return_value=RetryDecision(False, 2, 0, True, "prepared_attempt_never_started"))
+ side_effects = AsyncMock()
+ monkeypatch.setattr(
+ app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(
+ list_attempts_needing_recovery=AsyncMock(side_effect=[[prepared_attempt], []]),
+ list_stale_dispatch_claims=AsyncMock(return_value=[]),
+ ),
+ workflow_runs=SimpleNamespace(get_workflow_run=AsyncMock(return_value=failed_run)),
+ ),
+ )
+ monkeypatch.setattr(background_task_executor_module, "finalize_abandoned_attempt", finalize_abandoned)
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "mark_workflow_run_as_failed_if_not_final", mark_failed)
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "_run_terminal_side_effects_with_retries", side_effects)
+
+ executor = BackgroundTaskExecutor()
+ await executor._recover_pending_retries_once(resume_fresh=False)
+ await executor._recover_pending_retries_once(resume_fresh=False)
+
+ mark_failed.assert_not_awaited()
+ finalize_abandoned.assert_not_awaited()
+ side_effects.assert_not_awaited()
+
+
+async def test_recover_pending_retries_releases_unreleased_terminal_effects(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ terminal_attempt = SimpleNamespace(
+ workflow_run_id="wr_abandoned",
+ organization_id="org_test",
+ attempt_number=2,
+ retry_decision="abandoned",
+ decision_reason="process_restart",
+ side_effects_released_at=None,
+ webhook_sent_at=None,
+ modified_at=datetime.now(UTC) - timedelta(seconds=RETRY_DECISION_GRACE_SECONDS + 1),
+ )
+ terminal_run = SimpleNamespace(
+ workflow_run_id="wr_abandoned",
+ organization_id="org_test",
+ status=WorkflowRunStatus.failed,
+ )
+ list_recovery = AsyncMock(return_value=[terminal_attempt])
+ get_workflow_run = AsyncMock(return_value=terminal_run)
+ side_effects = AsyncMock()
+ monkeypatch.setattr(
+ app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(
+ list_attempts_needing_recovery=list_recovery, list_stale_dispatch_claims=AsyncMock(return_value=[])
+ ),
+ workflow_runs=SimpleNamespace(get_workflow_run=get_workflow_run),
+ ),
+ )
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "_run_terminal_side_effects_with_retries", side_effects)
+ monkeypatch.setattr(BackgroundTaskExecutor, "_start_retry_recovery_sweep", MagicMock())
+
+ await BackgroundTaskExecutor().recover_pending_retries()
- await asyncio.wait_for(ran.wait(), timeout=1)
+ side_effects.assert_awaited_once()
+ decision = side_effects.await_args.args[1]
+ assert decision == RetryDecision(False, 2, 0, True, "process_restart")
@pytest.mark.asyncio
-async def test_schedule_defers_to_background_tasks_when_present() -> None:
- calls: list[tuple[str, str]] = []
+async def test_recovery_reacquires_expired_side_effect_lease_after_effect_failure(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ old_claim = datetime.now(UTC) - timedelta(seconds=RETRY_DECISION_GRACE_SECONDS + 1)
+ attempts = [
+ SimpleNamespace(
+ workflow_run_id="wr_lease",
+ organization_id="org_test",
+ attempt_number=1,
+ retry_decision="final",
+ decision_reason="budget_exhausted",
+ side_effects_released_at=old_claim,
+ webhook_sent_at=None,
+ modified_at=old_claim,
+ ),
+ SimpleNamespace(
+ workflow_run_id="wr_lease",
+ organization_id="org_test",
+ attempt_number=1,
+ retry_decision="final",
+ decision_reason="budget_exhausted",
+ side_effects_released_at=old_claim,
+ webhook_sent_at=None,
+ modified_at=old_claim,
+ ),
+ ]
+ terminal_run = SimpleNamespace(
+ workflow_run_id="wr_lease",
+ organization_id="org_test",
+ status=WorkflowRunStatus.failed,
+ )
+ list_recovery = AsyncMock(side_effect=[[attempts[0]], [attempts[1]]])
+ get_workflow_run = AsyncMock(return_value=terminal_run)
+ release_calls: list[dict[str, object]] = []
- async def work(value: str, *, keyword: str) -> None:
- calls.append((value, keyword))
+ async def release_side_effects(*_args: object, **kwargs: object) -> None:
+ release_calls.append(kwargs)
+ if len(release_calls) == 1:
+ raise RuntimeError("logical terminal effect failed")
- background_tasks = BackgroundTasks()
- BackgroundTaskExecutor()._schedule(background_tasks, work, "positional", keyword="keyword")
+ monkeypatch.setattr(
+ app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(
+ list_attempts_needing_recovery=list_recovery, list_stale_dispatch_claims=AsyncMock(return_value=[])
+ ),
+ workflow_runs=SimpleNamespace(get_workflow_run=get_workflow_run),
+ ),
+ )
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "_run_terminal_side_effects_with_retries", release_side_effects)
- # Queued on the request's BackgroundTasks rather than started eagerly.
- assert calls == []
- await background_tasks()
- assert calls == [("positional", "keyword")]
+ executor = BackgroundTaskExecutor()
+ await executor._recover_pending_retries_once(resume_fresh=False)
+ await executor._recover_pending_retries_once(resume_fresh=False)
+
+ assert [call["side_effects_claim_at"] for call in release_calls] == [old_claim, old_claim]
@pytest.mark.asyncio
@@ -83,7 +2779,7 @@ async def test_execute_workflow_stamps_org_llm_defaults(monkeypatch: pytest.Monk
monkeypatch.setattr(
app.DATABASE.workflow_runs,
"get_workflow_run",
- AsyncMock(return_value=SimpleNamespace(sequential_credential_id=None)),
+ AsyncMock(return_value=SimpleNamespace(sequential_credential_id=None, status=WorkflowRunStatus.created)),
)
monkeypatch.setattr(
"skyvern.forge.sdk.executor.background_task_executor.initialize_skyvern_state_file",
@@ -93,28 +2789,599 @@ async def test_execute_workflow_stamps_org_llm_defaults(monkeypatch: pytest.Monk
"skyvern.forge.sdk.api.llm.custom_llm_registry.load_custom_llm_configs_for_organization",
AsyncMock(),
)
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", AsyncMock())
executor = BackgroundTaskExecutor()
executor._schedule = MagicMock() # type: ignore[method-assign]
+ await executor.execute_workflow(
+ request=None,
+ background_tasks=None,
+ organization=organization,
+ workflow_id="wf_test",
+ workflow_run_id="wr_test",
+ workflow_permanent_id="wpid_test",
+ max_steps_override=None,
+ api_key=None,
+ browser_session_id=None,
+ block_labels=None,
+ block_outputs=None,
+ )
+ _background_tasks, dispatch, attempt, execution_kwargs = executor._schedule.call_args.args
+
+ # The dispatch task stamps the defaults on the context the run executes in.
with skyvern_context.scoped(SkyvernContext(organization_id="org_test")) as context:
- await executor.execute_workflow(
- request=None,
- background_tasks=None,
- organization=organization,
- workflow_id="wf_test",
- workflow_run_id="wr_test",
- workflow_permanent_id="wpid_test",
- max_steps_override=None,
- api_key=None,
- browser_session_id=None,
- block_labels=None,
- block_outputs=None,
- )
+ await dispatch(attempt, execution_kwargs)
assert context.org_default_llm_key == "CUSTOM_LLM_oat_smart"
assert context.org_default_secondary_llm_key == "CUSTOM_LLM_oat_fast"
+async def test_execute_workflow_dispatches_from_latest_retry_attempt(monkeypatch: pytest.MonkeyPatch) -> None:
+ organization = SimpleNamespace(
+ organization_id="org_test",
+ default_llm_key=None,
+ default_secondary_llm_key=None,
+ )
+ monkeypatch.setattr(
+ app.DATABASE.workflow_runs,
+ "get_workflow_run",
+ AsyncMock(return_value=SimpleNamespace(sequential_credential_id=None, status=WorkflowRunStatus.created)),
+ )
+ monkeypatch.setattr(
+ app.DATABASE.workflow_run_attempts,
+ "get_attempts",
+ AsyncMock(
+ return_value=[
+ SimpleNamespace(attempt_number=1),
+ SimpleNamespace(attempt_number=2),
+ ]
+ ),
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.executor.background_task_executor.initialize_skyvern_state_file",
+ AsyncMock(),
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.api.llm.custom_llm_registry.load_custom_llm_configs_for_organization",
+ AsyncMock(),
+ )
+ executor = BackgroundTaskExecutor()
+ executor._schedule = MagicMock() # type: ignore[method-assign]
+
+ await executor.execute_workflow(
+ request=None,
+ background_tasks=None,
+ organization=organization,
+ workflow_id="wf_test",
+ workflow_run_id="wr_test",
+ workflow_permanent_id="wpid_test",
+ max_steps_override=None,
+ api_key=None,
+ browser_session_id=None,
+ block_labels=None,
+ block_outputs=None,
+ )
+
+ _background_tasks, dispatch, attempt, execution_kwargs = executor._schedule.call_args.args
+ assert dispatch == executor._dispatch_retry_resume
+ assert attempt.attempt_number == 2
+ assert execution_kwargs["attempt_number"] == 2
+
+
+async def test_first_dispatch_initializer_failure_is_retried_by_the_sweep(monkeypatch: pytest.MonkeyPatch) -> None:
+ organization = SimpleNamespace(organization_id="org_test", default_llm_key=None, default_secondary_llm_key=None)
+ monkeypatch.setattr(
+ app.DATABASE.workflow_runs,
+ "get_workflow_run",
+ AsyncMock(return_value=SimpleNamespace(sequential_credential_id=None, status=WorkflowRunStatus.created)),
+ )
+ monkeypatch.setattr(app.DATABASE.workflow_run_attempts, "get_attempts", AsyncMock(return_value=[]))
+ initializer_calls = 0
+
+ async def flaky_initialize(**kwargs: object) -> None:
+ nonlocal initializer_calls
+ initializer_calls += 1
+ if initializer_calls == 1:
+ raise RuntimeError("state file unavailable")
+
+ monkeypatch.setattr(background_task_executor_module, "initialize_skyvern_state_file", flaky_initialize)
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ execute = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)
+ executor = BackgroundTaskExecutor()
+ executor._schedule = MagicMock() # type: ignore[method-assign]
+
+ await executor.execute_workflow(
+ request=None,
+ background_tasks=None,
+ organization=organization,
+ workflow_id="wf_test",
+ workflow_run_id="wr_test",
+ workflow_permanent_id="wpid_test",
+ max_steps_override=None,
+ api_key=None,
+ browser_session_id=None,
+ block_labels=None,
+ block_outputs=None,
+ )
+ _background_tasks, dispatch, attempt, execution_kwargs = executor._schedule.call_args.args
+
+ # The scheduled dispatch fails to initialize; the run must stay owned by the sweep, not stuck.
+ await dispatch(attempt, execution_kwargs)
+ execute.assert_not_awaited()
+ assert ("wr_test", 1) in executor._retry_dispatches_needing_recovery
+
+ await executor._resume_pending_retry(attempt)
+ execute.assert_awaited_once()
+ assert execute.await_args is not None
+ assert execute.await_args.kwargs["attempt_number"] == 1
+ assert not executor._retry_dispatches_needing_recovery
+
+
[email protected]("lookup_fails", [False, True], ids=["lookup-ok", "lookup-fails"])
+async def test_lost_first_dispatch_is_recovered_after_a_restart(
+ sqlite_db: AgentDB, monkeypatch: pytest.MonkeyPatch, lookup_fails: bool
+) -> None:
+ async with sqlite_db.Session() as session:
+ session.add_all(
+ [
+ WorkflowRunModel(
+ workflow_run_id="wr_first",
+ organization_id="org_test",
+ workflow_id="wf_test",
+ workflow_permanent_id="wpid_test",
+ status="created",
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_first", organization_id="org_test", attempt_number=1, status="created"
+ ),
+ ]
+ )
+ await session.commit()
+ organization = SimpleNamespace(organization_id="org_test", default_llm_key=None, default_secondary_llm_key=None)
+ monkeypatch.setattr(app, "DATABASE", sqlite_db)
+ monkeypatch.setattr(sqlite_db.organizations, "get_organization", AsyncMock(return_value=organization))
+ monkeypatch.setattr(app.AGENT_FUNCTION, "get_workflow_run_execution_status", AsyncMock(return_value="absent"))
+ monkeypatch.setattr(BackgroundTaskExecutor, "_get_valid_api_key", AsyncMock(return_value="token"))
+ monkeypatch.setattr(background_task_executor_module, "initialize_skyvern_state_file", AsyncMock())
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ execute = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)
+ if lookup_fails:
+ real_get_attempts = sqlite_db.workflow_run_attempts.get_attempts
+ lookups = iter([RuntimeError("temporary database failure")])
+
+ async def flaky_get_attempts(workflow_run_id: str) -> list[WorkflowRunAttemptModel]:
+ failure = next(lookups, None)
+ if failure is not None:
+ raise failure
+ return await real_get_attempts(workflow_run_id)
+
+ monkeypatch.setattr(sqlite_db.workflow_run_attempts, "get_attempts", flaky_get_attempts)
+ dispatcher = BackgroundTaskExecutor()
+ dispatcher._schedule = MagicMock() # type: ignore[method-assign]
+
+ await dispatcher.execute_workflow(
+ request=None,
+ background_tasks=None,
+ organization=organization,
+ workflow_id="wf_test",
+ workflow_run_id="wr_first",
+ workflow_permanent_id="wpid_test",
+ max_steps_override=None,
+ api_key=None,
+ browser_session_id=None,
+ block_labels=None,
+ block_outputs=None,
+ )
+ dispatched = (await sqlite_db.workflow_run_attempts.get_attempts("wr_first"))[0]
+ assert dispatched.status == "queued" and dispatched.started_at is None
+ queued_run = await sqlite_db.workflow_runs.get_workflow_run("wr_first")
+ assert queued_run is not None and queued_run.status == WorkflowRunStatus.queued and queued_run.started_at is None
+
+ # The process exits before the scheduled dispatch runs; a fresh executor sweeps after the lease window.
+ later = background_task_executor_module.naive_utc_now() + timedelta(
+ seconds=2 * service_module.LEASE_TAKEOVER_SECONDS
+ )
+ for module in (service_module, background_task_executor_module, attempts_repository_module):
+ monkeypatch.setattr(module, "naive_utc_now", lambda: later)
+ recovering = BackgroundTaskExecutor()
+ await recovering._recover_pending_retries_once(resume_fresh=False)
+ await asyncio.gather(*recovering._background_tasks)
+
+ execute.assert_awaited_once()
+ assert execute.await_args is not None
+ assert execute.await_args.kwargs["attempt_number"] == 1
+ assert execute.await_args.kwargs["prepared_attempt_claimed"] is True
+ recovered = (await sqlite_db.workflow_run_attempts.get_attempts("wr_first"))[0]
+ assert recovered.status == "running" and recovered.started_at is not None
+
+
[email protected]("sweep_claims_first", [False, True], ids=["dispatch_claims", "sweep_claimed_first"])
+async def test_first_dispatch_runs_its_attempt_only_when_it_claims_it(
+ sqlite_db: AgentDB, monkeypatch: pytest.MonkeyPatch, sweep_claims_first: bool
+) -> None:
+ """The initializers run while the attempt is queued. A sweep that claims the attempt in that window
+ owns it, so the original dispatch must not execute the attempt as well."""
+ async with sqlite_db.Session() as session:
+ session.add_all(
+ [
+ WorkflowRunModel(
+ workflow_run_id="wr_first",
+ organization_id="org_test",
+ workflow_id="wf_test",
+ workflow_permanent_id="wpid_test",
+ status="created",
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_first", organization_id="org_test", attempt_number=1, status="created"
+ ),
+ ]
+ )
+ await session.commit()
+ organization = SimpleNamespace(organization_id="org_test", default_llm_key=None, default_secondary_llm_key=None)
+ monkeypatch.setattr(app, "DATABASE", sqlite_db)
+ monkeypatch.setattr(sqlite_db.organizations, "get_organization", AsyncMock(return_value=organization))
+ monkeypatch.setattr(BackgroundTaskExecutor, "_get_valid_api_key", AsyncMock(return_value="token"))
+ sweep_stamp: datetime | None = None
+
+ async def initialize_state(**_kwargs: Any) -> None:
+ nonlocal sweep_stamp
+ if sweep_claims_first:
+ sweep_stamp = await sqlite_db.workflow_run_attempts.claim_prepared_attempt_execution(
+ "wr_first", "org_test", 1
+ )
+ assert sweep_stamp is not None
+
+ monkeypatch.setattr(background_task_executor_module, "initialize_skyvern_state_file", initialize_state)
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ execute = AsyncMock(return_value=None)
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow", execute)
+ monkeypatch.setattr(
+ service_module, "get_recorded_decision", AsyncMock(return_value=RetryDecision(False, 1, 0, True, "final"))
+ )
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "_run_terminal_side_effects_with_retries", AsyncMock())
+ dispatcher = BackgroundTaskExecutor()
+
+ await dispatcher.execute_workflow(
+ request=None,
+ background_tasks=None,
+ organization=organization,
+ workflow_id="wf_test",
+ workflow_run_id="wr_first",
+ workflow_permanent_id="wpid_test",
+ max_steps_override=None,
+ api_key=None,
+ browser_session_id=None,
+ block_labels=None,
+ block_outputs=None,
+ )
+ await asyncio.gather(*dispatcher._background_tasks)
+
+ attempt = (await sqlite_db.workflow_run_attempts.get_attempts("wr_first"))[0]
+ assert attempt.status == "running" and attempt.started_at is not None
+ if sweep_claims_first:
+ execute.assert_not_awaited()
+ assert attempt.started_at == sweep_stamp
+ else:
+ execute.assert_awaited_once()
+ assert execute.await_args is not None
+ assert execute.await_args.kwargs["attempt_number"] == 1
+ assert execute.await_args.kwargs["dispatch_claim_started_at"] == attempt.started_at
+
+
+async def test_scheduled_run_whose_initializer_fails_is_recovered_after_a_restart(
+ sqlite_db: AgentDB, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ fire_time = datetime(2026, 6, 2, 10, 0, tzinfo=UTC)
+ schedule = SimpleNamespace(
+ workflow_schedule_id="wfs_test", workflow_permanent_id="wpid_test", organization_id="org_test", parameters={}
+ )
+ workflow_run_id = schedule_service_module.build_scheduled_workflow_run_id(schedule.workflow_schedule_id, fire_time)
+ async with sqlite_db.Session() as session:
+ session.add_all(
+ [
+ WorkflowRunModel(
+ workflow_run_id=workflow_run_id,
+ organization_id="org_test",
+ workflow_id="wf_test",
+ workflow_permanent_id="wpid_test",
+ status="created",
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id=workflow_run_id, organization_id="org_test", attempt_number=1, status="created"
+ ),
+ ]
+ )
+ await session.commit()
+ organization = SimpleNamespace(organization_id="org_test", default_llm_key=None, default_secondary_llm_key=None)
+ monkeypatch.setattr(app, "DATABASE", sqlite_db)
+ monkeypatch.setattr(sqlite_db.organizations, "get_organization", AsyncMock(return_value=organization))
+ monkeypatch.setattr(app.AGENT_FUNCTION, "get_workflow_run_execution_status", AsyncMock(return_value="absent"))
+ monkeypatch.setattr(BackgroundTaskExecutor, "_get_valid_api_key", AsyncMock(return_value="token"))
+ monkeypatch.setattr(
+ schedule_service_module,
+ "prepare_workflow",
+ AsyncMock(
+ return_value=SimpleNamespace(
+ workflow_run_id=workflow_run_id, browser_session_id=None, status=WorkflowRunStatus.created
+ )
+ ),
+ )
+ monkeypatch.setattr(schedule_service_module, "initialize_skyvern_state_file", AsyncMock())
+ monkeypatch.setattr(
+ schedule_service_module, "prepare_org_llm_runtime", AsyncMock(side_effect=RuntimeError("llm registry down"))
+ )
+ monkeypatch.setattr(background_task_executor_module, "initialize_skyvern_state_file", AsyncMock())
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ execute = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)
+ scheduler = schedule_service_module.LocalWorkflowScheduleScheduler(poll_interval_seconds=1, max_concurrent_runs=1)
+
+ with pytest.raises(RuntimeError, match="llm registry down"):
+ await scheduler._run_schedule(
+ schedule_service_module.DueWorkflowSchedule(schedule=schedule, previous_fire_time=fire_time) # type: ignore[arg-type]
+ )
+ execute.assert_not_awaited()
+ dispatched = (await sqlite_db.workflow_run_attempts.get_attempts(workflow_run_id))[0]
+ assert dispatched.status == "queued" and dispatched.started_at is None
+ queued_run = await sqlite_db.workflow_runs.get_workflow_run(workflow_run_id)
+ assert queued_run is not None and queued_run.status == WorkflowRunStatus.queued
+
+ # The scheduler now treats the fire as delivered; only the dispatch sweep can run the persisted run.
+ later = background_task_executor_module.naive_utc_now() + timedelta(
+ seconds=2 * service_module.LEASE_TAKEOVER_SECONDS
+ )
+ for module in (service_module, background_task_executor_module, attempts_repository_module):
+ monkeypatch.setattr(module, "naive_utc_now", lambda: later)
+ recovering = BackgroundTaskExecutor()
+ await recovering._recover_pending_retries_once(resume_fresh=False)
+ await asyncio.gather(*recovering._background_tasks)
+
+ execute.assert_awaited_once()
+ assert execute.await_args is not None
+ assert execute.await_args.kwargs["workflow_run_id"] == workflow_run_id
+ assert execute.await_args.kwargs["attempt_number"] == 1
+ assert execute.await_args.kwargs["prepared_attempt_claimed"] is True
+
+
[email protected]("persistent", [False, True], ids=["transient", "persistent"])
+async def test_first_dispatch_is_not_scheduled_without_a_durable_queued_attempt(
+ monkeypatch: pytest.MonkeyPatch, persistent: bool
+) -> None:
+ organization = SimpleNamespace(organization_id="org_test", default_llm_key=None, default_secondary_llm_key=None)
+ monkeypatch.setattr(
+ app.DATABASE.workflow_runs,
+ "get_workflow_run",
+ AsyncMock(return_value=SimpleNamespace(sequential_credential_id=None, status=WorkflowRunStatus.created)),
+ )
+ monkeypatch.setattr(app.DATABASE.workflow_run_attempts, "get_attempts", AsyncMock(return_value=[]))
+ failure = RuntimeError("temporary database failure")
+ queue_write = AsyncMock(side_effect=failure if persistent else [failure, True])
+ monkeypatch.setattr(app.DATABASE.workflow_runs, "queue_initial_dispatch", queue_write)
+ sleep = AsyncMock()
+ monkeypatch.setattr(retry_policy_module, "asyncio", ScopedAsyncio(sleep=sleep))
+ executor = BackgroundTaskExecutor()
+ executor._schedule = MagicMock() # type: ignore[method-assign]
+ dispatch_kwargs: dict[str, Any] = {
+ "request": None,
+ "background_tasks": None,
+ "organization": organization,
+ "workflow_id": "wf_test",
+ "workflow_run_id": "wr_test",
+ "workflow_permanent_id": "wpid_test",
+ "max_steps_override": None,
+ "api_key": None,
+ "browser_session_id": None,
+ "block_labels": None,
+ "block_outputs": None,
+ }
+
+ if persistent:
+ with pytest.raises(RuntimeError, match="temporary database failure"):
+ await executor.execute_workflow(**dispatch_kwargs)
+ assert queue_write.await_count == 3
+ executor._schedule.assert_not_called()
+ assert [call.args[0] for call in sleep.await_args_list] == [0.1, 0.2]
+ else:
+ await executor.execute_workflow(**dispatch_kwargs)
+ assert queue_write.await_count == 2
+ executor._schedule.assert_called_once()
+ assert [call.args[0] for call in sleep.await_args_list] == [0.1]
+
+
+async def test_run_canceled_before_its_first_dispatch_is_not_scheduled(
+ sqlite_db: AgentDB, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async with sqlite_db.Session() as session:
+ session.add_all(
+ [
+ WorkflowRunModel(
+ workflow_run_id="wr_canceled",
+ organization_id="org_test",
+ workflow_id="wf_test",
+ workflow_permanent_id="wpid_test",
+ status="canceled",
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_canceled",
+ organization_id="org_test",
+ attempt_number=1,
+ status="canceled",
+ retry_decision="revoked",
+ ),
+ ]
+ )
+ await session.commit()
+ organization = SimpleNamespace(organization_id="org_test", default_llm_key=None, default_secondary_llm_key=None)
+ monkeypatch.setattr(app, "DATABASE", sqlite_db)
+ # The dispatcher's own read still sees the run as created; the cancel commits before the queued write.
+ stale_run = SimpleNamespace(sequential_credential_id=None, status=WorkflowRunStatus.created)
+ monkeypatch.setattr(sqlite_db.workflow_runs, "get_workflow_run", AsyncMock(return_value=stale_run))
+ dispatcher = BackgroundTaskExecutor()
+ dispatcher._schedule = MagicMock() # type: ignore[method-assign]
+
+ await dispatcher.execute_workflow(
+ request=None,
+ background_tasks=None,
+ organization=organization,
+ workflow_id="wf_test",
+ workflow_run_id="wr_canceled",
+ workflow_permanent_id="wpid_test",
+ max_steps_override=None,
+ api_key=None,
+ browser_session_id=None,
+ block_labels=None,
+ block_outputs=None,
+ )
+
+ dispatcher._schedule.assert_not_called()
+ async with sqlite_db.Session() as session:
+ run = await session.get(WorkflowRunModel, "wr_canceled")
+ assert run is not None and run.status == "canceled" and run.queued_at is None
+ assert (await sqlite_db.workflow_run_attempts.get_attempts("wr_canceled"))[0].status == "canceled"
+
+
+async def test_queue_initial_dispatch_leaves_the_run_created_when_the_attempt_write_fails(
+ sqlite_db: AgentDB, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async with sqlite_db.Session() as session:
+ session.add_all(
+ [
+ WorkflowRunModel(
+ workflow_run_id="wr_partial",
+ organization_id="org_test",
+ workflow_id="wf_test",
+ workflow_permanent_id="wpid_test",
+ status="created",
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_partial", organization_id="org_test", attempt_number=1, status="created"
+ ),
+ ]
+ )
+ await session.commit()
+ real_update = workflow_runs_repository_module.update
+
+ def failing_attempt_update(model: Any) -> Any:
+ if model is WorkflowRunAttemptModel:
+ raise RuntimeError("database connection lost")
+ return real_update(model)
+
+ monkeypatch.setattr(workflow_runs_repository_module, "update", failing_attempt_update)
+
+ with pytest.raises(RuntimeError, match="database connection lost"):
+ await sqlite_db.workflow_runs.queue_initial_dispatch("wr_partial", 1)
+
+ # Neither row moved: a queued run whose attempt stayed created is invisible to dispatch recovery.
+ async with sqlite_db.Session() as session:
+ run = await session.get(WorkflowRunModel, "wr_partial")
+ assert run is not None and run.status == "created" and run.queued_at is None
+ assert (await sqlite_db.workflow_run_attempts.get_attempts("wr_partial"))[0].status == "created"
+
+
+async def test_scoped_inputs_are_marked_unrecoverable_before_the_dispatch_becomes_recoverable(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ organization = SimpleNamespace(organization_id="org_test", default_llm_key=None, default_secondary_llm_key=None)
+ monkeypatch.setattr(
+ app.DATABASE.workflow_runs,
+ "get_workflow_run",
+ AsyncMock(return_value=SimpleNamespace(sequential_credential_id=None, status=WorkflowRunStatus.created)),
+ )
+ monkeypatch.setattr(
+ app.DATABASE.workflow_run_attempts,
+ "get_attempts",
+ AsyncMock(side_effect=RuntimeError("temporary database failure")),
+ )
+ writes: list[str] = []
+
+ async def mark_unrecoverable(workflow_run_id: str, attempt_number: int) -> None:
+ writes.append(f"unrecoverable:{workflow_run_id}:{attempt_number}")
+
+ async def mark_queued(workflow_run_id: str, attempt_number: int) -> bool:
+ writes.append(f"queued:{workflow_run_id}:{attempt_number}")
+ return True
+
+ monkeypatch.setattr(app.DATABASE.workflow_run_attempts, "mark_attempt_inputs_unrecoverable", mark_unrecoverable)
+ monkeypatch.setattr(app.DATABASE.workflow_runs, "queue_initial_dispatch", mark_queued)
+ executor = BackgroundTaskExecutor()
+ executor._schedule = MagicMock() # type: ignore[method-assign]
+
+ await executor.execute_workflow(
+ request=None,
+ background_tasks=None,
+ organization=organization,
+ workflow_id="wf_test",
+ workflow_run_id="wr_test",
+ workflow_permanent_id="wpid_test",
+ max_steps_override=None,
+ api_key=None,
+ browser_session_id=None,
+ block_labels=["extract"],
+ block_outputs=None,
+ )
+
+ # A restart-recovered dispatch has no scoped inputs, so the marker must land before the queued write.
+ assert writes == ["unrecoverable:wr_test:1", "queued:wr_test:1"]
+ executor._schedule.assert_called_once()
+
+
+async def test_execute_workflow_schedules_plain_attempt_when_attempt_lookup_fails(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ organization = SimpleNamespace(
+ organization_id="org_test",
+ default_llm_key=None,
+ default_secondary_llm_key=None,
+ )
+ monkeypatch.setattr(
+ app.DATABASE.workflow_runs,
+ "get_workflow_run",
+ AsyncMock(return_value=SimpleNamespace(sequential_credential_id=None, status=WorkflowRunStatus.created)),
+ )
+ attempt_lookup = AsyncMock(side_effect=RuntimeError("temporary database failure"))
+ monkeypatch.setattr(app.DATABASE.workflow_run_attempts, "get_attempts", attempt_lookup)
+ monkeypatch.setattr(background_task_executor_module, "initialize_skyvern_state_file", AsyncMock())
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ # The owner's own bounded lookup fails too; the dispatch must stay owned by the recovery sweep.
+ owner = AsyncMock(side_effect=WorkflowRetryAttemptLookupError("execution was not started"))
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", owner)
+ executor = BackgroundTaskExecutor()
+
+ await executor.execute_workflow(
+ request=None,
+ background_tasks=None,
+ organization=organization,
+ workflow_id="wf_test",
+ workflow_run_id="wr_test",
+ workflow_permanent_id="wpid_test",
+ max_steps_override=None,
+ api_key=None,
+ browser_session_id=None,
+ block_labels=None,
+ block_outputs=None,
+ )
+ await asyncio.gather(*executor._background_tasks)
+
+ attempt_lookup.assert_awaited_once_with("wr_test")
+ assert owner.await_args.kwargs["attempt_number"] == 1
+ pending_attempt, pending_kwargs = executor._retry_dispatches_needing_recovery[("wr_test", 1)]
+ assert pending_attempt.attempt_number == 1
+ assert pending_kwargs["attempt_number"] == 1
+ assert ("wr_test", 1) in executor._retry_resumes_needing_recovery
+
+
@pytest.mark.asyncio
async def test_execute_task_v2_stamps_org_llm_defaults(monkeypatch: pytest.MonkeyPatch) -> None:
organization = SimpleNamespace(
@@ -300,3 +3567,509 @@ async def test_execute_workflow_terminalizes_when_forced_session_cleanup_fails(
mark_failed.assert_awaited_once()
executor._schedule.assert_not_called()
+
+
[email protected]("unrecoverable_inputs", [False, True])
+async def test_startup_recovers_prepared_retry_without_changing_its_inputs(
+ monkeypatch: pytest.MonkeyPatch, unrecoverable_inputs: bool
+) -> None:
+ attempt = SimpleNamespace(
+ workflow_run_id="wr_prepared_resume",
+ organization_id="org_test",
+ attempt_number=2,
+ status="queued",
+ started_at=None,
+ retry_decision=None,
+ decision_reason="unrecoverable_block_outputs" if unrecoverable_inputs else None,
+ pinned_browser_session_id="pinned-session",
+ modified_at=datetime.now(UTC) - timedelta(seconds=RETRY_DECISION_GRACE_SECONDS + 1),
+ )
+ run = SimpleNamespace(
+ workflow_run_id=attempt.workflow_run_id,
+ organization_id=attempt.organization_id,
+ status=WorkflowRunStatus.queued,
+ started_at=None,
+ failure_reason=None,
+ finished_at=None,
+ )
+ organization = SimpleNamespace(organization_id="org_test")
+ fail = AsyncMock(return_value=True)
+ claim_stamp = datetime.now(UTC)
+ database = SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(
+ list_attempts_needing_recovery=AsyncMock(return_value=[attempt]),
+ list_stale_dispatch_claims=AsyncMock(return_value=[]),
+ fail_prepared_workflow_run=fail,
+ claim_prepared_attempt_execution=AsyncMock(return_value=claim_stamp),
+ get_attempts=AsyncMock(return_value=[attempt]),
+ ),
+ workflow_runs=SimpleNamespace(get_workflow_run=AsyncMock(return_value=run)),
+ organizations=SimpleNamespace(
+ get_organization=AsyncMock(return_value=organization),
+ get_valid_org_auth_token=AsyncMock(return_value=SimpleNamespace(token="api-token")),
+ ),
+ )
+ monkeypatch.setattr(app, "DATABASE", database)
+ monkeypatch.setattr(background_task_executor_module, "initialize_skyvern_state_file", AsyncMock())
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ prepare = AsyncMock()
+ monkeypatch.setattr(background_task_executor_module, "prepare_next_attempt_result", prepare)
+ abandoned = AsyncMock(return_value=RetryDecision(False, 2, 0, True, "unrecoverable_block_outputs"))
+ monkeypatch.setattr(background_task_executor_module, "finalize_abandoned_attempt", abandoned)
+ execute = AsyncMock()
+ release = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "_run_terminal_side_effects_with_retries", release)
+ executor = BackgroundTaskExecutor()
+ await executor._recover_pending_retries_once(resume_fresh=True)
+ await asyncio.gather(*executor._background_tasks)
+
+ prepare.assert_not_awaited()
+ if unrecoverable_inputs:
+ execute.assert_not_awaited()
+ fail.assert_awaited_once()
+ abandoned.assert_awaited_once()
+ release.assert_awaited_once()
+ else:
+ fail.assert_not_awaited()
+ abandoned.assert_not_awaited()
+ execute.assert_awaited_once_with(
+ workflow_run_id=attempt.workflow_run_id,
+ api_key="api-token",
+ organization=organization,
+ browser_session_id="pinned-session",
+ block_labels=None,
+ block_outputs=None,
+ need_call_webhook=True,
+ attempt_number=2,
+ prepared_attempt_claimed=True,
+ dispatch_claim_started_at=claim_stamp,
+ on_execution_start=ANY,
+ )
+
+
[email protected]("ownership", ["absent", "running", "unknown"])
+async def test_periodic_recovery_resumes_prepared_attempt_after_it_ages(
+ sqlite_db: AgentDB, monkeypatch: pytest.MonkeyPatch, ownership: str
+) -> None:
+ now = datetime.now(UTC).replace(tzinfo=None)
+ async with sqlite_db.Session() as session:
+ session.add_all(
+ [
+ WorkflowRunModel(
+ workflow_run_id="wr_aged",
+ organization_id="org_test",
+ workflow_id="wf_test",
+ workflow_permanent_id="wpid_test",
+ status="queued",
+ queued_at=now,
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_aged",
+ organization_id="org_test",
+ attempt_number=2,
+ status="queued",
+ modified_at=now,
+ ),
+ ]
+ )
+ await session.commit()
+ monkeypatch.setattr(app, "DATABASE", sqlite_db)
+ monkeypatch.setattr(app.AGENT_FUNCTION, "get_workflow_run_execution_status", AsyncMock(return_value=ownership))
+ monkeypatch.setattr(
+ sqlite_db.organizations, "get_organization", AsyncMock(return_value=SimpleNamespace(organization_id="org_test"))
+ )
+ monkeypatch.setattr(BackgroundTaskExecutor, "_get_valid_api_key", AsyncMock(return_value="token"))
+ monkeypatch.setattr(background_task_executor_module, "initialize_skyvern_state_file", AsyncMock())
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ execute = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)
+ executor = BackgroundTaskExecutor()
+ await executor._recover_pending_retries_once(resume_fresh=True)
+ assert not executor._scheduled_retry_resumes
+ async with sqlite_db.Session() as session:
+ attempt = await session.get(WorkflowRunAttemptModel, ("wr_aged", 2))
+ attempt.modified_at = now - timedelta(seconds=background_task_executor_module.LEASE_TAKEOVER_SECONDS + 1)
+ await session.commit()
+ await executor._recover_pending_retries_once(resume_fresh=False)
+ await asyncio.gather(*executor._background_tasks)
+ assert execute.await_count == int(ownership == "absent")
+
+
+async def test_concurrent_prepared_recovery_dispatches_only_claim_winner(
+ sqlite_db: AgentDB, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async with sqlite_db.Session() as session:
+ session.add_all(
+ [
+ WorkflowRunModel(
+ workflow_run_id="wr_race",
+ organization_id="org_test",
+ workflow_id="wf_test",
+ workflow_permanent_id="wpid_test",
+ status="queued",
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_race", organization_id="org_test", attempt_number=2, status="queued"
+ ),
+ ]
+ )
+ await session.commit()
+ attempt = (await sqlite_db.workflow_run_attempts.get_attempts("wr_race"))[0]
+ monkeypatch.setattr(app, "DATABASE", sqlite_db)
+ monkeypatch.setattr(app.AGENT_FUNCTION, "get_workflow_run_execution_status", AsyncMock(return_value="absent"))
+ monkeypatch.setattr(
+ sqlite_db.organizations, "get_organization", AsyncMock(return_value=SimpleNamespace(organization_id="org_test"))
+ )
+ both_ready = asyncio.Event()
+ readers = 0
+
+ async def token(_self: BackgroundTaskExecutor, _org: str) -> str:
+ nonlocal readers
+ readers += 1
+ if readers == 2:
+ both_ready.set()
+ await both_ready.wait()
+ return "token"
+
+ monkeypatch.setattr(BackgroundTaskExecutor, "_get_valid_api_key", token)
+ monkeypatch.setattr(background_task_executor_module, "initialize_skyvern_state_file", AsyncMock())
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ execute = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", execute)
+ release = AsyncMock()
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "_run_terminal_side_effects_with_retries", release)
+ await asyncio.wait_for(
+ asyncio.gather(
+ BackgroundTaskExecutor()._resume_pending_retry(attempt),
+ BackgroundTaskExecutor()._resume_pending_retry(attempt),
+ ),
+ timeout=5,
+ )
+ execute.assert_awaited_once()
+ release.assert_not_awaited()
+ current = (await sqlite_db.workflow_run_attempts.get_attempts("wr_race"))[0]
+ assert current.started_at is not None
+ assert current.retry_decision is None
+
+
+ "entrance, escaped_exception",
+ [("in_process", False), ("in_process", True), ("recovery_pending", False), ("recovery_prepared", False)],
+)
+ "lane, outcome",
+ [
+ ("browser_session_id", "clear"),
+ ("browser_address", "clear"),
+ ("sequential_credential_id", "clear"),
+ ("sequential_key", "clear"),
+ ("reuse_bound_key", "clear"),
+ ("run_sequentially", "clear"),
+ ("depends_on_workflow_run_id", "clear"),
+ ("sequential_credential_id", "cancel"),
+ ("sequential_credential_id", "task_cancel"),
+ ("sequential_credential_id", "timeout"),
+ ("sequential_credential_id", "query_error"),
+ ("none", "clear"),
+ ],
+)
+async def test_in_process_retry_reacquires_serialized_lane(
+ sqlite_db: AgentDB,
+ monkeypatch: pytest.MonkeyPatch,
+ entrance: str,
+ escaped_exception: bool,
+ lane: str,
+ outcome: str,
+) -> None:
+ monkeypatch.setattr(app, "DATABASE", sqlite_db)
+ svc = app.WORKFLOW_SERVICE
+ now = datetime.now(UTC).replace(tzinfo=None)
+ identity = {lane: "shared-lane"} if lane not in {"none", "run_sequentially", "depends_on_workflow_run_id"} else {}
+ async with sqlite_db.Session() as session:
+ session.add(OrganizationModel(organization_id="org_test", organization_name="Test Organization"))
+ await session.commit()
+ session.add_all(
+ [
+ WorkflowModel(
+ workflow_id="wf_lane",
+ workflow_permanent_id="wpid_lane",
+ organization_id="org_test",
+ title="Retry lane",
+ version=1,
+ run_sequentially=lane == "run_sequentially",
+ workflow_definition={
+ "blocks": [],
+ "parameters": [],
+ "retry_policy": {"max_retries": 1, "delay_seconds": 0, "retry_on": [{"status": "failed"}]},
+ },
+ ),
+ WorkflowRunModel(
+ workflow_run_id="wr_retry",
+ workflow_id="wf_lane",
+ workflow_permanent_id="wpid_lane",
+ organization_id="org_test",
+ status="failed",
+ created_at=now - timedelta(seconds=40),
+ started_at=now - timedelta(seconds=30),
+ finished_at=now,
+ max_elapsed_time_minutes=1,
+ depends_on_workflow_run_id="wr_owner" if lane == "depends_on_workflow_run_id" else None,
+ **identity,
+ ),
+ WorkflowRunModel(
+ workflow_run_id="wr_owner",
+ workflow_id="wf_lane",
+ workflow_permanent_id="wpid_lane",
+ organization_id="org_test",
+ status="running",
+ queued_at=now,
+ **identity,
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_retry",
+ organization_id="org_test",
+ attempt_number=1,
+ status="failed",
+ retry_decision="retry",
+ started_at=now - timedelta(seconds=30),
+ finished_at=now,
+ interim_webhook_sent_at=now,
+ next_attempt_at=now,
+ pinned_browser_session_id=identity.get("browser_session_id"),
+ ),
+ ]
+ )
+ await session.commit()
+
+ monkeypatch.setattr(app.WORKFLOW_CONTEXT_MANAGER, "remove_workflow_run_context", MagicMock())
+ monkeypatch.setattr(svc, "_run_interim_side_effects_with_retries", AsyncMock(return_value="released"))
+ final_effects = AsyncMock(return_value="released")
+ monkeypatch.setattr(svc, "_run_terminal_side_effects_with_retries", final_effects)
+ monkeypatch.setattr(app.DATABASE.tasks, "get_tasks_by_workflow_run_id", AsyncMock(return_value=[]))
+ monkeypatch.setattr(app.DATABASE.observer, "get_workflow_run_blocks", AsyncMock(return_value=[]))
+ monkeypatch.setattr(svc, "_cascade_child_entities_on_terminal", AsyncMock())
+ monkeypatch.setattr(svc, "_sync_task_run_from_workflow_run", AsyncMock())
+ waiting = asyncio.Event()
+ release = asyncio.Event()
+ executed: list[int] = []
+
+ async def execute(**kwargs: object) -> WorkflowRun:
+ number = kwargs["attempt_number"]
+ assert isinstance(number, int)
+ executed.append(number)
+ if number == 1:
+ if escaped_exception:
+ raise RuntimeError("attempt failed")
+ return await svc.get_workflow_run("wr_retry", "org_test")
+ if lane != "none":
+ owner = await svc.get_workflow_run("wr_owner", "org_test")
+ assert owner.status == WorkflowRunStatus.completed, "retry started while the serialized lane was occupied"
+ completed = await sqlite_db.workflow_runs.update_workflow_run_if_not_final(
+ workflow_run_id="wr_retry", status=WorkflowRunStatus.completed
+ )
+ assert completed is not None
+ await service_module.on_terminal_transition(completed, completed.status, None, None, attempt_number=number)
+ return completed
+
+ async def sleep(seconds: float) -> None:
+ if seconds == 0:
+ await asyncio.sleep(0)
+ return
+ waiting.set()
+ await release.wait()
+
+ monkeypatch.setattr(svc, "execute_workflow", execute)
+ monkeypatch.setattr(service_module, "asyncio", ScopedAsyncio(sleep=sleep))
+ clearance_query = sqlite_db.workflow_runs.get_blocking_sequential_workflow_run
+ query_failed = False
+
+ async def check_lane(workflow_run_id: str) -> WorkflowRun | None:
+ nonlocal query_failed
+ assert lane != "none", "unserialized retry must not enter the admission gate"
+ if outcome == "query_error" and not query_failed:
+ query_failed = True
+ raise RuntimeError("primary unavailable")
+ return await clearance_query(workflow_run_id)
+
+ monkeypatch.setattr(sqlite_db.workflow_runs, "get_blocking_sequential_workflow_run", check_lane)
+ remaining_budget = service_module._get_workflow_run_max_elapsed_timeout_seconds
+
+ def budget(run: WorkflowRun) -> float:
+ remaining = remaining_budget(run)
+ assert 55 < remaining <= 60, "gate must use the prepared attempt's fresh runtime budget"
+ return 0.05 if outcome == "timeout" else remaining
+
+ monkeypatch.setattr(service_module, "_get_workflow_run_max_elapsed_timeout_seconds", budget)
+ recovering = entrance != "in_process"
+ if recovering:
+ monkeypatch.setattr(BackgroundTaskExecutor, "_get_valid_api_key", AsyncMock(return_value="token"))
+ monkeypatch.setattr(background_task_executor_module, "initialize_skyvern_state_file", AsyncMock())
+ monkeypatch.setattr(background_task_executor_module, "prepare_org_llm_runtime", AsyncMock())
+ if entrance == "recovery_prepared":
+ preparation = await service_module.prepare_next_attempt_result(
+ "wr_retry", "org_test", 1, clear_browser_address=False
+ )
+ assert preparation.status == "inserted"
+ recovered_attempt = (await sqlite_db.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ task = asyncio.create_task(BackgroundTaskExecutor()._resume_pending_retry(recovered_attempt))
+ else:
+ task = asyncio.create_task(
+ svc.execute_workflow_with_retries(
+ workflow_run_id="wr_retry", api_key=None, organization=SimpleNamespace(organization_id="org_test")
+ )
+ )
+ wait_task = asyncio.create_task(waiting.wait())
+ try:
+ if lane == "none":
+ await asyncio.wait_for(task, timeout=30)
+ result = await svc.get_workflow_run("wr_retry", "org_test")
+ assert result.status == WorkflowRunStatus.completed
+ assert executed == ([2] if recovering else [1, 2])
+ assert not waiting.is_set()
+ return
+
+ # A generous bound: the assertion is about ordering, and a loaded CI shard can take seconds to get here.
+ done, _pending = await asyncio.wait({task, wait_task}, timeout=30, return_when=asyncio.FIRST_COMPLETED)
+ if task in done:
+ await task
+ assert wait_task in done, "retry did not wait for the occupied lane"
+ attempts = await sqlite_db.workflow_run_attempts.get_attempts("wr_retry")
+ assert attempts[-1].attempt_number == 2
+ assert (attempts[-1].started_at is not None) == (entrance == "recovery_prepared")
+ assert executed == ([] if recovering else [1])
+ if outcome in {"clear", "query_error"}:
+ await sqlite_db.workflow_runs.update_workflow_run_if_not_final(
+ workflow_run_id="wr_owner", status=WorkflowRunStatus.completed
+ )
+ release.set()
+ elif outcome == "cancel":
+ await svc.mark_workflow_run_as_canceled("wr_retry")
+ release.set()
+ elif outcome == "task_cancel":
+ task.cancel()
+
+ if outcome == "task_cancel":
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(task, timeout=5)
+ result = await svc.get_workflow_run("wr_retry", "org_test")
+ else:
+ await asyncio.wait_for(task, timeout=5)
+ result = await svc.get_workflow_run("wr_retry", "org_test")
+ if outcome in {"clear", "query_error"}:
+ assert result.status == WorkflowRunStatus.completed
+ assert executed == ([2] if recovering else [1, 2])
+ elif outcome == "task_cancel":
+ # Only shutdown cancels the owner: the prepared attempt stays recoverable, nothing is finalized.
+ assert not result.status.is_final()
+ assert executed == ([] if recovering else [1])
+ attempt = (await sqlite_db.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ assert attempt.attempt_number == 2
+ assert attempt.retry_decision is None
+ assert (attempt.started_at is not None) == (entrance == "recovery_prepared")
+ final_effects.assert_not_awaited()
+ else:
+ assert result.status == (
+ WorkflowRunStatus.timed_out if outcome == "timeout" else WorkflowRunStatus.canceled
+ )
+ assert executed == ([] if recovering else [1])
+ attempt = (await sqlite_db.workflow_run_attempts.get_attempts("wr_retry"))[-1]
+ assert (attempt.started_at is not None) == (entrance == "recovery_prepared")
+ assert attempt.retry_decision in {"final", "revoked", "abandoned"}
+ assert not await sqlite_db.workflow_run_attempts.claim_prepared_attempt_execution("wr_retry", "org_test", 2)
+ assert final_effects.await_args.args[1].attempt_number == 2
+ finally:
+ for pending in [task, wait_task]:
+ if not pending.done():
+ pending.cancel()
+ await asyncio.gather(task, wait_task, return_exceptions=True)
+
+
+async def test_mark_attempt_started_never_revives_a_finalized_attempt(
+ sqlite_db: AgentDB, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A cancel can finalize the attempt between the run's running write and the attempt's; the
+ late running write must lose."""
+ monkeypatch.setattr(app, "DATABASE", sqlite_db)
+ async with sqlite_db.Session() as session:
+ session.add(OrganizationModel(organization_id="org_test", organization_name="Test Organization"))
+ await session.commit()
+ session.add_all(
+ [
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_live", organization_id="org_test", attempt_number=1, status="queued"
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_canceled",
+ organization_id="org_test",
+ attempt_number=1,
+ status="canceled",
+ retry_decision="revoked",
+ decision_reason="cancel",
+ ),
+ ]
+ )
+ await session.commit()
+
+ assert await mark_attempt_started("wr_live", 1) is True
+ assert await mark_attempt_started("wr_canceled", 1) is False
+
+ live = (await sqlite_db.workflow_run_attempts.get_attempts("wr_live"))[0]
+ canceled = (await sqlite_db.workflow_run_attempts.get_attempts("wr_canceled"))[0]
+ assert (live.status, live.started_at is not None) == ("running", True)
+ assert (canceled.status, canceled.started_at, canceled.retry_decision) == ("canceled", None, "revoked")
+
+
[email protected]("durable_decision", ["retry", "final"])
+async def test_late_owner_failure_leaves_a_recorded_retry_to_the_next_sweep(
+ monkeypatch: pytest.MonkeyPatch, durable_decision: str
+) -> None:
+ # The decision read after execution is outside the bounded lookup path. Its failure must not
+ # strand a recorded retry until the periodic sweep abandons it as stale.
+ executor = BackgroundTaskExecutor()
+ attempt = SimpleNamespace(workflow_run_id="wr_late", organization_id="org_late", attempt_number=1, started_at=None)
+ latest = SimpleNamespace(
+ workflow_run_id="wr_late",
+ organization_id="org_late",
+ attempt_number=2,
+ retry_decision=durable_decision,
+ next_attempt_prepared_at=None,
+ next_attempt_at=datetime.now(UTC),
+ )
+ monkeypatch.setattr(app.DATABASE.workflow_run_attempts, "get_attempts", AsyncMock(return_value=[attempt, latest]))
+
+ async def entry(**kwargs: Any) -> None:
+ kwargs["on_execution_start"]()
+ raise RuntimeError("decision read unavailable")
+
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "execute_workflow_with_retries", AsyncMock(side_effect=entry))
+
+ with pytest.raises(RuntimeError, match="decision read unavailable"):
+ await executor._dispatch_retry_resume(attempt, {"workflow_run_id": "wr_late", "attempt_number": 2})
+
+ key = ("wr_late", 2)
+ assert key not in executor._retry_dispatches_needing_recovery
+ assert (key in executor._retry_resumes_needing_recovery) is (durable_decision == "retry")
+
+ scheduled = Mock()
+ monkeypatch.setattr(executor, "_schedule_retry_resume", scheduled)
+ monkeypatch.setattr(executor, "_recover_stale_dispatch_claims", AsyncMock())
+ monkeypatch.setattr(executor, "_release_unreleased_terminal_effects", AsyncMock())
+
+ async def recover(*, process_attempt: Any) -> None:
+ await process_attempt(latest, False)
+
+ monkeypatch.setattr(app.WORKFLOW_SERVICE, "recover_pending_workflow_attempts", recover)
+ await executor._recover_pending_retries_once(resume_fresh=False)
+
+ if durable_decision == "retry":
+ scheduled.assert_called_once_with(latest)
+ else:
+ scheduled.assert_not_called()
+ assert key not in executor._retry_resumes_needing_recovery
diff --git a/tests/unit/test_block_downloaded_file_scoping.py b/tests/unit/test_block_downloaded_file_scoping.py
index c95c17dd3..d77ef1deb 100644
--- a/tests/unit/test_block_downloaded_file_scoping.py
+++ b/tests/unit/test_block_downloaded_file_scoping.py
@@ -7,10 +7,16 @@ previous blocks.
"""
import asyncio
+import os
+from datetime import UTC, datetime, timedelta, timezone
+from pathlib import Path
from unittest.mock import AsyncMock, patch
import pytest
+from skyvern.forge.sdk.artifact.storage import base as base_module
+from skyvern.forge.sdk.artifact.storage.local import LocalStorage
+from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.schemas.files import FileInfo
from skyvern.forge.sdk.workflow.loop_download_filter import (
@@ -19,8 +25,16 @@ from skyvern.forge.sdk.workflow.loop_download_filter import (
to_downloaded_file_signature,
)
from skyvern.forge.sdk.workflow.models.block import (
+ DOWNLOAD_BINDING_FAILURE_REASON,
+ CodeBlock,
capture_block_download_baseline,
)
+from tests.unit.test_code_block_downloads import (
+ _fake_storage_app,
+ _output_parameter,
+ _wire_block_runtime,
+ _wire_secure_runner,
+)
def _make_file_info(url: str, filename: str, checksum: str | None = None) -> FileInfo:
@@ -48,7 +62,7 @@ def test_second_block_excludes_first_blocks_files():
DOWNLOADED_FILE_SIGS_KEY: baseline_sigs,
}
- # After block 2 runs, get_downloaded_files returns both files
+ # After block 2 runs, get_current_attempt_downloaded_files returns both files
all_files = [file1, file2]
# Filter should return only file2 (new since baseline)
@@ -121,7 +135,7 @@ async def test_baseline_captured_when_loop_internal_state_is_none():
context = SkyvernContext(run_id="wr_test", loop_internal_state=None)
mock_storage = AsyncMock()
- mock_storage.get_downloaded_files = AsyncMock(return_value=[file1])
+ mock_storage.get_current_attempt_downloaded_files = AsyncMock(return_value=[file1])
with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:
mock_app.STORAGE = mock_storage
@@ -147,7 +161,7 @@ async def test_baseline_recaptured_when_set_by_previous_block():
)
mock_storage = AsyncMock()
- mock_storage.get_downloaded_files = AsyncMock(return_value=[file1, file2])
+ mock_storage.get_current_attempt_downloaded_files = AsyncMock(return_value=[file1, file2])
with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:
mock_app.STORAGE = mock_storage
@@ -172,7 +186,7 @@ async def test_baseline_recaptured_even_when_loop_set_it():
# exists alongside the loop's pre-iteration a.pdf.
sibling_file = _make_file_info("s3://bucket/b.pdf", "b.pdf", "checksum_b")
mock_storage = AsyncMock()
- mock_storage.get_downloaded_files = AsyncMock(
+ mock_storage.get_current_attempt_downloaded_files = AsyncMock(
return_value=[_make_file_info("s3://a.pdf", "a.pdf", "abc"), sibling_file]
)
@@ -182,7 +196,7 @@ async def test_baseline_recaptured_even_when_loop_set_it():
# Re-captured: the sibling's file is now part of this block's baseline, so it
# will be filtered out of this block's own output.
- mock_storage.get_downloaded_files.assert_called_once()
+ mock_storage.get_current_attempt_downloaded_files.assert_called_once()
assert len(context.loop_internal_state[DOWNLOADED_FILE_SIGS_KEY]) == 2
@@ -191,7 +205,7 @@ async def test_baseline_capture_degrades_on_timeout():
"""TimeoutError clears loop_internal_state and lets the block proceed."""
context = SkyvernContext(run_id="wr_test", loop_internal_state=None)
mock_storage = AsyncMock()
- mock_storage.get_downloaded_files = AsyncMock(side_effect=asyncio.TimeoutError)
+ mock_storage.get_current_attempt_downloaded_files = AsyncMock(side_effect=asyncio.TimeoutError)
with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:
mock_app.STORAGE = mock_storage
@@ -210,13 +224,13 @@ async def test_stale_loop_baseline_overwritten_by_fresh_capture():
}
context = SkyvernContext(run_id="wr_test", loop_internal_state=stale_loop_state)
mock_storage = AsyncMock()
- mock_storage.get_downloaded_files = AsyncMock(return_value=[])
+ mock_storage.get_current_attempt_downloaded_files = AsyncMock(return_value=[])
with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:
mock_app.STORAGE = mock_storage
await capture_block_download_baseline(context, "org_1", "wr_test", "block_1")
- mock_storage.get_downloaded_files.assert_called_once()
+ mock_storage.get_current_attempt_downloaded_files.assert_called_once()
assert context.loop_internal_state is not stale_loop_state
assert context.loop_internal_state[DOWNLOADED_FILE_SIGS_KEY] == []
@@ -226,7 +240,7 @@ async def test_baseline_capture_degrades_on_generic_exception():
"""Non-timeout exceptions (e.g. S3 errors) clear state and let the block proceed."""
context = SkyvernContext(run_id="wr_test", loop_internal_state=None)
mock_storage = AsyncMock()
- mock_storage.get_downloaded_files = AsyncMock(side_effect=RuntimeError("S3 blip"))
+ mock_storage.get_current_attempt_downloaded_files = AsyncMock(side_effect=RuntimeError("S3 blip"))
with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:
mock_app.STORAGE = mock_storage
@@ -295,7 +309,7 @@ async def test_sibling_download_blocks_in_loop_iteration_scope_to_own_files():
mock_storage = AsyncMock()
# Each baseline capture reads a snapshot of the files that exist at that moment.
- mock_storage.get_downloaded_files = AsyncMock(side_effect=lambda **_: list(run_files))
+ mock_storage.get_current_attempt_downloaded_files = AsyncMock(side_effect=lambda **_: list(run_files))
async def run_download_block(produced: FileInfo) -> list[FileInfo]:
with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:
@@ -317,3 +331,134 @@ async def test_sibling_download_blocks_in_loop_iteration_scope_to_own_files():
context.loop_internal_state = {DOWNLOADED_FILE_SIGS_KEY: [to_downloaded_file_signature(f) for f in run_files]}
out4 = await run_download_block(pp4)
assert [f.filename for f in out4] == ["page_4.pdf"]
+
+
[email protected]("attempt_number", [1, 2])
[email protected]("start_kind", ["aware", "naive", "missing"])
+async def test_current_attempt_downloads_preserve_unknown_dates_and_include_start_boundary(
+ tmp_path, monkeypatch, attempt_number, start_kind
+):
+ boundary = datetime(2026, 9, 9, 12, tzinfo=UTC)
+ started_at = {"aware": boundary, "naive": boundary.replace(tzinfo=None), "missing": None}[start_kind]
+ files = [
+ FileInfo(url="file:///old.pdf", modified_at=boundary - timedelta(microseconds=1)),
+ FileInfo(url="file:///old-naive.pdf", modified_at=(boundary - timedelta(seconds=1)).replace(tzinfo=None)),
+ FileInfo(url="file:///boundary.pdf", modified_at=boundary.replace(tzinfo=None)),
+ FileInfo(url="file:///offset.pdf", modified_at=boundary.astimezone(timezone(timedelta(hours=-4)))),
+ FileInfo(url="file:///new.pdf", modified_at=boundary + timedelta(seconds=1)),
+ FileInfo(url="file:///unknown.pdf", modified_at=None),
+ ]
+ storage = LocalStorage(str(tmp_path / "artifacts"))
+ monkeypatch.setattr(storage, "get_downloaded_files", AsyncMock(return_value=files))
+ resolve_attempt = AsyncMock(return_value=("wr_owner", attempt_number, started_at))
+ monkeypatch.setattr(base_module, "resolve_download_attempt", resolve_attempt)
+
+ result = await storage.get_current_attempt_downloaded_files("o_1", "wr_child")
+
+ assert result == (files[2:] if attempt_number > 1 and started_at is not None else files)
+ resolve_attempt.assert_awaited_once_with("o_1", "wr_child", attempt_number=None)
+ storage.get_downloaded_files.assert_awaited_once_with(organization_id="o_1", run_id="wr_child")
+
+
[email protected]("attempt_number", [1, 2])
[email protected]("change", ["rewrite", "late_stale", "unchanged"])
[email protected]("engine", ["inline", "secure"])
+async def test_code_block_binding_verdict_recognizes_proven_retry_rewrite(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, attempt_number: int, change: str, engine: str
+) -> None:
+ download_dir = tmp_path / "wr_1"
+ download_dir.mkdir()
+ monkeypatch.setattr("skyvern.forge.sdk.api.files.settings.DOWNLOAD_PATH", str(tmp_path))
+ old_file = download_dir / "report.pdf"
+ old_file.write_bytes(b"before")
+ old_time = datetime(2026, 1, 1, tzinfo=UTC).timestamp()
+ os.utime(old_file, (old_time, old_time))
+ cutoff = datetime(2026, 1, 2, tzinfo=UTC)
+ monkeypatch.setattr(
+ base_module, "resolve_download_attempt", AsyncMock(return_value=("wr_1", attempt_number, cutoff))
+ )
+ _fake_storage_app(monkeypatch, save=AsyncMock(), get=AsyncMock(return_value=[]))
+ _wire_block_runtime(monkeypatch)
+
+ def produce_download() -> None:
+ if change == "unchanged":
+ return
+ target = old_file if change == "rewrite" else download_dir / "late.pdf"
+ target.write_bytes(b"newly generated bytes")
+ os.utime(target, (old_time, old_time))
+
+ async def execute_code(*args: object, **kwargs: object) -> dict[str, bool]:
+ produce_download()
+ return {"ok": True}
+
+ if engine == "secure":
+ _wire_secure_runner(monkeypatch, output={"ok": True}, on_execute=produce_download)
+ else:
+ monkeypatch.setattr(CodeBlock, "execute_user_function_with_timeout", AsyncMock(side_effect=execute_code))
+ block = CodeBlock(label="download", code="value = 'unused'", output_parameter=_output_parameter("code_out"))
+ previous_context = skyvern_context.current()
+ skyvern_context.set(SkyvernContext(organization_id="o_1", workflow_run_id="wr_1", run_id="wr_1"))
+ try:
+ result = await block.execute(workflow_run_id="wr_1", workflow_run_block_id="", organization_id="o_1")
+ finally:
+ if previous_context is None:
+ skyvern_context.reset()
+ else:
+ skyvern_context.set(previous_context)
+
+ has_new_download = change == "rewrite" or (change == "late_stale" and attempt_number == 1)
+ assert (result.failure_reason == DOWNLOAD_BINDING_FAILURE_REASON) == has_new_download
+ assert result.success is not has_new_download
+ assert old_file.exists()
+
+
[email protected]("first_lookup_fails", [False, True])
+async def test_secure_code_block_reuses_retry_cutoff_when_lookup_is_transient(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, first_lookup_fails: bool
+) -> None:
+ download_dir = tmp_path / "wr_1"
+ download_dir.mkdir()
+ monkeypatch.setattr("skyvern.forge.sdk.api.files.settings.DOWNLOAD_PATH", str(tmp_path))
+ cutoff = datetime(2026, 1, 2, tzinfo=UTC)
+ resolved_attempt = ("wr_1", 2, cutoff)
+ lookup_error = RuntimeError("download attempt lookup unavailable")
+ resolve_attempt = AsyncMock(
+ side_effect=[lookup_error, resolved_attempt] if first_lookup_fails else [resolved_attempt, lookup_error]
+ )
+ monkeypatch.setattr(base_module, "resolve_download_attempt", resolve_attempt)
+ _fake_storage_app(monkeypatch, save=AsyncMock(), get=AsyncMock(return_value=[]))
+ _wire_block_runtime(monkeypatch)
+ register_downloads = AsyncMock(return_value=([], set()))
+ monkeypatch.setattr(CodeBlock, "_register_downloaded_files", register_downloads)
+
+ def materialize_stale_download() -> None:
+ late_file = download_dir / "late.pdf"
+ late_file.write_bytes(b"retained download")
+ old_time = (cutoff - timedelta(days=1)).timestamp()
+ os.utime(late_file, (old_time, old_time))
+
+ _wire_secure_runner(monkeypatch, output={"ok": True}, on_execute=materialize_stale_download)
+ block = CodeBlock(label="download", code="value = 'unused'", output_parameter=_output_parameter("code_out"))
+ previous_context = skyvern_context.current()
+ skyvern_context.set(SkyvernContext(organization_id="o_1", workflow_run_id="wr_1", run_id="wr_1"))
+ try:
+ result = await block.execute(workflow_run_id="wr_1", workflow_run_block_id="", organization_id="o_1")
+ finally:
+ if previous_context is None:
+ skyvern_context.reset()
+ else:
+ skyvern_context.set(previous_context)
+
+ if first_lookup_fails:
+ register_downloads.assert_awaited_once()
+ assert result.failure_reason == DOWNLOAD_BINDING_FAILURE_REASON
+ assert result.output_parameter_value["download_registration_failed"] is True
+ else:
+ register_downloads.assert_not_awaited()
+ assert result.success
+ assert result.failure_reason is None
+ assert result.output_parameter_value == {"ok": True}
+ resolve_attempt.assert_awaited_once_with("o_1", "wr_1", attempt_number=None)
diff --git a/tests/unit/test_block_output_download_refresh.py b/tests/unit/test_block_output_download_refresh.py
index f6ad3fc68..11bf3b66e 100644
--- a/tests/unit/test_block_output_download_refresh.py
+++ b/tests/unit/test_block_output_download_refresh.py
@@ -272,6 +272,51 @@ async def test_refresh_substitutes_screenshot_urls_from_map():
]
+async def test_refresh_scopes_screenshots_to_the_current_attempt():
+ """A retried run's block outputs carry screenshot ids from every attempt; only the current
+ attempt's artifacts are resolved when no historical scope is active."""
+ from skyvern.forge.sdk.workflow.service import WorkflowService
+
+ block_output = {
+ "task_screenshot_artifact_ids": ["s_1", "s_2"],
+ "workflow_screenshot_artifact_ids": ["ws_1"],
+ "downloaded_file_artifact_ids": [],
+ }
+ artifacts = {
+ "s_1": _make_artifact("s_1", "s3://bucket/s1.png"),
+ "s_2": _make_artifact("s_2", "s3://bucket/s2.png"),
+ "ws_1": _make_artifact("ws_1", "s3://bucket/ws1.png"),
+ }
+ get_artifacts_by_ids = AsyncMock(side_effect=lambda ids, _org: [artifacts[aid] for aid in ids])
+
+ with (
+ patch(
+ "skyvern.forge.sdk.workflow.service.app.DATABASE.artifacts.get_artifacts_by_ids", new=get_artifacts_by_ids
+ ),
+ patch(
+ "skyvern.forge.sdk.workflow.service.app.ARTIFACT_MANAGER.resolve_artifact_url_expiry_seconds",
+ new=AsyncMock(return_value=3600),
+ ),
+ patch(
+ "skyvern.forge.sdk.workflow.service.app.ARTIFACT_MANAGER.resolve_share_url",
+ new=AsyncMock(
+ side_effect=lambda artifact, **_: f"https://api.skyvern.com/v1/artifacts/{artifact.artifact_id}/content"
+ ),
+ ),
+ ):
+ result = await WorkflowService()._refresh_output_urls(
+ block_output,
+ organization_id="o_1",
+ workflow_run_id="wr_1",
+ current_attempt_artifacts=[artifacts["s_2"]],
+ )
+
+ assert result["task_screenshots"] == ["https://api.skyvern.com/v1/artifacts/s_2/content"]
+ assert result["workflow_screenshots"] == []
+ get_artifacts_by_ids.assert_awaited_once_with(["s_2"], "o_1")
+
+
@pytest.mark.asyncio
async def test_refresh_leaves_legacy_outputs_untouched():
"""Block outputs persisted before this change have no
@@ -521,3 +566,57 @@ async def test_refresh_fallback_skips_when_run_lookup_finds_no_match():
# No match → stored URL preserved.
assert refreshed["downloaded_files"][0]["url"] == "https://skyvern-uploads.s3.amazonaws.com/.../legacy.zip?sig=x"
+
+
[email protected]("via_artifact_ids", [True, False])
+async def test_refresh_decodes_local_snapshot_filenames(via_artifact_ids: bool):
+ # Local storage percent-encodes a retry snapshot's name in its file URI; block outputs and the
+ # legacy filename match must see the original name, not the encoded basename.
+ from skyvern.forge.sdk.workflow.service import WorkflowService
+
+ persisted_block_output = {
+ "task_id": "tsk_1",
+ "task_screenshot_artifact_ids": [],
+ "workflow_screenshot_artifact_ids": [],
+ "downloaded_file_artifact_ids": ["a_local"] if via_artifact_ids else None,
+ "downloaded_files": [
+ {
+ "url": "file:///tmp/downloads/wr_1/report%20%231.pdf",
+ "checksum": "sha-1",
+ "filename": "report #1.pdf",
+ "modified_at": None,
+ "artifact_id": "a_local" if via_artifact_ids else None,
+ }
+ ],
+ "downloaded_file_urls": ["file:///tmp/downloads/wr_1/report%20%231.pdf"],
+ }
+ snapshot = _make_artifact(
+ "a_local", "file:///tmp/artifacts/downloads/local/o_1/wr_1/attempts/2/report%20%231.pdf", checksum="sha-1"
+ )
+ fresh_url = "https://api.skyvern.com/v1/artifacts/a_local/content?sig=fresh"
+
+ with (
+ patch(
+ "skyvern.forge.sdk.workflow.service.app.DATABASE.artifacts.get_artifacts_by_ids",
+ new=AsyncMock(return_value=[snapshot]),
+ ),
+ patch(
+ "skyvern.forge.sdk.workflow.service.app.DATABASE.artifacts.list_artifacts_for_run_by_type",
+ new=AsyncMock(return_value=[snapshot]),
+ ),
+ patch(
+ "skyvern.forge.sdk.workflow.service.app.ARTIFACT_MANAGER.resolve_artifact_url_expiry_seconds",
+ new=AsyncMock(return_value=3600),
+ ),
+ patch(
+ "skyvern.forge.sdk.workflow.service.app.ARTIFACT_MANAGER.resolve_share_url",
+ new=AsyncMock(return_value=fresh_url),
+ ),
+ ):
+ refreshed = await WorkflowService()._refresh_output_urls(
+ persisted_block_output, organization_id="o_1", workflow_run_id="wr_1"
+ )
+
+ assert [(file["filename"], file["url"]) for file in refreshed["downloaded_files"]] == [("report #1.pdf", fresh_url)]
+ assert refreshed["downloaded_file_urls"] == [fresh_url]
diff --git a/tests/unit/test_cached_artifact_bundling.py b/tests/unit/test_cached_artifact_bundling.py
index 7e3b69c44..e4900dcf0 100644
--- a/tests/unit/test_cached_artifact_bundling.py
+++ b/tests/unit/test_cached_artifact_bundling.py
@@ -216,7 +216,7 @@ class TestUpdateWorkflowBlockFlush:
mock_app.DATABASE.tasks.update_step = AsyncMock()
mock_app.DATABASE.tasks.update_task = AsyncMock(return_value=MagicMock(extracted_information=None))
mock_app.DATABASE.observer.update_workflow_run_block = AsyncMock()
- mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
+ mock_app.STORAGE.get_current_attempt_downloaded_files = AsyncMock(return_value=[])
mock_app.WORKFLOW_SERVICE.get_recent_task_screenshot_artifacts = AsyncMock(return_value=[])
mock_app.WORKFLOW_SERVICE.get_recent_workflow_screenshot_artifacts = AsyncMock(return_value=[])
mock_app.WORKFLOW_SERVICE.send_workflow_response = AsyncMock()
@@ -275,7 +275,7 @@ class TestUpdateWorkflowBlockFlush:
mock_app.DATABASE.tasks.update_step = AsyncMock()
mock_app.DATABASE.tasks.update_task = AsyncMock(return_value=MagicMock(extracted_information=None))
mock_app.DATABASE.observer.update_workflow_run_block = AsyncMock()
- mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
+ mock_app.STORAGE.get_current_attempt_downloaded_files = AsyncMock(return_value=[])
mock_app.WORKFLOW_SERVICE.get_recent_task_screenshot_artifacts = AsyncMock(return_value=[])
mock_app.WORKFLOW_SERVICE.get_recent_workflow_screenshot_artifacts = AsyncMock(return_value=[])
mock_app.WORKFLOW_SERVICE.send_workflow_response = AsyncMock()
@@ -308,7 +308,7 @@ async def test_cached_billing_failure_marks_workflow_block_failed() -> None:
mock_app.DATABASE.tasks.update_task = AsyncMock(return_value=MagicMock(extracted_information=None))
mock_app.DATABASE.tasks.get_step = AsyncMock(return_value=MagicMock())
mock_app.DATABASE.observer.update_workflow_run_block = AsyncMock()
- mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
+ mock_app.STORAGE.get_current_attempt_downloaded_files = AsyncMock(return_value=[])
mock_app.WORKFLOW_SERVICE.get_recent_task_screenshot_artifacts = AsyncMock(return_value=[])
mock_app.WORKFLOW_SERVICE.get_recent_workflow_screenshot_artifacts = AsyncMock(return_value=[])
mock_app.AGENT_FUNCTION.post_cache_step_execution = AsyncMock(side_effect=RuntimeError("meter failed"))
diff --git a/tests/unit/test_cached_download_s3_upload.py b/tests/unit/test_cached_download_s3_upload.py
index 2f6cb4cda..d1b1593ae 100644
--- a/tests/unit/test_cached_download_s3_upload.py
+++ b/tests/unit/test_cached_download_s3_upload.py
@@ -11,6 +11,8 @@ Validates that the cached download flow:
from __future__ import annotations
import asyncio
+import os
+from datetime import UTC, datetime
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -18,6 +20,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from structlog.testing import capture_logs
+from skyvern.forge.sdk.api import files as files_module
+from skyvern.services import script_service
from tests.unit._fingerprint_expectations import expected_fingerprint
MODULE = "skyvern.services.script_service"
@@ -240,6 +244,7 @@ async def test_cached_download_awaits_in_flight_downloads_before_snapshot(setup,
download_dir=download_dir,
organization_id="o_test_org",
browser_session_id=None,
+ attempt_started_at=None,
)
with patch.object(
@@ -261,6 +266,7 @@ async def test_cached_download_awaits_in_flight_downloads_before_snapshot(setup,
download_dir=download_dir,
organization_id="o_test_org",
browser_session_id=None,
+ attempt_started_at=None,
)
dispatch_files.assert_awaited_once()
finally:
@@ -1092,3 +1098,83 @@ async def test_poll_succeeds_with_late_start_and_long_running_crdownload(setup,
refs["storage"].save_downloaded_files.assert_called_once()
finally:
_cleanup(refs)
+
+
+async def test_cached_download_does_not_dispatch_stale_file_appearing_after_baseline(setup, tmp_path: Path) -> None:
+ download_dir = tmp_path / "downloads"
+ started_at = datetime(2026, 1, 1, tzinfo=UTC)
+ stale = download_dir / "old.pdf"
+ fresh = download_dir / "fresh.pdf"
+ for path, offset in ((stale, -1), (fresh, 0)):
+ path.write_bytes(b"download")
+ os.utime(path, (started_at.timestamp() + offset,) * 2)
+ refs = setup(
+ get_side_effect=[[], ["fresh.pdf"]],
+ list_files_side_effect=[[], [str(stale), str(fresh)]],
+ )
+ try:
+ with (
+ patch(
+ "skyvern.forge.sdk.artifact.storage.base.resolve_download_attempt",
+ AsyncMock(return_value=("wr_test_run", 2, started_at)),
+ ),
+ patch.object(script_service.FileDownloadBlock, "_dispatch_files_to_storage", autospec=True) as dispatch,
+ ):
+ await script_service.download(
+ prompt="Download report",
+ label="test_block",
+ download_target="s3",
+ s3_bucket="bucket",
+ aws_access_key_id="access-key",
+ aws_secret_access_key="secret-key",
+ region_name="us-east-1",
+ )
+ assert dispatch.await_args.kwargs["files_to_upload"] == [str(fresh)]
+ refs["fallback"].assert_not_awaited()
+ finally:
+ _cleanup(refs)
+
+
+async def test_cached_retry_download_does_not_wait_for_retained_partial(setup):
+ refs = setup(get_side_effect=[[], ["current.pdf"]])
+ download_dir = refs["download_dir"]
+ stale = download_dir / "previous.pdf.crdownload"
+ stale.write_bytes(b"old partial")
+ os.utime(stale, (100, 100))
+ current = download_dir / "current.pdf"
+
+ async def download_current(*_args, **_kwargs):
+ current.write_bytes(b"new download")
+
+ refs["run_cached"].side_effect = download_current
+ try:
+ with (
+ patch(
+ "skyvern.forge.sdk.artifact.storage.base.resolve_download_attempt",
+ new=AsyncMock(return_value=("wr_test_run", 2, datetime.fromtimestamp(200, tz=UTC))),
+ ),
+ patch.object(script_service, "list_files_in_directory", files_module.list_files_in_directory),
+ patch.object(
+ script_service,
+ "check_downloading_files_and_wait_for_download_to_complete",
+ files_module.check_downloading_files_and_wait_for_download_to_complete,
+ ),
+ patch.object(script_service.FileDownloadBlock, "_dispatch_files_to_storage", new=AsyncMock()) as dispatch,
+ ):
+ async with asyncio.timeout(2):
+ await script_service.download(
+ prompt="Download report",
+ label="download",
+ download_target="s3",
+ s3_bucket="bucket",
+ aws_access_key_id="test-key",
+ aws_secret_access_key="test-secret",
+ region_name="us-east-1",
+ )
+ assert dispatch.await_args.kwargs["files_to_upload"] == [str(current)]
+ assert stale.read_bytes() == b"old partial"
+ refs["fallback"].assert_not_awaited()
+ finally:
+ _cleanup(refs)
diff --git a/tests/unit/test_code_block_downloads.py b/tests/unit/test_code_block_downloads.py
index 6b712e158..c1529014a 100644
--- a/tests/unit/test_code_block_downloads.py
+++ b/tests/unit/test_code_block_downloads.py
@@ -246,7 +246,8 @@ def _fake_storage_app(
),
STORAGE=SimpleNamespace(
save_downloaded_files=save,
- get_downloaded_files=get,
+ get_current_attempt_downloaded_files=get,
+ get_downloaded_file_signature_aliases=lambda _: [],
list_downloading_files_in_browser_session=in_flight or AsyncMock(return_value=[]),
),
AGENT_FUNCTION=SimpleNamespace(
diff --git a/tests/unit/test_code_block_downstream_sinks.py b/tests/unit/test_code_block_downstream_sinks.py
index d3565e72c..f730f03e9 100644
--- a/tests/unit/test_code_block_downstream_sinks.py
+++ b/tests/unit/test_code_block_downstream_sinks.py
@@ -24,6 +24,7 @@ from skyvern.forge.sdk.workflow.models.workflow import WorkflowRun, WorkflowRunS
from skyvern.forge.sdk.workflow.service import WorkflowService
from skyvern.schemas.workflows import BlockResult, BlockStatus
from skyvern.services import webhook_service
+from tests.unit.force_stub_app import make_workflow_run_attempts_fake
LONG_CREDENTIAL = "templated-password-very-long-13668"
SHORT_CREDENTIAL = "12"
@@ -119,6 +120,7 @@ async def _status_response_from_captured_output(
),
get_workflow_run_retried_by=AsyncMock(return_value=None),
),
+ workflow_run_attempts=make_workflow_run_attempts_fake(),
),
)
monkeypatch.setattr(app, "WORKFLOW_CONTEXT_MANAGER", SimpleNamespace(workflow_run_contexts={}))
diff --git a/tests/unit/test_code_block_sandbox.py b/tests/unit/test_code_block_sandbox.py
index 449cb8b56..b63d57c81 100644
--- a/tests/unit/test_code_block_sandbox.py
+++ b/tests/unit/test_code_block_sandbox.py
@@ -1067,7 +1067,7 @@ async def wrapper({default_args}):
values: dict[str, object] = {}
secrets: dict[str, object] = {}
include_secrets_in_templates = False
- organization_id = None
+ organization_id: str | None = None
workflow_title = "Test Workflow"
workflow_id = "w_test"
workflow_permanent_id = "wpid_test"
@@ -1150,7 +1150,7 @@ async def wrapper({default_args}):
values: dict[str, object] = {}
secrets: dict[str, object] = {}
include_secrets_in_templates = False
- organization_id = None
+ organization_id: str | None = None
workflow_title = "Test Workflow"
workflow_id = "w_test"
workflow_permanent_id = "wpid_test"
diff --git a/tests/unit/test_copilot_failure_publication.py b/tests/unit/test_copilot_failure_publication.py
index 4aa2d1cd3..465c9ade7 100644
--- a/tests/unit/test_copilot_failure_publication.py
+++ b/tests/unit/test_copilot_failure_publication.py
@@ -159,6 +159,7 @@ async def test_failure_is_committed_before_exact_page_capture_finishes(
engine="secure_runner",
resolved_download_id=None,
download_dir_before=None,
+ attempt_started_at=None,
)
)
await asyncio.wait_for(capture_started.wait(), timeout=1)
@@ -233,6 +234,7 @@ async def test_continuation_cancels_pending_capture_without_attaching(
engine="secure_runner",
resolved_download_id=None,
download_dir_before=None,
+ attempt_started_at=None,
)
await asyncio.wait_for(capture_started.wait(), timeout=1)
await context.cancel_failure_evidence_capture()
@@ -736,6 +738,7 @@ async def test_end_url_is_persisted_while_the_frame_is_still_stalled(
engine="secure_runner",
resolved_download_id=None,
download_dir_before=None,
+ attempt_started_at=None,
)
await asyncio.wait_for(capture_started.wait(), timeout=1)
@@ -831,6 +834,7 @@ async def test_capture_failure_leaves_committed_failure_intact(monkeypatch: pyte
engine="secure_runner",
resolved_download_id=None,
download_dir_before=None,
+ attempt_started_at=None,
)
await asyncio.wait_for(capture_attempted.wait(), timeout=1)
await context.drain_failure_evidence_capture()
@@ -870,6 +874,7 @@ async def test_missing_page_publishes_failure_without_starting_capture(monkeypat
engine="inline",
resolved_download_id=None,
download_dir_before=None,
+ attempt_started_at=None,
)
assert result.failure_reason == failure_reason
diff --git a/tests/unit/test_credential_fallback.py b/tests/unit/test_credential_fallback.py
index ef5f0ae7c..64a1a650f 100644
--- a/tests/unit/test_credential_fallback.py
+++ b/tests/unit/test_credential_fallback.py
@@ -23,6 +23,7 @@ from skyvern.forge.sdk.workflow.models.workflow import WorkflowRun, WorkflowRunS
from skyvern.forge.sdk.workflow.service import WorkflowService
from skyvern.forge.sdk.workflow.workflow_definition_converter import convert_workflow_definition
from skyvern.schemas.workflows import CredentialParameterYAML, WorkflowDefinitionYAML
+from tests.unit.force_stub_app import make_workflow_run_attempts_fake
def _credential_parameter(
@@ -903,6 +904,7 @@ async def test_clean_up_workflow_schedules_credential_fallback_retry() -> None:
mock_app.WORKFLOW_CONTEXT_MANAGER.has_workflow_run_context.return_value = False
mock_app.WORKFLOW_CONTEXT_MANAGER.remove_workflow_run_context = MagicMock()
mock_app.AGENT_FUNCTION.on_workflow_run_terminal = AsyncMock()
+ mock_app.DATABASE.workflow_run_attempts = make_workflow_run_attempts_fake()
await service.clean_up_workflow(
workflow=workflow,
@@ -942,6 +944,7 @@ async def test_clean_up_workflow_preserves_body_success_without_retrying_finally
mock_app.WORKFLOW_CONTEXT_MANAGER.has_workflow_run_context.return_value = False
mock_app.WORKFLOW_CONTEXT_MANAGER.remove_workflow_run_context = MagicMock()
mock_app.AGENT_FUNCTION.on_workflow_run_terminal = AsyncMock()
+ mock_app.DATABASE.workflow_run_attempts = make_workflow_run_attempts_fake()
await service.clean_up_workflow(
workflow=workflow,
@@ -986,6 +989,7 @@ async def test_clean_up_workflow_schedules_retry_even_when_webhook_raises() -> N
mock_app.WORKFLOW_CONTEXT_MANAGER.has_workflow_run_context.return_value = False
mock_app.WORKFLOW_CONTEXT_MANAGER.remove_workflow_run_context = MagicMock()
mock_app.AGENT_FUNCTION.on_workflow_run_terminal = AsyncMock()
+ mock_app.DATABASE.workflow_run_attempts = make_workflow_run_attempts_fake()
with pytest.raises(RuntimeError):
await service.clean_up_workflow(
@@ -1025,6 +1029,7 @@ async def test_clean_up_workflow_schedules_retry_when_earlier_cleanup_step_raise
mock_app.WORKFLOW_CONTEXT_MANAGER.has_workflow_run_context.return_value = False
mock_app.WORKFLOW_CONTEXT_MANAGER.remove_workflow_run_context = MagicMock()
mock_app.AGENT_FUNCTION.on_workflow_run_terminal = AsyncMock()
+ mock_app.DATABASE.workflow_run_attempts = make_workflow_run_attempts_fake()
with pytest.raises(RuntimeError):
await service.clean_up_workflow(
diff --git a/tests/unit/test_credential_rotation.py b/tests/unit/test_credential_rotation.py
index d57bb570d..75eef23ed 100644
--- a/tests/unit/test_credential_rotation.py
+++ b/tests/unit/test_credential_rotation.py
@@ -1,12 +1,16 @@
from __future__ import annotations
-from datetime import datetime, timedelta, timezone
+import asyncio
+import random
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
from types import SimpleNamespace
+from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
import pytest_asyncio
-from sqlalchemy import func, select
+from sqlalchemy import event, func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncEngine
@@ -19,13 +23,27 @@ from skyvern.exceptions import (
from skyvern.forge.sdk.copilot.output_policy import OutputPolicyReason, evaluate_output_policy
from skyvern.forge.sdk.copilot.request_policy import RequestPolicy
from skyvern.forge.sdk.db.agent_db import AgentDB, _build_engine
-from skyvern.forge.sdk.db.models import Base, WorkflowRunCredentialSelectionModel
+from skyvern.forge.sdk.db.models import (
+ Base,
+ CredentialModel,
+ CredentialParameterModel,
+ WorkflowModel,
+ WorkflowRunAttemptModel,
+ WorkflowRunCredentialSelectionModel,
+ WorkflowRunModel,
+)
+from skyvern.forge.sdk.db.repositories import workflow_runs as workflow_runs_repository_module
from skyvern.forge.sdk.db.repositories.workflow_run_credential_selections import (
WorkflowRunCredentialSelectionsRepository,
)
+from skyvern.forge.sdk.workflow import credential_selection as credential_selection_module
+from skyvern.forge.sdk.workflow import retry_policy as retry_policy_module
from skyvern.forge.sdk.workflow.browser_profile_key import build_browser_profile_key_digest
from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
-from skyvern.forge.sdk.workflow.credential_selection import select_credential_for_run
+from skyvern.forge.sdk.workflow.credential_selection import (
+ clear_credential_selections_for_retry,
+ select_credential_for_run,
+)
from skyvern.forge.sdk.workflow.models.parameter import (
ContextParameter,
CredentialParameter,
@@ -34,7 +52,7 @@ from skyvern.forge.sdk.workflow.models.parameter import (
WorkflowParameter,
WorkflowParameterType,
)
-from skyvern.forge.sdk.workflow.models.workflow import WorkflowRequestBody
+from skyvern.forge.sdk.workflow.models.workflow import WorkflowDefinition, WorkflowRequestBody
from skyvern.forge.sdk.workflow.service import WorkflowService
from skyvern.forge.sdk.workflow.workflow_definition_converter import convert_workflow_definition
from skyvern.schemas.workflows import CredentialParameterYAML, WorkflowDefinitionYAML
@@ -47,7 +65,7 @@ def _credential_parameter(
credential_ids: list[str] | None = None,
selection_strategy: str | None = None,
) -> CredentialParameter:
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
return CredentialParameter(
key=key,
credential_parameter_id=f"cp_{key}",
@@ -64,7 +82,7 @@ def _workflow_parameter(
key: str,
workflow_parameter_type: WorkflowParameterType = WorkflowParameterType.STRING,
) -> WorkflowParameter:
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
return WorkflowParameter(
key=key,
workflow_parameter_id=f"wp_{key}",
@@ -192,7 +210,7 @@ async def _select(repo: _SelectionRepo, credential_ids: list[str], strategy: str
@pytest.mark.asyncio
async def test_round_robin_picks_unseen_first() -> None:
- repo = _SelectionRepo(latest={"cred_a": datetime.now(timezone.utc)})
+ repo = _SelectionRepo(latest={"cred_a": datetime.now(UTC)})
selected = await _select(repo, ["cred_a", "cred_b", "cred_c"])
@@ -202,7 +220,7 @@ async def test_round_robin_picks_unseen_first() -> None:
@pytest.mark.asyncio
async def test_round_robin_picks_oldest_last_used_and_ties_by_list_order() -> None:
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
repo = _SelectionRepo(latest={"cred_a": now, "cred_b": now - timedelta(minutes=5), "cred_c": now})
selected = await _select(repo, ["cred_a", "cred_b", "cred_c"])
@@ -322,7 +340,7 @@ async def test_select_rotating_credentials_keeps_override_and_selects_remaining(
def _fallback_only_credential_parameter() -> CredentialParameter:
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
return CredentialParameter(
key="login_cred",
credential_parameter_id="cp_login",
@@ -361,7 +379,7 @@ async def test_select_render_resolves_indirect_fallback_primary_from_parameter_v
# 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)
+ now = datetime.now(UTC)
service = WorkflowService()
workflow = _setup_workflow_with_rotating_credential(browser_profile_key="{{ login_cred }}")
workflow.workflow_definition.parameters = [
@@ -795,7 +813,7 @@ async def _attempt_setup_rotation_profile_run(
workflow_permanent_id="wpid_test",
organization=organization,
)
- except Exception as exc:
+ except RuntimeError as exc:
caught = exc
return result, mock_app, service, caught
@@ -890,8 +908,10 @@ async def test_direct_bindings_snapshot_only_opted_in_credentials_and_runtime_re
parallel_context = _runtime_context()
assert workflow_run.sequential_credential_id == "cred_serial"
- assert await sequential_context.resolve_credential_parameter_id(sequential, "org_test") == "cred_serial"
- assert await parallel_context.resolve_credential_parameter_id(parallel, "org_test") == "cred_parallel"
+ with patch("skyvern.forge.sdk.workflow.context_manager.app") as context_app:
+ context_app.DATABASE.workflow_run_credential_selections = _SelectionRepo()
+ assert await sequential_context.resolve_credential_parameter_id(sequential, "org_test") == "cred_serial"
+ assert await parallel_context.resolve_credential_parameter_id(parallel, "org_test") == "cred_parallel"
@pytest.mark.asyncio
@@ -920,7 +940,9 @@ async def test_plain_indirect_binding_snapshots_and_runtime_resolves_bound_param
context.values[account_parameter.key] = "cred_runtime"
assert workflow_run.sequential_credential_id == "cred_runtime"
- assert await context.resolve_credential_parameter_id(login, "org_test") == "cred_runtime"
+ with patch("skyvern.forge.sdk.workflow.context_manager.app") as context_app:
+ context_app.DATABASE.workflow_run_credential_selections = _SelectionRepo()
+ assert await context.resolve_credential_parameter_id(login, "org_test") == "cred_runtime"
assert context.get_resolved_credential_parameter_id(login.key) == "cred_runtime"
@@ -944,7 +966,7 @@ async def test_runtime_only_indirect_binding_defers_credential_validation_until_
runtime_parameter_type: str,
) -> None:
source = _workflow_parameter("source")
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
runtime_parameter = (
ContextParameter(key="runtime_credential", source=source)
if runtime_parameter_type == "context"
@@ -977,6 +999,7 @@ async def test_runtime_only_indirect_binding_fails_closed_if_resolved_credential
organization = SimpleNamespace(organization_id="org_test")
with patch("skyvern.forge.sdk.workflow.context_manager.app") as mock_app:
+ mock_app.DATABASE.workflow_run_credential_selections = _SelectionRepo()
mock_app.DATABASE.credentials.get_credential = AsyncMock(
return_value=SimpleNamespace(credential_id="cred_runtime", run_sequentially=True)
)
@@ -1022,6 +1045,7 @@ async def test_runtime_credential_registration_proceeds_when_lane_is_safe(
credential_service.get_credential_item = AsyncMock(return_value=SimpleNamespace(credential=credential))
with patch("skyvern.forge.sdk.workflow.context_manager.app") as mock_app:
+ mock_app.DATABASE.workflow_run_credential_selections = _SelectionRepo()
mock_app.DATABASE.credentials.get_credential = AsyncMock(return_value=db_credential)
mock_app.DATABASE.workflow_runs.get_workflow_run = AsyncMock(
return_value=SimpleNamespace(sequential_credential_id=stamped_credential_id)
@@ -1053,8 +1077,12 @@ async def test_keyed_rotation_snapshot_and_runtime_reuse_one_persisted_selection
selection_repo=repo,
)
context = _runtime_context()
- with patch("skyvern.forge.sdk.workflow.credential_selection.app") as selection_app:
+ with (
+ patch("skyvern.forge.sdk.workflow.credential_selection.app") as selection_app,
+ patch("skyvern.forge.sdk.workflow.context_manager.app") as context_app,
+ ):
selection_app.DATABASE.workflow_run_credential_selections = repo
+ context_app.DATABASE.workflow_run_credential_selections = repo
runtime_credential_id = await context.resolve_credential_parameter_id(login, "org_test")
assert workflow_run.sequential_credential_id == "cred_a"
@@ -1242,3 +1270,798 @@ async def test_keyed_rotation_selection_failure_fails_closed_even_with_non_seque
SimpleNamespace(credential_id="cred_b", run_sequentially=False),
],
)
+
+
+def _retry_workflow(parameter: CredentialParameter) -> WorkflowModel:
+ return WorkflowModel(
+ workflow_id="wf_test",
+ workflow_permanent_id="wpid_test",
+ organization_id="org_test",
+ title="Credential rotation",
+ workflow_definition=WorkflowDefinition(parameters=[parameter], blocks=[]).model_dump(mode="json"),
+ )
+
+
+async def test_retry_rebinds_only_its_run_and_organization_selections(sqlite_db) -> None:
+ repo = sqlite_db.workflow_run_credential_selections
+ await sqlite_db.organizations.create_organization("Test", organization_id="org_test")
+ async with sqlite_db.Session() as session:
+ session.add(_retry_workflow(_credential_parameter(key="login", credential_ids=["cred_a", "cred_b"])))
+ session.add(
+ WorkflowRunModel(
+ workflow_run_id="wr_retry",
+ workflow_id="wf_test",
+ workflow_permanent_id="wpid_test",
+ organization_id="org_test",
+ status="failed",
+ )
+ )
+ session.add_all(
+ CredentialModel(
+ credential_id=credential_id,
+ organization_id="org_test",
+ name="Login",
+ credential_type="password",
+ )
+ for credential_id in ["cred_a", "cred_b"]
+ )
+ await session.commit()
+ for run_id, org_id, key in (
+ ("wr_retry", "org_test", "login"),
+ ("wr_other", "org_test", "other_login"),
+ ("wr_retry", "org_other", "other_login"),
+ ):
+ await repo.create_selection(
+ organization_id=org_id,
+ workflow_run_id=run_id,
+ workflow_permanent_id="wpid_test",
+ parameter_key=key,
+ credential_id="cred_a",
+ )
+ with patch("skyvern.forge.sdk.workflow.credential_selection.app") as selection_app:
+ selection_app.DATABASE = sqlite_db
+ workflow = await sqlite_db.workflows.get_workflow("wf_test", organization_id="org_test")
+ assert workflow is not None
+ previous_history = await repo.get_latest_selections(
+ organization_id="org_test",
+ workflow_permanent_id="wpid_test",
+ parameter_key="login",
+ credential_ids=["cred_a", "cred_b"],
+ )
+ await clear_credential_selections_for_retry(
+ "wr_retry", "org_test", attempt_number=1, workflow_definition=workflow.workflow_definition
+ )
+ assert await repo.get_selection("wr_retry", "login") == "cred_a"
+ await clear_credential_selections_for_retry(
+ "wr_retry", "org_test", attempt_number=2, workflow_definition=workflow.workflow_definition
+ )
+ assert await repo.get_selection("wr_retry", "login") == "cred_b"
+ selected = await select_credential_for_run(
+ workflow_run_id="wr_retry",
+ organization_id="org_test",
+ workflow_permanent_id="wpid_test",
+ parameter_key="login",
+ credential_ids=["cred_a", "cred_b"],
+ selection_strategy=None,
+ )
+ assert selected == "cred_b"
+ history = await repo.get_latest_selections(
+ organization_id="org_test",
+ workflow_permanent_id="wpid_test",
+ parameter_key="login",
+ credential_ids=["cred_a", "cred_b"],
+ )
+ assert history.keys() == {"cred_a", "cred_b"}
+ assert history["cred_a"] == previous_history["cred_a"]
+ assert await repo.get_selections_for_run("wr_retry") == {"login": "cred_b", "other_login": "cred_a"}
+ assert await repo.get_selection("wr_other", "other_login") == "cred_a"
+ assert await repo.get_selection("wr_retry", "other_login") == "cred_a"
+ with patch("skyvern.forge.sdk.workflow.credential_selection.app") as selection_app:
+ selection_app.DATABASE = sqlite_db
+ await clear_credential_selections_for_retry(
+ "wr_retry", "org_test", attempt_number=3, workflow_definition=workflow.workflow_definition
+ )
+ assert await repo.get_selection("wr_retry", "login") == "cred_a"
+ assert (
+ await select_credential_for_run(
+ workflow_run_id="wr_retry",
+ organization_id="org_test",
+ workflow_permanent_id="wpid_test",
+ parameter_key="login",
+ credential_ids=["cred_a", "cred_b"],
+ selection_strategy=None,
+ )
+ == "cred_a"
+ )
+ async with sqlite_db.Session() as session:
+ rows = (
+ await session.execute(
+ select(
+ WorkflowRunCredentialSelectionModel.workflow_run_id,
+ WorkflowRunCredentialSelectionModel.credential_id,
+ ).where(
+ WorkflowRunCredentialSelectionModel.organization_id == "org_test",
+ WorkflowRunCredentialSelectionModel.parameter_key == "login",
+ )
+ )
+ ).all()
+ assert set(rows) == {("wr_retry:attempt:1", "cred_a"), ("wr_retry:attempt:2", "cred_b"), ("wr_retry", "cred_a")}
+
+
[email protected]("failure_statement", ["UPDATE", "INSERT INTO"])
+async def test_next_attempt_preparation_atomically_clears_and_reselects_credentials(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ failure_statement: str,
+) -> None:
+ url = f"sqlite+aiosqlite:///{tmp_path / 'credentials.db'}"
+ engine = _build_engine(url)
+ async with engine.begin() as connection:
+ await connection.run_sync(Base.metadata.create_all)
+ database = AgentDB(url, db_engine=engine)
+ stub = SimpleNamespace(
+ DATABASE=database, WORKFLOW_CONTEXT_MANAGER=SimpleNamespace(remove_workflow_run_context=lambda _run: None)
+ )
+ monkeypatch.setattr(retry_policy_module, "app", stub)
+ monkeypatch.setattr(credential_selection_module, "app", stub)
+ repo = database.workflow_run_credential_selections
+ try:
+ await database.organizations.create_organization("Test", organization_id="org_test")
+ async with database.Session() as session:
+ session.add(_retry_workflow(_credential_parameter(key="login", credential_ids=["cred_a", "cred_b"])))
+ session.add_all(
+ CredentialModel(
+ credential_id=credential_id,
+ organization_id="org_test",
+ name="Login",
+ credential_type="password",
+ )
+ for credential_id in ["cred_a", "cred_b"]
+ )
+ session.add_all(
+ [
+ WorkflowRunModel(
+ workflow_run_id="wr_retry",
+ workflow_id="wf_test",
+ workflow_permanent_id="wpid_test",
+ organization_id="org_test",
+ status="failed",
+ ),
+ WorkflowRunModel(
+ workflow_run_id="wr_legacy",
+ workflow_id="wf_test",
+ workflow_permanent_id="wpid_test",
+ organization_id="org_test",
+ status="failed",
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_retry",
+ organization_id="org_test",
+ attempt_number=1,
+ status="failed",
+ retry_decision="retry",
+ ),
+ ]
+ )
+ await session.commit()
+ for run_id, org_id, key in (
+ ("wr_retry", "org_test", "login"),
+ ("wr_other", "org_test", "login"),
+ ("wr_retry", "org_other", "other_login"),
+ ("wr_legacy", "org_test", "login"),
+ ):
+ await repo.create_selection(
+ organization_id=org_id,
+ workflow_run_id=run_id,
+ workflow_permanent_id="wpid_test",
+ parameter_key=key,
+ credential_id="cred_a",
+ )
+ legacy = await retry_policy_module.prepare_next_attempt_result("wr_legacy", "org_test", 1)
+ assert legacy.status == "failed"
+ assert await repo.get_selection("wr_legacy", "login") == "cred_a"
+
+ def fail_after_clear(
+ _connection: Any,
+ _cursor: Any,
+ statement: str,
+ _parameters: Any,
+ _context: Any,
+ _many: bool,
+ ) -> None:
+ if statement.startswith(f"{failure_statement} workflow_run_credential_selections"):
+ raise RuntimeError("crash after credential archive before preparation commit")
+
+ event.listen(engine.sync_engine, "after_cursor_execute", fail_after_clear)
+ try:
+ with pytest.raises(RuntimeError, match="crash after credential archive"):
+ await retry_policy_module.prepare_next_attempt_result("wr_retry", "org_test", 1)
+ finally:
+ event.remove(engine.sync_engine, "after_cursor_execute", fail_after_clear)
+ assert await repo.get_selection("wr_retry", "login") == "cred_a"
+ attempts = await database.workflow_run_attempts.get_attempts("wr_retry")
+ assert len(attempts) == 1 and attempts[0].next_attempt_prepared_at is None
+ run = await database.workflow_runs.get_workflow_run("wr_retry")
+ assert run is not None and run.status.value == "failed"
+
+ # Both real preparation callers observe attempt 1. Only the winning transaction may clear.
+ cleared = asyncio.Event()
+ release_commit = asyncio.Event()
+ clear_calls = 0
+ clear = workflow_runs_repository_module.clear_credential_selections_for_retry
+
+ async def pause_before_commit(*args: Any, **kwargs: Any) -> None:
+ nonlocal clear_calls
+ clear_calls += 1
+ await clear(*args, **kwargs)
+ cleared.set()
+ await release_commit.wait()
+
+ monkeypatch.setattr(
+ workflow_runs_repository_module, "clear_credential_selections_for_retry", pause_before_commit
+ )
+ winner = asyncio.create_task(retry_policy_module.prepare_next_attempt_result("wr_retry", "org_test", 1))
+ loser = None
+ try:
+ await asyncio.wait_for(cleared.wait(), timeout=5)
+ assert await repo.get_selection("wr_retry", "login") == "cred_a"
+ loser = asyncio.create_task(retry_policy_module.prepare_next_attempt_result("wr_retry", "org_test", 1))
+ release_commit.set()
+ result = await winner
+ assert result.status == "inserted"
+ assert await repo.get_selection("wr_retry", "login") == "cred_b"
+ selected = await select_credential_for_run(
+ workflow_run_id="wr_retry",
+ organization_id="org_test",
+ workflow_permanent_id="wpid_test",
+ parameter_key="login",
+ credential_ids=["cred_a", "cred_b"],
+ selection_strategy=None,
+ )
+ assert selected == "cred_b"
+ assert (await loser).status in {"already_prepared", "failed"}
+ finally:
+ release_commit.set()
+ await asyncio.gather(winner, *([loser] if loser is not None else []), return_exceptions=True)
+ assert clear_calls == 1
+ repeat = await retry_policy_module.prepare_next_attempt_result("wr_retry", "org_test", 1)
+ assert repeat.status == "already_prepared"
+ assert await repo.get_selection("wr_retry", "login") == "cred_b"
+ assert await repo.get_selection("wr_other", "login") == "cred_a"
+ assert await repo.get_selection("wr_retry", "other_login") == "cred_a"
+ assert await repo.get_selection("wr_legacy", "login") == "cred_a"
+ assert [row.attempt_number for row in await database.workflow_run_attempts.get_attempts("wr_retry")] == [1, 2]
+ finally:
+ await engine.dispose()
+
+
+ "pool_kind",
+ [
+ "sequential",
+ "mixed",
+ "unverified",
+ "fallback",
+ "stale_metadata",
+ "missing_metadata",
+ "fallback_only_empty",
+ "fallback_only_absent",
+ ],
+)
+async def test_retry_retains_credential_pool_binding_when_new_lane_cannot_be_admitted(
+ sqlite_db: AgentDB,
+ monkeypatch: pytest.MonkeyPatch,
+ pool_kind: str,
+) -> None:
+ sequential_credential_id = "cred_a" if pool_kind == "sequential" else None
+ await sqlite_db.organizations.create_organization("Test", organization_id="org_test")
+ fallback_only = pool_kind in {"fallback", "fallback_only_empty", "fallback_only_absent"}
+ parameter = _credential_parameter(
+ credential_ids=["cred_a"] if pool_kind == "stale_metadata" else ["cred_a", "cred_b"]
+ )
+ if fallback_only:
+ parameter = parameter.model_copy(
+ update={
+ "credential_id": "cred_b",
+ "credential_ids": [] if pool_kind == "fallback_only_empty" else None,
+ "fallback_credential_ids": ["cred_a"],
+ }
+ )
+ async with sqlite_db.Session() as session:
+ session.add_all(
+ [
+ _retry_workflow(parameter),
+ WorkflowRunModel(
+ workflow_run_id="wr_test",
+ workflow_id="wf_test",
+ workflow_permanent_id="wpid_test",
+ organization_id="org_test",
+ status="failed",
+ sequential_credential_id=sequential_credential_id,
+ fallback_attempt=1 if fallback_only else 0,
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_test",
+ organization_id="org_test",
+ attempt_number=1,
+ status="failed",
+ retry_decision="retry",
+ ),
+ CredentialModel(
+ credential_id="cred_a",
+ organization_id="org_test",
+ name="Login",
+ credential_type="password",
+ item_id="item_a",
+ run_sequentially=pool_kind == "sequential",
+ ),
+ ]
+ )
+ if pool_kind != "missing_metadata":
+ session.add(
+ CredentialParameterModel(
+ workflow_id="wf_test",
+ key="login_cred",
+ credential_id=parameter.credential_id,
+ credential_ids=parameter.credential_ids,
+ fallback_credential_ids=parameter.fallback_credential_ids,
+ )
+ )
+ if pool_kind != "unverified":
+ session.add(
+ CredentialModel(
+ credential_id="cred_b",
+ organization_id="org_test",
+ name="Alternate login",
+ credential_type="password",
+ item_id="item_b",
+ run_sequentially=pool_kind not in {"fallback_only_empty", "fallback_only_absent"},
+ )
+ )
+ await session.commit()
+ repo = sqlite_db.workflow_run_credential_selections
+ if fallback_only:
+ await repo.create_selection(
+ organization_id="org_test",
+ workflow_run_id="wr_test",
+ workflow_permanent_id="wpid_test",
+ parameter_key="login_cred",
+ credential_id="cred_a",
+ )
+ stub = SimpleNamespace(
+ DATABASE=sqlite_db, WORKFLOW_CONTEXT_MANAGER=SimpleNamespace(remove_workflow_run_context=lambda _run: None)
+ )
+ monkeypatch.setattr(retry_policy_module, "app", stub)
+ monkeypatch.setattr(credential_selection_module, "app", stub)
+
+ credential = MagicMock()
+ credential.model_dump.return_value = {}
+ credential_service = MagicMock()
+ credential_service.get_credential_item = AsyncMock(return_value=SimpleNamespace(credential=credential))
+ with patch("skyvern.forge.sdk.workflow.context_manager.app") as context_app:
+ context_app.DATABASE = sqlite_db
+ context_app.CREDENTIAL_VAULT_SERVICES.get.return_value = credential_service
+ context_app.AGENT_FUNCTION.process_registered_credential_item = AsyncMock(
+ side_effect=lambda *, workflow_run_id, db_credential, credential_item: credential_item
+ )
+ first_context = _runtime_context()
+ workflow = await sqlite_db.workflows.get_workflow("wf_test", organization_id="org_test")
+ assert workflow is not None
+ await first_context.register_credential_parameter_value(
+ workflow.workflow_definition.parameters[0],
+ SimpleNamespace(organization_id="org_test"),
+ )
+ assert first_context.get_resolved_credential_parameter_id("login_cred") == "cred_a"
+
+ if pool_kind == "stale_metadata":
+ parameter = parameter.model_copy(update={"credential_ids": ["cred_a", "cred_b"]})
+ await sqlite_db.workflows.update_workflow_and_reconcile_definition_params(
+ "wf_test",
+ organization_id="org_test",
+ workflow_definition=WorkflowDefinition(parameters=[parameter], blocks=[]),
+ )
+ if pool_kind in {"stale_metadata", "missing_metadata"}:
+ async with sqlite_db.Session() as session:
+ metadata = await session.scalar(
+ select(CredentialParameterModel).where(CredentialParameterModel.workflow_id == "wf_test")
+ )
+ if pool_kind == "stale_metadata":
+ assert metadata is not None and metadata.credential_ids == ["cred_a"]
+ else:
+ assert metadata is None
+
+ preparation = await retry_policy_module.prepare_next_attempt_result("wr_test", "org_test", 1)
+ assert preparation.status == "inserted"
+ assert preparation.serialized_identity is (pool_kind == "sequential")
+ workflow = await sqlite_db.workflows.get_workflow("wf_test", organization_id="org_test")
+ assert workflow is not None
+ context = _runtime_context()
+ await context.register_credential_parameter_value(
+ workflow.workflow_definition.parameters[0],
+ SimpleNamespace(organization_id="org_test"),
+ )
+ assert context.get_resolved_credential_parameter_id("login_cred") == "cred_a"
+ run = await sqlite_db.workflow_runs.get_workflow_run("wr_test", "org_test")
+ assert run is not None and run.sequential_credential_id == sequential_credential_id
+ assert run.fallback_attempt == (1 if fallback_only else 0)
+ assert await repo.get_selections_for_run("wr_test") == {"login_cred": "cred_a"}
+
+
+@pytest_asyncio.fixture
+async def retry_rotation_db(sqlite_db: AgentDB, monkeypatch: pytest.MonkeyPatch) -> AgentDB:
+ await sqlite_db.organizations.create_organization("Test", organization_id="org_test")
+ async with sqlite_db.Session() as session:
+ session.add_all(
+ [
+ _retry_workflow(_credential_parameter(credential_ids=["cred_a", "cred_b"])),
+ WorkflowRunModel(
+ workflow_run_id="wr_test",
+ workflow_id="wf_test",
+ workflow_permanent_id="wpid_test",
+ organization_id="org_test",
+ status="failed",
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_test",
+ organization_id="org_test",
+ attempt_number=1,
+ status="failed",
+ retry_decision="retry",
+ ),
+ *[
+ CredentialModel(
+ credential_id=credential_id,
+ organization_id="org_test",
+ name="Login",
+ credential_type="password",
+ item_id=f"item_{credential_id}",
+ run_sequentially=False,
+ )
+ for credential_id in ["cred_a", "cred_b"]
+ ],
+ ]
+ )
+ await session.commit()
+ monkeypatch.setattr(credential_selection_module, "app", SimpleNamespace(DATABASE=sqlite_db))
+ return sqlite_db
+
+
+async def test_retry_registers_prepared_binding_after_definition_edit(retry_rotation_db: AgentDB) -> None:
+ database = retry_rotation_db
+ repo = database.workflow_run_credential_selections
+ parameter = _credential_parameter(credential_ids=["cred_a"])
+ async with database.Session() as session:
+ workflow = await session.get(WorkflowModel, "wf_test")
+ workflow.workflow_definition = WorkflowDefinition(parameters=[parameter], blocks=[]).model_dump(mode="json")
+ credential_b = await session.get(CredentialModel, "cred_b")
+ credential_b.run_sequentially = True
+ await session.commit()
+ await repo.create_selection(
+ organization_id="org_test",
+ workflow_run_id="wr_test",
+ workflow_permanent_id="wpid_test",
+ parameter_key="login_cred",
+ credential_id="cred_a",
+ )
+ preparation = await database.workflow_runs.prepare_next_attempt_atomic("wr_test", "org_test", 1, "failed", None)
+ assert preparation.status == "inserted"
+ prepared_credential = await repo.get_selection("wr_test", "login_cred")
+ parameter = parameter.model_copy(update={"credential_ids": ["cred_a", "cred_b"]})
+ await database.workflows.update_workflow_and_reconcile_definition_params(
+ "wf_test",
+ organization_id="org_test",
+ workflow_definition=WorkflowDefinition(parameters=[parameter], blocks=[]),
+ )
+ workflow = await database.workflows.get_workflow("wf_test", organization_id="org_test")
+ assert workflow is not None
+ credential = MagicMock()
+ credential.model_dump.return_value = {}
+ credential_service = MagicMock()
+ credential_service.get_credential_item = AsyncMock(return_value=SimpleNamespace(credential=credential))
+ with patch("skyvern.forge.sdk.workflow.context_manager.app") as context_app:
+ context_app.DATABASE = database
+ context_app.CREDENTIAL_VAULT_SERVICES.get.return_value = credential_service
+ context_app.AGENT_FUNCTION.process_registered_credential_item = AsyncMock(
+ side_effect=lambda *, workflow_run_id, db_credential, credential_item: credential_item
+ )
+ context = _runtime_context()
+ await context.register_credential_parameter_value(
+ workflow.workflow_definition.parameters[0], SimpleNamespace(organization_id="org_test")
+ )
+ assert context.get_resolved_credential_parameter_id("login_cred") == prepared_credential == "cred_a"
+ assert context.has_value("login_cred")
+ run = await database.workflow_runs.get_workflow_run("wr_test", "org_test")
+ assert run is not None and run.sequential_credential_id is None
+ assert await repo.get_selections_for_run("wr_test") == {"login_cred": "cred_a"}
+
+
[email protected]("history_kind", ["unseen", "oldest", "tie"])
+async def test_retry_preparation_binds_lru_and_alternates(retry_rotation_db: AgentDB, history_kind: str) -> None:
+ database = retry_rotation_db
+ repo = database.workflow_run_credential_selections
+ now = datetime.now(UTC).replace(tzinfo=None)
+ async with database.Session() as session:
+ session.add(
+ WorkflowRunCredentialSelectionModel(
+ organization_id="org_test",
+ workflow_run_id="wr_test",
+ workflow_permanent_id="wpid_test",
+ parameter_key="login_cred",
+ credential_id="cred_a",
+ created_at=now - timedelta(minutes=1),
+ )
+ )
+ if history_kind != "unseen":
+ session.add(
+ WorkflowRunCredentialSelectionModel(
+ organization_id="org_test",
+ workflow_run_id="wr_history",
+ workflow_permanent_id="wpid_test",
+ parameter_key="login_cred",
+ credential_id="cred_b",
+ created_at=now - timedelta(minutes=1 if history_kind == "tie" else 2),
+ )
+ )
+ if history_kind == "tie":
+ workflow = await session.get(WorkflowModel, "wf_test")
+ workflow.workflow_definition = WorkflowDefinition(
+ parameters=[_credential_parameter(credential_ids=["cred_b", "cred_a"])], blocks=[]
+ ).model_dump(mode="json")
+ await session.commit()
+ for from_attempt, expected_credential in [(1, "cred_b"), (2, "cred_a"), (3, "cred_b")]:
+ preparation = await database.workflow_runs.prepare_next_attempt_atomic(
+ "wr_test", "org_test", from_attempt, "failed", None
+ )
+ assert preparation.status == "inserted"
+ assert await repo.get_selection("wr_test", "login_cred") == expected_credential
+ async with database.Session() as session:
+ run = await session.get(WorkflowRunModel, "wr_test")
+ run.status = "failed"
+ attempt = await session.scalar(
+ select(WorkflowRunAttemptModel).where(
+ WorkflowRunAttemptModel.workflow_run_id == "wr_test",
+ WorkflowRunAttemptModel.attempt_number == from_attempt + 1,
+ )
+ )
+ attempt.status = "failed"
+ attempt.retry_decision = "retry"
+ await session.commit()
+ async with database.Session() as session:
+ bindings = (
+ await session.execute(
+ select(
+ WorkflowRunCredentialSelectionModel.workflow_run_id,
+ WorkflowRunCredentialSelectionModel.credential_id,
+ ).where(WorkflowRunCredentialSelectionModel.workflow_run_id != "wr_history")
+ )
+ ).all()
+ assert set(bindings) == {
+ ("wr_test:attempt:1", "cred_a"),
+ ("wr_test:attempt:2", "cred_b"),
+ ("wr_test:attempt:3", "cred_a"),
+ ("wr_test", "cred_b"),
+ }
+
+
[email protected]("pool", [["cred_a", "cred_b", "cred_c"], ["cred_a"]])
+async def test_retry_preparation_uses_random_strategy(
+ retry_rotation_db: AgentDB, monkeypatch: pytest.MonkeyPatch, pool: list[str]
+) -> None:
+ database = retry_rotation_db
+ async with database.Session() as session:
+ workflow = await session.get(WorkflowModel, "wf_test")
+ workflow.workflow_definition = WorkflowDefinition(
+ parameters=[_credential_parameter(credential_ids=pool, selection_strategy="random")], blocks=[]
+ ).model_dump(mode="json")
+ session.add(
+ CredentialModel(
+ credential_id="cred_c",
+ organization_id="org_test",
+ name="Login",
+ credential_type="password",
+ item_id="item_c",
+ run_sequentially=False,
+ )
+ )
+ await session.commit()
+ repo = database.workflow_run_credential_selections
+ await repo.create_selection(
+ organization_id="org_test",
+ workflow_run_id="wr_test",
+ workflow_permanent_id="wpid_test",
+ parameter_key="login_cred",
+ credential_id="cred_a",
+ )
+ monkeypatch.setattr(credential_selection_module, "random", random.Random(0))
+ preparation = await database.workflow_runs.prepare_next_attempt_atomic("wr_test", "org_test", 1, "failed", None)
+
+ assert preparation.status == "inserted"
+ selected = await repo.get_selection("wr_test", "login_cred")
+ assert selected == ("cred_c" if len(pool) > 1 else "cred_a")
+ assert selected in pool
+ if len(pool) > 1:
+ assert selected != "cred_a"
+ assert await repo.get_selection("wr_test:attempt:1", "login_cred") == "cred_a"
+
+
[email protected]("duplicate_kind", ["credential", "workflow", "output", "context"])
+async def test_retry_preparation_retains_duplicate_parameter_keys(
+ retry_rotation_db: AgentDB, duplicate_kind: str
+) -> None:
+ database = retry_rotation_db
+ parameter = _credential_parameter(credential_ids=["cred_a", "cred_b"])
+ duplicates = {
+ "credential": parameter.model_copy(update={"credential_ids": ["cred_a"]}),
+ "workflow": _workflow_parameter(parameter.key),
+ "output": OutputParameter(
+ key=parameter.key,
+ output_parameter_id="op_test",
+ workflow_id="wf_test",
+ created_at=parameter.created_at,
+ modified_at=parameter.modified_at,
+ ),
+ "context": ContextParameter(key=parameter.key, source=_workflow_parameter("source")),
+ }
+ async with database.Session() as session:
+ workflow = await session.get(WorkflowModel, "wf_test")
+ workflow.workflow_definition = WorkflowDefinition(
+ parameters=[parameter, duplicates[duplicate_kind]], blocks=[]
+ ).model_dump(mode="json")
+ await session.commit()
+ repo = database.workflow_run_credential_selections
+ await repo.create_selection(
+ organization_id="org_test",
+ workflow_run_id="wr_test",
+ workflow_permanent_id="wpid_test",
+ parameter_key=parameter.key,
+ credential_id="cred_a",
+ )
+ preparation = await database.workflow_runs.prepare_next_attempt_atomic("wr_test", "org_test", 1, "failed", None)
+ assert preparation.status == "inserted"
+ assert await repo.get_selection("wr_test", parameter.key) == "cred_a"
+ async with database.Session() as session:
+ bindings = (await session.scalars(select(WorkflowRunCredentialSelectionModel))).all()
+ assert len(bindings) == 1 and bindings[0].workflow_run_id == "wr_test"
+
+
+async def test_retry_without_selections_never_loads_definition(
+ retry_rotation_db: AgentDB, sqlite_engine: AsyncEngine
+) -> None:
+ database = retry_rotation_db
+ repo = database.workflow_run_credential_selections
+ for run_id, org_id in [("wr_other", "org_test"), ("wr_test", "org_other")]:
+ await repo.create_selection(
+ organization_id=org_id,
+ workflow_run_id=run_id,
+ workflow_permanent_id="wpid_test",
+ parameter_key="login_cred",
+ credential_id="cred_a",
+ )
+
+ def reject_definition_read(
+ _connection: Any, _cursor: Any, statement: str, _parameters: Any, _context: Any, _many: bool
+ ) -> None:
+ if " from workflows " in " ".join(statement.lower().split()) and "workflows.workflow_definition" in statement:
+ raise AssertionError("Preparation loaded a definition without credential selections")
+
+ event.listen(sqlite_engine.sync_engine, "before_cursor_execute", reject_definition_read)
+ try:
+ with patch.object(
+ workflow_runs_repository_module.WorkflowDefinition,
+ "model_validate",
+ side_effect=AssertionError("Preparation parsed a definition without credential selections"),
+ ):
+ preparation = await database.workflow_runs.prepare_next_attempt_atomic(
+ "wr_test", "org_test", 1, "failed", None
+ )
+ finally:
+ event.remove(sqlite_engine.sync_engine, "before_cursor_execute", reject_definition_read)
+ assert preparation.status == "inserted"
+ attempts = await database.workflow_run_attempts.get_attempts("wr_test")
+ assert [(attempt.attempt_number, attempt.status) for attempt in attempts] == [(1, "failed"), (2, "queued")]
+
+
[email protected]("resolver", ["context", "service"])
[email protected]("single_credential_id", ["cred_b", "cred_c"])
[email protected]("credential_ids", [None, []], ids=["none", "empty"])
[email protected]("prepared_binding", [True, False], ids=["prepared", "unbound"])
+async def test_retry_runtime_registration_with_single_credential_definition(
+ retry_rotation_db: AgentDB,
+ resolver: str,
+ single_credential_id: str,
+ credential_ids: list[str] | None,
+ prepared_binding: bool,
+) -> None:
+ database = retry_rotation_db
+ repo = database.workflow_run_credential_selections
+ single_parameter = _credential_parameter(credential_id=single_credential_id, credential_ids=credential_ids)
+ initial_parameter = _credential_parameter(credential_ids=["cred_a"]) if prepared_binding else single_parameter
+ sequential_credential_id = "cred_b" if not prepared_binding and single_credential_id == "cred_b" else None
+ async with database.Session() as session:
+ workflow = await session.get(WorkflowModel, "wf_test")
+ workflow.workflow_definition = WorkflowDefinition(parameters=[initial_parameter], blocks=[]).model_dump(
+ mode="json"
+ )
+ credential_b = await session.get(CredentialModel, "cred_b")
+ credential_b.run_sequentially = True
+ session.add(
+ CredentialModel(
+ credential_id="cred_c",
+ organization_id="org_test",
+ name="Login",
+ credential_type="password",
+ item_id="item_cred_c",
+ run_sequentially=False,
+ )
+ )
+ run = await session.get(WorkflowRunModel, "wr_test")
+ run.sequential_credential_id = sequential_credential_id
+ await session.commit()
+ if prepared_binding:
+ await repo.create_selection(
+ organization_id="org_test",
+ workflow_run_id="wr_test",
+ workflow_permanent_id="wpid_test",
+ parameter_key="login_cred",
+ credential_id="cred_a",
+ )
+ preparation = await database.workflow_runs.prepare_next_attempt_atomic("wr_test", "org_test", 1, "failed", None)
+ assert preparation.status == "inserted"
+ expected_binding = "cred_a" if prepared_binding else None
+ assert await repo.get_selection("wr_test", "login_cred") == expected_binding
+ attempts = await database.workflow_run_attempts.get_attempts("wr_test")
+ assert [(attempt.attempt_number, attempt.status) for attempt in attempts] == [(1, "failed"), (2, "queued")]
+ await database.workflows.update_workflow_and_reconcile_definition_params(
+ "wf_test",
+ organization_id="org_test",
+ workflow_definition=WorkflowDefinition(parameters=[single_parameter], blocks=[]),
+ )
+ workflow = await database.workflows.get_workflow("wf_test", organization_id="org_test")
+ assert workflow is not None
+ parameter = workflow.workflow_definition.parameters[0]
+ assert isinstance(parameter, CredentialParameter)
+ assert parameter.credential_id == single_credential_id
+ assert parameter.credential_ids == credential_ids
+ assert parameter.fallback_credential_ids is None
+ credential = MagicMock()
+ credential.model_dump.return_value = {}
+ credential_service = MagicMock()
+ credential_service.get_credential_item = AsyncMock(return_value=SimpleNamespace(credential=credential))
+ with (
+ patch("skyvern.forge.sdk.workflow.context_manager.app") as context_app,
+ patch("skyvern.forge.sdk.workflow.service.app") as service_app,
+ ):
+ context_app.DATABASE = database
+ context_app.CREDENTIAL_VAULT_SERVICES.get.return_value = credential_service
+ context_app.AGENT_FUNCTION.process_registered_credential_item = AsyncMock(
+ side_effect=lambda *, workflow_run_id, db_credential, credential_item: credential_item
+ )
+ service_app.DATABASE = database
+ service_app.WORKFLOW_CONTEXT_MANAGER.workflow_run_contexts = {}
+ context = _runtime_context()
+ context.attempt_number = 2
+ organization = SimpleNamespace(organization_id="org_test")
+ if resolver == "context":
+ await context.register_credential_parameter_value(parameter, organization)
+ else:
+ resolved = await WorkflowService()._resolve_credential_parameter_id(
+ parameter=parameter,
+ workflow_run_id="wr_test",
+ organization_id="org_test",
+ workflow_permanent_id="wpid_test",
+ )
+ await context._register_credential_parameter_value(resolved, parameter, organization)
+ assert context.get_resolved_credential_parameter_id("login_cred") == (expected_binding or single_credential_id)
+ assert context.has_value("login_cred")
+ run = await database.workflow_runs.get_workflow_run("wr_test", "org_test")
+ assert run is not None and run.sequential_credential_id == sequential_credential_id
+ assert await repo.get_selections_for_run("wr_test") == ({"login_cred": "cred_a"} if prepared_binding else {})
diff --git a/tests/unit/test_data_export_block.py b/tests/unit/test_data_export_block.py
index ebd71dbe9..e38778148 100644
--- a/tests/unit/test_data_export_block.py
+++ b/tests/unit/test_data_export_block.py
@@ -90,7 +90,7 @@ async def test_export_block_writes_and_registers_one_parquet_file_per_loop_itera
monkeypatch.setattr(app.STORAGE, "save_downloaded_files", AsyncMock())
monkeypatch.setattr(
app.STORAGE,
- "get_downloaded_files",
+ "get_current_attempt_downloaded_files",
AsyncMock(
return_value=[FileInfo(url="https://example.test/items-0003.parquet", filename="items-0003.parquet")]
),
diff --git a/tests/unit/test_download_dir_rebind.py b/tests/unit/test_download_dir_rebind.py
index df02d6502..cfb7052be 100644
--- a/tests/unit/test_download_dir_rebind.py
+++ b/tests/unit/test_download_dir_rebind.py
@@ -999,6 +999,7 @@ async def test_file_upload_block_empty_scan_without_registered_downloads_succeed
patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app,
):
mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
+ mock_app.STORAGE.get_current_attempt_downloaded_files = mock_app.STORAGE.get_downloaded_files
mock_app.AGENT_FUNCTION.upload_file_to_customer_storage = AsyncMock()
result = await block.execute(
workflow_run_id="wr_empty",
@@ -1054,6 +1055,7 @@ async def test_file_upload_block_empty_scan_with_registered_downloads_fails(tmp_
mock_app.STORAGE.get_downloaded_files = AsyncMock(
return_value=[FileInfo(url="https://example.com/invoice.pdf", filename="invoice.pdf")]
)
+ mock_app.STORAGE.get_current_attempt_downloaded_files = mock_app.STORAGE.get_downloaded_files
result = await block.execute(
workflow_run_id="wr_empty",
workflow_run_block_id="wrb_x",
@@ -1110,6 +1112,7 @@ async def test_file_upload_block_empty_scan_with_alternate_download_dir_files_fa
patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app,
):
mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
+ mock_app.STORAGE.get_current_attempt_downloaded_files = mock_app.STORAGE.get_downloaded_files
mock_app.AGENT_FUNCTION.upload_file_to_customer_storage = AsyncMock()
result = await block.execute(
workflow_run_id="wr_empty",
@@ -1170,6 +1173,7 @@ async def test_file_upload_block_empty_scan_with_too_many_alternate_files_report
patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app,
):
mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
+ mock_app.STORAGE.get_current_attempt_downloaded_files = mock_app.STORAGE.get_downloaded_files
mock_app.AGENT_FUNCTION.upload_file_to_customer_storage = AsyncMock()
result = await block.execute(
workflow_run_id="wr_empty",
@@ -1224,6 +1228,7 @@ async def test_file_upload_block_empty_scan_with_browser_session_downloads_fails
return_value=["s3://downloads/session/invoice.pdf"]
)
mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
+ mock_app.STORAGE.get_current_attempt_downloaded_files = mock_app.STORAGE.get_downloaded_files
mock_app.AGENT_FUNCTION.upload_file_to_customer_storage = AsyncMock()
result = await block.execute(
workflow_run_id="wr_empty",
@@ -1240,6 +1245,86 @@ async def test_file_upload_block_empty_scan_with_browser_session_downloads_fails
mock_app.AGENT_FUNCTION.upload_file_to_customer_storage.assert_not_awaited()
[email protected]("from_current_attempt", [False, True], ids=["earlier-attempt", "current-attempt"])
+async def test_file_upload_block_empty_scan_scopes_registered_downloads_to_the_attempt(
+ tmp_path, from_current_attempt: bool
+) -> None:
+ from datetime import UTC, datetime, timedelta
+ from functools import partial
+
+ from skyvern.forge.sdk.artifact.storage.base import BaseStorage
+ from skyvern.forge.sdk.schemas.files import FileInfo
+ from skyvern.forge.sdk.workflow.models.block import FileUploadBlock
+ from skyvern.schemas.workflows import BlockStatus, FileStorageType
+
+ started_at = datetime(2026, 9, 12, 12, 0, tzinfo=UTC)
+ registered = FileInfo(
+ url="s3://downloads/wr_empty/invoice.pdf",
+ modified_at=started_at + timedelta(seconds=1 if from_current_attempt else -60),
+ )
+ block = FileUploadBlock.model_construct(
+ label="upload",
+ storage_type=FileStorageType.S3,
+ s3_bucket="bucket",
+ aws_access_key_id="ak",
+ aws_secret_access_key="sk",
+ path=None,
+ continue_on_empty=False,
+ )
+ empty_dir = tmp_path / "wr_empty"
+ empty_dir.mkdir()
+ sentinel = object()
+ workflow_run_context = MagicMock()
+ workflow_run_context.organization_id = "org_1"
+
+ with (
+ patch.object(FileUploadBlock, "get_workflow_run_context", return_value=workflow_run_context),
+ patch.object(FileUploadBlock, "format_potential_template_parameters", return_value=None),
+ patch.object(FileUploadBlock, "record_output_parameter_value", new_callable=AsyncMock) as mock_record,
+ patch.object(
+ FileUploadBlock, "build_block_result", new_callable=AsyncMock, return_value=sentinel
+ ) as mock_result,
+ patch(
+ "skyvern.forge.sdk.workflow.models.block.get_path_for_workflow_download_directory",
+ return_value=empty_dir,
+ ),
+ patch("skyvern.forge.sdk.workflow.models.block.skyvern_context.current", return_value=None),
+ patch(
+ "skyvern.forge.sdk.workflow.models.block.get_download_retry_started_at",
+ AsyncMock(return_value=started_at),
+ ),
+ patch(
+ "skyvern.forge.sdk.artifact.storage.base.get_download_retry_started_at",
+ AsyncMock(return_value=started_at),
+ ),
+ patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app,
+ ):
+ mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[registered])
+ # The real attempt filter runs over the mocked run-wide listing.
+ mock_app.STORAGE.get_current_attempt_downloaded_files = partial(
+ BaseStorage.get_current_attempt_downloaded_files, mock_app.STORAGE
+ )
+ mock_app.AGENT_FUNCTION.upload_file_to_customer_storage = AsyncMock()
+ result = await block.execute(
+ workflow_run_id="wr_empty",
+ workflow_run_block_id="wrb_x",
+ organization_id="org_1",
+ browser_session_id=None,
+ )
+
+ assert result is sentinel
+ if from_current_attempt:
+ assert mock_result.await_args.kwargs["status"] == BlockStatus.failed
+ assert "registered_download_count=1" in mock_result.await_args.kwargs["failure_reason"]
+ mock_record.assert_not_awaited()
+ else:
+ assert mock_result.await_args.kwargs["status"] == BlockStatus.completed
+ assert mock_result.await_args.kwargs["output_parameter_value"] == []
+ mock_record.assert_awaited_once()
+ mock_app.AGENT_FUNCTION.upload_file_to_customer_storage.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_file_upload_block_empty_scan_registered_download_timeout_fails_with_unknown_count(tmp_path) -> None:
"""SKY-11225: unknown registered-download state fails closed with a readable failure reason."""
@@ -1278,6 +1363,7 @@ async def test_file_upload_block_empty_scan_registered_download_timeout_fails_wi
patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app,
):
mock_app.STORAGE.get_downloaded_files = AsyncMock(side_effect=asyncio.TimeoutError)
+ mock_app.STORAGE.get_current_attempt_downloaded_files = mock_app.STORAGE.get_downloaded_files
result = await block.execute(
workflow_run_id="wr_empty",
workflow_run_block_id="wrb_x",
@@ -1516,6 +1602,7 @@ async def test_register_downloaded_files_reports_visibility_for_a_non_secure_eng
with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:
mock_app.STORAGE.save_downloaded_files = AsyncMock()
mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
+ mock_app.STORAGE.get_current_attempt_downloaded_files = mock_app.STORAGE.get_downloaded_files
with capture_logs() as logs:
await block._register_downloaded_files(
@@ -1551,6 +1638,7 @@ async def test_register_downloaded_files_uses_download_run_id_as_storage_key() -
with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:
mock_app.STORAGE.save_downloaded_files = AsyncMock()
mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
+ mock_app.STORAGE.get_current_attempt_downloaded_files = mock_app.STORAGE.get_downloaded_files
await block._register_downloaded_files(
engine="inline",
@@ -1573,6 +1661,7 @@ async def test_register_downloaded_files_defaults_to_workflow_run_id() -> None:
with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:
mock_app.STORAGE.save_downloaded_files = AsyncMock()
mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
+ mock_app.STORAGE.get_current_attempt_downloaded_files = mock_app.STORAGE.get_downloaded_files
await block._register_downloaded_files(
engine="inline",
@@ -1593,6 +1682,7 @@ async def test_register_pdf_uses_download_run_id_as_storage_key() -> None:
with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:
mock_app.STORAGE.save_downloaded_files = AsyncMock()
mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
+ mock_app.STORAGE.get_current_attempt_downloaded_files = mock_app.STORAGE.get_downloaded_files
await block._register_pdf_as_downloaded_file(
organization_id="org_1",
@@ -1614,6 +1704,7 @@ async def test_register_pdf_defaults_to_workflow_run_id() -> None:
with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:
mock_app.STORAGE.save_downloaded_files = AsyncMock()
mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
+ mock_app.STORAGE.get_current_attempt_downloaded_files = mock_app.STORAGE.get_downloaded_files
await block._register_pdf_as_downloaded_file(
organization_id="org_1",
@@ -1683,6 +1774,7 @@ async def test_print_page_block_threads_resolved_id_to_all_sinks(tmp_path) -> No
patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app,
):
mock_app.STORAGE.get_downloaded_files = AsyncMock(side_effect=fake_get_downloaded_files)
+ mock_app.STORAGE.get_current_attempt_downloaded_files = mock_app.STORAGE.get_downloaded_files
result = await block.execute(
workflow_run_id="wr_block",
workflow_run_block_id="wrb_x",
diff --git a/tests/unit/test_download_file_action_handler.py b/tests/unit/test_download_file_action_handler.py
index 198697adb..62293850d 100644
--- a/tests/unit/test_download_file_action_handler.py
+++ b/tests/unit/test_download_file_action_handler.py
@@ -1426,7 +1426,7 @@ async def test_handle_action_reconnects_context_closed_during_download_wait(
xhr_capture.drain = AsyncMock(return_value=False)
list_calls = 0
- def list_files(_path: Path | str) -> list[str]:
+ def list_files(_path: Path | str, *, attempt_started_at: datetime | None = None) -> list[str]:
nonlocal list_calls, page_closed
list_calls += 1
if list_calls == 2:
@@ -1570,7 +1570,9 @@ async def test_handle_action_stops_batch_after_restoring_blank_page_when_downloa
patch("skyvern.webeye.actions.handler.get_download_dir", return_value=temp_dir),
patch(
"skyvern.webeye.actions.handler.list_files_in_directory",
- side_effect=lambda _path: [str(downloaded_file)] if downloaded_file.exists() else [],
+ side_effect=lambda _path, *, attempt_started_at=None: (
+ [str(downloaded_file)] if downloaded_file.exists() else []
+ ),
),
patch(
"skyvern.webeye.actions.handler.check_downloading_files_and_wait_for_download_to_complete",
@@ -1638,7 +1640,9 @@ async def test_handle_action_does_not_close_recovered_page_when_download_finishe
patch("skyvern.webeye.actions.handler.get_download_dir", return_value=temp_dir),
patch(
"skyvern.webeye.actions.handler.list_files_in_directory",
- side_effect=lambda _path: [str(downloaded_file)] if downloaded_file.exists() else [],
+ side_effect=lambda _path, *, attempt_started_at=None: (
+ [str(downloaded_file)] if downloaded_file.exists() else []
+ ),
),
patch(
"skyvern.webeye.actions.handler.check_downloading_files_and_wait_for_download_to_complete",
@@ -3125,7 +3129,7 @@ async def test_handle_action_download_admits_request_event_queued_by_action(
clock = _FakeMonotonic()
clock.advance_after_next_read(0.01)
- def list_files(_download_dir: object) -> list[str]:
+ def list_files(_download_dir: object, *, attempt_started_at: datetime | None = None) -> list[str]:
nonlocal list_calls
list_calls += 1
if list_calls == 2:
@@ -5136,7 +5140,7 @@ async def test_handle_action_hard_deadline_drain_uses_zero_remaining_budget_and_
(staging_dir / "completed.pdf").write_bytes(b"%PDF-1.4 completed")
list_calls = 0
- def list_files(path: Path | str) -> list[str]:
+ def list_files(path: Path | str, *, attempt_started_at: datetime | None = None) -> list[str]:
nonlocal list_calls
list_calls += 1
if list_calls == 2:
@@ -5200,7 +5204,7 @@ async def test_handle_action_xhr_body_finishing_within_remaining_deadline_is_col
staging_dir.mkdir()
list_calls = 0
- def list_files(path: Path | str) -> list[str]:
+ def list_files(path: Path | str, *, attempt_started_at: datetime | None = None) -> list[str]:
nonlocal list_calls
list_calls += 1
if list_calls == 2:
diff --git a/tests/unit/test_downloaded_files_artifact_urls.py b/tests/unit/test_downloaded_files_artifact_urls.py
index d51b72ffa..55e3cd611 100644
--- a/tests/unit/test_downloaded_files_artifact_urls.py
+++ b/tests/unit/test_downloaded_files_artifact_urls.py
@@ -2,14 +2,44 @@
from __future__ import annotations
+import hashlib
+import os
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
from urllib.parse import urlparse
import pytest
+import skyvern.forge.sdk.artifact.manager as manager_module
+import skyvern.forge.sdk.artifact.storage.azure as azure_module
+import skyvern.forge.sdk.artifact.storage.base as base_module
+import skyvern.forge.sdk.artifact.storage.gcs as gcs_module
+import skyvern.forge.sdk.artifact.storage.local as local_module
+import skyvern.forge.sdk.artifact.storage.s3 as s3_module
+from skyvern.config import settings
+from skyvern.forge.sdk.api.files import parse_uri_to_path
from skyvern.forge.sdk.artifact.manager import ArtifactManager
from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType
+from skyvern.forge.sdk.artifact.storage.local import LocalStorage
from skyvern.forge.sdk.artifact.storage.s3 import S3Storage
+from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
+from skyvern.forge.sdk.schemas.files import FileInfo
+from skyvern.forge.sdk.workflow.context_manager import WorkflowContextManager
+from skyvern.forge.sdk.workflow.loop_download_filter import (
+ DOWNLOADED_FILE_SIGS_KEY,
+ filter_downloaded_files_for_current_iteration,
+ to_downloaded_file_signature,
+)
+from skyvern.forge.sdk.workflow.models import block as block_module
+from skyvern.forge.sdk.workflow.models.block import PrintPageBlock
+from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, ParameterType
+from skyvern.forge.sdk.workflow.runtime_completion import CompletionCriterion, grade_completion_contract
+from skyvern.forge.sdk.workflow.service import WorkflowService
+from tests.unit.conftest import FakeWorkflowRunAttemptsRepository
+from tests.unit.forge.sdk.artifact.storage.test_azure_storage import AzureStorageForTests
+from tests.unit.forge.sdk.artifact.storage.test_gcs_storage import GcsStorageForTests
def _is_amazonaws_s3_url(url: str) -> bool:
@@ -44,6 +74,7 @@ async def test_create_download_artifact_is_idempotent_per_run_and_uri():
)
find_existing = AsyncMock(return_value=existing)
mock_db_create = AsyncMock()
+ mock_refresh = AsyncMock()
with (
patch(
@@ -54,6 +85,10 @@ async def test_create_download_artifact_is_idempotent_per_run_and_uri():
"skyvern.forge.sdk.artifact.manager.app.DATABASE.artifacts.create_artifact",
mock_db_create,
),
+ patch(
+ "skyvern.forge.sdk.artifact.manager.app.DATABASE.artifacts.refresh_download_artifact_content",
+ mock_refresh,
+ ),
):
artifact_id = await manager.create_download_artifact(
organization_id="o_1",
@@ -65,6 +100,7 @@ async def test_create_download_artifact_is_idempotent_per_run_and_uri():
assert artifact_id == "a_existing"
mock_db_create.assert_not_awaited()
+ mock_refresh.assert_not_awaited()
@pytest.mark.asyncio
@@ -118,7 +154,7 @@ async def test_create_download_artifact_inserts_row_without_uploading():
@pytest.mark.asyncio
-async def test_save_downloaded_files_registers_artifact_per_file(tmp_path):
+async def test_save_downloaded_files_registers_artifact_per_file(tmp_path, monkeypatch):
"""After uploading each file to S3, save_downloaded_files should create an
Artifact row so later retrieval can build short /v1/artifacts URLs."""
download_dir = tmp_path / "downloads"
@@ -141,6 +177,9 @@ async def test_save_downloaded_files_registers_artifact_per_file(tmp_path):
patch("skyvern.forge.sdk.artifact.storage.s3.app") as app_module,
):
app_module.ARTIFACT_MANAGER = mock_artifact_manager
+ app_module.DATABASE.workflow_runs.get_workflow_run = AsyncMock(return_value=None)
+ app_module.DATABASE.workflow_run_attempts = FakeWorkflowRunAttemptsRepository()
+ monkeypatch.setattr(base_module, "app", app_module)
await storage.save_downloaded_files(organization_id="o_1", run_id="wr_1")
assert mock_create_download.await_count == 2
@@ -158,6 +197,50 @@ async def test_save_downloaded_files_registers_artifact_per_file(tmp_path):
assert call.kwargs["run_id"] == "wr_1"
+async def test_local_retry_snapshot_uri_survives_fragment_and_query_characters(tmp_path, monkeypatch):
+ # A raw file:// URI turns "#" and "?" into a fragment and a query, so the snapshot path read back
+ # from the artifact row no longer exists and the saved download drops out of the listing.
+ storage = LocalStorage(str(tmp_path / "artifacts"))
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir()
+ (download_dir / "report #1?.pdf").write_bytes(b"attempt two bytes")
+ rows: list[Artifact] = []
+
+ async def register(**kwargs):
+ rows.append(
+ _make_artifact(
+ f"a_{len(rows)}",
+ kwargs["uri"],
+ checksum=kwargs["checksum"],
+ file_size=kwargs["file_size"],
+ created_at=datetime.now(UTC).isoformat(),
+ )
+ )
+
+ fake_app = SimpleNamespace(
+ STORAGE=storage,
+ ARTIFACT_MANAGER=SimpleNamespace(create_download_artifact=register),
+ DATABASE=SimpleNamespace(
+ artifacts=SimpleNamespace(list_artifacts_for_run_by_type=AsyncMock(side_effect=lambda **kwargs: list(rows)))
+ ),
+ )
+ monkeypatch.setattr(local_module, "app", fake_app)
+ monkeypatch.setattr(local_module, "get_download_dir", lambda *args, **kwargs: str(download_dir))
+ started_at = datetime.now(UTC) - timedelta(minutes=1)
+ monkeypatch.setattr(base_module, "resolve_download_attempt", AsyncMock(return_value=("wr_1", 2, started_at)))
+
+ await storage.save_downloaded_files(organization_id="o_1", run_id="wr_1")
+
+ assert len(rows) == 1
+ snapshot = Path(parse_uri_to_path(rows[0].uri))
+ assert snapshot.name == "report #1?.pdf"
+ assert snapshot.parent.name == "2"
+ assert snapshot.read_bytes() == b"attempt two bytes"
+ listed = await storage.get_downloaded_files("o_1", "wr_1")
+ assert [(file.filename, file.artifact_id) for file in listed] == [("report #1?.pdf", "a_0")]
+
+
def _make_artifact(
artifact_id: str,
uri: str,
@@ -384,6 +467,11 @@ async def test_content_endpoint_download_returns_attachment_with_filename():
assert media_type == "application/octet-stream"
assert disposition.startswith("attachment;")
assert 'filename="invoice.pdf"' in disposition
+ local_snapshot = _make_artifact(
+ "a_local", "file:///tmp/artifacts/downloads/local/o_1/wr_1/attempts/2/report%20%231.pdf"
+ )
+ _, local_disposition = _artifact_response_config(local_snapshot)
+ assert 'filename="report #1.pdf"' in local_disposition
def test_content_endpoint_non_download_stays_inline():
@@ -702,12 +790,15 @@ async def test_create_download_artifact_refreshes_checksum_for_changed_bytes():
mock_db_create.assert_not_awaited()
mock_refresh.assert_awaited_once()
assert mock_refresh.await_args.kwargs["checksum"] == "fresh"
+ assert mock_refresh.await_args.kwargs["file_size"] == 10
@pytest.mark.asyncio
-async def test_create_download_artifact_keeps_row_untouched_for_identical_bytes():
- """A byte-identical re-save (a loop iteration re-uploading the same file) must not touch the
- row, or every iteration's URL would read as a new download."""
+async def test_create_download_artifact_does_not_touch_row_for_identical_bytes(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.artifact.manager.app.DATABASE.workflow_run_attempts",
+ FakeWorkflowRunAttemptsRepository([SimpleNamespace(attempt_number=2, started_at=None)]),
+ )
manager = ArtifactManager()
existing = Artifact(
@@ -787,3 +878,497 @@ async def test_create_download_artifact_propagates_refresh_failure():
checksum="fresh",
file_size=10,
)
+
+
[email protected]("backend", ["s3", "azure", "gcs", "local"])
[email protected]("child_save", [False, True])
[email protected]("retry_bytes", [b"attempt one", b"different attempt two bytes"])
[email protected]("signed_artifact_urls", [True, False])
+async def test_retry_downloads_preserve_attempt_objects_and_rows(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ backend: str,
+ child_save: bool,
+ retry_bytes: bytes,
+ signed_artifact_urls: bool,
+):
+ monkeypatch.setattr(
+ settings, "ARTIFACT_CONTENT_HMAC_KEYRING", _DUMMY_KEYRING_JSON if signed_artifact_urls else None
+ )
+ storage = {
+ "s3": lambda: S3Storage(),
+ "azure": lambda: AzureStorageForTests("uploads"),
+ "gcs": lambda: GcsStorageForTests("uploads"),
+ "local": lambda: LocalStorage(str(tmp_path / "artifacts")),
+ }[backend]()
+ storage.async_client = MagicMock()
+ if backend in ("s3", "gcs"):
+ monkeypatch.setattr(storage, "_get_storage_class_for_org", AsyncMock(return_value="STANDARD"))
+ if backend == "gcs":
+ monkeypatch.setattr(storage, "_get_tags_for_org", AsyncMock(return_value=None))
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir()
+ file_path = download_dir / "report.pdf"
+ original_bytes = b"attempt one"
+ file_path.write_bytes(original_bytes)
+ first_start = datetime.now(UTC) - timedelta(minutes=2)
+ second_start = first_start + timedelta(minutes=1)
+ write_time = first_start + timedelta(seconds=1)
+ attempts = FakeWorkflowRunAttemptsRepository([SimpleNamespace(attempt_number=1, started_at=first_start)])
+ rows: dict[str, Artifact] = {}
+ objects: dict[str, bytes] = {}
+ object_info: dict[str, dict] = {}
+
+ async def upload(*, uri: str, file_path: str, metadata: dict[str, str], **kwargs):
+ objects[uri] = Path(file_path).read_bytes()
+ object_info[uri] = {"Metadata": metadata, "ContentLength": len(objects[uri]), "LastModified": write_time}
+
+ async def list_files(*, uri: str):
+ return [urlparse(key).path.lstrip("/") for key in objects if key.startswith(uri + "/")]
+
+ async def get_object_info(uri: str):
+ return object_info[uri]
+
+ async def sign_urls(uris: list[str]):
+ return [f"https://storage.example{urlparse(uri).path}?signature=test" for uri in uris]
+
+ async def find(*, uri: str, **kwargs):
+ return next((row for row in rows.values() if row.uri == uri), None)
+
+ async def create(**kwargs):
+ row = Artifact(**kwargs, created_at=write_time, modified_at=write_time)
+ rows[row.artifact_id] = row
+ return row
+
+ async def refresh(*, artifact_id: str, checksum: str | None, file_size: int | None, **kwargs):
+ row = rows[artifact_id]
+ row.checksum, row.file_size, row.modified_at = checksum, file_size, write_time
+
+ async def list_rows(**kwargs):
+ return list(rows.values())
+
+ current_context = SkyvernContext(workflow_run_id="wr_child_1" if child_save else "wr_1")
+
+ async def get_attempts(workflow_run_id):
+ if workflow_run_id != "wr_1":
+ return [SimpleNamespace(attempt_number=1, started_at=write_time)]
+ return attempts.attempts
+
+ manager = ArtifactManager()
+ fake_app = SimpleNamespace(
+ ARTIFACT_MANAGER=manager,
+ WORKFLOW_CONTEXT_MANAGER=WorkflowContextManager(),
+ DATABASE=SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(get_attempts=get_attempts),
+ workflow_runs=SimpleNamespace(get_workflow_run=AsyncMock(return_value=None)),
+ artifacts=SimpleNamespace(
+ find_download_artifact=find,
+ create_artifact=create,
+ refresh_download_artifact_content=refresh,
+ list_artifacts_for_run_by_type=list_rows,
+ ),
+ ),
+ )
+ backend_module = {"s3": s3_module, "azure": azure_module, "gcs": gcs_module, "local": local_module}[backend]
+ for module in (manager_module, base_module, backend_module):
+ monkeypatch.setattr(module, "app", fake_app)
+ monkeypatch.setattr(backend_module, "get_download_dir", lambda **kwargs: str(download_dir))
+ monkeypatch.setattr(manager_module.skyvern_context, "current", lambda: current_context)
+ monkeypatch.setattr(storage.async_client, "upload_file_from_path", upload)
+ monkeypatch.setattr(storage.async_client, "list_files", list_files)
+ monkeypatch.setattr(storage.async_client, "get_object_info", get_object_info)
+ signing_method = {
+ "s3": "create_presigned_urls",
+ "azure": "create_sas_urls",
+ "gcs": "create_signed_urls",
+ "local": "unused",
+ }[backend]
+ monkeypatch.setattr(storage.async_client, signing_method, sign_urls)
+ monkeypatch.setattr(
+ manager,
+ "resolve_share_url",
+ AsyncMock(
+ side_effect=lambda artifact, **kwargs: f"https://api.example/v1/artifacts/{artifact.artifact_id}/content"
+ ),
+ )
+ monkeypatch.setattr(manager, "resolve_artifact_url_expiry_seconds", AsyncMock(return_value=3600))
+
+ await storage.save_downloaded_files(organization_id="o_1", run_id="wr_1")
+ first = next(iter(rows.values())).model_copy(deep=True)
+ assert first.uri.endswith("/o_1/wr_1/report.pdf")
+ await storage.save_downloaded_files(organization_id="o_1", run_id="wr_1")
+ assert list(rows) == [first.artifact_id]
+ first_files = await storage.get_downloaded_files(organization_id="o_1", run_id="wr_1")
+ first_signature = to_downloaded_file_signature(first_files[0])
+
+ current_context.workflow_run_id = "wr_child_2" if child_save else "wr_1"
+ attempts.attempts.append(SimpleNamespace(attempt_number=2, started_at=second_start))
+ write_time = second_start + timedelta(seconds=1)
+ file_path.write_bytes(retry_bytes)
+ os.utime(file_path, (write_time.timestamp(), write_time.timestamp()))
+ await storage.save_downloaded_files(organization_id="o_1", run_id="wr_1")
+
+ current_context.workflow_run_id = "wr_1"
+ await storage.save_downloaded_files(organization_id="o_1", run_id="wr_1", attempt_number=2)
+ if backend == "local":
+ objects = {row.uri: await storage.retrieve_artifact(row) for row in rows.values()}
+ assert len(objects) == 2
+ assert len(rows) == 2
+ second = next(row for row in rows.values() if row.artifact_id != first.artifact_id)
+ assert second.uri == first.uri.removesuffix("report.pdf") + "attempts/2/report.pdf"
+ assert objects[first.uri] == original_bytes
+ assert rows[first.artifact_id] == first
+ assert first.checksum == hashlib.sha256(original_bytes).hexdigest()
+ assert objects[second.uri] == retry_bytes
+ assert second.checksum == hashlib.sha256(retry_bytes).hexdigest()
+ assert second.file_size == len(retry_bytes)
+
+ service = WorkflowService()
+ all_files = await storage.get_downloaded_files(organization_id="o_1", run_id="wr_1")
+ current_files = service._filter_downloaded_files_to_attempt(
+ all_files, attempt_rows=attempts.attempts, attempt_number=2, artifact_ids={second.artifact_id}
+ )
+ historical_files = service._filter_downloaded_files_to_attempt(
+ all_files, attempt_rows=attempts.attempts, attempt_number=1, artifact_ids={first.artifact_id}
+ )
+ assert [file.artifact_id for file in current_files] == [second.artifact_id]
+ assert [file.artifact_id for file in historical_files] == [first.artifact_id]
+ assert to_downloaded_file_signature(historical_files[0]) == first_signature
+ if backend == "local":
+ assert first_files[0].url == first.uri
+ assert Path(urlparse(first_files[0].url).path).read_bytes() == original_bytes
+ assert first_files[0].file_size == first.file_size
+ assert first_files[0].modified_at == first.modified_at
+ assert historical_files[0].url == first.uri
+ assert historical_files[0].checksum == first.checksum
+ assert current_files[0].url == second.uri
+ assert current_files[0].checksum == second.checksum
+ assert (
+ filter_downloaded_files_for_current_iteration(
+ all_files,
+ {DOWNLOADED_FILE_SIGS_KEY: [first_signature]},
+ aliases=storage.get_downloaded_file_signature_aliases,
+ )
+ == current_files
+ )
+ second_signature = to_downloaded_file_signature(current_files[0])
+ assert second_signature != first_signature
+ assert grade_completion_contract(
+ (CompletionCriterion("download", "registered_download"),), registered_download_count=len(current_files)
+ ).satisfied
+ assert not grade_completion_contract(
+ (CompletionCriterion("downloads", "registered_download", min_count=2),),
+ registered_download_count=len(current_files),
+ ).satisfied
+
+ second_snapshot = second.model_copy(deep=True)
+ await storage.save_downloaded_files(organization_id="o_1", run_id="wr_1")
+ assert len(rows) == 2
+ assert rows[second.artifact_id] == second_snapshot
+ assert (
+ await manager.create_download_artifact(
+ organization_id="o_1",
+ run_id="wr_1",
+ workflow_run_id="wr_1",
+ uri=second.uri,
+ filename="report.pdf",
+ checksum=second.checksum,
+ file_size=second.file_size,
+ )
+ == second.artifact_id
+ )
+ repeated = await storage.get_downloaded_files(organization_id="o_1", run_id="wr_1")
+ assert (
+ to_downloaded_file_signature(next(file for file in repeated if file.artifact_id == second.artifact_id))
+ == second_signature
+ )
+
+ if backend == "local":
+ fake_app.WORKFLOW_CONTEXT_MANAGER.workflow_run_contexts["wr_1"] = SimpleNamespace(attempt_number=1)
+ historical_read = await storage.get_downloaded_files(organization_id="o_1", run_id="wr_1")
+ assert {file.url for file in historical_read} == {first.uri, second.uri}
+ file_path.unlink()
+ assert await storage.get_downloaded_files(organization_id="o_1", run_id="wr_1") == historical_read
+
+ file_path.write_bytes(b"unsaved replacement")
+ unsaved_path = download_dir / "unsaved.pdf"
+ unsaved_path.write_bytes(b"unsaved download")
+ mixed_files = await storage.get_downloaded_files(organization_id="o_1", run_id="wr_1")
+ assert {file.url for file in mixed_files} == {
+ first.uri,
+ second.uri,
+ f"file://{file_path}",
+ f"file://{unsaved_path}",
+ }
+ for live_path in (file_path, unsaved_path):
+ live_file = next(file for file in mixed_files if file.url == f"file://{live_path}")
+ assert live_file.artifact_id is None
+ assert live_file.checksum == hashlib.sha256(live_path.read_bytes()).hexdigest()
+ assert live_file.file_size == live_path.stat().st_size
+ assert live_file.modified_at == datetime.fromtimestamp(live_path.stat().st_mtime, tz=UTC)
+
+ monkeypatch.setattr(
+ fake_app.DATABASE.artifacts,
+ "list_artifacts_for_run_by_type",
+ AsyncMock(side_effect=RuntimeError("artifact repository unavailable")),
+ )
+ unattributed_files = await storage.get_downloaded_files(organization_id="o_1", run_id="wr_1")
+ assert {file.url for file in unattributed_files} == {f"file://{file_path}", f"file://{unsaved_path}"}
+ assert all(file.artifact_id is None for file in unattributed_files)
+
+
[email protected]("backend", ["s3", "azure", "gcs", "local"])
[email protected]("failure", ["lookup_error", "unstarted_attempt"])
+async def test_save_downloaded_files_fails_open_when_the_attempt_cannot_be_resolved(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, backend: str, failure: str
+):
+ """A database blip while resolving the attempt, or an attempt row with no start time, must
+ save every downloaded file rather than none; the read path already fails open the same way."""
+ storage = {
+ "s3": lambda: S3Storage(),
+ "azure": lambda: AzureStorageForTests("uploads"),
+ "gcs": lambda: GcsStorageForTests("uploads"),
+ "local": lambda: LocalStorage(str(tmp_path / "artifacts")),
+ }[backend]()
+ storage.async_client = MagicMock()
+ if backend in ("s3", "gcs"):
+ monkeypatch.setattr(storage, "_get_storage_class_for_org", AsyncMock(return_value="STANDARD"))
+ if backend == "gcs":
+ monkeypatch.setattr(storage, "_get_tags_for_org", AsyncMock(return_value=None))
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir()
+ (download_dir / "report.pdf").write_bytes(b"attempt two bytes")
+ now = datetime.now(UTC)
+ rows: dict[str, Artifact] = {}
+ objects: dict[str, bytes] = {}
+
+ async def upload(*, uri: str, file_path: str, metadata: dict[str, str], **kwargs):
+ objects[uri] = Path(file_path).read_bytes()
+
+ async def find(*, uri: str, **kwargs):
+ return next((row for row in rows.values() if row.uri == uri), None)
+
+ async def create(**kwargs):
+ row = Artifact(**kwargs, created_at=now, modified_at=now)
+ rows[row.artifact_id] = row
+ return row
+
+ async def list_rows(**kwargs):
+ return list(rows.values())
+
+ get_workflow_run = (
+ AsyncMock(side_effect=RuntimeError("database unavailable"))
+ if failure == "lookup_error"
+ else AsyncMock(return_value=SimpleNamespace(parent_workflow_run_id=None))
+ )
+ attempts = [
+ SimpleNamespace(attempt_number=1, started_at=now - timedelta(minutes=5)),
+ SimpleNamespace(attempt_number=2, started_at=None),
+ ]
+ fake_app = SimpleNamespace(
+ ARTIFACT_MANAGER=ArtifactManager(),
+ WORKFLOW_CONTEXT_MANAGER=WorkflowContextManager(),
+ DATABASE=SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(get_attempts=AsyncMock(return_value=attempts)),
+ workflow_runs=SimpleNamespace(get_workflow_run=get_workflow_run),
+ artifacts=SimpleNamespace(
+ find_download_artifact=find,
+ create_artifact=create,
+ refresh_download_artifact_content=AsyncMock(),
+ list_artifacts_for_run_by_type=list_rows,
+ ),
+ ),
+ )
+ backend_module = {"s3": s3_module, "azure": azure_module, "gcs": gcs_module, "local": local_module}[backend]
+ for module in (manager_module, base_module, backend_module):
+ monkeypatch.setattr(module, "app", fake_app)
+ monkeypatch.setattr(backend_module, "get_download_dir", lambda **kwargs: str(download_dir))
+ monkeypatch.setattr(manager_module.skyvern_context, "current", lambda: None)
+ monkeypatch.setattr(base_module.skyvern_context, "current", lambda: None)
+ monkeypatch.setattr(storage.async_client, "upload_file_from_path", upload)
+ monkeypatch.setattr(storage.async_client, "list_files", AsyncMock(return_value=[]))
+
+ await storage.save_downloaded_files(organization_id="o_1", run_id="wr_1", attempt_number=2)
+
+ saved_uris = [row.uri for row in rows.values()]
+ assert len(saved_uris) == 1
+ assert saved_uris[0].endswith("/o_1/wr_1/attempts/2/report.pdf")
+ if backend != "local":
+ assert list(objects) == saved_uris
+
+
[email protected]("run_id", ["wr_root", "wr_nested", "tsk_v2_root", "tsk_v2_child"])
[email protected]("with_context", [True, False])
+async def test_download_attempt_resolves_parent_owner(monkeypatch, run_id, with_context):
+ started_at = datetime.now(UTC)
+ parents = {"wr_root": None, "wr_nested": "wr_root"}
+
+ async def get_workflow_run(workflow_run_id, *, organization_id):
+ assert organization_id == "o_1"
+ return SimpleNamespace(parent_workflow_run_id=parents[workflow_run_id])
+
+ get_attempts = AsyncMock(return_value=[SimpleNamespace(attempt_number=2, started_at=started_at)])
+ fake_app = SimpleNamespace(
+ DATABASE=SimpleNamespace(
+ workflow_runs=SimpleNamespace(get_workflow_run=get_workflow_run),
+ workflow_run_attempts=SimpleNamespace(get_attempts=get_attempts),
+ tasks=SimpleNamespace(
+ get_run=AsyncMock(
+ return_value=SimpleNamespace(
+ parent_workflow_run_id="wr_nested" if run_id == "tsk_v2_child" else None
+ )
+ )
+ ),
+ observer=SimpleNamespace(get_task_v2=AsyncMock(return_value=SimpleNamespace(workflow_run_id="wr_root"))),
+ ),
+ WORKFLOW_CONTEXT_MANAGER=WorkflowContextManager(),
+ )
+ monkeypatch.setattr(base_module, "app", fake_app)
+ context = SkyvernContext(workflow_run_id="wr_nested") if with_context else None
+ monkeypatch.setattr(base_module.skyvern_context, "current", lambda: context)
+ owner, number, start = await base_module.resolve_download_attempt("o_1", run_id)
+ assert (owner, number, start) == ("wr_root", 2, started_at)
+ get_attempts.assert_awaited_once_with("wr_root")
+ if with_context or run_id in {"wr_nested", "tsk_v2_child"}:
+ assert await base_module.resolve_download_attempt("o_1", run_id, attempt_number=1) == ("wr_root", 2, started_at)
+ else:
+ assert await base_module.resolve_download_attempt("o_1", run_id, attempt_number=1) == ("wr_root", 1, None)
+
+
+ "attempt_number, stale_retry_file, metadata_timeout",
+ [
+ (1, False, False),
+ (2, False, False),
+ (2, True, False),
+ pytest.param(1, False, True, id="no-policy-metadata-timeout"),
+ ],
+)
+async def test_print_page_excludes_live_http_download_after_snapshot_registration(
+ tmp_path, monkeypatch, attempt_number, stale_retry_file, metadata_timeout
+):
+ storage = LocalStorage(str(tmp_path / "artifacts"))
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir()
+ http_file = download_dir / ("printed.pdf" if stale_retry_file else "http-report.pdf")
+ http_file.write_bytes(b"printed PDF" if stale_retry_file else b"HTTP response")
+ context = SkyvernContext(workflow_run_id="wr_1", run_id="wr_1")
+ rows: list[Artifact] = []
+
+ async def register(**kwargs):
+ rows.append(
+ _make_artifact(
+ f"a_{len(rows)}",
+ kwargs["uri"],
+ checksum=kwargs["checksum"],
+ file_size=kwargs["file_size"],
+ created_at=datetime.now(UTC).isoformat(),
+ )
+ )
+
+ fake_app = SimpleNamespace(
+ STORAGE=storage,
+ ARTIFACT_MANAGER=SimpleNamespace(create_download_artifact=register),
+ DATABASE=SimpleNamespace(
+ artifacts=SimpleNamespace(list_artifacts_for_run_by_type=AsyncMock(side_effect=lambda **kwargs: list(rows)))
+ ),
+ )
+ for module in (local_module, block_module):
+ monkeypatch.setattr(module, "app", fake_app)
+ monkeypatch.setattr(module, "get_download_dir", lambda *args, **kwargs: str(download_dir))
+ started_at = datetime.now(UTC) - timedelta(minutes=1)
+ resolve_attempt = AsyncMock(return_value=("wr_1", 1, started_at - timedelta(minutes=1)))
+ monkeypatch.setattr(base_module, "resolve_download_attempt", resolve_attempt)
+ if stale_retry_file:
+ list_artifacts = fake_app.DATABASE.artifacts.list_artifacts_for_run_by_type
+ list_artifacts.side_effect = RuntimeError("repository unavailable")
+ with pytest.raises(RuntimeError, match="repository unavailable"):
+ await storage.save_downloaded_files(organization_id="o_1", run_id="wr_1")
+ list_artifacts.side_effect = lambda **kwargs: list(rows)
+ stale_timestamp = (started_at - timedelta(seconds=1)).timestamp()
+ os.utime(http_file, (stale_timestamp, stale_timestamp))
+ assert rows == []
+ assert [file.url for file in await storage.get_downloaded_files("o_1", "wr_1")] == [f"file://{http_file}"]
+ resolve_attempt.return_value = ("wr_1", attempt_number, None if metadata_timeout else started_at)
+ if metadata_timeout:
+
+ async def resolve_listing_attempt(*args, **kwargs):
+ if rows:
+ raise TimeoutError("attempt metadata unavailable")
+ return "wr_1", 1, None
+
+ monkeypatch.setattr(base_module, "resolve_download_attempt", resolve_listing_attempt)
+ monkeypatch.setattr(block_module.skyvern_context, "current", lambda: context)
+ monkeypatch.setattr(
+ PrintPageBlock, "get_workflow_run_context", lambda *args: SimpleNamespace(organization_id="o_1")
+ )
+ monkeypatch.setattr(PrintPageBlock, "render_templatable_field", lambda self, field, value, ctx: value)
+ monkeypatch.setattr(
+ PrintPageBlock,
+ "get_or_create_browser_state",
+ AsyncMock(
+ return_value=SimpleNamespace(
+ get_working_page=AsyncMock(return_value=SimpleNamespace(pdf=AsyncMock(return_value=b"printed PDF")))
+ )
+ ),
+ )
+ monkeypatch.setattr(PrintPageBlock, "_upload_pdf_artifact", AsyncMock(return_value=(None, None)))
+ monkeypatch.setattr(PrintPageBlock, "record_output_parameter_value", AsyncMock())
+ monkeypatch.setattr(
+ PrintPageBlock, "build_block_result", AsyncMock(side_effect=lambda **kwargs: SimpleNamespace(**kwargs))
+ )
+ block = PrintPageBlock(
+ label="print",
+ custom_filename="printed.pdf",
+ output_parameter=OutputParameter(
+ parameter_type=ParameterType.OUTPUT,
+ key="print_output",
+ output_parameter_id="op_1",
+ workflow_id="wf_1",
+ created_at=datetime.now(UTC),
+ modified_at=datetime.now(UTC),
+ ),
+ )
+
+ result = await block.execute(workflow_run_id="wr_1", workflow_run_block_id="wrb_1", organization_id="o_1")
+
+ assert result.success is True
+ assert [file["filename"] for file in result.output_parameter_value["downloaded_files"]] == ["printed.pdf"]
+ assert context.loop_internal_state[DOWNLOADED_FILE_SIGS_KEY] == (
+ []
+ if stale_retry_file
+ else [("http-report.pdf", hashlib.sha256(b"HTTP response").hexdigest(), f"file://{http_file}")]
+ )
+ printed = next(row for row in rows if row.uri.endswith("/printed.pdf"))
+ assert result.output_parameter_value["downloaded_file_urls"] == [printed.uri]
+ assert Path(urlparse(printed.uri).path).read_bytes() == b"printed PDF"
+ if stale_retry_file:
+ assert printed.uri.endswith("/attempts/2/printed.pdf")
+ assert result.output_parameter_value["downloaded_files"][0]["url"] == printed.uri
+
+
+def test_local_snapshot_aliases_consume_primary_before_live_baseline_and_preserve_duplicates(tmp_path, monkeypatch):
+ storage = LocalStorage(str(tmp_path / "artifacts"))
+ download_dir = tmp_path / "downloads"
+ monkeypatch.setattr(local_module, "get_download_dir", lambda **kwargs: str(download_dir / kwargs["run_id"]))
+ first = FileInfo(
+ url=f"file://{storage.artifact_path}/{local_module.DOWNLOAD_FILE_PREFIX}/{settings.ENV}/o_1/wr_1/report.pdf",
+ filename="report.pdf",
+ checksum="same-bytes",
+ )
+ retry = first.model_copy(update={"url": first.url.removesuffix("report.pdf") + "attempts/2/report.pdf"})
+ live = first.model_copy(update={"url": f"file://{download_dir}/wr_1/report.pdf"})
+ baseline = {DOWNLOADED_FILE_SIGS_KEY: [to_downloaded_file_signature(first), to_downloaded_file_signature(live)]}
+
+ assert filter_downloaded_files_for_current_iteration(
+ [first, retry, first], baseline, aliases=storage.get_downloaded_file_signature_aliases
+ ) == [first]
+ assert filter_downloaded_files_for_current_iteration(
+ [retry, retry],
+ {DOWNLOADED_FILE_SIGS_KEY: [to_downloaded_file_signature(live)]},
+ aliases=storage.get_downloaded_file_signature_aliases,
+ ) == [retry]
diff --git a/tests/unit/test_execute_workflow_resolution.py b/tests/unit/test_execute_workflow_resolution.py
index 8c26368b2..7d0d7c0a9 100644
--- a/tests/unit/test_execute_workflow_resolution.py
+++ b/tests/unit/test_execute_workflow_resolution.py
@@ -2,13 +2,19 @@
from types import SimpleNamespace
from typing import Any, cast
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, Mock, call
import pytest
+from sqlalchemy.ext.asyncio import AsyncEngine
+from skyvern.exceptions import WorkflowNotFoundForWorkflowRun, WorkflowRetryAttemptLookupError
+from skyvern.forge.sdk.db.agent_db import AgentDB
+from skyvern.forge.sdk.db.models import WorkflowModel, WorkflowRunAttemptModel, WorkflowRunModel
from skyvern.forge.sdk.workflow import service as service_module
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
+from skyvern.forge.sdk.workflow.retry_policy import RetryDecision
from skyvern.forge.sdk.workflow.service import WorkflowService
+from tests.unit.scoped_asyncio import ScopedAsyncio
class _StopForTest(Exception):
@@ -16,7 +22,7 @@ class _StopForTest(Exception):
@pytest.mark.asyncio
-async def test_execute_workflow_resolves_by_run_workflow_id(monkeypatch: pytest.MonkeyPatch) -> None:
+async def test_execute_workflow_resolves_pinned_definition_including_deleted(monkeypatch: pytest.MonkeyPatch) -> None:
captured: dict[str, Any] = {}
async def _capture_resolution(**kwargs: Any) -> Any:
@@ -36,7 +42,7 @@ async def test_execute_workflow_resolves_by_run_workflow_id(monkeypatch: pytest.
"get_workflow_by_permanent_id",
AsyncMock(side_effect=AssertionError("execution must resolve by run.workflow_id")),
)
- monkeypatch.setattr(service, "get_workflow", _capture_resolution)
+ monkeypatch.setattr(service, "get_workflow_by_workflow_run_id", _capture_resolution)
organization = SimpleNamespace(organization_id="o_1")
with pytest.raises(_StopForTest):
@@ -46,8 +52,7 @@ async def test_execute_workflow_resolves_by_run_workflow_id(monkeypatch: pytest.
organization=cast(Any, organization),
)
- # The exact version stamped on the run executes, not latest-by-permanent-id.
- assert captured["workflow_id"] == "w_v7"
+ assert captured == {"workflow_run_id": "wr_1", "organization_id": "o_1", "filter_deleted": False}
@pytest.mark.asyncio
@@ -62,7 +67,7 @@ async def test_execute_workflow_canceled_run_skips_resolution(monkeypatch: pytes
service = WorkflowService()
monkeypatch.setattr(service, "get_workflow_run", AsyncMock(return_value=workflow_run))
get_workflow = AsyncMock(side_effect=AssertionError("must not resolve a canceled run's workflow"))
- monkeypatch.setattr(service, "get_workflow", get_workflow)
+ monkeypatch.setattr(service, "get_workflow_by_workflow_run_id", get_workflow)
organization = SimpleNamespace(organization_id="o_1")
result = await service.execute_workflow(
@@ -102,7 +107,7 @@ async def test_execute_workflow_fails_empty_definition_before_marking_running(
service = WorkflowService()
monkeypatch.setattr(service, "get_workflow_run", AsyncMock(return_value=workflow_run))
- monkeypatch.setattr(service, "get_workflow", AsyncMock(return_value=workflow))
+ monkeypatch.setattr(service, "get_workflow_by_workflow_run_id", AsyncMock(return_value=workflow))
monkeypatch.setattr(service_module.workflow_script_service, "workflow_has_conditionals", lambda _workflow: False)
monkeypatch.setattr(service, "bind_browser_action_policy", AsyncMock())
mark_workflow_run_as_running = AsyncMock(
@@ -132,5 +137,213 @@ async def test_execute_workflow_fails_empty_definition_before_marking_running(
browser_session_id=None,
close_browser_on_completion=True,
need_call_webhook=True,
+ attempt_number=1,
)
mark_workflow_run_as_running.assert_not_awaited()
+
+
[email protected]("has_attempt_rows", [True, False])
+async def test_cleanup_derives_ownership_when_eligibility_lookup_fails(
+ monkeypatch: pytest.MonkeyPatch, has_attempt_rows: bool
+) -> None:
+ service = WorkflowService()
+ run = SimpleNamespace(
+ workflow_run_id="wr_1",
+ organization_id="o_1",
+ status=WorkflowRunStatus.failed,
+ failure_reason="temporary failure",
+ failure_category=None,
+ finished_at=None,
+ )
+ attempt_rows = [SimpleNamespace(attempt_number=1, retry_decision="final", decision_reason="matched")]
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "get_attempts",
+ AsyncMock(return_value=attempt_rows if has_attempt_rows else []),
+ )
+ monkeypatch.setattr(
+ service_module, "is_retry_eligible_run", AsyncMock(side_effect=RuntimeError("read unavailable"))
+ )
+ monkeypatch.setattr(service_module, "mark_stream_closing", Mock())
+ monkeypatch.setattr(service_module.analytics, "capture", Mock())
+ monkeypatch.setattr(
+ service_module, "get_recorded_decision", AsyncMock(return_value=RetryDecision(False, 1, 0, True, "matched"))
+ )
+ terminal_hook = AsyncMock(side_effect=_StopForTest)
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "on_workflow_run_terminal", terminal_hook)
+
+ with pytest.raises(_StopForTest):
+ await service.clean_up_workflow(
+ workflow=cast(Any, SimpleNamespace()),
+ workflow_run=cast(Any, run),
+ need_call_webhook=True,
+ )
+
+ terminal_hook.assert_awaited_once()
+ assert terminal_hook.await_args.kwargs["is_final_attempt"] is not has_attempt_rows
+
+
+async def test_retry_entry_lookup_transient_failure_preserves_cleanup_decision(monkeypatch: pytest.MonkeyPatch) -> None:
+ service = WorkflowService()
+ run = SimpleNamespace(
+ workflow_run_id="wr_1",
+ organization_id="o_1",
+ status=WorkflowRunStatus.failed,
+ failure_reason="temporary failure",
+ failure_category=None,
+ finished_at=None,
+ )
+ attempt = SimpleNamespace(attempt_number=1, retry_decision="retry", decision_reason="matched")
+ get_attempts = AsyncMock(side_effect=[RuntimeError("read unavailable"), [attempt], [attempt]])
+ monkeypatch.setattr(service_module.app.DATABASE.workflow_run_attempts, "get_attempts", get_attempts)
+ monkeypatch.setattr(service_module.app.DATABASE.workflow_runs, "get_workflow_run", AsyncMock(return_value=run))
+ monkeypatch.setattr(service_module, "is_retry_eligible_run", AsyncMock(return_value=True))
+ monkeypatch.setattr(service_module, "mark_stream_closing", Mock())
+ monkeypatch.setattr(service_module.analytics, "capture", Mock())
+ monkeypatch.setattr(
+ service_module.app.AGENT_FUNCTION, "on_workflow_run_terminal", AsyncMock(side_effect=_StopForTest)
+ )
+ decision = RetryDecision(True, 1, 0, False, "matched")
+ monkeypatch.setattr(service_module, "get_recorded_decision", AsyncMock(return_value=decision))
+ abandon = AsyncMock(return_value=RetryDecision(False, 1, 0, True, "caller_not_retry_aware"))
+ monkeypatch.setattr(service_module, "finalize_abandoned_attempt", abandon)
+ interim = AsyncMock(return_value="lease_held_by_other_young")
+ monkeypatch.setattr(service, "_run_interim_side_effects_with_retries", interim)
+ sleep = AsyncMock()
+ monkeypatch.setattr(service_module, "asyncio", ScopedAsyncio(sleep=sleep))
+
+ async def execute(**kwargs: Any) -> Any:
+ with pytest.raises(_StopForTest):
+ await service.clean_up_workflow(
+ workflow=cast(Any, SimpleNamespace()),
+ workflow_run=cast(Any, run),
+ need_call_webhook=kwargs["need_call_webhook"],
+ )
+ return run
+
+ execute_mock = AsyncMock(side_effect=execute)
+ monkeypatch.setattr(service, "execute_workflow", execute_mock)
+ result = await service.execute_workflow_with_retries(
+ workflow_run_id="wr_1",
+ api_key="k",
+ organization=cast(Any, SimpleNamespace(organization_id="o_1")),
+ )
+
+ assert result is run
+ abandon.assert_not_awaited()
+ assert attempt.retry_decision == "retry"
+ assert attempt.decision_reason == "matched"
+ assert execute_mock.await_args.kwargs["need_call_webhook"] is False
+ interim.assert_awaited_once_with(run, decision, api_key="k")
+ sleep.assert_awaited_once_with(service_module.WORKFLOW_ATTEMPT_LOOKUP_RETRY_DELAY_SECONDS)
+ assert get_attempts.await_count == 3
+
+
+async def test_retry_entry_lookup_persistent_failure_preserves_attempt_without_execution(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ service = WorkflowService()
+ error = RuntimeError("read unavailable")
+ attempt = SimpleNamespace(attempt_number=1, retry_decision="retry", decision_reason="matched")
+ get_attempts = AsyncMock(side_effect=error)
+ repository = SimpleNamespace(get_attempts=get_attempts, attempts=[attempt])
+ monkeypatch.setattr(service_module.app.DATABASE, "workflow_run_attempts", repository)
+ execute = AsyncMock()
+ monkeypatch.setattr(service, "execute_workflow", execute)
+ sleep = AsyncMock()
+ monkeypatch.setattr(service_module, "asyncio", ScopedAsyncio(sleep=sleep))
+
+ with pytest.raises(WorkflowRetryAttemptLookupError) as raised:
+ await service.execute_workflow_with_retries(
+ workflow_run_id="wr_1",
+ api_key="k",
+ organization=cast(Any, SimpleNamespace(organization_id="o_1")),
+ )
+
+ assert raised.value.__cause__ is error
+ execute.assert_not_awaited()
+ assert get_attempts.await_count == 3
+ assert sleep.await_args_list == [call(0.1), call(0.2)]
+ assert repository.attempts == [attempt]
+ assert vars(attempt) == {"attempt_number": 1, "retry_decision": "retry", "decision_reason": "matched"}
+
+
[email protected]("need_call_webhook", [True, False])
+async def test_retry_entry_lookup_empty_first_attempt_keeps_plain_execution(
+ monkeypatch: pytest.MonkeyPatch,
+ need_call_webhook: bool,
+) -> None:
+ service = WorkflowService()
+ get_attempts = AsyncMock(return_value=[])
+ monkeypatch.setattr(service_module.app.DATABASE.workflow_run_attempts, "get_attempts", get_attempts)
+ execute = AsyncMock()
+ monkeypatch.setattr(service, "execute_workflow", execute)
+ organization = cast(Any, SimpleNamespace(organization_id="o_1"))
+ kwargs: dict[str, Any] = {
+ "workflow_run_id": "wr_1",
+ "api_key": "k",
+ "organization": organization,
+ "block_labels": ["block_1"],
+ "block_outputs": {"prior": 1},
+ "browser_session_id": "pbs_1",
+ "need_call_webhook": need_call_webhook,
+ "workflow_override": None,
+ "requested_completion_contract": {"result": "done"},
+ "attempt_number": 1,
+ }
+
+ result = await service.execute_workflow_with_retries(**kwargs)
+
+ assert result is execute.return_value
+ execute.assert_awaited_once_with(**kwargs)
+ get_attempts.assert_awaited_once_with("wr_1")
+
+
[email protected]("retry_loop", [False, True])
+async def test_retry_execution_rejects_missing_pinned_version(
+ monkeypatch: pytest.MonkeyPatch, sqlite_engine: AsyncEngine, retry_loop: bool
+) -> None:
+ database = AgentDB("sqlite+aiosqlite:///:memory:", db_engine=sqlite_engine)
+ monkeypatch.setattr(service_module.app, "DATABASE", database)
+ async with database.Session() as session:
+ session.add_all(
+ [
+ WorkflowRunModel(
+ workflow_run_id="wr_1",
+ workflow_id="wf_missing",
+ workflow_permanent_id="wpid_1",
+ organization_id="o_1",
+ status="queued",
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_1", organization_id="o_1", attempt_number=2, status="queued"
+ ),
+ WorkflowModel(
+ workflow_id="wf_latest",
+ workflow_permanent_id="wpid_1",
+ organization_id="o_1",
+ title="Workflow",
+ workflow_definition={"parameters": [], "blocks": []},
+ ),
+ ]
+ )
+ await session.commit()
+
+ service = WorkflowService()
+ execute = service.execute_workflow_with_retries if retry_loop else service.execute_workflow
+ with pytest.raises(WorkflowNotFoundForWorkflowRun):
+ await execute(
+ workflow_run_id="wr_1",
+ api_key=None,
+ organization=cast(Any, SimpleNamespace(organization_id="o_1")),
+ attempt_number=2,
+ )
+ run = await database.workflow_runs.get_workflow_run("wr_1", "o_1")
+ assert run is not None
+ assert run.status == WorkflowRunStatus.queued
+ assert run.workflow_id == "wf_missing"
diff --git a/tests/unit/test_extraction_block_export.py b/tests/unit/test_extraction_block_export.py
index 78b760d37..7ef0cd792 100644
--- a/tests/unit/test_extraction_block_export.py
+++ b/tests/unit/test_extraction_block_export.py
@@ -98,7 +98,7 @@ async def test_export_enabled_defaults_to_this_blocks_own_extraction(
lambda _run_id: download_directory,
)
monkeypatch.setattr(app.STORAGE, "save_downloaded_files", AsyncMock())
- monkeypatch.setattr(app.STORAGE, "get_downloaded_files", AsyncMock(return_value=[]))
+ monkeypatch.setattr(app.STORAGE, "get_current_attempt_downloaded_files", AsyncMock(return_value=[]))
block = _block(export_enabled=True, export_data_schema=_RECORD_SCHEMA, export_file_name="records")
result = await block.execute("run-id", "block-id", organization_id="org-id")
@@ -162,7 +162,7 @@ async def test_export_enabled_with_null_extraction_exports_zero_rows(
lambda _run_id: download_directory,
)
monkeypatch.setattr(app.STORAGE, "save_downloaded_files", AsyncMock())
- monkeypatch.setattr(app.STORAGE, "get_downloaded_files", AsyncMock(return_value=[]))
+ monkeypatch.setattr(app.STORAGE, "get_current_attempt_downloaded_files", AsyncMock(return_value=[]))
block = _block(export_enabled=True, export_data_schema=_RECORD_SCHEMA)
result = await block.execute("run-id", "block-id", organization_id="org-id")
diff --git a/tests/unit/test_fetch_recording_urls.py b/tests/unit/test_fetch_recording_urls.py
index 4926302e4..f91efc873 100644
--- a/tests/unit/test_fetch_recording_urls.py
+++ b/tests/unit/test_fetch_recording_urls.py
@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock
import pytest
from skyvern.forge import app
+from skyvern.forge.sdk.artifact.models import ArtifactType
from skyvern.forge.sdk.schemas.files import FileInfo
from skyvern.forge.sdk.workflow.service import WorkflowService
@@ -212,3 +213,35 @@ async def test_legacy_run_recording_served_for_non_session_run(monkeypatch) -> N
assert urls == ["legacy_url"]
get_session.assert_not_awaited() # no browser session to fall back to
+
+
[email protected]("scope", ["current_attempt", "historical"])
+async def test_current_retry_scope_keeps_the_unfinalized_recording_hidden(monkeypatch, scope: str) -> None:
+ # A live retry on a retained session is scoped to its own attempt's artifacts, but its non-clip
+ # recording is still open; only a finished historical attempt returns its recording as is.
+ unfinalized = SimpleNamespace(
+ artifact_id="a_attempt2",
+ artifact_type=ArtifactType.RECORDING,
+ uri="s3://b/browser_sessions/pbs_1/wr_1/recording.webm",
+ )
+ list_run_artifacts = AsyncMock(return_value=[unfinalized])
+ monkeypatch.setattr(app.DATABASE.artifacts, "list_artifacts_for_run_by_type", list_run_artifacts, raising=False)
+ monkeypatch.setattr(
+ app.STORAGE, "get_shared_recordings_in_browser_session", AsyncMock(return_value=[]), raising=False
+ )
+ get_links = AsyncMock(return_value=["attempt2_url"])
+ monkeypatch.setattr(app.ARTIFACT_MANAGER, "get_share_links_with_bundle_support", get_links, raising=False)
+ monkeypatch.setattr(app.ARTIFACT_MANAGER, "is_recording_archived", AsyncMock(return_value=False), raising=False)
+
+ urls, archived = await WorkflowService._fetch_recording_urls(
+ object(), _workflow_run(), None, "o_1", **{f"{scope}_artifacts": [unfinalized]}
+ )
+
+ list_run_artifacts.assert_not_awaited()
+ assert archived is False
+ if scope == "current_attempt":
+ assert urls == []
+ get_links.assert_not_awaited()
+ else:
+ assert urls == ["attempt2_url"]
diff --git a/tests/unit/test_file_download_access_control.py b/tests/unit/test_file_download_access_control.py
index 1c772d930..f197247fe 100644
--- a/tests/unit/test_file_download_access_control.py
+++ b/tests/unit/test_file_download_access_control.py
@@ -13,6 +13,7 @@ from skyvern.config import settings
from skyvern.constants import DOWNLOAD_FILE_PREFIX
from skyvern.exceptions import BlockedHost, SkyvernHTTPException
from skyvern.forge.sdk.api import files
+from skyvern.forge.sdk.artifact.storage.local import LocalStorage
from skyvern.utils.url_validators import MAX_SAFE_REDIRECTS
from tests.unit.conftest import LEGACY_DOWNLOAD_ESCAPE_CASES
@@ -78,6 +79,101 @@ async def test_download_file_returns_canonical_legacy_download(legacy_download_u
assert await files.download_file(legacy_download_uris["canonical"]) == os.path.realpath(safe_path)
+async def test_local_download_snapshots_remain_readable_and_contained(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ legacy_download_uris: dict[str, str],
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ assert os.path.realpath(os.path.join(settings.ARTIFACT_STORAGE_PATH, "downloads")) in files._LOCAL_DOWNLOAD_ROOTS
+ default_root = tmp_path / "artifacts" / "downloads"
+ custom_root = tmp_path / "custom-artifacts" / "downloads"
+ malformed_org_ids = ("/", str(tmp_path), "../..", "", ".", "..", "o_test/wr_test", "o_test\\wr_test")
+ monkeypatch.setattr(files, "_LOCAL_DOWNLOAD_ROOTS", {str(default_root)})
+ monkeypatch.setattr(settings, "ENV", "local")
+ LocalStorage(str(custom_root.parent))
+ assert (
+ files.validate_download_url((custom_root / "local/o_1/wr_1/report.pdf").as_uri(), organization_id="o_1") is True
+ )
+ assert (
+ files.validate_download_url(
+ (custom_root.parent / "downloads-evil/local/o_1/wr_1/report.pdf").as_uri(), organization_id="o_1"
+ )
+ is False
+ )
+
+ for root in (default_root, custom_root):
+ for attempt_path in ("report.txt", "attempts/2/report.txt"):
+ snapshot = root / "local" / "o_test" / "wr_test" / attempt_path
+ snapshot.parent.mkdir(parents=True, exist_ok=True)
+ snapshot.write_text("preserved download")
+
+ for organization_id in (None, "o_other", "o_tes", *malformed_org_ids):
+ caplog.clear()
+ assert files.validate_download_url(snapshot.as_uri(), organization_id=organization_id) is False
+ assert "Legacy local file path traversal blocked" in caplog.text
+ caplog.clear()
+ with pytest.raises(PermissionError, match="outside the downloads directory"):
+ await files.download_file(snapshot.as_uri(), organization_id=organization_id)
+ assert "Legacy local file path traversal blocked" in caplog.text
+
+ assert files.validate_download_url(snapshot.as_uri(), organization_id="o_test") is True
+ assert files._resolve_legacy_download_path(str(snapshot), organization_id="o_test") == str(
+ snapshot.resolve()
+ )
+ resolved = await files.download_file(snapshot.as_uri(), organization_id="o_test")
+ assert Path(resolved).read_text() == "preserved download"
+
+ other_org = root / "local" / "o_other"
+ other_org.mkdir()
+ cross_org_link = other_org / "report.txt"
+ cross_org_link.symlink_to(snapshot)
+ for rejected_uri in (
+ cross_org_link.as_uri(),
+ (other_org / ".." / "o_test" / "wr_test" / "report.txt").as_uri(),
+ f"{other_org.as_uri()}/%2E%2E/o_test/wr_test/report.txt",
+ ):
+ assert files.validate_download_url(rejected_uri, organization_id="o_other") is False
+ with pytest.raises(PermissionError, match="outside the downloads directory"):
+ await files.download_file(rejected_uri, organization_id="o_other")
+
+ sibling = root.parent / "downloads-evil" / "secret.txt"
+ sibling.parent.mkdir()
+ sibling.write_text("outside snapshot root")
+ for organization_id in malformed_org_ids:
+ assert files.validate_download_url(sibling.as_uri(), organization_id=organization_id) is False
+ with pytest.raises(PermissionError, match="outside the downloads directory"):
+ await files.download_file(sibling.as_uri(), organization_id=organization_id)
+
+ scope_symlink = root / "local" / "o_link"
+ scope_symlink.symlink_to(sibling.parent, target_is_directory=True)
+ for rejected_uri in ((scope_symlink / sibling.name).as_uri(), sibling.as_uri()):
+ caplog.clear()
+ assert files.validate_download_url(rejected_uri, organization_id="o_link") is False
+ assert "Legacy local file path traversal blocked" in caplog.text
+ caplog.clear()
+ with pytest.raises(PermissionError, match="outside the downloads directory"):
+ await files.download_file(rejected_uri, organization_id="o_link")
+ assert "Legacy local file path traversal blocked" in caplog.text
+
+ symlink = root / "local" / "o_test" / "escape.txt"
+ symlink.symlink_to(sibling)
+ for rejected_uri in (sibling.as_uri(), symlink.as_uri(), legacy_download_uris["parent_traversal"]):
+ assert files.validate_download_url(rejected_uri, organization_id="o_test") is False
+ with pytest.raises(PermissionError, match="outside the downloads directory"):
+ await files.download_file(rejected_uri, organization_id="o_test")
+
+ for organization_id in (None, "o_test", "o_other", *malformed_org_ids):
+ canonical_uri = legacy_download_uris["canonical"]
+ assert files.validate_download_url(canonical_uri, organization_id=organization_id) is True
+ assert await files.download_file(canonical_uri, organization_id=organization_id) == os.path.realpath(
+ files.parse_uri_to_path(canonical_uri)
+ )
+ monkeypatch.setattr(settings, "ENV", "prod")
+ assert files.validate_download_url(snapshot.as_uri(), organization_id="o_test") is False
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("case", LEGACY_DOWNLOAD_ESCAPE_CASES)
async def test_download_file_rejects_legacy_path_escape(
diff --git a/tests/unit/test_file_download_targets.py b/tests/unit/test_file_download_targets.py
index 77c20a2bb..f1fef97fe 100644
--- a/tests/unit/test_file_download_targets.py
+++ b/tests/unit/test_file_download_targets.py
@@ -178,6 +178,7 @@ async def _execute_file_download(
mock_app.DATABASE.observer.update_workflow_run_block = AsyncMock()
mock_app.STORAGE.save_downloaded_files = AsyncMock(side_effect=storage_save_side_effect)
mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=downloaded_file_infos or [])
+ mock_app.STORAGE.get_current_attempt_downloaded_files = mock_app.STORAGE.get_downloaded_files
result = await block.execute(
workflow_run_id="workflow-run-id",
workflow_run_block_id="workflow-run-block-id",
@@ -828,6 +829,55 @@ async def test_same_name_identical_content_frozen_mtime_is_not_delivered(tmp_pat
execution.upload.assert_not_awaited()
[email protected]("attempt_number", [1, 2])
[email protected]("change", ["content", "mtime"])
+async def test_retry_download_delivers_proven_rewrite_with_old_mtime(
+ tmp_path: Path, attempt_number: int, change: str
+) -> None:
+ download_dir = tmp_path / "downloads"
+ rewritten, unchanged = _write_downloads(download_dir, "report.pdf", "unchanged.pdf")
+ rewritten.write_bytes(b"before")
+ old_time = datetime(2026, 1, 1, tzinfo=UTC).timestamp()
+ for file in (rewritten, unchanged):
+ os.utime(file, (old_time, old_time))
+ late_stale = download_dir / "late.pdf"
+ fresh = download_dir / "fresh.pdf"
+ cutoff = datetime(2026, 1, 2, tzinfo=UTC)
+
+ def produce_downloads() -> None:
+ rewritten.write_bytes(b"after!" if change == "content" else b"before")
+ rewritten_time = old_time if change == "content" else old_time + 1
+ os.utime(rewritten, (rewritten_time, rewritten_time))
+ late_stale.write_bytes(b"previous attempt")
+ os.utime(late_stale, (old_time, old_time))
+ fresh.write_bytes(b"new download")
+ os.utime(fresh, (cutoff.timestamp(), cutoff.timestamp()))
+
+ block = _file_download_block(
+ FileDownloadTarget.SFTP,
+ sftp_host="sftp.example.com",
+ sftp_username="skyvern",
+ sftp_password="password",
+ )
+ with patch(
+ "skyvern.forge.sdk.artifact.storage.base.resolve_download_attempt",
+ AsyncMock(return_value=("wr_1", attempt_number, cutoff)),
+ ):
+ execution = await _execute_file_download(
+ block, _browser_result(block), download_dir, during_execute=produce_downloads
+ )
+
+ delivered = {call.kwargs["file_path"] for call in execution.upload.await_args_list}
+ expected = {str(rewritten), str(fresh)}
+ if attempt_number == 1:
+ expected.add(str(late_stale))
+ assert execution.result.success
+ assert delivered == expected
+ assert unchanged.read_bytes() == b"unchanged.pdf"
+ assert late_stale.read_bytes() == b"previous attempt"
+
+
@pytest.mark.asyncio
async def test_nonempty_scoped_download_missing_locally_is_noop(tmp_path: Path) -> None:
block = _file_download_block(
diff --git a/tests/unit/test_file_upload_limits.py b/tests/unit/test_file_upload_limits.py
index dd29816db..367f13adf 100644
--- a/tests/unit/test_file_upload_limits.py
+++ b/tests/unit/test_file_upload_limits.py
@@ -1,3 +1,5 @@
+import os
+from datetime import UTC, datetime
from pathlib import Path
import pytest
@@ -37,3 +39,19 @@ def test_cloud_storage_block_rejects_more_than_300_files(tmp_path: Path, max_fil
download_files_path=str(tmp_path),
max_file_count=max_file_count,
)
+
+
+def test_stale_downloads_do_not_count_toward_upload_limit(tmp_path: Path) -> None:
+ started_at = datetime(2026, 1, 1, tzinfo=UTC)
+ stale = tmp_path / "stale.pdf"
+ fresh = tmp_path / "fresh.pdf"
+ stale.write_bytes(b"old")
+ fresh.write_bytes(b"new")
+ os.utime(stale, (started_at.timestamp() - 1,) * 2)
+ os.utime(fresh, (started_at.timestamp(),) * 2)
+
+ files = FileUploadBlock.model_construct()._get_files_to_upload_from_download_dir(
+ download_files_path=str(tmp_path), max_file_count=1, attempt_started_at=started_at
+ )
+
+ assert files == [str(fresh)]
diff --git a/tests/unit/test_file_upload_prompt.py b/tests/unit/test_file_upload_prompt.py
index 6ab036db0..f44aa33e0 100644
--- a/tests/unit/test_file_upload_prompt.py
+++ b/tests/unit/test_file_upload_prompt.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
+import os
import unicodedata
from datetime import UTC, datetime
from pathlib import Path
@@ -126,6 +127,7 @@ async def _execute_file_upload(
) as handler_factory,
):
mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
+ mock_app.STORAGE.get_current_attempt_downloaded_files = mock_app.STORAGE.get_downloaded_files
mock_app.AGENT_FUNCTION.upload_file_to_customer_storage = upload
mock_app.DATABASE.observer.get_workflow_run_block = AsyncMock(return_value=workflow_run_block)
mock_app.ARTIFACT_MANAGER.create_workflow_run_block_artifacts = persist_artifacts
@@ -613,3 +615,29 @@ def test_file_upload_selection_prompt_renders_filenames_as_contained_json_data()
assert r"\u2460invoice.pdf" in rendered
assert '"1invoice.pdf"' not in rendered
assert '"files_to_upload"' in rendered
+
+
[email protected]("attempt", [2, 1, None, "lookup_failure"])
+async def test_upload_ignores_files_from_previous_attempts(tmp_path: Path, attempt: int | str | None) -> None:
+ download_dir = tmp_path / "downloads"
+ _write_candidates(download_dir, names=("report.pdf", "report (1).pdf"))
+ started_at = datetime(2026, 1, 1, tzinfo=UTC)
+ os.utime(download_dir / "report.pdf", (started_at.timestamp() - 10,) * 2)
+ os.utime(download_dir / "report (1).pdf", (started_at.timestamp(),) * 2)
+ resolver = AsyncMock(
+ side_effect=RuntimeError("attempt lookup unavailable") if attempt == "lookup_failure" else None,
+ return_value=("wr_upload", attempt or 1, started_at if attempt is not None else None),
+ )
+ with (
+ patch("skyvern.forge.sdk.artifact.storage.base.resolve_download_attempt", resolver),
+ structlog.testing.capture_logs() as logs,
+ ):
+ execution = await _execute_file_upload(_file_upload_block(None), download_dir)
+
+ assert execution.result.success is True
+ uploaded_names = {Path(call.kwargs["file_path"]).name for call in execution.upload.await_args_list}
+ assert uploaded_names == ({"report (1).pdf"} if attempt == 2 else {"report.pdf", "report (1).pdf"})
+ assert (download_dir / "report.pdf").exists()
+ if attempt == "lookup_failure":
+ assert any(row["log_level"] == "warning" and "attempt" in row["event"] for row in logs)
diff --git a/tests/unit/test_log_artifacts.py b/tests/unit/test_log_artifacts.py
index 9e2881a7a..d1924ea40 100644
--- a/tests/unit/test_log_artifacts.py
+++ b/tests/unit/test_log_artifacts.py
@@ -1,16 +1,33 @@
"""Tests for skyvern.forge.sdk.log_artifacts."""
+import asyncio
+import logging
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
from unittest.mock import AsyncMock, patch
import pytest
+from sqlalchemy.ext.asyncio import create_async_engine
+from skyvern.forge import app
+from skyvern.forge.sdk.artifact.manager import ArtifactManager
+from skyvern.forge.sdk.artifact.models import ArtifactType
+from skyvern.forge.sdk.artifact.storage.local import LocalStorage
from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.db.agent_db import AgentDB
+from skyvern.forge.sdk.db.models import Base, WorkflowRunAttemptModel
+from skyvern.forge.sdk.forge_log import skyvern_logs_processor
from skyvern.forge.sdk.log_artifacts import (
save_step_logs,
save_task_logs,
save_workflow_run_block_logs,
save_workflow_run_logs,
)
+from skyvern.forge.sdk.workflow import service as service_module
+from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
+from skyvern.forge.sdk.workflow.retry_policy import RetryDecision
+from skyvern.forge.sdk.workflow.service import WorkflowService
@pytest.mark.asyncio
@@ -202,3 +219,185 @@ async def test_save_workflow_run_block_logs_with_context_filters_by_block_id(mon
assert kwargs["log"] == [{"workflow_run_block_id": "wrb_match", "msg": "keep"}]
finally:
skyvern_context.reset()
+
+
[email protected]("replace_context_during_lookup", [False, True])
[email protected]("attempt_raises", [False, True])
+async def test_retry_logs_keep_both_attempts_and_update_only_current_attempt(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ workflow_context_manager_factory,
+ replace_context_during_lookup: bool,
+ attempt_raises: bool,
+) -> None:
+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+ database = AgentDB("sqlite+aiosqlite:///:memory:", db_engine=engine)
+ manager = ArtifactManager()
+ monkeypatch.setattr(app, "DATABASE", database)
+ monkeypatch.setattr(app, "ARTIFACT_MANAGER", manager)
+ monkeypatch.setattr(app, "STORAGE", LocalStorage(str(tmp_path)))
+ monkeypatch.setattr("skyvern.forge.sdk.log_artifacts.settings.ENABLE_LOG_ARTIFACTS", True)
+ context = skyvern_context.SkyvernContext(
+ organization_id="o_logs",
+ workflow_run_id="wr_logs",
+ log=[{"workflow_run_id": "wr_logs", "event": "legacy entry"}],
+ )
+ skyvern_context.set(context)
+ original_get_attempts = database.workflow_run_attempts.get_attempts
+ lookup_entered = asyncio.Event()
+ release_lookup = asyncio.Event()
+ attempt_one_contents: dict[str, bytes] = {}
+ attempt_two_contents: dict[str, bytes] = {}
+
+ async def delayed_get_attempts(workflow_run_id: str) -> list[WorkflowRunAttemptModel]:
+ lookup_entered.set()
+ await release_lookup.wait()
+ return await original_get_attempts(workflow_run_id)
+
+ service = WorkflowService()
+ run = SimpleNamespace(
+ workflow_run_id="wr_logs",
+ organization_id="o_logs",
+ status=WorkflowRunStatus.failed,
+ depends_on_workflow_run_id=None,
+ )
+ release_late_log = asyncio.Event()
+ late_log_task: asyncio.Task[None] | None = None
+
+ def set_workflow_context(attempt: int) -> None:
+ monkeypatch.setattr(
+ app,
+ "WORKFLOW_CONTEXT_MANAGER",
+ workflow_context_manager_factory(workflow_run_id="wr_logs", attempt_number=attempt, mask_secrets=False),
+ )
+
+ async def log_and_save(message: str) -> None:
+ skyvern_logs_processor(logging.getLogger(__name__), "info", {"workflow_run_id": "wr_logs", "event": message})
+ await save_workflow_run_logs("wr_logs")
+ await manager.wait_for_upload_aiotasks(["wr_logs"])
+
+ async def save_late_log() -> None:
+ await release_late_log.wait()
+ await log_and_save("late first")
+
+ async def execute_attempt(*, attempt_number: int, **_kwargs: Any) -> Any:
+ nonlocal attempt_one_contents, attempt_two_contents, late_log_task
+ set_workflow_context(attempt_number)
+ if attempt_number == 1:
+ await log_and_save("first failed")
+ attempt_one_contents = {
+ artifact.uri: Path(artifact.uri.removeprefix("file://")).read_bytes()
+ for artifact in await database.artifacts.get_artifacts_by_entity_id(
+ workflow_run_id="wr_logs", organization_id="o_logs"
+ )
+ }
+ late_log_task = asyncio.create_task(save_late_log())
+ if attempt_raises:
+ raise RuntimeError("attempt failed")
+ else:
+ assert attempt_number == 2
+ await log_and_save("second started")
+ await log_and_save("second completed")
+ app.WORKFLOW_CONTEXT_MANAGER.workflow_run_contexts.pop("wr_logs")
+ await save_workflow_run_logs("wr_logs")
+ await manager.wait_for_upload_aiotasks(["wr_logs"])
+ for uri, content in attempt_one_contents.items():
+ assert Path(uri.removeprefix("file://")).read_bytes() == content
+ attempt_two_contents = {
+ artifact.uri: Path(artifact.uri.removeprefix("file://")).read_bytes()
+ for artifact in await database.artifacts.get_artifacts_by_entity_id(
+ workflow_run_id="wr_logs", organization_id="o_logs"
+ )
+ if "/attempts/2/" in artifact.uri
+ }
+ run.status = WorkflowRunStatus.completed
+ return run
+
+ async def prepare_attempt(**_kwargs: Any) -> SimpleNamespace:
+ async with database.Session() as session:
+ session.add(
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_logs", organization_id="o_logs", attempt_number=2, status="running"
+ )
+ )
+ await session.commit()
+ return SimpleNamespace(status="inserted", pinned_browser_session_id=None, serialized_identity=True)
+
+ async def wait_for_clearance(_run: Any, _attempt_number: int) -> None:
+ assert skyvern_context.current_workflow_log_attempt("wr_logs") is None
+
+ monkeypatch.setattr(service, "execute_workflow", execute_attempt)
+ monkeypatch.setattr(service, "_wait_for_retry_sequential_clearance", wait_for_clearance)
+ monkeypatch.setattr(service, "_run_interim_side_effects_with_retries", AsyncMock(return_value="released"))
+ monkeypatch.setattr(service, "_run_terminal_side_effects_with_retries", AsyncMock(return_value="released"))
+ monkeypatch.setattr(database.workflow_runs, "get_workflow_run", AsyncMock(return_value=run))
+ monkeypatch.setattr(
+ database.workflow_run_attempts, "claim_prepared_attempt_execution", AsyncMock(return_value=True)
+ )
+ monkeypatch.setattr(service_module, "prepare_next_attempt_result", prepare_attempt)
+ monkeypatch.setattr(
+ service_module,
+ "get_recorded_decision",
+ AsyncMock(
+ side_effect=[
+ RetryDecision(True, 1, 0, True, "matched"),
+ RetryDecision(True, 1, 0, True, "matched"),
+ RetryDecision(False, 2, 0, True, "budget_exhausted"),
+ ]
+ ),
+ )
+
+ try:
+ async with database.Session() as session:
+ session.add(
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_logs", organization_id="o_logs", attempt_number=1, status="running"
+ )
+ )
+ await session.commit()
+ await service.execute_workflow_with_retries(
+ workflow_run_id="wr_logs", api_key=None, organization=SimpleNamespace(organization_id="o_logs")
+ )
+ assert attempt_one_contents
+ assert attempt_two_contents
+ assert skyvern_context.current_workflow_log_attempt("wr_logs") is None
+ assert late_log_task is not None
+ set_workflow_context(1)
+ if replace_context_during_lookup:
+ monkeypatch.setattr(database.workflow_run_attempts, "get_attempts", delayed_get_attempts)
+ release_late_log.set()
+ if replace_context_during_lookup:
+ await asyncio.wait_for(lookup_entered.wait(), timeout=5)
+ set_workflow_context(2)
+ release_lookup.set()
+ await late_log_task
+ artifacts = await database.artifacts.get_artifacts_by_entity_id(
+ workflow_run_id="wr_logs", organization_id="o_logs"
+ )
+ assert len(artifacts) == 4
+ for artifact in artifacts:
+ assert artifact.artifact_type in (ArtifactType.SKYVERN_LOG, ArtifactType.SKYVERN_LOG_RAW)
+ content = Path(artifact.uri.removeprefix("file://")).read_bytes()
+ assert b"legacy entry" in content
+ if "/attempts/2/" in artifact.uri:
+ assert content == attempt_two_contents[artifact.uri]
+ assert b"second started" in content
+ assert b"second completed" in content
+ assert b"first failed" not in content
+ assert b"late first" not in content
+ else:
+ assert "/wr_logs/" in artifact.uri
+ assert "/attempts/" not in artifact.uri
+ assert b"first failed" in content
+ assert b"late first" in content
+ assert b"second started" not in content
+ assert b"second completed" not in content
+ finally:
+ if late_log_task is not None and not late_log_task.done():
+ late_log_task.cancel()
+ await asyncio.gather(late_log_task, return_exceptions=True)
+ skyvern_context.reset()
+ await engine.dispose()
diff --git a/tests/unit/test_missing_starter_url.py b/tests/unit/test_missing_starter_url.py
index a23741e67..5e17b54f2 100644
--- a/tests/unit/test_missing_starter_url.py
+++ b/tests/unit/test_missing_starter_url.py
@@ -257,7 +257,7 @@ async def test_create_task_rejects_about_blank_url_inherited_from_later_block()
workflow = SimpleNamespace(workflow_id="w_missing_starter_url_test")
workflow_run = _workflow_run_for_create_task()
- workflow_run_context = SimpleNamespace(get_value=MagicMock())
+ workflow_run_context = SimpleNamespace(get_value=MagicMock(), attempt_number=1)
with patch("skyvern.forge.agent.app") as mock_app:
mock_app.BROWSER_MANAGER = browser_manager
@@ -311,7 +311,7 @@ async def test_create_task_uses_latest_non_blank_page_for_inherited_marker_url()
workflow = SimpleNamespace(workflow_id="w_missing_starter_url_test")
workflow_run = _workflow_run_for_create_task()
- workflow_run_context = SimpleNamespace(get_value=MagicMock())
+ workflow_run_context = SimpleNamespace(get_value=MagicMock(), attempt_number=1)
with patch("skyvern.forge.agent.app") as mock_app:
mock_app.BROWSER_MANAGER = browser_manager
diff --git a/tests/unit/test_onboarding_milestone_hooks.py b/tests/unit/test_onboarding_milestone_hooks.py
index ded5e415a..15275c1b6 100644
--- a/tests/unit/test_onboarding_milestone_hooks.py
+++ b/tests/unit/test_onboarding_milestone_hooks.py
@@ -14,6 +14,7 @@ from skyvern.forge.agent_functions import AgentFunction
from skyvern.forge.sdk.services import org_auth_service
from skyvern.forge.sdk.workflow.models.tags import CallerType
from skyvern.schemas.workflows import WorkflowCreateYAMLRequest, WorkflowDefinitionYAML, WorkflowRequest
+from tests.unit.force_stub_app import make_workflow_run_attempts_fake
@pytest.fixture()
@@ -517,6 +518,7 @@ class TestWorkflowRunCompleteHookFires:
mock_db.workflow_runs.update_workflow_run_if_not_final = AsyncMock(return_value=mock_workflow_run)
mock_db.workflow_runs.update_workflow_run = AsyncMock(return_value=mock_workflow_run)
mock_db.tags.apply_system_run_tag_changes = AsyncMock()
+ mock_db.workflow_run_attempts = make_workflow_run_attempts_fake()
with (
patch("skyvern.forge.sdk.workflow.service.app") as mock_app,
@@ -571,6 +573,7 @@ class TestWorkflowRunCompleteHookFires:
workflow_run_id="wr_1",
organization_id="o_789",
status="completed",
+ is_final_attempt=True,
)
return browser_cleanup_result
@@ -586,6 +589,7 @@ class TestWorkflowRunCompleteHookFires:
AsyncMock()
)
mock_app.WORKFLOW_CONTEXT_MANAGER.remove_workflow_run_context = MagicMock()
+ mock_app.DATABASE.workflow_run_attempts = make_workflow_run_attempts_fake()
mock_app.DATABASE.workflow_runs.get_workflow_runs_by_parent_workflow_run_id = AsyncMock(return_value=[])
from skyvern.forge.sdk.workflow.service import WorkflowService
@@ -604,6 +608,7 @@ class TestWorkflowRunCompleteHookFires:
workflow_run_id="wr_1",
organization_id="o_789",
status="completed",
+ is_final_attempt=True,
)
@pytest.mark.asyncio
diff --git a/tests/unit/test_output_parameter_size_guards.py b/tests/unit/test_output_parameter_size_guards.py
index 20b0dcc59..3295b37a7 100644
--- a/tests/unit/test_output_parameter_size_guards.py
+++ b/tests/unit/test_output_parameter_size_guards.py
@@ -42,6 +42,7 @@ from skyvern.schemas.workflows import BlockType
from skyvern.services import run_service, task_v2_service
from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.actions import Action
+from tests.unit.force_stub_app import make_workflow_run_attempts_fake
# ---------- Layer 1: truncate_oversized_jsonb_value ----------
@@ -390,6 +391,7 @@ async def _build_status_response(
get_workflow_run_block_errors=AsyncMock(return_value=[]),
get_workflow_run_retried_by=AsyncMock(return_value=None),
),
+ workflow_run_attempts=make_workflow_run_attempts_fake(),
),
)
monkeypatch.setattr(workflow_service_module, "RUN_RESPONSE_MAX_VALUE_BYTES", cap)
diff --git a/tests/unit/test_print_page_block_downloaded_files.py b/tests/unit/test_print_page_block_downloaded_files.py
index f14321bdc..b08390be9 100644
--- a/tests/unit/test_print_page_block_downloaded_files.py
+++ b/tests/unit/test_print_page_block_downloaded_files.py
@@ -84,14 +84,15 @@ async def test_print_page_block_includes_downloaded_files_in_output(
)
save_mock = AsyncMock()
- # capture_block_download_baseline calls get_downloaded_files first (empty here),
+ # capture_block_download_baseline calls get_current_attempt_downloaded_files first (empty here),
# then the helper calls it again post-PDF.
get_mock = AsyncMock(side_effect=[[], [file_info]])
fake_app = SimpleNamespace(
STORAGE=SimpleNamespace(
+ get_downloaded_file_signature_aliases=lambda _: [],
save_downloaded_files=save_mock,
- get_downloaded_files=get_mock,
+ get_current_attempt_downloaded_files=get_mock,
),
)
monkeypatch.setattr(block_module, "app", fake_app)
@@ -174,8 +175,9 @@ async def test_print_page_block_filters_downloads_to_current_loop_iteration(
# post-PDF read sees both. The block must scope its output to just the new one.
fake_app = SimpleNamespace(
STORAGE=SimpleNamespace(
+ get_downloaded_file_signature_aliases=lambda _: [],
save_downloaded_files=AsyncMock(),
- get_downloaded_files=AsyncMock(side_effect=[[prev_file], [prev_file, new_file]]),
+ get_current_attempt_downloaded_files=AsyncMock(side_effect=[[prev_file], [prev_file, new_file]]),
),
)
monkeypatch.setattr(block_module, "app", fake_app)
@@ -224,13 +226,14 @@ async def test_print_page_block_tolerates_save_failure(
skyvern_context.set(SkyvernContext(organization_id="o_1", workflow_run_id="wr_1", run_id="wr_1"))
save_mock = AsyncMock(side_effect=RuntimeError("S3 down"))
- # Baseline-capture awaits get_downloaded_files once before save runs.
+ # Baseline-capture awaits get_current_attempt_downloaded_files once before save runs.
get_mock = AsyncMock(return_value=[])
fake_app = SimpleNamespace(
STORAGE=SimpleNamespace(
+ get_downloaded_file_signature_aliases=lambda _: [],
save_downloaded_files=save_mock,
- get_downloaded_files=get_mock,
+ get_current_attempt_downloaded_files=get_mock,
),
)
monkeypatch.setattr(block_module, "app", fake_app)
@@ -305,8 +308,9 @@ async def test_print_page_block_excludes_files_downloaded_by_prior_block(
get_mock = AsyncMock(side_effect=[[prior_file], [prior_file, new_file]])
fake_app = SimpleNamespace(
STORAGE=SimpleNamespace(
+ get_downloaded_file_signature_aliases=lambda _: [],
save_downloaded_files=AsyncMock(),
- get_downloaded_files=get_mock,
+ get_current_attempt_downloaded_files=get_mock,
),
)
monkeypatch.setattr(block_module, "app", fake_app)
diff --git a/tests/unit/test_run_sdk_action_failures.py b/tests/unit/test_run_sdk_action_failures.py
index 8d9e2575a..a1000e9ae 100644
--- a/tests/unit/test_run_sdk_action_failures.py
+++ b/tests/unit/test_run_sdk_action_failures.py
@@ -139,6 +139,44 @@ async def test_caller_provided_run_keeps_general_task_type(
mock_app.WORKFLOW_SERVICE.mark_workflow_run_as_completed.assert_not_awaited()
+ ("run_is_live_here", "expected_attempt"),
+ [(False, 2), (True, 3)],
+ ids=["run_owned_by_another_process", "run_live_in_this_process"],
+)
+async def test_caller_provided_run_stamps_the_current_attempt(
+ mock_request: Any, mock_organization: Any, mock_app: Any, run_is_live_here: bool, expected_attempt: int
+) -> None:
+ """A retried run owned by another process has no local context; the durable rows decide."""
+ mock_app.WORKFLOW_CONTEXT_MANAGER.has_workflow_run_context = MagicMock(return_value=run_is_live_here)
+ mock_app.WORKFLOW_CONTEXT_MANAGER.get_attempt_number = MagicMock(return_value=3)
+ mock_app.DATABASE.workflow_run_attempts.get_attempts = AsyncMock(
+ return_value=[MagicMock(attempt_number=1), MagicMock(attempt_number=2)]
+ )
+ mock_app.WORKFLOW_SERVICE.mark_workflow_run_as_completed = AsyncMock()
+
+ with (
+ patch("skyvern.forge.sdk.routes.sdk.app", mock_app),
+ patch("skyvern.forge.sdk.routes.sdk.skyvern_context") as mock_ctx,
+ patch(
+ "skyvern.core.script_generations.script_skyvern_page.ScriptSkyvernPage.create_scraped_page",
+ new_callable=AsyncMock,
+ side_effect=RuntimeError("stop inside action"),
+ ),
+ ):
+ mock_ctx.ensure_context.return_value = MagicMock(request_id="req_test", tz_info=None, prompt=None)
+ with pytest.raises(RuntimeError, match="stop inside action"):
+ await run_sdk_action(mock_request, organization=mock_organization)
+
+ assert mock_app.DATABASE.tasks.create_task.await_args.kwargs["attempt_number"] == expected_attempt
+ assert mock_app.DATABASE.observer.create_workflow_run_block.await_args.kwargs["attempt_number"] == expected_attempt
+ assert mock_app.WORKFLOW_CONTEXT_MANAGER.initialize_workflow_run_context.await_args.kwargs["attempt_number"] == (
+ expected_attempt
+ )
+ assert mock_app.DATABASE.workflow_run_attempts.get_attempts.await_count == (0 if run_is_live_here else 1)
+
+
@pytest.mark.asyncio
async def test_minted_sdk_action_uses_inline_dispatch_without_generic_executor(
mock_request: Any, mock_organization: Any, mock_app: Any
diff --git a/tests/unit/test_runs_list_run_tag_filter.py b/tests/unit/test_runs_list_run_tag_filter.py
index 76e0577b9..55e2c71e2 100644
--- a/tests/unit/test_runs_list_run_tag_filter.py
+++ b/tests/unit/test_runs_list_run_tag_filter.py
@@ -28,6 +28,7 @@ from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.services import org_auth_service
from skyvern.forge.sdk.workflow.models.tags import TagEventType, TagSource
from skyvern.schemas.run_enums import RunType
+from tests.unit.force_stub_app import make_workflow_run_attempts_fake
ORG_ID = "o_test"
@@ -302,6 +303,7 @@ def route_client(monkeypatch: pytest.MonkeyPatch) -> TestClient:
app_mock = MagicMock()
app_mock.DATABASE.workflow_runs = workflow_runs_mock
+ app_mock.DATABASE.workflow_run_attempts = make_workflow_run_attempts_fake()
app_mock.AGENT_FUNCTION.is_workflow_tagging_enabled = AsyncMock(return_value=True)
test_app = FastAPI()
diff --git a/tests/unit/test_runs_v2_route.py b/tests/unit/test_runs_v2_route.py
index e86a5357a..d6ee095c4 100644
--- a/tests/unit/test_runs_v2_route.py
+++ b/tests/unit/test_runs_v2_route.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timezone
+from datetime import UTC, datetime, timedelta, timezone
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock, call
@@ -10,11 +10,15 @@ from fastapi import BackgroundTasks, HTTPException
from skyvern.constants import SKYVERN_MCP_USER_AGENT, SKYVERN_UI_USER_AGENT
from skyvern.exceptions import WorkflowNotFound
from skyvern.forge.sdk.db.enums import WorkflowRunTriggerType
+from skyvern.forge.sdk.db.models import WorkflowRunAttemptModel
from skyvern.forge.sdk.routes import agent_protocol
+from skyvern.forge.sdk.schemas.tasks import Task, TaskStatus
from skyvern.forge.sdk.workflow.models.tags import CallerType, TagSource
-from skyvern.forge.sdk.workflow.models.workflow import WorkflowRequestBody, WorkflowRunStatus
+from skyvern.forge.sdk.workflow.models.workflow import WorkflowRequestBody, WorkflowRun, WorkflowRunStatus
+from skyvern.forge.sdk.workflow.service import WorkflowService
from skyvern.schemas.run_enums import RunEngine, RunType
from skyvern.schemas.runs import MAX_SEARCH_FETCH_LIMIT, TaskRunRequest
+from tests.unit.force_stub_app import make_workflow_run_attempts_fake
def _caller(org_id: str = "org_123") -> SimpleNamespace:
@@ -25,6 +29,107 @@ def _caller(org_id: str = "org_123") -> SimpleNamespace:
)
+async def test_get_runs_enriches_retry_state_preserving_tasks_and_order(monkeypatch: pytest.MonkeyPatch) -> None:
+ now = datetime(2026, 4, 1, tzinfo=UTC)
+ next_attempt_at = now + timedelta(minutes=5)
+ retrying_run = WorkflowRun(
+ workflow_run_id="wr_retrying",
+ workflow_id="wf_123",
+ workflow_permanent_id="wpid_123",
+ organization_id="org_123",
+ status=WorkflowRunStatus.failed,
+ created_at=now,
+ modified_at=now,
+ finished_at=now,
+ )
+ completed_run = retrying_run.model_copy(
+ update={"workflow_run_id": "wr_completed", "status": WorkflowRunStatus.completed}
+ )
+ revoked_run = retrying_run.model_copy(update={"workflow_run_id": "wr_revoked"})
+ task = Task(
+ task_id="tsk_123",
+ organization_id="org_123",
+ url="https://example.com",
+ status=TaskStatus.completed,
+ created_at=now,
+ modified_at=now,
+ )
+ task_before = task.model_dump()
+ attempts = make_workflow_run_attempts_fake()
+ attempts.get_latest_attempts_for_runs.return_value = {
+ "wr_retrying": WorkflowRunAttemptModel(
+ workflow_run_id="wr_retrying",
+ organization_id="org_123",
+ attempt_number=1,
+ status="failed",
+ finished_at=now,
+ retry_decision="retry",
+ next_attempt_at=next_attempt_at,
+ next_attempt_prepared_at=None,
+ ),
+ "wr_completed": WorkflowRunAttemptModel(
+ workflow_run_id="wr_completed",
+ organization_id="org_123",
+ attempt_number=2,
+ status="completed",
+ finished_at=now,
+ retry_decision="final",
+ next_attempt_at=None,
+ ),
+ # A cancel during the delay keeps the scheduled time on the row; the list must not advertise it.
+ "wr_revoked": WorkflowRunAttemptModel(
+ workflow_run_id="wr_revoked",
+ organization_id="org_123",
+ attempt_number=1,
+ status="failed",
+ finished_at=now,
+ retry_decision="revoked",
+ next_attempt_at=next_attempt_at,
+ next_attempt_prepared_at=None,
+ ),
+ }
+ workflow_runs = SimpleNamespace(
+ get_all_runs=AsyncMock(return_value=[retrying_run, task, completed_run, revoked_run])
+ )
+ monkeypatch.setattr(
+ agent_protocol.app, "DATABASE", SimpleNamespace(workflow_runs=workflow_runs, workflow_run_attempts=attempts)
+ )
+ monkeypatch.setattr(agent_protocol.app, "WORKFLOW_SERVICE", WorkflowService())
+ monkeypatch.setattr(agent_protocol.analytics, "capture", lambda *args, **kwargs: None)
+
+ response = await agent_protocol.get_runs(
+ current_org=SimpleNamespace(organization_id="org_123"),
+ page=2,
+ page_size=5,
+ status=[WorkflowRunStatus.failed, WorkflowRunStatus.completed],
+ search_key="example",
+ )
+
+ rows = orjson.loads(response.body)
+ assert len(rows) == 4
+ assert rows[0]["workflow_run_id"] == "wr_retrying"
+ assert rows[0]["attempt"] == 1
+ assert rows[0]["retry_pending"] is True
+ assert rows[0]["next_attempt_at"] == next_attempt_at.isoformat()
+ assert rows[1] == orjson.loads(orjson.dumps(task_before))
+ assert task.model_dump() == task_before
+ assert rows[2]["workflow_run_id"] == "wr_completed"
+ assert rows[2]["attempt"] == 2
+ assert rows[2]["retry_pending"] is False
+ assert rows[2]["next_attempt_at"] is None
+ assert rows[3]["workflow_run_id"] == "wr_revoked"
+ assert rows[3]["retry_pending"] is False
+ assert rows[3]["next_attempt_at"] is None
+ workflow_runs.get_all_runs.assert_awaited_once_with(
+ "org_123",
+ page=2,
+ page_size=5,
+ status=[WorkflowRunStatus.failed, WorkflowRunStatus.completed],
+ search_key="example",
+ )
+
+
@pytest.mark.asyncio
async def test_get_runs_v2_serializes_mapping_rows_from_database(monkeypatch: pytest.MonkeyPatch) -> None:
mock_workflow_runs = SimpleNamespace(
@@ -48,7 +153,10 @@ async def test_get_runs_v2_serializes_mapping_rows_from_database(monkeypatch: py
]
)
)
- mock_database = SimpleNamespace(workflow_runs=mock_workflow_runs)
+ mock_database = SimpleNamespace(
+ workflow_runs=mock_workflow_runs,
+ workflow_run_attempts=make_workflow_run_attempts_fake(),
+ )
monkeypatch.setattr(agent_protocol.app, "DATABASE", mock_database)
response = await agent_protocol.get_runs_v2(
@@ -85,14 +193,72 @@ async def test_get_runs_v2_serializes_mapping_rows_from_database(monkeypatch: py
"workflow_deleted": False,
"script_run": False,
"trigger_type": "mcp",
+ "attempt": 1,
+ "retry_pending": False,
+ "next_attempt_at": None,
}
]
+async def test_get_runs_v2_applies_retry_decision_grace_window(monkeypatch: pytest.MonkeyPatch) -> None:
+ mock_workflow_runs = SimpleNamespace(
+ get_all_runs_v2=AsyncMock(
+ return_value=[
+ {
+ "task_run_id": "tr_123",
+ "run_id": "wr_123",
+ "task_run_type": "workflow_run",
+ "status": "completed",
+ "title": "Workflow run",
+ "started_at": None,
+ # The task_runs mirror can lag the canonical workflow_runs row. Retry grace
+ # must use the latter so list and detail agree during that window.
+ "finished_at": None,
+ "workflow_run_finished_at": datetime.now(UTC) - timedelta(seconds=30),
+ "created_at": "2026-04-01T00:00:00Z",
+ "workflow_permanent_id": "wpid_123",
+ "workflow_deleted": False,
+ "script_run": False,
+ "trigger_type": "mcp",
+ "searchable_text": "Workflow run",
+ }
+ ]
+ )
+ )
+ mock_attempt = SimpleNamespace(
+ attempt_number=1,
+ retry_decision=None,
+ next_attempt_prepared_at=None,
+ next_attempt_at=None,
+ )
+ mock_database = SimpleNamespace(
+ workflow_runs=mock_workflow_runs,
+ workflow_run_attempts=SimpleNamespace(
+ get_latest_attempts_for_runs=AsyncMock(return_value={"wr_123": mock_attempt})
+ ),
+ )
+ monkeypatch.setattr(agent_protocol.app, "DATABASE", mock_database)
+
+ response = await agent_protocol.get_runs_v2(
+ current_org=SimpleNamespace(organization_id="org_123"),
+ page=1,
+ page_size=5,
+ search_key=None,
+ run_type=[RunType.workflow_run],
+ failure_category=None,
+ )
+
+ assert orjson.loads(response.body)[0]["retry_pending"] is True
+
+
@pytest.mark.asyncio
async def test_get_runs_v2_forwards_workflow_permanent_id_filter(monkeypatch: pytest.MonkeyPatch) -> None:
mock_workflow_runs = SimpleNamespace(get_all_runs_v2=AsyncMock(return_value=[]))
- mock_database = SimpleNamespace(workflow_runs=mock_workflow_runs)
+ mock_database = SimpleNamespace(
+ workflow_runs=mock_workflow_runs,
+ workflow_run_attempts=make_workflow_run_attempts_fake(),
+ )
monkeypatch.setattr(agent_protocol.app, "DATABASE", mock_database)
await agent_protocol.get_runs_v2(
diff --git a/tests/unit/test_saved_session_proxy_pin.py b/tests/unit/test_saved_session_proxy_pin.py
index 751399391..cd5838dd3 100644
--- a/tests/unit/test_saved_session_proxy_pin.py
+++ b/tests/unit/test_saved_session_proxy_pin.py
@@ -45,7 +45,7 @@ def _workflow(
code_version=None,
adaptive_caching=False,
sequential_key=None,
- workflow_definition=SimpleNamespace(parameters=parameters or [], blocks=[]),
+ workflow_definition=SimpleNamespace(parameters=parameters or [], blocks=[], retry_policy=None),
)
@@ -141,7 +141,14 @@ async def _create_forced_workflow_run(
get_or_create_profile = get_or_create_profile or AsyncMock(return_value=(_profile(), False))
update_profile = update_profile or AsyncMock(return_value=_profile())
create_events: list[str] = []
- created_workflow_run = SimpleNamespace(workflow_run_id="wr_forced")
+ created_workflow_run = SimpleNamespace(
+ workflow_run_id="wr_forced",
+ workflow_id="wf_test",
+ organization_id="org_test",
+ parent_workflow_run_id=None,
+ debug_session_id=None,
+ copilot_session_id=None,
+ )
async def _create_workflow_run(**_: object) -> SimpleNamespace:
create_events.append("create_workflow_run")
@@ -753,7 +760,16 @@ async def test_create_workflow_run_non_force_path_single_create_no_update(monkey
browser_session_id="pbs_requested",
proxy_location=ProxyLocation.RESIDENTIAL_ISP,
)
- create_workflow_run = AsyncMock(return_value=SimpleNamespace(workflow_run_id="wr_non_force"))
+ create_workflow_run = AsyncMock(
+ return_value=SimpleNamespace(
+ workflow_run_id="wr_non_force",
+ workflow_id="wf_test",
+ organization_id="org_test",
+ parent_workflow_run_id=None,
+ debug_session_id=None,
+ copilot_session_id=None,
+ )
+ )
update_workflow_run = AsyncMock()
monkeypatch.setattr(
app.DATABASE.browser_sessions,
diff --git a/tests/unit/test_script_skyvern_page.py b/tests/unit/test_script_skyvern_page.py
index f340a7a23..1d9a5bb52 100644
--- a/tests/unit/test_script_skyvern_page.py
+++ b/tests/unit/test_script_skyvern_page.py
@@ -10,14 +10,25 @@ and wait() (accepts both seconds= and timeout_ms= parameter styles).
import asyncio
import contextlib
import inspect
+import os
import re
import time
+from contextvars import ContextVar
+from datetime import UTC, datetime
+from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
+import httpx
import pytest
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
+import skyvern.forge.api_app as api_app_module
+import skyvern.forge.sdk.artifact.manager as artifact_manager_module
+import skyvern.forge.sdk.artifact.storage.base as storage_base_module
+import skyvern.forge.sdk.artifact.storage.local as local_storage_module
+import skyvern.forge.sdk.workflow.service as workflow_service_module
+import skyvern.library.embedded_server_factory as embedded_server_module
from skyvern.config import settings
from skyvern.core.script_generations.real_skyvern_page_ai import RealSkyvernPageAi
from skyvern.core.script_generations.script_skyvern_page import ScriptSkyvernPage
@@ -30,7 +41,17 @@ from skyvern.exceptions import (
SkyvernHTTPException,
StaleFrameSelectionError,
)
+from skyvern.forge.sdk.api import files as files_module
+from skyvern.forge.sdk.artifact.manager import ArtifactManager
+from skyvern.forge.sdk.artifact.models import Artifact
+from skyvern.forge.sdk.artifact.storage.local import LocalStorage
+from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
+from skyvern.forge.sdk.schemas.organizations import Organization
+from skyvern.forge.sdk.services import org_auth_service
+from skyvern.forge.sdk.workflow.service import WorkflowService
+from skyvern.library.skyvern import Skyvern
+from skyvern.library.skyvern_browser_page import SkyvernBrowserPage
from skyvern.services import script_service
from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.handler import ActionHandler
@@ -3866,3 +3887,217 @@ async def test_select_ai_fallback_propagates_a_mid_action_stale_frame_refusal(mo
with pytest.raises(StaleFrameSelectionError):
await page.fill_from_mapping([field], {0: "France"})
+
+
[email protected]("organization_source", ["api_key", "embedded", "none"])
+async def test_library_page_reads_response_snapshot_with_trusted_organization(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, organization_source: str
+) -> None:
+ monkeypatch.setattr(settings, "ENV", "local")
+ monkeypatch.setattr(skyvern_context, "_context", ContextVar("test_context", default=None))
+ download_dir = tmp_path / "live_downloads"
+ download_dir.mkdir()
+ live_file = download_dir / "report.pdf"
+ live_file.write_bytes(b"attempt one")
+ storage = LocalStorage(str(tmp_path / "artifacts"))
+ rows: list[Artifact] = []
+
+ async def find_artifact(*, uri: str, **kwargs):
+ return next((row for row in rows if row.uri == uri), None)
+
+ async def create_artifact(**kwargs):
+ row = Artifact(**kwargs, created_at=datetime.now(UTC), modified_at=datetime.now(UTC))
+ rows.append(row)
+ return row
+
+ fake_app = SimpleNamespace(
+ STORAGE=storage,
+ ARTIFACT_MANAGER=ArtifactManager(),
+ DATABASE=SimpleNamespace(
+ workflow_runs=SimpleNamespace(get_workflow_run=AsyncMock(return_value=None)),
+ workflow_run_attempts=SimpleNamespace(get_attempts=AsyncMock(return_value=[])),
+ artifacts=SimpleNamespace(
+ list_artifacts_for_run_by_type=AsyncMock(side_effect=lambda **kwargs: list(rows)),
+ find_download_artifact=find_artifact,
+ create_artifact=create_artifact,
+ ),
+ ),
+ )
+ for module in (artifact_manager_module, storage_base_module, local_storage_module, workflow_service_module):
+ monkeypatch.setattr(module, "app", fake_app)
+ monkeypatch.setattr(local_storage_module, "get_download_dir", lambda **kwargs: str(download_dir))
+ await storage.save_downloaded_files(organization_id="o_1", run_id="wr_1", attempt_number=1)
+ _, urls = await WorkflowService()._fetch_downloaded_files(
+ SimpleNamespace(workflow_run_id="wr_1", organization_id="o_1"), task_v2=None
+ )
+ assert urls == [rows[0].uri]
+ snapshot_url = urls[0]
+ live_file.write_bytes(b"attempt two")
+
+ def authenticate(request: httpx.Request) -> httpx.Response:
+ assert request.url.path == "/api/v1/organizations/me"
+ if request.headers.get("x-api-key") != "test-api-key":
+ return httpx.Response(401)
+ return httpx.Response(200, json={"organization_id": "o_1"})
+
+ transport: httpx.AsyncBaseTransport = httpx.MockTransport(authenticate)
+ if organization_source == "embedded":
+ monkeypatch.setattr(settings, "OTEL_ENABLED", False)
+ monkeypatch.delenv("LMNR_PROJECT_API_KEY", raising=False)
+ monkeypatch.setattr(api_app_module, "start_forge_app", lambda: SimpleNamespace(setup_api_app=None))
+ api = api_app_module.create_api_app()
+
+ async def authenticated_org() -> Organization:
+ organization = Organization(
+ organization_id="o_1",
+ organization_name="Test organization",
+ created_at=datetime.now(UTC),
+ modified_at=datetime.now(UTC),
+ )
+ org_auth_service.apply_request_org_context(organization)
+ return organization
+
+ api.dependency_overrides[org_auth_service.get_current_org] = authenticated_org
+ transport = httpx.ASGITransport(app=api)
+
+ async with httpx.AsyncClient(transport=transport) as http_client:
+ if organization_source == "embedded":
+ http_client.headers["x-api-key"] = "test-api-key"
+ monkeypatch.setattr(embedded_server_module, "create_embedded_server", lambda **kwargs: http_client)
+ sdk = Skyvern.local(use_in_memory_db=True)
+ else:
+ sdk = Skyvern(
+ api_key="test-api-key" if organization_source == "api_key" else "",
+ base_url="https://api.example.test",
+ httpx_client=http_client,
+ )
+ uploaded_bytes: list[bytes] = []
+
+ async def set_input_files(path: str, **kwargs) -> None:
+ uploaded_bytes.append(Path(path).read_bytes())
+
+ raw_page = create_mock_page()
+ raw_page.locator = MagicMock(return_value=SimpleNamespace(set_input_files=set_input_files))
+ with patch("skyvern.core.script_generations.skyvern_page.Page.__init__", return_value=None):
+ page = SkyvernBrowserPage(SimpleNamespace(skyvern=sdk), raw_page)
+
+ if organization_source == "none":
+ with pytest.raises(PermissionError):
+ await page.download_file(download_url=snapshot_url)
+ with pytest.raises(PermissionError):
+ await page.upload_file(selector="#file", files=snapshot_url, ai=None)
+ assert uploaded_bytes == []
+ return
+
+ context = SkyvernContext()
+ skyvern_context.set(context)
+ downloaded_path = await page.download_file(download_url=snapshot_url)
+ assert Path(downloaded_path).read_bytes() == b"attempt one"
+ await page.upload_file(selector="#file", files=snapshot_url)
+ await page.upload_file(selector="#file", files=snapshot_url, ai=None)
+ assert uploaded_bytes == [b"attempt one", b"attempt one"]
+ assert skyvern_context.current() is context
+ assert context.organization_id is None
+ assert context.request_id is None
+
+ context = SkyvernContext()
+ skyvern_context.set(context)
+ downloaded_path = await page.download_file(download_url=snapshot_url)
+ assert Path(downloaded_path).read_bytes() == b"attempt one"
+ await page.upload_file(selector="#file", files=snapshot_url, ai=None)
+ assert uploaded_bytes[-1] == b"attempt one"
+ assert skyvern_context.current() is context
+
+ context = SkyvernContext(organization_id="o_other")
+ skyvern_context.set(context)
+ with pytest.raises(PermissionError):
+ await page.download_file(download_url=snapshot_url)
+ with pytest.raises(PermissionError):
+ await page.upload_file(selector="#file", files=snapshot_url, ai=None)
+ assert skyvern_context.current() is context
+
+
[email protected]("lookup_failure", ["offline", "unauthorized"])
+async def test_library_page_unscoped_files_skip_organization_lookup(
+ monkeypatch: pytest.MonkeyPatch, legacy_download_uris: dict[str, str], lookup_failure: str
+) -> None:
+ monkeypatch.setattr(settings, "ENV", "local")
+ monkeypatch.setattr(skyvern_context, "_context", ContextVar("test_context", default=None))
+ requests: list[httpx.Request] = []
+
+ def unavailable_api(request: httpx.Request) -> httpx.Response:
+ requests.append(request)
+ if lookup_failure == "offline":
+ raise httpx.ConnectError("API unavailable", request=request)
+ return httpx.Response(401)
+
+ uploaded_bytes: list[bytes] = []
+
+ async def set_input_files(path: str, **kwargs) -> None:
+ uploaded_bytes.append(Path(path).read_bytes())
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(unavailable_api)) as http_client:
+ sdk = Skyvern(api_key="test-api-key", base_url="https://api.example.test", httpx_client=http_client)
+ raw_page = create_mock_page()
+ raw_page.locator = MagicMock(return_value=SimpleNamespace(set_input_files=set_input_files))
+ with patch("skyvern.core.script_generations.skyvern_page.Page.__init__", return_value=None):
+ page = SkyvernBrowserPage(SimpleNamespace(skyvern=sdk), raw_page)
+ url = legacy_download_uris["canonical"]
+ local_path = await page.download_file(download_url=url)
+ assert Path(local_path).read_text() == "STORMBREAKER-safe-body"
+ for ai in ("fallback", None):
+ await page.upload_file(selector="#file", files=url, ai=ai)
+ assert uploaded_bytes == [b"STORMBREAKER-safe-body"] * 2
+ assert await page._get_file_organization_id(files_module.parse_uri_to_path(url)) is None
+
+ with patch(
+ "skyvern.core.script_generations.skyvern_page.download_file_from_url",
+ AsyncMock(return_value=local_path),
+ ):
+ for scheme in ("http", "https"):
+ public_url = f"{scheme}://example.test/report.pdf"
+ assert await page.download_file(download_url=public_url) == local_path
+ for ai in ("fallback", None):
+ await page.upload_file(selector="#file", files=public_url, ai=ai)
+ assert requests == []
+
+
[email protected]("attempt", [2, 1, None, "lookup_error"])
+async def test_click_progress_ignores_retained_partial_rename(tmp_path, mock_scraped_page, mock_ai, attempt) -> None:
+ page = _make_script_page(mock_scraped_page, mock_ai)
+ cutoff = datetime.fromtimestamp(200, tz=UTC)
+ stale = tmp_path / "previous.pdf.crdownload"
+ stale.write_bytes(b"old bytes")
+ os.utime(stale, (100, 100))
+ context = SkyvernContext(organization_id="o_test", workflow_run_id="wr_retry")
+
+ async def click(_page):
+ stale.rename(tmp_path / "previous.pdf")
+
+ with (
+ patch.object(
+ storage_base_module,
+ "resolve_download_attempt",
+ new=AsyncMock(
+ return_value=("wr_retry", attempt or 1, cutoff if attempt else None),
+ side_effect=RuntimeError("lookup unavailable") if attempt == "lookup_error" else None,
+ ),
+ ),
+ patch("skyvern.core.script_generations.script_skyvern_page.skyvern_context.current", return_value=context),
+ patch(
+ "skyvern.core.script_generations.script_skyvern_page.get_path_for_workflow_download_directory",
+ return_value=tmp_path,
+ ),
+ patch.object(settings, "CACHED_ACTION_DELAY_SECONDS", 0),
+ patch.object(page, "_wait_for_page_ready_before_action", new=AsyncMock()),
+ patch.object(page, "_create_action_and_result_after_execution", new=AsyncMock()) as record,
+ patch.object(page, "_create_screenshot_after_execution", new=AsyncMock()),
+ patch.object(page, "_create_html_action_after_execution", new=AsyncMock()),
+ ):
+ await page._decorate_call(click, ActionType.CLICK)
+ assert record.await_args.kwargs["download_triggered"] is (attempt != 2)
+ assert record.await_args.kwargs["downloaded_files"] == (None if attempt == 2 else ["previous.pdf"])
+ assert (tmp_path / "previous.pdf").stat().st_mtime == 100
diff --git a/tests/unit/test_send_email_block.py b/tests/unit/test_send_email_block.py
index 11bb11c79..6beb4f07c 100644
--- a/tests/unit/test_send_email_block.py
+++ b/tests/unit/test_send_email_block.py
@@ -17,6 +17,7 @@
from __future__ import annotations
+import os
import pickle
import re
import smtplib
@@ -1138,3 +1139,30 @@ async def test_a_substituted_newline_is_flattened_rather_than_failing_the_send(
assert message["Subject"] == "Report okBcc: [email protected]"
assert message["BCC"] == "[email protected]"
+
+
+async def test_email_download_directory_ignores_previous_attempt_files(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, offline_address_validation: None
+) -> None:
+ monkeypatch.setattr(settings, "DOWNLOAD_PATH", str(tmp_path))
+ download_dir = tmp_path / "wr_email"
+ download_dir.mkdir()
+ started_at = datetime(2026, 1, 1, tzinfo=UTC)
+ for name, offset in (("old.txt", -1), ("fresh.txt", 0)):
+ path = download_dir / name
+ path.write_text(name)
+ os.utime(path, (started_at.timestamp() + offset,) * 2)
+ block = _send_email_block(file_attachments=[settings.WORKFLOW_DOWNLOAD_DIRECTORY_PARAMETER_KEY])
+ context = _run_context()
+ with (
+ patch("skyvern.forge.sdk.workflow.models.block.skyvern_context.current", return_value=None),
+ patch(
+ "skyvern.forge.sdk.artifact.storage.base.resolve_download_attempt",
+ AsyncMock(return_value=("wr_email", 2, started_at)),
+ ),
+ ):
+ message = await block._build_email_message(context, "wr_email", "o_1")
+
+ assert [part.get_filename() for part in message.iter_attachments()] == ["fresh.txt"]
+ assert (download_dir / "old.txt").read_text() == "old.txt"
diff --git a/tests/unit/test_task_run_status_sync.py b/tests/unit/test_task_run_status_sync.py
index 676338eee..2ce8be67d 100644
--- a/tests/unit/test_task_run_status_sync.py
+++ b/tests/unit/test_task_run_status_sync.py
@@ -1,10 +1,15 @@
"""Tests for task_run status write-through sync."""
+from datetime import UTC, datetime, timedelta
from unittest.mock import AsyncMock, MagicMock
import pytest
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker
from skyvern.forge.sdk.db.agent_db import AgentDB
+from skyvern.forge.sdk.db.models import TaskRunModel, WorkflowRunModel
+from skyvern.forge.sdk.db.repositories.tasks import TasksRepository
@pytest.fixture
@@ -57,6 +62,78 @@ async def test_sync_task_run_status_no_raise_on_error(agent_db, mock_session):
)
[email protected]("current_status", ["completed", "failed", "running"])
[email protected]("run_id, run_type", [("wr_retry", "workflow_run"), ("tsk_v2_retry", "task_v2")])
+async def test_delayed_workflow_sync_preserves_current_attempt(
+ sqlite_engine: AsyncEngine, current_status: str, run_id: str, run_type: str
+) -> None:
+ factory = async_sessionmaker(sqlite_engine, expire_on_commit=False)
+ repo = TasksRepository(session_factory=factory, debug_enabled=False)
+ first_started_at = datetime(2026, 1, 1, tzinfo=UTC).replace(tzinfo=None)
+ first_finished_at = first_started_at + timedelta(minutes=1)
+ current_started_at = first_finished_at + timedelta(minutes=1)
+ current_finished_at = current_started_at + timedelta(minutes=1) if current_status != "running" else None
+ async with factory() as session:
+ workflow_run = WorkflowRunModel(
+ workflow_run_id="wr_retry",
+ workflow_id="w_retry",
+ workflow_permanent_id="wpid_retry",
+ organization_id="org_1",
+ status="failed",
+ started_at=first_started_at,
+ finished_at=first_finished_at,
+ )
+ task_run = TaskRunModel(run_id=run_id, task_run_type=run_type, organization_id="org_1", status="running")
+ session.add_all([workflow_run, task_run])
+ await session.commit()
+
+ # The fire-and-forget sync captures attempt 1 before the retry decision.
+ delayed_payload = {
+ "organization_id": "org_1",
+ "run_id": run_id,
+ "source_workflow_run_id": workflow_run.workflow_run_id,
+ "status": workflow_run.status,
+ "started_at": workflow_run.started_at,
+ "finished_at": workflow_run.finished_at,
+ }
+
+ # Retry preparation reopens the same source row; attempt 2 then advances.
+ workflow_run.status = "queued"
+ workflow_run.finished_at = None
+ await session.commit()
+ workflow_run.status = current_status
+ workflow_run.started_at = current_started_at
+ workflow_run.finished_at = current_finished_at
+ await session.commit()
+
+ await repo.sync_task_run_status(
+ organization_id="org_1",
+ run_id=run_id,
+ source_workflow_run_id="wr_retry",
+ status=current_status,
+ started_at=current_started_at,
+ finished_at=current_finished_at,
+ )
+ async with factory() as session:
+ current = await session.scalar(select(TaskRunModel).where(TaskRunModel.run_id == run_id))
+ assert (current.status, current.started_at, current.finished_at) == (
+ current_status,
+ current_started_at,
+ current_finished_at,
+ )
+
+ # Deliver the older payload only after attempt 2 has already been synced.
+ await repo.sync_task_run_status(**delayed_payload)
+ async with factory() as session:
+ current = await session.scalar(select(TaskRunModel).where(TaskRunModel.run_id == run_id))
+ assert (current.status, current.started_at, current.finished_at) == (
+ current_status,
+ current_started_at,
+ current_finished_at,
+ )
+
+
def test_terminal_statuses_match_run_status():
"""Guard: TERMINAL_STATUSES and RunStatus.is_final() must agree.
diff --git a/tests/unit/test_task_runs_sync_activity.py b/tests/unit/test_task_runs_sync_activity.py
index f737885c7..71cd8e8e2 100644
--- a/tests/unit/test_task_runs_sync_activity.py
+++ b/tests/unit/test_task_runs_sync_activity.py
@@ -1,11 +1,12 @@
import importlib.util
import sys
+from datetime import UTC, datetime, timedelta
from pathlib import Path
from types import ModuleType, SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
-from sqlalchemy import Boolean, Column, DateTime, Integer, String, Text
+from sqlalchemy import Boolean, Column, DateTime, Integer, String, Text, create_engine, insert, select
from sqlalchemy.orm import declarative_base
@@ -28,6 +29,7 @@ def _load_task_runs_sync_activity_module(monkeypatch: pytest.MonkeyPatch):
id = Column(Integer, primary_key=True)
run_id = Column(String)
+ organization_id = Column(String)
task_run_type = Column(String)
status = Column(String)
started_at = Column(DateTime)
@@ -47,6 +49,7 @@ def _load_task_runs_sync_activity_module(monkeypatch: pytest.MonkeyPatch):
id = Column(Integer, primary_key=True)
workflow_run_id = Column(String)
+ organization_id = Column(String)
status = Column(String)
started_at = Column(DateTime)
finished_at = Column(DateTime)
@@ -55,6 +58,16 @@ def _load_task_runs_sync_activity_module(monkeypatch: pytest.MonkeyPatch):
parent_workflow_run_id = Column(String)
debug_session_id = Column(String)
+ class WorkflowRunAttemptModel(base):
+ __tablename__ = "workflow_run_attempts"
+
+ id = Column(Integer, primary_key=True)
+ workflow_run_id = Column(String)
+ organization_id = Column(String)
+ attempt_number = Column(Integer)
+ retry_decision = Column(String)
+ next_attempt_prepared_at = Column(DateTime)
+
class WorkflowRunParameterModel(base):
__tablename__ = "workflow_run_parameters"
@@ -89,6 +102,7 @@ def _load_task_runs_sync_activity_module(monkeypatch: pytest.MonkeyPatch):
models_module.TaskRunModel = TaskRunModel
models_module.TaskV2Model = TaskV2Model
models_module.WorkflowRunModel = WorkflowRunModel
+ models_module.WorkflowRunAttemptModel = WorkflowRunAttemptModel
models_module.WorkflowRunParameterModel = WorkflowRunParameterModel
cloud_db_stub = SimpleNamespace(Session=MagicMock())
@@ -139,24 +153,27 @@ async def test_task_runs_sync_activity_commits_each_successful_sync(monkeypatch:
task_runs_sync_activity = _load_task_runs_sync_activity_module(monkeypatch)
workflow_session = _mock_session(2)
+ reopened_session = _mock_session(1)
task_session = _mock_session(3)
task_v2_session = _mock_session(5)
monkeypatch.setattr(
task_runs_sync_activity.cloud_db,
"Session",
- MagicMock(side_effect=[workflow_session, task_session, task_v2_session]),
+ MagicMock(side_effect=[workflow_session, reopened_session, task_session, task_v2_session]),
)
results = await task_runs_sync_activity.task_runs_sync_activity()
assert results == {
"workflow_runs_synced": 2,
+ "workflow_runs_reopened": 1,
"tasks_synced": 3,
"task_v2_synced": 5,
"errors": [],
}
workflow_session.commit.assert_awaited_once()
+ reopened_session.commit.assert_awaited_once()
task_session.commit.assert_awaited_once()
task_v2_session.commit.assert_awaited_once()
@@ -167,6 +184,7 @@ async def test_task_runs_sync_activity_handles_partial_failure(monkeypatch: pyte
task_runs_sync_activity = _load_task_runs_sync_activity_module(monkeypatch)
workflow_session = _mock_session(2)
+ reopened_session = _mock_session(1)
failing_session = _mock_session(0)
failing_session.execute = AsyncMock(side_effect=Exception("DB error"))
task_v2_session = _mock_session(5)
@@ -174,7 +192,7 @@ async def test_task_runs_sync_activity_handles_partial_failure(monkeypatch: pyte
monkeypatch.setattr(
task_runs_sync_activity.cloud_db,
"Session",
- MagicMock(side_effect=[workflow_session, failing_session, task_v2_session]),
+ MagicMock(side_effect=[workflow_session, reopened_session, failing_session, task_v2_session]),
)
results = await task_runs_sync_activity.task_runs_sync_activity()
@@ -189,9 +207,8 @@ async def test_task_runs_sync_activity_handles_partial_failure(monkeypatch: pyte
async def test_sync_statements_include_created_at_filter(monkeypatch: pytest.MonkeyPatch) -> None:
"""Verify that all three sync statements include created_at >= cutoff."""
mod = _load_task_runs_sync_activity_module(monkeypatch)
- from datetime import datetime, timezone
- cutoff = datetime.now(timezone.utc)
+ cutoff = datetime.now(UTC)
for builder_name in ("_build_sync_workflow_runs_stmt", "_build_sync_tasks_stmt", "_build_sync_task_v2_stmt"):
builder = getattr(mod, builder_name)
@@ -205,9 +222,8 @@ async def test_tasks_sync_includes_task_v3(monkeypatch: pytest.MonkeyPatch) -> N
"""A task_v3 row must be repaired by the catch-up sync like task_v1/CUA rows, or a v3 run whose
write-through failed would sit non-terminal in /runs history forever."""
mod = _load_task_runs_sync_activity_module(monkeypatch)
- from datetime import datetime, timezone
- stmt = mod._build_sync_tasks_stmt(datetime.now(timezone.utc))
+ stmt = mod._build_sync_tasks_stmt(datetime.now(UTC))
bound_values: list = []
for value in stmt.compile().params.values():
if isinstance(value, (list, tuple)):
@@ -216,3 +232,74 @@ async def test_tasks_sync_includes_task_v3(monkeypatch: pytest.MonkeyPatch) -> N
bound_values.append(value)
assert "task_v3" in bound_values
assert "task_v1" in bound_values # existing types still covered
+
+
+def test_reopened_run_sync_is_bounded_and_preserves_other_organizations(monkeypatch: pytest.MonkeyPatch) -> None:
+ mod = _load_task_runs_sync_activity_module(monkeypatch)
+ engine = create_engine("sqlite:///:memory:")
+ mod.TaskRunModel.metadata.create_all(engine)
+ now = datetime.now(UTC)
+ cutoff = now - timedelta(hours=168)
+ count = mod.REOPENED_RUN_BATCH_SIZE + 5
+ with engine.begin() as conn:
+ conn.execute(
+ insert(mod.WorkflowRunModel),
+ [
+ {"id": i, "workflow_run_id": f"wr_{i:04}", "organization_id": "o_retry", "status": "running"}
+ for i in range(count)
+ ],
+ )
+ conn.execute(
+ insert(mod.WorkflowRunAttemptModel),
+ [
+ {
+ "id": i,
+ "workflow_run_id": f"wr_{i:04}",
+ "organization_id": "o_retry",
+ "attempt_number": 1,
+ "retry_decision": "retry",
+ "next_attempt_prepared_at": now,
+ }
+ for i in range(count)
+ ],
+ )
+ conn.execute(
+ insert(mod.TaskRunModel),
+ [
+ {
+ "id": i,
+ "run_id": f"wr_{i:04}",
+ "organization_id": "o_retry",
+ "status": "failed",
+ "task_run_type": "workflow_run",
+ "finished_at": now,
+ }
+ for i in range(count)
+ ],
+ )
+ conn.execute(
+ insert(mod.TaskRunModel),
+ {
+ "id": count,
+ "run_id": "wr_0000",
+ "organization_id": "o_other",
+ "status": "failed",
+ "task_run_type": "workflow_run",
+ "finished_at": now,
+ },
+ )
+ stmt = mod._build_sync_reopened_workflow_runs_stmt(cutoff)
+ conn.execute(stmt)
+ statuses = conn.execute(select(mod.TaskRunModel.status)).scalars().all()
+ assert statuses.count("running") == mod.REOPENED_RUN_BATCH_SIZE
+ conn.execute(stmt)
+ statuses = conn.execute(select(mod.TaskRunModel.status)).scalars().all()
+ assert statuses.count("running") == count
+ assert statuses.count("failed") == 1
+ assert (
+ conn.execute(select(mod.TaskRunModel.finished_at).where(mod.TaskRunModel.status == "running"))
+ .scalars()
+ .all()
+ == [None] * count
+ )
+ engine.dispose()
diff --git a/tests/unit/test_taskv2_block_browser_address_propagation.py b/tests/unit/test_taskv2_block_browser_address_propagation.py
index 38c147de7..dc618d07c 100644
--- a/tests/unit/test_taskv2_block_browser_address_propagation.py
+++ b/tests/unit/test_taskv2_block_browser_address_propagation.py
@@ -76,7 +76,10 @@ async def test_taskv2_block_forwards_browser_connection_fields_to_child(
get_recent_task_screenshot_artifacts=AsyncMock(return_value=[]),
get_recent_workflow_screenshot_artifacts=AsyncMock(return_value=[]),
),
- STORAGE=SimpleNamespace(get_downloaded_files=AsyncMock(side_effect=[[], []])),
+ STORAGE=SimpleNamespace(
+ get_current_attempt_downloaded_files=AsyncMock(side_effect=[[], []]),
+ get_downloaded_file_signature_aliases=lambda _: [],
+ ),
WORKFLOW_CONTEXT_MANAGER=SimpleNamespace(has_workflow_run_context=lambda _run_id: False),
)
monkeypatch.setattr(block_module, "app", fake_app)
diff --git a/tests/unit/test_taskv2_block_downloaded_files.py b/tests/unit/test_taskv2_block_downloaded_files.py
index ba5a5da36..f85060a02 100644
--- a/tests/unit/test_taskv2_block_downloaded_files.py
+++ b/tests/unit/test_taskv2_block_downloaded_files.py
@@ -135,7 +135,10 @@ async def test_taskv2_block_uses_pre_run_loop_state_for_download_filtering(
),
# First read is the block's own baseline capture (only a.zip exists yet); the
# second is the post-run read (a.zip from before + b.zip downloaded this block).
- STORAGE=SimpleNamespace(get_downloaded_files=AsyncMock(side_effect=[[a_zip], [a_zip, b_zip]])),
+ STORAGE=SimpleNamespace(
+ get_current_attempt_downloaded_files=AsyncMock(side_effect=[[a_zip], [a_zip, b_zip]]),
+ get_downloaded_file_signature_aliases=lambda _: [],
+ ),
WORKFLOW_CONTEXT_MANAGER=SimpleNamespace(has_workflow_run_context=lambda _run_id: False),
)
monkeypatch.setattr(block_module, "app", fake_app)
diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.py
index 9c1530b74..c43a7023e 100644
--- a/tests/unit/test_taskv3_loop.py
+++ b/tests/unit/test_taskv3_loop.py
@@ -5328,7 +5328,7 @@ async def test_pre_batch_fingerprint_sample_is_bounded_by_an_already_elapsed_dea
assert outcome.status == "completed"
assert outcome.cap_trip is not None and "deadline" in outcome.cap_trip
assert fp_calls["n"] == 0 # deadline already gone -- the hanging sampler was never awaited
- assert elapsed <= 0.3
+ assert elapsed < 2.0, elapsed # loose wall-clock bound: an awaited sampler would add its full 5s sleep
@pytest.mark.asyncio
diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.py
index 2ef922244..dc92da0e6 100644
--- a/tests/unit/test_taskv3_tools.py
+++ b/tests/unit/test_taskv3_tools.py
@@ -11,13 +11,16 @@ import contextlib
import html
import itertools
import json
+import os
import re
import time
from collections.abc import AsyncIterator
+from datetime import UTC, datetime
from html import escape as html_escape
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Awaitable, Callable
+from unittest.mock import AsyncMock
import pytest
@@ -29,6 +32,8 @@ from structlog.testing import capture_logs
import skyvern.forge.taskv3.loop as taskv3_loop
import skyvern.forge.taskv3.tools as taskv3_tools
from skyvern.config import settings
+from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.taskv3.code_surface import (
CodeToolSurface,
apply_surface,
@@ -22139,6 +22144,101 @@ async def test_a_selector_rewrite_does_not_outlive_the_call_that_made_it() -> No
assert "not rendered" not in str(raised.value), str(raised.value)[:400]
[email protected]("attempt", [2, 1, None, "lookup_error"])
+async def test_download_signal_ignores_retained_partial_rename(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, attempt
+) -> None:
+ cutoff = datetime.fromtimestamp(200, tz=UTC)
+ result = ("wr_retry", attempt or 1, cutoff if attempt else None)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.artifact.storage.base.resolve_download_attempt",
+ AsyncMock(
+ return_value=result,
+ side_effect=RuntimeError("lookup unavailable") if attempt == "lookup_error" else None,
+ ),
+ )
+ monkeypatch.setattr(
+ skyvern_context, "current", lambda: SkyvernContext(organization_id="o_test", workflow_run_id="wr_retry")
+ )
+ stale = tmp_path / "previous.pdf.crdownload"
+ stale.write_bytes(b"old bytes")
+ os.utime(stale, (100, 100))
+ tools = build_browser_tools(_fixed_page_provider(_FakePage()), downloads_dir=str(tmp_path))
+ await _prime(tools)
+ stale.rename(tmp_path / "previous.pdf")
+ result = await _tool(tools, "wait").handler({"time_ms": 1})
+ assert bool((result.data or {}).get("download_new")) is (attempt != 2)
+ assert ("Downloaded: previous.pdf" in result.content) is (attempt != 2)
+ assert (tmp_path / "previous.pdf").stat().st_mtime == 100
+ (tmp_path / "current.pdf").write_bytes(b"current bytes")
+ current = await _tool(tools, "wait").handler({"time_ms": 1})
+ assert (current.data or {}).get("download_new") is True
+ assert "Downloaded: current.pdf" in current.content
+
+
[email protected]("cancel_first", [False, True])
+async def test_download_signal_waits_for_cutoff_before_concurrent_tools(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, cancel_first: bool
+) -> None:
+ lookup_started = asyncio.Event()
+ release_lookup = asyncio.Event()
+ second_entered = asyncio.Event()
+ cutoff = datetime.fromtimestamp(200, tz=UTC)
+ stale = tmp_path / "previous.pdf.crdownload"
+ stale.write_bytes(b"old bytes")
+ os.utime(stale, (100, 100))
+
+ async def resolve_attempt(*_args, **_kwargs):
+ lookup_started.set()
+ await release_lookup.wait()
+ return "wr_retry", 2, cutoff
+
+ monkeypatch.setattr("skyvern.forge.sdk.artifact.storage.base.resolve_download_attempt", resolve_attempt)
+ monkeypatch.setattr(
+ skyvern_context, "current", lambda: SkyvernContext(organization_id="o_test", workflow_run_id="wr_retry")
+ )
+ tools = build_browser_tools(_fixed_page_provider(_FakePage()), downloads_dir=str(tmp_path))
+ wait = _tool(tools, "wait").handler
+
+ async def second_call():
+ second_entered.set()
+ return await wait({"time_ms": 1})
+
+ async with asyncio.timeout(2):
+ first = asyncio.create_task(wait({"time_ms": 1}))
+ try:
+ await lookup_started.wait()
+ if cancel_first:
+ first.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await first
+ second = asyncio.create_task(second_call())
+ try:
+ await second_entered.wait()
+ stale.rename(tmp_path / "previous.pdf")
+ await asyncio.sleep(0.01)
+ assert not second.done()
+ release_lookup.set()
+ result = await second
+ if not cancel_first:
+ await first
+ finally:
+ second.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await second
+ finally:
+ first.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await first
+ assert not (result.data or {}).get("download_new")
+ assert "Downloaded: previous.pdf" not in result.content
+ (tmp_path / "current.pdf").write_bytes(b"new bytes")
+ current = await wait({"time_ms": 1})
+ assert (current.data or {}).get("download_new") is True
+
+
# A form that repeats a section renders the same caption many times over: eight `Year` inputs, five
# `Add Another` buttons. observe printed each of them as the same bytes, so the digest offered the
# model N indistinguishable addresses for N different fields and nothing to choose between them.
diff --git a/tests/unit/test_webhook_ssrf.py b/tests/unit/test_webhook_ssrf.py
index 6ce9e24c6..4c753730d 100644
--- a/tests/unit/test_webhook_ssrf.py
+++ b/tests/unit/test_webhook_ssrf.py
@@ -8,13 +8,17 @@ was validated, or a rebinding host answers again with a private address at conne
from __future__ import annotations
import socket
-from unittest.mock import MagicMock, patch
+from datetime import UTC, datetime, timedelta
+from unittest.mock import AsyncMock, MagicMock, patch
import httpx
import pytest
from skyvern.exceptions import BlockedHost, SkyvernHTTPException
+from skyvern.forge.sdk.db.models import WorkflowRunAttemptModel
from skyvern.forge.sdk.routes import webhooks as webhook_routes
+from skyvern.forge.sdk.workflow.models.workflow import WorkflowRun, WorkflowRunStatus
+from skyvern.forge.sdk.workflow.retry_policy import compute_attempt_view
from skyvern.schemas.webhooks import TestWebhookRequest as WebhookTestPayload
from skyvern.services import webhook_service
from skyvern.utils.url_validators import pinned_ip_client, resolve_fetch_host_ips
@@ -25,6 +29,116 @@ PUBLIC_IP = "93.184.216.34"
METADATA_IP = "169.254.169.254"
+async def test_replay_of_a_running_run_without_attempt_rows_is_not_blocked(monkeypatch: pytest.MonkeyPatch) -> None:
+ run = WorkflowRun.model_construct(
+ workflow_run_id="wr_replay", status=WorkflowRunStatus.running, failure_reason=None, finished_at=None
+ )
+ monkeypatch.setattr(webhook_service.app.DATABASE.workflow_runs, "get_workflow_run", AsyncMock(return_value=run))
+ monkeypatch.setattr(webhook_service.app.DATABASE.workflow_run_attempts, "get_attempts", AsyncMock(return_value=[]))
+ build_payload = AsyncMock(
+ return_value=webhook_service._WebhookPayload(
+ run_id="wr_replay", run_type="workflow_run", payload={}, default_webhook_url=REBINDING_HOST_URL
+ )
+ )
+ deliver = AsyncMock(return_value=(200, 1, "ok", None))
+ monkeypatch.setattr(webhook_service, "_build_webhook_payload", build_payload)
+ monkeypatch.setattr(webhook_service, "_deliver_webhook", deliver)
+ monkeypatch.setattr(
+ webhook_service, "_validate_target_url", AsyncMock(return_value=(REBINDING_HOST_URL, (PUBLIC_IP,)))
+ )
+
+ await webhook_service.replay_run_webhook("o_replay", "wr_replay", None, api_key="test-key")
+
+ deliver.assert_awaited_once()
+
+
+ ("active_status", "final_decision"),
+ [
+ (WorkflowRunStatus.queued, "final"),
+ (WorkflowRunStatus.running, "revoked"),
+ (WorkflowRunStatus.running, "abandoned"),
+ ],
+)
+async def test_replay_waits_for_logical_run_finality(
+ monkeypatch: pytest.MonkeyPatch, active_status: WorkflowRunStatus, final_decision: str
+) -> None:
+ finished_at = datetime(2026, 1, 1, tzinfo=UTC).replace(tzinfo=None)
+ run = WorkflowRun.model_construct(
+ workflow_run_id="wr_replay",
+ status=WorkflowRunStatus.failed,
+ failure_reason=None,
+ started_at=finished_at - timedelta(minutes=1),
+ finished_at=finished_at,
+ )
+ first = WorkflowRunAttemptModel(
+ attempt_number=1,
+ status="failed",
+ retry_decision="retry",
+ started_at=run.started_at,
+ finished_at=finished_at,
+ next_attempt_at=finished_at + timedelta(seconds=1),
+ )
+ attempts = [first]
+ monkeypatch.setattr(webhook_service.app.DATABASE.workflow_runs, "get_workflow_run", AsyncMock(return_value=run))
+ monkeypatch.setattr(
+ webhook_service.app.DATABASE.workflow_run_attempts, "get_attempts", AsyncMock(return_value=attempts)
+ )
+ build_payload = AsyncMock(
+ return_value=webhook_service._WebhookPayload(
+ run_id="wr_replay", run_type="workflow_run", payload={}, default_webhook_url=REBINDING_HOST_URL
+ )
+ )
+ deliver = AsyncMock(return_value=(200, 1, "ok", None))
+ monkeypatch.setattr(webhook_service, "_build_webhook_payload", build_payload)
+ monkeypatch.setattr(webhook_service, "_deliver_webhook", deliver)
+ monkeypatch.setattr(
+ webhook_service, "_validate_target_url", AsyncMock(return_value=(REBINDING_HOST_URL, (PUBLIC_IP,)))
+ )
+
+ async def assert_replay_blocked() -> None:
+ with pytest.raises(SkyvernHTTPException, match="unavailable until it is final") as exc_info:
+ await webhook_service.replay_run_webhook("o_replay", "wr_replay", None, api_key="test-key")
+ assert exc_info.value.status_code == 409
+ build_payload.assert_not_awaited()
+ deliver.assert_not_awaited()
+
+ pending_view = compute_attempt_view(run, attempts)
+ assert pending_view.retry_pending
+ assert pending_view.next_attempt_at == first.next_attempt_at
+ await assert_replay_blocked()
+
+ first.next_attempt_prepared_at = first.next_attempt_at
+ second = WorkflowRunAttemptModel(attempt_number=2, status=active_status.value)
+ attempts.append(second)
+ run.finished_at = None
+ run.started_at = None
+ run.status = active_status
+ if active_status == WorkflowRunStatus.running:
+ run.started_at = second.started_at = first.next_attempt_at
+ prepared_view = compute_attempt_view(run, attempts)
+ assert not prepared_view.retry_pending
+ assert prepared_view.next_attempt_at is None
+ await assert_replay_blocked()
+
+ run.status = WorkflowRunStatus.failed
+ run.finished_at = second.finished_at = finished_at + timedelta(minutes=1)
+ second.status = "failed"
+ assert not compute_attempt_view(run, attempts).retry_pending
+ await assert_replay_blocked()
+
+ second.retry_decision = final_decision
+ response = await webhook_service.replay_run_webhook("o_replay", "wr_replay", None, api_key="test-key")
+ assert response.status_code == 200
+ deliver.assert_awaited_once()
+
+ attempts.clear()
+ response = await webhook_service.replay_run_webhook("o_replay", "wr_replay", None, api_key="test-key")
+ assert response.status_code == 200
+
+
@pytest.fixture
def resolves_to_metadata_ip(monkeypatch: pytest.MonkeyPatch) -> None:
def _resolve(host: str, *args: object, **kwargs: object) -> list:
diff --git a/tests/unit/test_workflow_elapsed_timeout.py b/tests/unit/test_workflow_elapsed_timeout.py
index 210233c6d..1a36e7fa6 100644
--- a/tests/unit/test_workflow_elapsed_timeout.py
+++ b/tests/unit/test_workflow_elapsed_timeout.py
@@ -25,6 +25,7 @@ from skyvern.forge.sdk.workflow.models.workflow import (
from skyvern.forge.sdk.workflow.service import WorkflowService
from skyvern.schemas.runs import WorkflowRunRequest
from skyvern.schemas.workflows import WorkflowCreateYAMLRequest, WorkflowDefinitionYAML
+from tests.unit.force_stub_app import make_workflow_run_attempts_fake
def _workflow_run(
@@ -242,7 +243,7 @@ async def test_execute_workflow_returns_after_elapsed_timeout_without_finally(mo
monkeypatch.setattr(service_module, "publish_copilot_runtime_secret_values", publish_runtime_secrets)
monkeypatch.setattr(svc, "get_workflow_run", AsyncMock(return_value=created_run))
- monkeypatch.setattr(svc, "get_workflow", AsyncMock(return_value=workflow))
+ monkeypatch.setattr(svc, "get_workflow_by_workflow_run_id", AsyncMock(return_value=workflow))
monkeypatch.setattr(svc, "bind_browser_action_policy", AsyncMock(return_value=None))
monkeypatch.setattr(svc, "mark_workflow_run_as_running", AsyncMock(return_value=running_run))
monkeypatch.setattr(svc, "get_workflow_run_parameter_tuples", AsyncMock(return_value=[]))
@@ -327,7 +328,7 @@ async def test_execute_workflow_times_out_slow_pre_block_script_lookup(monkeypat
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, "get_workflow_by_workflow_run_id", AsyncMock(return_value=workflow))
monkeypatch.setattr(svc, "bind_browser_action_policy", AsyncMock(return_value=None))
monkeypatch.setattr(svc, "mark_workflow_run_as_running", AsyncMock(return_value=running_run))
monkeypatch.setattr(svc, "get_workflow_run_parameter_tuples", AsyncMock(return_value=[]))
@@ -388,6 +389,7 @@ async def test_execute_workflow_preserves_completed_status_after_post_run_timeou
workflow_runs=SimpleNamespace(
get_workflow_run=AsyncMock(return_value=completed_run),
),
+ workflow_run_attempts=make_workflow_run_attempts_fake(),
)
timeout_seconds = iter([10.0, 0.01])
@@ -417,7 +419,7 @@ async def test_execute_workflow_preserves_completed_status_after_post_run_timeou
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, "get_workflow_by_workflow_run_id", AsyncMock(return_value=workflow))
monkeypatch.setattr(svc, "bind_browser_action_policy", AsyncMock(return_value=None))
monkeypatch.setattr(svc, "mark_workflow_run_as_running", AsyncMock(return_value=running_run))
monkeypatch.setattr(svc, "get_workflow_run_parameter_tuples", AsyncMock(return_value=[]))
@@ -481,6 +483,7 @@ async def test_execute_workflow_preserves_timed_out_status_after_non_terminal_po
workflow_runs=SimpleNamespace(
get_workflow_run=AsyncMock(return_value=running_run),
),
+ workflow_run_attempts=make_workflow_run_attempts_fake(),
)
timeout_seconds = iter([10.0, 0.01])
@@ -510,7 +513,7 @@ async def test_execute_workflow_preserves_timed_out_status_after_non_terminal_po
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, "get_workflow_by_workflow_run_id", AsyncMock(return_value=workflow))
monkeypatch.setattr(svc, "bind_browser_action_policy", AsyncMock(return_value=None))
monkeypatch.setattr(svc, "mark_workflow_run_as_running", AsyncMock(return_value=running_run))
monkeypatch.setattr(svc, "get_workflow_run_parameter_tuples", AsyncMock(return_value=[]))
@@ -580,6 +583,7 @@ async def test_execute_workflow_marks_timed_out_when_post_run_budget_is_exhauste
workflow_runs=SimpleNamespace(
get_workflow_run=AsyncMock(return_value=running_run),
),
+ workflow_run_attempts=make_workflow_run_attempts_fake(),
)
timeout_seconds = iter([10.0, 0.0001])
@@ -607,7 +611,7 @@ async def test_execute_workflow_marks_timed_out_when_post_run_budget_is_exhauste
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, "get_workflow_by_workflow_run_id", AsyncMock(return_value=workflow))
monkeypatch.setattr(svc, "bind_browser_action_policy", AsyncMock(return_value=None))
monkeypatch.setattr(svc, "mark_workflow_run_as_running", AsyncMock(return_value=running_run))
monkeypatch.setattr(svc, "get_workflow_run_parameter_tuples", AsyncMock(return_value=[]))
@@ -658,6 +662,7 @@ async def test_shield_post_run_elapsed_timeout_waits_for_status_write_after_canc
workflow_runs=SimpleNamespace(
get_workflow_run=AsyncMock(side_effect=refresh_workflow_run),
),
+ workflow_run_attempts=make_workflow_run_attempts_fake(),
)
monkeypatch.setattr(service_module.app, "DATABASE", database)
@@ -763,6 +768,7 @@ async def test_execute_workflow_refreshes_terminal_status_after_immediate_post_r
workflow_runs=SimpleNamespace(
get_workflow_run=AsyncMock(side_effect=refresh_workflow_run),
),
+ workflow_run_attempts=make_workflow_run_attempts_fake(),
)
timeout_seconds = iter([10.0, 0.0])
@@ -788,7 +794,7 @@ async def test_execute_workflow_refreshes_terminal_status_after_immediate_post_r
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, "get_workflow_by_workflow_run_id", AsyncMock(return_value=workflow))
monkeypatch.setattr(svc, "bind_browser_action_policy", AsyncMock(return_value=None))
monkeypatch.setattr(svc, "mark_workflow_run_as_running", AsyncMock(return_value=running_run))
monkeypatch.setattr(svc, "get_workflow_run_parameter_tuples", AsyncMock(return_value=[]))
@@ -851,6 +857,7 @@ async def test_execute_workflow_refreshes_failed_status_after_finally_write_time
workflow_runs=SimpleNamespace(
get_workflow_run=AsyncMock(side_effect=[running_run, failed_run]),
),
+ workflow_run_attempts=make_workflow_run_attempts_fake(),
)
timeout_seconds = iter([10.0, 0.01])
@@ -881,7 +888,7 @@ async def test_execute_workflow_refreshes_failed_status_after_finally_write_time
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, "get_workflow_by_workflow_run_id", AsyncMock(return_value=workflow))
monkeypatch.setattr(svc, "bind_browser_action_policy", AsyncMock(return_value=None))
monkeypatch.setattr(svc, "mark_workflow_run_as_running", AsyncMock(return_value=running_run))
monkeypatch.setattr(svc, "get_workflow_run_parameter_tuples", AsyncMock(return_value=[]))
@@ -946,6 +953,7 @@ async def test_execute_workflow_runs_finally_for_existing_timed_out_status(
workflow_runs=SimpleNamespace(
get_workflow_run=AsyncMock(return_value=timed_out_run),
),
+ workflow_run_attempts=make_workflow_run_attempts_fake(),
)
monkeypatch.setattr(service_module.app, "WORKFLOW_CONTEXT_MANAGER", workflow_context_manager)
@@ -968,7 +976,7 @@ async def test_execute_workflow_runs_finally_for_existing_timed_out_status(
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, "get_workflow_by_workflow_run_id", AsyncMock(return_value=workflow))
monkeypatch.setattr(svc, "bind_browser_action_policy", AsyncMock(return_value=None))
monkeypatch.setattr(svc, "mark_workflow_run_as_running", AsyncMock(return_value=running_run))
monkeypatch.setattr(svc, "get_workflow_run_parameter_tuples", AsyncMock(return_value=[]))
@@ -1051,7 +1059,7 @@ async def test_execute_workflow_preserves_escaped_failure_cause_before_terminal(
failure_log = Mock()
monkeypatch.setattr(svc, "get_workflow_run", AsyncMock(return_value=created_run))
- monkeypatch.setattr(svc, "get_workflow", AsyncMock(return_value=workflow))
+ monkeypatch.setattr(svc, "get_workflow_by_workflow_run_id", AsyncMock(return_value=workflow))
monkeypatch.setattr(svc, "bind_browser_action_policy", AsyncMock(return_value=None))
monkeypatch.setattr(svc, "mark_workflow_run_as_running", AsyncMock(return_value=running_run))
monkeypatch.setattr(svc, "get_workflow_run_parameter_tuples", AsyncMock(return_value=[]))
@@ -1221,7 +1229,7 @@ async def test_execute_workflow_skips_interrupted_finalize_for_cancellation(
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, "get_workflow_by_workflow_run_id", AsyncMock(return_value=workflow))
monkeypatch.setattr(svc, "bind_browser_action_policy", AsyncMock(return_value=None))
monkeypatch.setattr(svc, "mark_workflow_run_as_running", AsyncMock(return_value=running_run))
monkeypatch.setattr(svc, "get_workflow_run_parameter_tuples", AsyncMock(return_value=[]))
diff --git a/tests/unit/test_workflow_run_detail_template_cross_org.py b/tests/unit/test_workflow_run_detail_template_cross_org.py
index c99992541..fd351f0ed 100644
--- a/tests/unit/test_workflow_run_detail_template_cross_org.py
+++ b/tests/unit/test_workflow_run_detail_template_cross_org.py
@@ -13,6 +13,7 @@ from skyvern.forge.sdk.workflow.models.workflow import (
WorkflowStatus,
)
from skyvern.forge.sdk.workflow.service import WorkflowService
+from tests.unit.force_stub_app import make_workflow_run_attempts_fake
TEMPLATE_ORG_ID = "o_template"
CALLER_ORG_ID = "o_caller"
@@ -94,6 +95,7 @@ async def test_template_run_detail_resolves_via_run_join(monkeypatch: pytest.Mon
get_workflow_run_block_errors=AsyncMock(return_value=[]),
get_workflow_run_retried_by=AsyncMock(return_value=None),
),
+ workflow_run_attempts=make_workflow_run_attempts_fake(),
),
)
diff --git a/tests/unit/test_workflow_run_minutes_gate.py b/tests/unit/test_workflow_run_minutes_gate.py
index 6aec90ca5..f77035135 100644
--- a/tests/unit/test_workflow_run_minutes_gate.py
+++ b/tests/unit/test_workflow_run_minutes_gate.py
@@ -16,6 +16,7 @@ only the post-claim row can say whether the task started.
from __future__ import annotations
+import asyncio
import copy
from collections.abc import Iterator
from datetime import UTC, datetime, timedelta, tzinfo
@@ -35,6 +36,7 @@ from skyvern.forge.sdk.workflow.models.block import BlockType
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
from skyvern.forge.sdk.workflow.service import WorkflowService
from skyvern.schemas.run_enums import RunEngine
+from tests.unit.force_stub_app import make_workflow_run_attempts_fake
def _make_row(*, started: bool) -> MagicMock:
@@ -45,6 +47,7 @@ def _make_row(*, started: bool) -> MagicMock:
row.organization_id = "org_gate"
row.parent_workflow_run_id = None
row.created_at = now - timedelta(minutes=30)
+ row.queued_at = None
row.started_at = (now - timedelta(minutes=20)) if started else None
row.status = WorkflowRunStatus.canceled
row.run_with = None
@@ -108,6 +111,70 @@ async def test_conditional_cancel_emits_minutes_only_for_runs_that_started(
_assert_emission(record_run_duration, started=started)
[email protected]("writer", ["status_write", "conditional_cancel"])
+async def test_terminal_write_bookkeeping_survives_decision_recording_failure(
+ monkeypatch: pytest.MonkeyPatch,
+ record_run_duration: AsyncMock,
+ writer: str,
+) -> None:
+ row = _make_row(started=True)
+ monkeypatch.setattr(
+ app.DATABASE.workflow_runs,
+ "update_workflow_run_if_not_final",
+ AsyncMock(return_value=row),
+ )
+ monkeypatch.setattr(
+ service_module, "on_terminal_transition", AsyncMock(side_effect=RuntimeError("read unavailable"))
+ )
+ attempts = make_workflow_run_attempts_fake()
+ undecided = SimpleNamespace(attempt_number=1, retry_decision=None, next_attempt_prepared_at=None)
+ attempts.get_attempts = AsyncMock(return_value=[undecided])
+ monkeypatch.setattr(app.DATABASE, "workflow_run_attempts", attempts)
+ service = WorkflowService()
+
+ from structlog.testing import capture_logs
+
+ with capture_logs() as logs, pytest.raises(RuntimeError, match="read unavailable"):
+ if writer == "status_write":
+ await service._update_workflow_run_status(workflow_run_id="wr_gate", status=WorkflowRunStatus.canceled)
+ else:
+ await service.mark_workflow_run_as_canceled_if_not_final(workflow_run_id="wr_gate")
+
+ _assert_emission(record_run_duration, started=True)
+ # The decision was never recorded, so this event is not the run's canonical outcome yet.
+ duration_logs = [e for e in logs if e.get("event") == "Workflow run duration metrics"]
+ assert len(duration_logs) == 1
+ assert duration_logs[0]["retry_pending"] is True
+
+
+async def test_terminal_bookkeeping_survives_attempt_lookup_failure(
+ monkeypatch: pytest.MonkeyPatch, record_run_duration: AsyncMock
+) -> None:
+ row = _make_row(started=True)
+ monkeypatch.setattr(app.DATABASE.workflow_runs, "update_workflow_run_if_not_final", AsyncMock(return_value=row))
+ monkeypatch.setattr(service_module, "on_terminal_transition", AsyncMock())
+ attempts = make_workflow_run_attempts_fake()
+ attempts.get_attempts = AsyncMock(side_effect=RuntimeError("read unavailable"))
+ monkeypatch.setattr(app.DATABASE, "workflow_run_attempts", attempts)
+ service = WorkflowService()
+ sync_task_run = AsyncMock()
+ monkeypatch.setattr(service, "_sync_task_run_from_workflow_run", sync_task_run)
+ terminal_hooks = MagicMock()
+ monkeypatch.setattr(service, "_schedule_workflow_run_terminal_hooks", terminal_hooks)
+
+ await service._update_workflow_run_status(workflow_run_id="wr_gate", status=WorkflowRunStatus.canceled)
+ # The set is shared across service instances; only this loop's task is ours to drain.
+ loop = asyncio.get_running_loop()
+ await asyncio.gather(*[task for task in service._background_tasks if task.get_loop() is loop])
+
+ _assert_emission(record_run_duration, started=True)
+ sync_task_run.assert_awaited_once()
+ # Enrolment is unknown, so the no-policy terminal hooks are not fired for a possibly enrolled run.
+ terminal_hooks.assert_not_called()
+
+
def _make_task(*, status: TaskStatus, started_at: datetime | None, finished_at: datetime | None = None) -> Task:
now = datetime.now(UTC)
return Task(
@@ -232,6 +299,7 @@ async def test_finally_block_re_finalization_records_only_the_minutes_it_added(
failure_reason=None,
failure_category=None,
created_at=started_at,
+ queued_at=None,
started_at=started_at,
finished_at=None,
run_with="agent",
@@ -276,7 +344,11 @@ async def test_finally_block_re_finalization_records_only_the_minutes_it_added(
get_workflow_run_context=lambda _workflow_run_id: SimpleNamespace(browser_session_id=None),
),
)
- monkeypatch.setattr(service_module.app, "DATABASE", SimpleNamespace(workflow_runs=store))
+ monkeypatch.setattr(
+ service_module.app,
+ "DATABASE",
+ SimpleNamespace(workflow_runs=store, workflow_run_attempts=make_workflow_run_attempts_fake()),
+ )
monkeypatch.setattr(service_module.workflow_script_service, "workflow_has_conditionals", lambda _workflow: False)
monkeypatch.setattr(
service_module.workflow_script_service,
@@ -305,7 +377,7 @@ async def test_finally_block_re_finalization_records_only_the_minutes_it_added(
return None
monkeypatch.setattr(svc, "get_workflow_run", AsyncMock(side_effect=lambda **_: store.snapshot()))
- monkeypatch.setattr(svc, "get_workflow", AsyncMock(return_value=workflow))
+ monkeypatch.setattr(svc, "get_workflow_by_workflow_run_id", AsyncMock(return_value=workflow))
monkeypatch.setattr(svc, "bind_browser_action_policy", AsyncMock(return_value=None))
monkeypatch.setattr(svc, "mark_workflow_run_as_running", AsyncMock(side_effect=lambda **_: store.snapshot()))
monkeypatch.setattr(svc, "get_workflow_run_parameter_tuples", AsyncMock(return_value=[]))
@@ -602,3 +674,48 @@ async def test_duration_log_survives_a_failed_arm_lookup(
assert len(duration_logs) == 1
assert duration_logs[0]["task_v3_ab_arm"] == "unknown"
assert record_run_duration.await_count == 1
+
+
+ ("decisions", "expected"),
+ [([], (None, False)), (["retry"], (1, True)), (["retry", "final"], (2, False)), ([None], (1, True))],
+ ids=["no-rows", "retry", "retry-then-final", "undecided"],
+)
+async def test_duration_log_names_the_attempt_and_whether_a_retry_is_pending(
+ monkeypatch: pytest.MonkeyPatch,
+ record_run_duration: AsyncMock,
+ decisions: list[str | None],
+ expected: tuple[int | None, bool],
+) -> None:
+ # A policy run emits this event once per attempt; the outcome consumers keep the event without a pending retry.
+ # An undecided attempt inside the grace window is still pending: its decision write may have failed.
+ from structlog.testing import capture_logs
+
+ rows = [
+ SimpleNamespace(attempt_number=number, retry_decision=decision, next_attempt_prepared_at=None)
+ for number, decision in enumerate(decisions, 1)
+ ]
+ monkeypatch.setattr(app.DATABASE.workflow_run_attempts, "get_attempts", AsyncMock(return_value=rows))
+
+ with capture_logs() as logs:
+ await WorkflowService()._after_workflow_run_status_write(_make_row(started=True), WorkflowRunStatus.failed)
+
+ [event] = [e for e in logs if e.get("event") == "Workflow run duration metrics"]
+ assert (event["attempt_number"], event["retry_pending"]) == expected
+
+
+async def test_duration_log_measures_queue_time_from_the_queue_ticket(record_run_duration: AsyncMock) -> None:
+ # A retry re-queues the run long after it was created; its queue wait starts at that ticket.
+ from structlog.testing import capture_logs
+
+ row = _make_row(started=True)
+ row.queued_at = row.started_at - timedelta(minutes=2)
+
+ with capture_logs() as logs:
+ await WorkflowService()._after_workflow_run_status_write(row, WorkflowRunStatus.completed)
+
+ [event] = [e for e in logs if e.get("event") == "Workflow run duration metrics"]
+ assert event["queued_seconds"] == pytest.approx(120, abs=5)
+ assert event["duration_seconds"] == pytest.approx(20 * 60, abs=5)
diff --git a/tests/unit/test_workflow_run_step_budget.py b/tests/unit/test_workflow_run_step_budget.py
index b9f26c7dc..b4f12d53f 100644
--- a/tests/unit/test_workflow_run_step_budget.py
+++ b/tests/unit/test_workflow_run_step_budget.py
@@ -20,6 +20,7 @@ def _make_task(
task = MagicMock()
task.task_id = task_id
task.organization_id = organization_id
+ task.attempt_number = None
task.workflow_run_id = workflow_run_id
return task
diff --git a/tests/unit/test_workflow_runtime_completion.py b/tests/unit/test_workflow_runtime_completion.py
index 09d0d54bb..bd87a4dcd 100644
--- a/tests/unit/test_workflow_runtime_completion.py
+++ b/tests/unit/test_workflow_runtime_completion.py
@@ -11,6 +11,7 @@ from unittest.mock import AsyncMock
import pytest
+from skyvern.exceptions import WorkflowNotFound
from skyvern.forge.sdk.schemas.files import FileInfo
from skyvern.forge.sdk.workflow import service as service_module
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
@@ -272,6 +273,31 @@ async def test_finalize_grades_the_version_the_run_executed(monkeypatch: pytest.
assert seen == [run.workflow_id]
+async def test_finalize_grades_the_version_execution_loaded_when_it_is_soft_deleted(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Execution resolves the pinned version deleted-inclusive; grading must not re-read it through the
+ active-only lookup and wave the contract through once that version has been soft-deleted."""
+ service, run, statuses = _wire_finalize(monkeypatch, contract=None, downloaded=[])
+
+ async def _soft_deleted(workflow_id: str, organization_id: str | None = None):
+ raise WorkflowNotFound(workflow_id=workflow_id)
+
+ monkeypatch.setattr(service, "get_workflow", _soft_deleted)
+ executed = SimpleNamespace(workflow_definition={**_DEFINITION_BASE, "completion_contract": _DERIVED_CONTRACT})
+
+ await service._finalize_workflow_run_status(
+ workflow_run_id=run.workflow_run_id,
+ workflow_run=run,
+ pre_finally_status=WorkflowRunStatus.running,
+ pre_finally_failure_reason=None,
+ workflow=executed,
+ )
+
+ assert statuses == [WorkflowRunStatus.terminated]
+
+
def test_contract_comes_from_the_request_not_the_code() -> None:
"""The obligation is what the user asked for, never the shape of the generated code."""
from skyvern.forge.sdk.copilot.completion_verification import registered_download_completion_criterion
diff --git a/tests/unit/test_workflow_schedule_service.py b/tests/unit/test_workflow_schedule_service.py
index 574aa60d0..c1d8011ba 100644
--- a/tests/unit/test_workflow_schedule_service.py
+++ b/tests/unit/test_workflow_schedule_service.py
@@ -7,9 +7,11 @@ from unittest.mock import AsyncMock
import pytest
+import skyvern.forge.sdk.workflow.retry_policy as retry_policy_module
import skyvern.services.workflow_schedule_service as schedule_service
from skyvern.forge.sdk.db.enums import WorkflowRunTriggerType
from skyvern.forge.sdk.schemas.workflow_schedules import WorkflowSchedule
+from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
def _schedule(*, modified_at: datetime | None = None) -> WorkflowSchedule:
@@ -93,10 +95,21 @@ async def test_dispatch_due_schedules_launches_scheduled_workflow(monkeypatch: p
workflow_id="w_test",
workflow_permanent_id="wpid_test",
browser_session_id=None,
+ status=WorkflowRunStatus.created,
)
prepare_workflow = AsyncMock(return_value=fake_workflow_run)
initialize_state = AsyncMock()
- execute_workflow = AsyncMock()
+ prepare_llm = AsyncMock()
+ execution_started = asyncio.Event()
+ execution_release = asyncio.Event()
+ execution_completed = asyncio.Event()
+
+ async def execute_workflow_with_retries(**_kwargs: object) -> None:
+ execution_started.set()
+ await execution_release.wait()
+ execution_completed.set()
+
+ execute_workflow = AsyncMock(side_effect=execute_workflow_with_retries)
fake_app = SimpleNamespace(
DATABASE=SimpleNamespace(
schedules=SimpleNamespace(
@@ -104,16 +117,22 @@ async def test_dispatch_due_schedules_launches_scheduled_workflow(monkeypatch: p
has_schedule_fired_since=AsyncMock(return_value=False),
),
organizations=SimpleNamespace(get_organization=AsyncMock(return_value=fake_org)),
+ workflow_runs=SimpleNamespace(queue_initial_dispatch=AsyncMock(return_value=True)),
),
- WORKFLOW_SERVICE=SimpleNamespace(execute_workflow=execute_workflow),
+ WORKFLOW_SERVICE=SimpleNamespace(execute_workflow_with_retries=execute_workflow),
)
monkeypatch.setattr(schedule_service, "app", fake_app)
+ monkeypatch.setattr(retry_policy_module, "app", fake_app)
monkeypatch.setattr(schedule_service, "compute_previous_fire_time", lambda *_args: previous_fire_time)
monkeypatch.setattr(schedule_service, "prepare_workflow", prepare_workflow)
monkeypatch.setattr(schedule_service, "initialize_skyvern_state_file", initialize_state)
+ monkeypatch.setattr(schedule_service, "prepare_org_llm_runtime", prepare_llm)
scheduler = schedule_service.LocalWorkflowScheduleScheduler(poll_interval_seconds=1, max_concurrent_runs=1)
tasks = await scheduler.dispatch_due_schedules()
+ await asyncio.wait_for(execution_started.wait(), timeout=1)
+ assert tasks[0].done() is False
+ execution_release.set()
await asyncio.gather(*tasks)
assert len(tasks) == 1
@@ -127,9 +146,15 @@ async def test_dispatch_due_schedules_launches_scheduled_workflow(monkeypatch: p
workflow_run_id=expected_workflow_run_id,
organization_id="org_test",
)
+ prepare_llm.assert_awaited_once_with(fake_app.DATABASE, "org_test", fake_org)
+ assert execution_completed.is_set()
execute_workflow.assert_awaited_once_with(
workflow_run_id=expected_workflow_run_id,
api_key=None,
organization=fake_org,
browser_session_id=None,
+ block_labels=None,
+ block_outputs=None,
+ need_call_webhook=True,
+ claim_initial_attempt=True,
)
diff --git a/tests/unit/test_workflow_service_cancel.py b/tests/unit/test_workflow_service_cancel.py
index 6e20bd10f..ac20e09d7 100644
--- a/tests/unit/test_workflow_service_cancel.py
+++ b/tests/unit/test_workflow_service_cancel.py
@@ -18,21 +18,28 @@ from __future__ import annotations
import asyncio
from datetime import UTC, datetime, timedelta, tzinfo
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
-from skyvern.exceptions import WorkflowNotFound, WorkflowRunNotFound
+from skyvern.exceptions import BrowserSessionClosed, BrowserSessionStartupTimeout, WorkflowNotFound, WorkflowRunNotFound
from skyvern.forge import app
+from skyvern.forge.sdk.workflow import service as service_module
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
+from skyvern.forge.sdk.workflow.retry_policy import TERMINAL_RELEASE_RETRY_MAX_ATTEMPTS
+from skyvern.forge.sdk.workflow.service import (
+ WorkflowBrowserCleanupResult,
+ WorkflowService,
+ _browser_lease_failure_category,
+)
+from skyvern.services import run_service
@pytest.mark.asyncio
async def test_mark_canceled_if_not_final_returns_conditional_result(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- from skyvern.forge.sdk.workflow.service import WorkflowService
-
updated_row = MagicMock()
updated_row.status = WorkflowRunStatus.canceled
@@ -55,6 +62,7 @@ def _make_updated_row(now: datetime | None = None) -> MagicMock:
row = MagicMock()
row.status = WorkflowRunStatus.canceled
row.created_at = now - timedelta(seconds=30)
+ row.queued_at = None
row.started_at = now - timedelta(seconds=20)
row.workflow_id = "wf_abc"
row.organization_id = "org_abc"
@@ -75,8 +83,6 @@ async def test_completion_tags_write_final_status_execution_mode_and_primary_fai
monkeypatch: pytest.MonkeyPatch,
final_status: WorkflowRunStatus,
) -> None:
- from skyvern.forge.sdk.workflow.service import WorkflowService
-
workflow_run = _make_updated_row()
workflow_run.workflow_run_id = f"wr_{final_status.value}"
workflow_run.status = final_status
@@ -103,8 +109,6 @@ async def test_completion_tags_write_final_status_execution_mode_and_primary_fai
async def test_completion_tags_write_status_and_execution_mode_for_completed_run(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- from skyvern.forge.sdk.workflow.service import WorkflowService
-
workflow_run = _make_updated_row()
workflow_run.workflow_run_id = "wr_completed"
workflow_run.status = "completed"
@@ -126,8 +130,6 @@ async def test_completion_tags_write_status_and_execution_mode_for_completed_run
async def test_completion_tag_write_failure_does_not_interrupt_finalization(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- from skyvern.forge.sdk.workflow.service import WorkflowService
-
workflow_run = _make_updated_row()
workflow_run.workflow_run_id = "wr_completion"
monkeypatch.setattr(
@@ -143,8 +145,6 @@ async def test_completion_tag_write_failure_does_not_interrupt_finalization(
async def test_conditional_cancel_writes_completion_tags(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- from skyvern.forge.sdk.workflow.service import WorkflowService
-
updated_row = _make_updated_row()
updated_row.workflow_run_id = "wr_canceled"
monkeypatch.setattr(
@@ -171,11 +171,9 @@ async def test_mark_canceled_if_not_final_logs_duration_metrics(
statuses. ``recorded_seconds`` must equal the sample handed to
``record_run_duration`` so a log query keyed on it reconciles with the metric.
"""
- from skyvern.forge.sdk.workflow import service as service_module
- from skyvern.forge.sdk.workflow.service import WorkflowService
-
fixed_now = datetime(2026, 1, 1, tzinfo=UTC)
updated_row = _make_updated_row(fixed_now)
+ updated_row.workflow_run_id = "wr_live"
updated_row.parent_workflow_run_id = None
class FrozenDateTime(datetime):
@@ -231,9 +229,8 @@ async def test_mark_canceled_if_not_final_syncs_task_runs(
the ``_sync_task_run_from_workflow_run`` write-through so downstream
consumers reading ``task_runs`` see the cancel event.
"""
- from skyvern.forge.sdk.workflow.service import WorkflowService
-
updated_row = _make_updated_row()
+ updated_row.workflow_run_id = "wr_sync"
monkeypatch.setattr(
app.DATABASE.workflow_runs,
"update_workflow_run_if_not_final",
@@ -266,9 +263,6 @@ async def test_mark_canceled_if_not_final_skips_side_effects_on_terminal_row(
terminal status's own ``_update_workflow_run_status`` call already emitted
them.
"""
- from skyvern.forge.sdk.workflow import service as service_module
- from skyvern.forge.sdk.workflow.service import WorkflowService
-
monkeypatch.setattr(
app.DATABASE.workflow_runs,
"update_workflow_run_if_not_final",
@@ -298,8 +292,6 @@ async def test_mark_canceled_if_not_final_is_noop_on_terminal_row(
) -> None:
"""DB returns None when the row is already terminal — helper must propagate
that as None instead of raising or writing a conflicting row."""
- from skyvern.forge.sdk.workflow.service import WorkflowService
-
delegate = AsyncMock(return_value=None)
monkeypatch.setattr(app.DATABASE.workflow_runs, "update_workflow_run_if_not_final", delegate)
@@ -330,8 +322,6 @@ async def test_mark_canceled_rejects_transition_on_terminal_row(
terminal rows; the service helper must propagate the existing row back to
callers without writing ``canceled``.
"""
- from skyvern.forge.sdk.workflow.service import WorkflowService
-
existing_row = MagicMock()
existing_row.status = terminal_status
@@ -364,8 +354,6 @@ async def test_mark_canceled_writes_when_row_is_non_terminal(
"""SKY-9188: a non-terminal run still transitions to ``canceled`` through
the conditional update path.
"""
- from skyvern.forge.sdk.workflow.service import WorkflowService
-
canceled_row = MagicMock()
canceled_row.status = WorkflowRunStatus.canceled
@@ -395,8 +383,6 @@ async def test_mark_canceled_raises_when_row_missing(
``WorkflowRunNotFound`` rather than silently pretending the cancel
succeeded.
"""
- from skyvern.forge.sdk.workflow.service import WorkflowService
-
conditional_update = AsyncMock(return_value=None)
monkeypatch.setattr(app.DATABASE.workflow_runs, "update_workflow_run_if_not_final", conditional_update)
get_workflow_run = AsyncMock(return_value=None)
@@ -410,9 +396,6 @@ async def test_mark_canceled_raises_when_row_missing(
@pytest.mark.asyncio
async def test_cleanup_after_cancellation_emits_only_canceled_webhook(monkeypatch: pytest.MonkeyPatch) -> None:
- from skyvern.forge.sdk.workflow import service as service_module
- from skyvern.forge.sdk.workflow.service import WorkflowBrowserCleanupResult, WorkflowService
-
running_run = _make_updated_row()
running_run.workflow_run_id = "wr_canceled_during_cleanup"
running_run.status = WorkflowRunStatus.running
@@ -445,7 +428,7 @@ async def test_cleanup_after_cancellation_emits_only_canceled_webhook(monkeypatc
pre_finally_failure_reason=None,
)
await svc.clean_up_workflow(
- workflow=MagicMock(),
+ workflow=SimpleNamespace(workflow_definition=SimpleNamespace(retry_policy=None)),
workflow_run=finalized_run,
browser_cleanup_result=WorkflowBrowserCleanupResult(
browser_state=None,
@@ -465,6 +448,147 @@ async def test_cleanup_after_cancellation_emits_only_canceled_webhook(monkeypatc
assert webhook_statuses == [WorkflowRunStatus.canceled]
+async def test_cancel_policy_run_leaves_attachment_deletion_to_terminal_side_effects(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ workflow_run = _make_updated_row()
+ workflow_run.workflow_run_id = "wr_policy_cancel"
+ workflow_run.status = WorkflowRunStatus.running
+ canceled_run = _make_updated_row()
+ canceled_run.workflow_run_id = workflow_run.workflow_run_id
+ attempts = [MagicMock(attempt_number=1)]
+ monkeypatch.setattr(
+ run_service.app.DATABASE.workflow_runs,
+ "get_workflow_run",
+ AsyncMock(return_value=workflow_run),
+ )
+ monkeypatch.setattr(
+ run_service.app.DATABASE.workflow_runs,
+ "get_workflow_runs_by_parent_workflow_run_id",
+ AsyncMock(return_value=[]),
+ )
+ monkeypatch.setattr(
+ run_service.app.DATABASE.workflow_run_attempts, "get_attempts", AsyncMock(return_value=attempts)
+ )
+ monkeypatch.setattr(
+ run_service.app.WORKFLOW_SERVICE, "mark_workflow_run_as_canceled", AsyncMock(return_value=canceled_run)
+ )
+ decision = run_service.RetryDecision(False, 1, 0, True, "cancel")
+ monkeypatch.setattr(run_service, "get_recorded_decision", AsyncMock(return_value=decision))
+ terminal_effects = AsyncMock()
+ monkeypatch.setattr(run_service.app.WORKFLOW_SERVICE, "_run_terminal_side_effects_with_retries", terminal_effects)
+ delete = AsyncMock()
+ monkeypatch.setattr(run_service.uploaded_file_service, "delete_files_attached_to_run", delete)
+ webhook = AsyncMock()
+ monkeypatch.setattr(run_service.app.WORKFLOW_SERVICE, "execute_workflow_webhook", webhook)
+
+ await run_service.cancel_workflow_run(workflow_run.workflow_run_id, organization_id="org_abc")
+
+ delete.assert_not_awaited()
+ terminal_effects.assert_awaited_once_with(canceled_run, decision, api_key=None)
+ webhook.assert_not_awaited()
+
+
+async def test_cancel_policy_run_retries_failed_terminal_release_without_raising(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ workflow_run = _make_updated_row()
+ workflow_run.workflow_run_id = "wr_policy_cancel_effect_failed"
+ workflow_run.status = WorkflowRunStatus.running
+ canceled_run = _make_updated_row()
+ canceled_run.workflow_run_id = workflow_run.workflow_run_id
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ retry_decision="final",
+ decision_reason="cancel",
+ side_effects_released_at=None,
+ webhook_sent_at=None,
+ interim_webhook_sent_at=None,
+ )
+ monkeypatch.setattr(
+ run_service.app.DATABASE.workflow_runs,
+ "get_workflow_run",
+ AsyncMock(return_value=workflow_run),
+ )
+ monkeypatch.setattr(
+ run_service.app.DATABASE.workflow_runs,
+ "get_workflow_runs_by_parent_workflow_run_id",
+ AsyncMock(return_value=[]),
+ )
+ monkeypatch.setattr(
+ run_service.app.DATABASE.workflow_run_attempts,
+ "get_attempts",
+ AsyncMock(return_value=[attempt]),
+ )
+ svc = WorkflowService()
+ monkeypatch.setattr(svc, "mark_workflow_run_as_canceled", AsyncMock(return_value=canceled_run))
+ monkeypatch.setattr(run_service.app, "WORKFLOW_SERVICE", svc)
+ decision = run_service.RetryDecision(False, 1, 0, True, "cancel")
+ monkeypatch.setattr(run_service, "get_recorded_decision", AsyncMock(return_value=decision))
+
+ release_calls = 0
+
+ async def fail_release(*_args: object, **_kwargs: object) -> str:
+ nonlocal release_calls
+ release_calls += 1
+ return "effect_failed"
+
+ monkeypatch.setattr(svc, "run_terminal_side_effects", fail_release)
+ warning = MagicMock()
+ monkeypatch.setattr(service_module.LOG, "warning", warning)
+
+ # The cancel operation itself succeeded; a failed best-effort release is retried and left
+ # for the durable recovery owner instead of being raised through the API path.
+ await run_service.cancel_workflow_run(workflow_run.workflow_run_id, organization_id="org_abc")
+
+ assert release_calls == TERMINAL_RELEASE_RETRY_MAX_ATTEMPTS
+ assert any(
+ call.args
+ and "exhausted" in str(call.args[0])
+ and call.kwargs.get("workflow_run_id") == workflow_run.workflow_run_id
+ and call.kwargs.get("attempt_number") == 1
+ and call.kwargs.get("outcome") == "effect_failed"
+ for call in warning.call_args_list
+ )
+
+
+async def test_cancel_no_policy_run_deletes_attachments_before_webhook(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ workflow_run = _make_updated_row()
+ workflow_run.workflow_run_id = "wr_no_policy_cancel"
+ workflow_run.status = WorkflowRunStatus.running
+ canceled_run = _make_updated_row()
+ canceled_run.workflow_run_id = workflow_run.workflow_run_id
+ monkeypatch.setattr(
+ run_service.app.DATABASE.workflow_runs,
+ "get_workflow_run",
+ AsyncMock(return_value=workflow_run),
+ )
+ monkeypatch.setattr(
+ run_service.app.DATABASE.workflow_runs,
+ "get_workflow_runs_by_parent_workflow_run_id",
+ AsyncMock(return_value=[]),
+ )
+ monkeypatch.setattr(run_service.app.DATABASE.workflow_run_attempts, "get_attempts", AsyncMock(return_value=[]))
+ monkeypatch.setattr(
+ run_service.app.WORKFLOW_SERVICE, "mark_workflow_run_as_canceled", AsyncMock(return_value=canceled_run)
+ )
+ order: list[str] = []
+ delete = AsyncMock(side_effect=lambda **_kwargs: order.append("delete"))
+ webhook = AsyncMock(side_effect=lambda *args, **kwargs: order.append("webhook"))
+ monkeypatch.setattr(run_service.uploaded_file_service, "delete_files_attached_to_run", delete)
+ monkeypatch.setattr(run_service.app.WORKFLOW_SERVICE, "execute_workflow_webhook", webhook)
+
+ await run_service.cancel_workflow_run(workflow_run.workflow_run_id, organization_id="org_abc")
+
+ assert order == ["delete", "webhook"]
+ delete.assert_awaited_once_with(run_id=workflow_run.workflow_run_id)
+
+
@pytest.mark.asyncio
async def test_execute_workflow_webhook_tolerates_soft_deleted_workflow(
monkeypatch: pytest.MonkeyPatch,
@@ -472,8 +596,6 @@ async def test_execute_workflow_webhook_tolerates_soft_deleted_workflow(
"""If the workflow row has been soft-deleted by the time cleanup runs,
``execute_workflow_webhook`` should log a warning and return — not raise.
"""
- from skyvern.forge.sdk.workflow.service import WorkflowService
-
svc = WorkflowService()
async def raise_not_found(*args: object, **kwargs: object) -> None:
@@ -494,8 +616,6 @@ async def test_build_status_response_uses_filter_deleted_false_when_allowed(
"""``allow_deleted=True`` goes through the run-joined repository lookup with
``filter_deleted=False`` so soft-deleted workflows still resolve.
"""
- from skyvern.forge.sdk.workflow.service import WorkflowService
-
svc = WorkflowService()
by_run = AsyncMock(return_value=MagicMock())
@@ -608,9 +728,6 @@ async def test_shielded_finalize_skipped_when_pre_finally_status_unset() -> None
def test_lease_failure_category_persists_only_typed_browser_loss() -> None:
- from skyvern.exceptions import BrowserSessionClosed, BrowserSessionStartupTimeout
- from skyvern.forge.sdk.workflow.service import _browser_lease_failure_category
-
closed = _browser_lease_failure_category(BrowserSessionClosed("pbs_x"))
timeout = _browser_lease_failure_category(BrowserSessionStartupTimeout("pbs_x"))
diff --git a/tests/unit/test_workflow_service_managed_browser_profile.py b/tests/unit/test_workflow_service_managed_browser_profile.py
index 6ddeadb38..8ebc93905 100644
--- a/tests/unit/test_workflow_service_managed_browser_profile.py
+++ b/tests/unit/test_workflow_service_managed_browser_profile.py
@@ -1,26 +1,52 @@
from __future__ import annotations
import asyncio
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta, tzinfo
from types import SimpleNamespace
from typing import Any
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, Mock
import pytest
+import pytest_asyncio
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncEngine
from skyvern.forge import app
+from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.db.agent_db import AgentDB
+from skyvern.forge.sdk.db.enums import BrowserSeedSource
+from skyvern.forge.sdk.db.models import (
+ BrowserProfileModel,
+ CredentialModel,
+ WorkflowModel,
+ WorkflowRunAttemptModel,
+ WorkflowRunCredentialSelectionModel,
+ WorkflowRunModel,
+)
+from skyvern.forge.sdk.db.repositories.workflow_runs import PrepareNextAttemptResult
+from skyvern.forge.sdk.schemas.files import FileInfo
+from skyvern.forge.sdk.schemas.persistent_browser_sessions import BrowserSessionCloseReason
from skyvern.forge.sdk.workflow import service as service_module
from skyvern.forge.sdk.workflow.browser_profile_key import (
build_browser_profile_key_digest,
build_workflow_browser_session_storage_key,
)
from skyvern.forge.sdk.workflow.models.block import BlockType
-from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
+from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowRequestBody, WorkflowRun, WorkflowRunStatus
+from skyvern.forge.sdk.workflow.retry_policy import (
+ RETRY_DECISION_FINAL,
+ RETRY_DECISION_RETRY,
+ RETRY_DECISION_REVOKED,
+ RetryDecision,
+)
from skyvern.forge.sdk.workflow.service import (
WorkflowBrowserCleanupResult,
WorkflowService,
)
-from skyvern.schemas.workflows import BlockStatus
+from skyvern.schemas.workflows import BlockStatus, WorkflowRetryPolicy
+from skyvern.webeye.real_browser_manager import RealBrowserManager
+from tests.unit.force_stub_app import make_workflow_run_attempts_fake
+from tests.unit.scoped_asyncio import ScopedAsyncio
def _workflow(browser_profile_key: str | None = None) -> SimpleNamespace:
@@ -46,7 +72,7 @@ def _workflow_run(browser_profile_id: str | None = None) -> SimpleNamespace:
)
-def _execute_workflow() -> SimpleNamespace:
+def _execute_workflow(*, retry_policy: object | None = None) -> SimpleNamespace:
return SimpleNamespace(
workflow_id="wf_1",
persist_browser_session=True,
@@ -60,6 +86,7 @@ def _execute_workflow() -> SimpleNamespace:
parameters=[],
finally_block_label=None,
blocks=[SimpleNamespace(block_type=BlockType.TASK)],
+ retry_policy=retry_policy,
),
)
@@ -73,6 +100,7 @@ def _execute_workflow_run(status: WorkflowRunStatus) -> SimpleNamespace:
organization_id="o_test",
browser_session_id=None,
browser_profile_id="bp_managed",
+ browser_seed_source=BrowserSeedSource.own_memory,
browser_address=None,
start_fresh_browser=None,
reuse_browser_session=None,
@@ -80,11 +108,14 @@ def _execute_workflow_run(status: WorkflowRunStatus) -> SimpleNamespace:
failure_reason=None,
ignore_inherited_workflow_system_prompt=False,
parent_workflow_run_id=None,
+ depends_on_workflow_run_id=None,
proxy_location=None,
max_elapsed_time_minutes=1,
started_at=now,
created_at=now,
- code_gen=False,
+ code_gen=None,
+ debug_session_id=None,
+ copilot_session_id=None,
run_with="agent",
)
@@ -130,7 +161,9 @@ def _patch_execute_workflow_deps(
update_workflow_run_if_not_final=AsyncMock(return_value=refreshed_run),
get_workflow_runs_by_parent_workflow_run_id=AsyncMock(return_value=[]),
),
+ debug=SimpleNamespace(has_block_run_for_workflow_run=AsyncMock(return_value=False)),
artifacts=SimpleNamespace(claim_session_download_artifacts_for_run=AsyncMock(return_value=0)),
+ workflow_run_attempts=make_workflow_run_attempts_fake(),
)
monkeypatch.setattr(service_module.app, "WORKFLOW_CONTEXT_MANAGER", workflow_context_manager)
@@ -147,9 +180,10 @@ def _patch_execute_workflow_deps(
monkeypatch.setattr(service_module, "is_adaptive_caching", lambda _workflow, _workflow_run: False)
monkeypatch.setattr(svc, "get_workflow_run", AsyncMock(return_value=created_run))
- monkeypatch.setattr(svc, "get_workflow", AsyncMock(return_value=workflow))
+ monkeypatch.setattr(svc, "get_workflow_by_workflow_run_id", AsyncMock(return_value=workflow))
monkeypatch.setattr(svc, "bind_browser_action_policy", AsyncMock(return_value=None))
monkeypatch.setattr(svc, "mark_workflow_run_as_running", AsyncMock(return_value=running_run))
+ monkeypatch.setattr(service_module, "mark_attempt_started", AsyncMock(return_value=True))
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))
@@ -422,6 +456,869 @@ async def test_execute_workflow_persists_managed_profile_before_final_status(
svc._persist_workflow_browser_session_if_needed.assert_awaited_once()
+async def test_execute_workflow_with_attempt_row_still_records_final_webhook(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ workflow = _execute_workflow(retry_policy=WorkflowRetryPolicy(max_retries=1, retry_on=[{"status": "failed"}]))
+ completed_run = _execute_workflow_run(WorkflowRunStatus.completed)
+ order: list[str] = []
+
+ svc = WorkflowService()
+ _patch_execute_workflow_deps(monkeypatch, svc, workflow, _execute_workflow_run(WorkflowRunStatus.running))
+ _patch_browser_cleanup(monkeypatch, svc, order)
+ monkeypatch.setattr(
+ svc,
+ "_persist_workflow_browser_session_if_needed",
+ AsyncMock(side_effect=lambda **_kwargs: order.append("store")),
+ )
+ _patch_finalize(monkeypatch, svc, order, completed_run)
+ monkeypatch.setattr(svc, "persist_video_data", AsyncMock(side_effect=lambda *a, **k: order.append("video")))
+ webhook = AsyncMock(side_effect=lambda *a, **k: order.append("webhook"))
+ monkeypatch.setattr(svc, "execute_workflow_webhook", webhook)
+
+ attempt = SimpleNamespace(attempt_number=1, retry_decision=RETRY_DECISION_FINAL)
+ service_module.app.DATABASE.workflow_run_attempts.get_attempts = AsyncMock(return_value=[attempt])
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ AsyncMock(return_value=True),
+ )
+ monkeypatch.setattr(
+ service_module,
+ "get_recorded_decision",
+ AsyncMock(return_value=RetryDecision(False, 1, 0, True, RETRY_DECISION_FINAL)),
+ )
+ result = await _run_execute_workflow(svc)
+
+ assert result is completed_run
+ assert order == ["teardown", "store", "finalize", "video", "webhook"]
+ webhook.assert_awaited_once_with(
+ completed_run,
+ None,
+ claim_kind="final",
+ skip_side_effects_lease_check=True,
+ )
+
+
[email protected]("claim_replaced", [False, True], ids=["claim_current", "claim_replaced"])
+async def test_execute_workflow_with_retries_stops_when_its_dispatch_claim_was_replaced(
+ monkeypatch: pytest.MonkeyPatch, claim_replaced: bool
+) -> None:
+ """The sweep releases a stale dispatch claim and re-issues it to another dispatch. The superseded
+ dispatch must neither run blocks nor fail the run its new owner is executing."""
+ workflow = _execute_workflow(retry_policy=WorkflowRetryPolicy(max_retries=1, retry_on=[{"status": "failed"}]))
+ final_run = _execute_workflow_run(WorkflowRunStatus.completed)
+ order: list[str] = []
+
+ svc = WorkflowService()
+ _patch_execute_workflow_deps(monkeypatch, svc, workflow, final_run)
+ _patch_browser_cleanup(monkeypatch, svc, order)
+ monkeypatch.setattr(svc, "_persist_workflow_browser_session_if_needed", AsyncMock())
+ _patch_finalize(monkeypatch, svc, order, final_run)
+ monkeypatch.setattr(svc, "persist_video_data", AsyncMock())
+ monkeypatch.setattr(svc, "execute_workflow_webhook", AsyncMock())
+ monkeypatch.setattr(svc, "_run_terminal_side_effects_with_retries", AsyncMock())
+ monkeypatch.setattr(service_module, "mark_attempt_started", AsyncMock(return_value=False))
+ claimed_at = datetime.now(UTC).replace(tzinfo=None)
+ row_started_at = claimed_at + timedelta(seconds=1) if claim_replaced else claimed_at
+ attempt = SimpleNamespace(
+ attempt_number=1, retry_decision=None, started_at=row_started_at, pinned_browser_session_id=None
+ )
+ service_module.app.DATABASE.workflow_run_attempts.get_attempts = AsyncMock(return_value=[attempt])
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ AsyncMock(return_value=True),
+ )
+ monkeypatch.setattr(
+ service_module,
+ "get_recorded_decision",
+ AsyncMock(return_value=RetryDecision(False, 1, 0, True, RETRY_DECISION_FINAL)),
+ )
+ fail_run = AsyncMock()
+ monkeypatch.setattr(svc, "mark_workflow_run_as_failed_if_not_final", fail_run)
+
+ result = await svc.execute_workflow_with_retries(
+ workflow_run_id="wr_test",
+ api_key=None,
+ organization=SimpleNamespace(organization_id="o_test"),
+ prepared_attempt_claimed=True,
+ dispatch_claim_started_at=claimed_at,
+ )
+
+ if claim_replaced:
+ # The superseded owner hands back the run as currently read, untouched.
+ assert result is svc.get_workflow_run.return_value
+ assert svc._execute_workflow_blocks.await_count == 0
+ else:
+ assert result is final_run
+ assert svc._execute_workflow_blocks.await_count == 1
+ fail_run.assert_not_awaited()
+
+
+ ("attempt", "expected_block_runs"),
+ [
+ (SimpleNamespace(attempt_number=1, retry_decision=RETRY_DECISION_REVOKED, started_at=None), 0),
+ (SimpleNamespace(attempt_number=1, retry_decision=None, started_at=datetime.now(UTC)), 1),
+ ],
+ ids=["cancel_finalized_the_attempt", "activity_re_entered_a_started_attempt"],
+)
+async def test_execute_workflow_stops_when_the_attempt_was_finalized_before_it_started(
+ monkeypatch: pytest.MonkeyPatch,
+ attempt: SimpleNamespace,
+ expected_block_runs: int,
+) -> None:
+ """The attempt-start CAS loses to a cancel that lands after the running write; the run must not
+ resolve secrets or run blocks after its final webhook. A re-entered activity still continues."""
+ workflow = _execute_workflow(retry_policy=WorkflowRetryPolicy(max_retries=1, retry_on=[{"status": "failed"}]))
+ final_status = WorkflowRunStatus.canceled if expected_block_runs == 0 else WorkflowRunStatus.completed
+ final_run = _execute_workflow_run(final_status)
+ order: list[str] = []
+
+ svc = WorkflowService()
+ _patch_execute_workflow_deps(monkeypatch, svc, workflow, final_run)
+ _patch_browser_cleanup(monkeypatch, svc, order)
+ monkeypatch.setattr(svc, "_persist_workflow_browser_session_if_needed", AsyncMock())
+ _patch_finalize(monkeypatch, svc, order, final_run)
+ monkeypatch.setattr(svc, "persist_video_data", AsyncMock())
+ monkeypatch.setattr(svc, "execute_workflow_webhook", AsyncMock())
+ monkeypatch.setattr(service_module, "mark_attempt_started", AsyncMock(return_value=False))
+ service_module.app.DATABASE.workflow_run_attempts.get_attempts = AsyncMock(return_value=[attempt])
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ AsyncMock(return_value=True),
+ )
+ monkeypatch.setattr(
+ service_module,
+ "get_recorded_decision",
+ AsyncMock(return_value=RetryDecision(False, 1, 0, True, RETRY_DECISION_FINAL)),
+ )
+
+ result = await _run_execute_workflow(svc)
+
+ assert result is final_run
+ assert svc._execute_workflow_blocks.await_count == expected_block_runs
+ assert svc.get_workflow_run_parameter_tuples.await_count == expected_block_runs
+
+
+async def test_execute_workflow_abandons_retry_for_non_retry_aware_caller(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ workflow = _execute_workflow(retry_policy=WorkflowRetryPolicy(max_retries=1, retry_on=[{"status": "failed"}]))
+ completed_run = _execute_workflow_run(WorkflowRunStatus.completed)
+ completed_run.finished_at = datetime.now(UTC)
+ order: list[str] = []
+
+ svc = WorkflowService()
+ _patch_execute_workflow_deps(monkeypatch, svc, workflow, _execute_workflow_run(WorkflowRunStatus.running))
+ _patch_browser_cleanup(monkeypatch, svc, order)
+ monkeypatch.setattr(
+ svc,
+ "_persist_workflow_browser_session_if_needed",
+ AsyncMock(side_effect=lambda **_kwargs: order.append("store")),
+ )
+ _patch_finalize(monkeypatch, svc, order, completed_run)
+ monkeypatch.setattr(svc, "persist_video_data", AsyncMock(side_effect=lambda *a, **k: order.append("video")))
+ webhook = AsyncMock(side_effect=lambda *a, **k: order.append("webhook"))
+ monkeypatch.setattr(svc, "execute_workflow_webhook", webhook)
+
+ attempt = SimpleNamespace(attempt_number=1, retry_decision=RETRY_DECISION_RETRY)
+ service_module.app.DATABASE.workflow_run_attempts.get_attempts = AsyncMock(return_value=[attempt])
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ AsyncMock(return_value=True),
+ )
+ monkeypatch.setattr(
+ service_module,
+ "get_recorded_decision",
+ AsyncMock(return_value=RetryDecision(True, 1, 5, False, None)),
+ )
+ finalize_abandoned = AsyncMock(return_value=RetryDecision(False, 1, 0, True, "caller_not_retry_aware"))
+ monkeypatch.setattr(service_module, "finalize_abandoned_attempt", finalize_abandoned)
+
+ result = await _run_execute_workflow(svc)
+
+ assert result is completed_run
+ assert order == ["teardown", "store", "finalize", "video", "webhook"]
+ finalize_abandoned.assert_awaited_once_with(
+ workflow_run_id="wr_test",
+ organization_id="o_test",
+ reason="caller_not_retry_aware",
+ status=WorkflowRunStatus.completed,
+ failure_reason=None,
+ finished_at=completed_run.finished_at,
+ attempt_number=1,
+ )
+ webhook.assert_awaited_once_with(
+ completed_run,
+ None,
+ claim_kind="final",
+ skip_side_effects_lease_check=True,
+ )
+
+
+async def test_execute_workflow_with_retries_retries_escaped_exception(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc = WorkflowService()
+ organization = SimpleNamespace(organization_id="o_test")
+ running_run = _execute_workflow_run(WorkflowRunStatus.running)
+ failed_run = _execute_workflow_run(WorkflowRunStatus.failed)
+ completed_run = _execute_workflow_run(WorkflowRunStatus.completed)
+ attempt_rows = [
+ SimpleNamespace(
+ attempt_number=1,
+ retry_decision=None,
+ finished_at=None,
+ decision_reason=None,
+ next_attempt_at=None,
+ )
+ ]
+ monkeypatch.setattr(
+ service_module.app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(
+ get_attempts=AsyncMock(return_value=attempt_rows),
+ claim_prepared_attempt_execution=AsyncMock(return_value=True),
+ ),
+ workflow_runs=SimpleNamespace(
+ get_workflow_run=AsyncMock(side_effect=[running_run, completed_run]),
+ ),
+ ),
+ )
+ execute = AsyncMock(side_effect=[RuntimeError("escaped"), completed_run])
+ monkeypatch.setattr(svc, "execute_workflow", execute)
+ mark_failed = AsyncMock(return_value=failed_run)
+ monkeypatch.setattr(svc, "mark_workflow_run_as_failed_if_not_final", mark_failed)
+ side_effects = AsyncMock()
+ monkeypatch.setattr(svc, "run_terminal_side_effects", side_effects)
+ decisions = [
+ RetryDecision(True, 1, 0, False, "matched"),
+ RetryDecision(True, 1, 0, False, "matched"),
+ RetryDecision(False, 2, 0, True, "no_match"),
+ ]
+ monkeypatch.setattr(service_module, "get_recorded_decision", AsyncMock(side_effect=decisions))
+ prepare = AsyncMock(
+ return_value=PrepareNextAttemptResult(
+ status="inserted",
+ pinned_browser_session_id="browser-2",
+ )
+ )
+ monkeypatch.setattr(service_module, "prepare_next_attempt_result", prepare)
+
+ result = await svc.execute_workflow_with_retries(
+ workflow_run_id="wr_test",
+ api_key=None,
+ organization=organization,
+ )
+
+ assert result is completed_run
+ assert [call.kwargs["attempt_number"] for call in execute.await_args_list] == [1, 2]
+ mark_failed.assert_awaited_once_with(
+ workflow_run_id="wr_test",
+ failure_reason="escaped",
+ cascade_children=True,
+ )
+ prepare.assert_awaited_once_with(
+ workflow_run_id="wr_test",
+ organization_id="o_test",
+ from_attempt=1,
+ clear_browser_address=False,
+ )
+ assert [call.args[1] for call in side_effects.await_args_list] == [decisions[0], decisions[2]]
+
+
+async def test_execute_workflow_with_retries_leaves_pending_retry_for_recovery_on_cancellation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc = WorkflowService()
+ organization = SimpleNamespace(organization_id="o_test")
+ completed_run = _execute_workflow_run(WorkflowRunStatus.completed)
+ completed_run.finished_at = datetime.now(UTC)
+ attempt_rows = [
+ SimpleNamespace(
+ attempt_number=1,
+ retry_decision=None,
+ finished_at=None,
+ decision_reason=None,
+ next_attempt_at=None,
+ )
+ ]
+ monkeypatch.setattr(
+ service_module.app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(get_attempts=AsyncMock(return_value=attempt_rows)),
+ workflow_runs=SimpleNamespace(
+ get_workflow_run=AsyncMock(return_value=completed_run),
+ ),
+ ),
+ )
+ monkeypatch.setattr(svc, "execute_workflow", AsyncMock(return_value=completed_run))
+ retry_decision = RetryDecision(True, 1, 30, False, "matched")
+ monkeypatch.setattr(service_module, "get_recorded_decision", AsyncMock(return_value=retry_decision))
+
+ side_effects_started = asyncio.Event()
+
+ async def record_side_effects(*_args: Any, **_kwargs: Any) -> None:
+ side_effects_started.set()
+
+ side_effects = AsyncMock(side_effect=record_side_effects)
+ monkeypatch.setattr(svc, "run_terminal_side_effects", side_effects)
+ prepare = AsyncMock()
+ monkeypatch.setattr(service_module, "prepare_next_attempt_result", prepare)
+ finalize_abandoned = AsyncMock()
+ monkeypatch.setattr(service_module, "finalize_abandoned_attempt", finalize_abandoned)
+
+ task = asyncio.create_task(
+ svc.execute_workflow_with_retries(
+ workflow_run_id="wr_test",
+ api_key=None,
+ organization=organization,
+ )
+ )
+ await asyncio.wait_for(side_effects_started.wait(), timeout=1)
+ task.cancel()
+
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ # Shutdown must not convert the durable retry; recovery resumes it on the next start.
+ finalize_abandoned.assert_not_awaited()
+ assert [call.args[1] for call in side_effects.await_args_list] == [retry_decision]
+ prepare.assert_not_awaited()
+
+
+async def test_execute_workflow_with_retries_sleeps_until_the_recorded_next_attempt(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # The decision stamps next_attempt_at before cleanup and interim webhooks run; the owner must not
+ # add the full policy delay on top of that work.
+ svc = WorkflowService()
+ organization = SimpleNamespace(organization_id="o_test")
+ completed_run = _execute_workflow_run(WorkflowRunStatus.completed)
+ completed_run.finished_at = datetime.now(UTC)
+ attempt_rows = [
+ SimpleNamespace(
+ attempt_number=1, retry_decision=None, finished_at=None, decision_reason=None, next_attempt_at=None
+ )
+ ]
+ monkeypatch.setattr(
+ service_module.app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(get_attempts=AsyncMock(return_value=attempt_rows)),
+ workflow_runs=SimpleNamespace(get_workflow_run=AsyncMock(return_value=completed_run)),
+ ),
+ )
+ monkeypatch.setattr(svc, "execute_workflow", AsyncMock(return_value=completed_run))
+ retry_decision = RetryDecision(
+ True, 1, 30, False, "matched", next_attempt_at=datetime.now(UTC) + timedelta(seconds=2)
+ )
+ monkeypatch.setattr(service_module, "get_recorded_decision", AsyncMock(return_value=retry_decision))
+ monkeypatch.setattr(svc, "run_terminal_side_effects", AsyncMock())
+ monkeypatch.setattr(svc, "_prepare_recorded_retry", AsyncMock(return_value=None))
+ sleep = AsyncMock()
+ monkeypatch.setattr(service_module, "asyncio", ScopedAsyncio(sleep=sleep))
+
+ result = await svc.execute_workflow_with_retries(workflow_run_id="wr_test", api_key=None, organization=organization)
+
+ assert result is completed_run
+ (slept,) = (call.args[0] for call in sleep.await_args_list)
+ assert 0 < slept <= 2
+
+
+async def test_execute_workflow_with_retries_re_raises_escaped_exception_after_final_effects(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc = WorkflowService()
+ organization = SimpleNamespace(organization_id="o_test")
+ running_run = _execute_workflow_run(WorkflowRunStatus.running)
+ failed_run = _execute_workflow_run(WorkflowRunStatus.failed)
+ attempt_rows = [SimpleNamespace(attempt_number=1)]
+ get_run = AsyncMock(return_value=running_run)
+ monkeypatch.setattr(
+ service_module.app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(get_attempts=AsyncMock(return_value=attempt_rows)),
+ workflow_runs=SimpleNamespace(get_workflow_run=get_run),
+ ),
+ )
+ monkeypatch.setattr(svc, "execute_workflow", AsyncMock(side_effect=RuntimeError("escaped")))
+ mark_failed = AsyncMock(return_value=failed_run)
+ monkeypatch.setattr(svc, "mark_workflow_run_as_failed_if_not_final", mark_failed)
+ side_effects = AsyncMock()
+ monkeypatch.setattr(svc, "run_terminal_side_effects", side_effects)
+ final_decision = RetryDecision(False, 1, 0, True, "no_match")
+ monkeypatch.setattr(service_module, "get_recorded_decision", AsyncMock(return_value=final_decision))
+
+ with pytest.raises(RuntimeError, match="escaped"):
+ await svc.execute_workflow_with_retries(
+ workflow_run_id="wr_test",
+ api_key=None,
+ organization=organization,
+ )
+
+ get_run.assert_awaited_once_with(workflow_run_id="wr_test", organization_id="o_test")
+ mark_failed.assert_awaited_once_with(
+ workflow_run_id="wr_test",
+ failure_reason="escaped",
+ cascade_children=True,
+ )
+ side_effects.assert_awaited_once()
+ assert side_effects.await_args.args == (failed_run, final_decision)
+ assert side_effects.await_args.kwargs["api_key"] is None
+
+
+async def test_cleanup_claims_session_downloads_from_retry_attempt_start(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc = WorkflowService()
+ workflow = _execute_workflow(retry_policy=WorkflowRetryPolicy(max_retries=1, retry_on=[{"status": "failed"}]))
+ workflow_run = _execute_workflow_run(WorkflowRunStatus.completed)
+ workflow_run.created_at = datetime(2026, 9, 7, 10, 0, tzinfo=UTC)
+ attempt_started_at = datetime(2026, 9, 7, 12, 0, tzinfo=UTC)
+ attempt = SimpleNamespace(attempt_number=2, started_at=attempt_started_at)
+ claim = AsyncMock(return_value=1)
+ monkeypatch.setattr(
+ service_module.app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(get_attempts=AsyncMock(return_value=[attempt])),
+ debug=SimpleNamespace(has_block_run_for_workflow_run=AsyncMock(return_value=False)),
+ artifacts=SimpleNamespace(claim_session_download_artifacts_for_run=claim),
+ ),
+ )
+ monkeypatch.setattr(
+ service_module.app,
+ "AGENT_FUNCTION",
+ SimpleNamespace(
+ on_workflow_run_terminal=AsyncMock(),
+ is_block_scoped_workflow_run=AsyncMock(return_value=False),
+ ),
+ )
+ monkeypatch.setattr(
+ service_module.app,
+ "WORKFLOW_CONTEXT_MANAGER",
+ SimpleNamespace(
+ remove_workflow_run_context=lambda _workflow_run_id: None,
+ has_workflow_run_context=lambda _workflow_run_id: False,
+ ),
+ )
+ monkeypatch.setattr(
+ service_module.skyvern_context,
+ "current",
+ lambda: SimpleNamespace(browser_session_id="bs_retry", run_id=workflow_run.workflow_run_id),
+ )
+ monkeypatch.setattr(service_module.app.STORAGE, "save_downloaded_files", AsyncMock())
+ monkeypatch.setattr(service_module.app.ARTIFACT_MANAGER, "wait_for_upload_aiotasks", AsyncMock())
+ monkeypatch.setattr(
+ service_module, "get_recorded_decision", AsyncMock(return_value=RetryDecision(False, 2, 0, True, "final"))
+ )
+ monkeypatch.setattr(svc, "run_terminal_side_effects", AsyncMock())
+
+ await svc.clean_up_workflow(
+ workflow=workflow,
+ workflow_run=workflow_run,
+ browser_cleanup_result=WorkflowBrowserCleanupResult(
+ browser_state=None,
+ tasks=[],
+ all_workflow_task_ids=[],
+ child_workflow_run_ids=[],
+ close_browser_on_completion=True,
+ ),
+ attempt_number=2,
+ )
+
+ claim.assert_awaited_once_with(
+ run_id=workflow_run.workflow_run_id,
+ browser_session_id="bs_retry",
+ organization_id=workflow_run.organization_id,
+ run_started_at=attempt_started_at,
+ )
+
+
+async def test_cleanup_uses_legacy_path_when_retry_attempt_lookup_fails(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc = WorkflowService()
+ workflow = _execute_workflow()
+ workflow_run = _execute_workflow_run(WorkflowRunStatus.completed)
+ get_attempts = AsyncMock(side_effect=RuntimeError("attempt lookup unavailable"))
+ monkeypatch.setattr(
+ service_module.app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(get_attempts=get_attempts),
+ debug=SimpleNamespace(has_block_run_for_workflow_run=AsyncMock(return_value=False)),
+ ),
+ )
+ terminal_hook = AsyncMock()
+ monkeypatch.setattr(
+ service_module.app,
+ "AGENT_FUNCTION",
+ SimpleNamespace(
+ on_workflow_run_terminal=terminal_hook,
+ is_block_scoped_workflow_run=AsyncMock(return_value=False),
+ ),
+ )
+ monkeypatch.setattr(
+ service_module.app,
+ "WORKFLOW_CONTEXT_MANAGER",
+ SimpleNamespace(remove_workflow_run_context=Mock(), has_workflow_run_context=lambda _workflow_run_id: False),
+ )
+ monkeypatch.setattr(service_module.skyvern_context, "current", lambda: None)
+ save_downloads = AsyncMock()
+ monkeypatch.setattr(service_module.app.STORAGE, "save_downloaded_files", save_downloads)
+ wait_for_uploads = AsyncMock()
+ monkeypatch.setattr(service_module.app.ARTIFACT_MANAGER, "wait_for_upload_aiotasks", wait_for_uploads)
+ delete_attachments = AsyncMock()
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", delete_attachments)
+ legacy_webhook = AsyncMock()
+ monkeypatch.setattr(svc, "execute_workflow_webhook", legacy_webhook)
+ policy_effects = AsyncMock()
+ monkeypatch.setattr(svc, "run_terminal_side_effects", policy_effects)
+
+ await svc.clean_up_workflow(
+ workflow=workflow,
+ workflow_run=workflow_run,
+ browser_cleanup_result=WorkflowBrowserCleanupResult(
+ browser_state=None,
+ tasks=[],
+ all_workflow_task_ids=[],
+ child_workflow_run_ids=[],
+ close_browser_on_completion=True,
+ ),
+ schedule_credential_fallback_retry=False,
+ )
+
+ get_attempts.assert_awaited_once_with(workflow_run.workflow_run_id)
+ terminal_hook.assert_awaited_once_with(
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=workflow_run.organization_id,
+ status=workflow_run.status,
+ is_final_attempt=True,
+ )
+ wait_for_uploads.assert_awaited_once_with([])
+ save_downloads.assert_awaited_once_with(
+ organization_id=workflow_run.organization_id,
+ run_id=workflow_run.workflow_run_id,
+ )
+ delete_attachments.assert_awaited_once_with(run_id=workflow_run.workflow_run_id)
+ legacy_webhook.assert_awaited_once_with(workflow_run, None)
+ policy_effects.assert_not_awaited()
+
+
+async def test_cleanup_skips_logical_effects_when_policy_attempt_lookup_fails(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc = WorkflowService()
+ workflow = _execute_workflow(retry_policy=WorkflowRetryPolicy(max_retries=1, retry_on=[{"status": "failed"}]))
+ workflow_run = _execute_workflow_run(WorkflowRunStatus.completed)
+ get_attempts = AsyncMock(side_effect=RuntimeError("attempt lookup unavailable"))
+ monkeypatch.setattr(
+ service_module.app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(get_attempts=get_attempts),
+ debug=SimpleNamespace(has_block_run_for_workflow_run=AsyncMock(return_value=False)),
+ ),
+ )
+ terminal_hook = AsyncMock()
+ monkeypatch.setattr(
+ service_module.app,
+ "AGENT_FUNCTION",
+ SimpleNamespace(
+ on_workflow_run_terminal=terminal_hook,
+ is_block_scoped_workflow_run=AsyncMock(return_value=False),
+ ),
+ )
+ monkeypatch.setattr(
+ service_module.app,
+ "WORKFLOW_CONTEXT_MANAGER",
+ SimpleNamespace(remove_workflow_run_context=Mock(), has_workflow_run_context=lambda _workflow_run_id: False),
+ )
+ monkeypatch.setattr(service_module.skyvern_context, "current", lambda: None)
+ monkeypatch.setattr(service_module.app.STORAGE, "save_downloaded_files", AsyncMock())
+ monkeypatch.setattr(service_module.app.ARTIFACT_MANAGER, "wait_for_upload_aiotasks", AsyncMock())
+ delete_attachments = AsyncMock()
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", delete_attachments)
+ legacy_webhook = AsyncMock()
+ monkeypatch.setattr(svc, "execute_workflow_webhook", legacy_webhook)
+ policy_effects = AsyncMock()
+ monkeypatch.setattr(svc, "run_terminal_side_effects", policy_effects)
+ credential_fallback = Mock()
+ monkeypatch.setattr(svc, "_schedule_credential_fallback_retry", credential_fallback)
+
+ await svc.clean_up_workflow(
+ workflow=workflow,
+ workflow_run=workflow_run,
+ browser_cleanup_result=WorkflowBrowserCleanupResult(
+ browser_state=None,
+ tasks=[],
+ all_workflow_task_ids=[],
+ child_workflow_run_ids=[],
+ close_browser_on_completion=True,
+ ),
+ )
+
+ terminal_hook.assert_awaited_once_with(
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=workflow_run.organization_id,
+ status=workflow_run.status,
+ is_final_attempt=False,
+ )
+ delete_attachments.assert_not_awaited()
+ legacy_webhook.assert_not_awaited()
+ policy_effects.assert_not_awaited()
+ credential_fallback.assert_not_called()
+
+
+async def test_cleanup_uses_legacy_path_when_policy_run_has_no_attempt_row(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Enrollment is the attempt row. A definition with a policy but no row ran the ordinary path, so
+ # cleanup owes the legacy webhook and attachment deletion; no recovery sweep can supply them later.
+ svc = WorkflowService()
+ workflow = _execute_workflow(retry_policy=WorkflowRetryPolicy(max_retries=1, retry_on=[{"status": "failed"}]))
+ workflow_run = _execute_workflow_run(WorkflowRunStatus.completed)
+ monkeypatch.setattr(
+ service_module.app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(get_attempts=AsyncMock(return_value=[])),
+ debug=SimpleNamespace(has_block_run_for_workflow_run=AsyncMock(return_value=False)),
+ ),
+ )
+ terminal_hook = AsyncMock()
+ monkeypatch.setattr(
+ service_module.app,
+ "AGENT_FUNCTION",
+ SimpleNamespace(
+ on_workflow_run_terminal=terminal_hook,
+ is_block_scoped_workflow_run=AsyncMock(return_value=False),
+ ),
+ )
+ monkeypatch.setattr(
+ service_module.app,
+ "WORKFLOW_CONTEXT_MANAGER",
+ SimpleNamespace(remove_workflow_run_context=Mock(), has_workflow_run_context=lambda _workflow_run_id: False),
+ )
+ monkeypatch.setattr(service_module.skyvern_context, "current", lambda: None)
+ monkeypatch.setattr(service_module.app.STORAGE, "save_downloaded_files", AsyncMock())
+ monkeypatch.setattr(service_module.app.ARTIFACT_MANAGER, "wait_for_upload_aiotasks", AsyncMock())
+ delete_attachments = AsyncMock()
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", delete_attachments)
+ legacy_webhook = AsyncMock()
+ monkeypatch.setattr(svc, "execute_workflow_webhook", legacy_webhook)
+ policy_effects = AsyncMock()
+ monkeypatch.setattr(svc, "run_terminal_side_effects", policy_effects)
+
+ await svc.clean_up_workflow(
+ workflow=workflow,
+ workflow_run=workflow_run,
+ browser_cleanup_result=WorkflowBrowserCleanupResult(
+ browser_state=None,
+ tasks=[],
+ all_workflow_task_ids=[],
+ child_workflow_run_ids=[],
+ close_browser_on_completion=True,
+ ),
+ schedule_credential_fallback_retry=False,
+ )
+
+ terminal_hook.assert_awaited_once_with(
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=workflow_run.organization_id,
+ status=workflow_run.status,
+ is_final_attempt=True,
+ )
+ delete_attachments.assert_awaited_once_with(run_id=workflow_run.workflow_run_id)
+ legacy_webhook.assert_awaited_once_with(workflow_run, None)
+ policy_effects.assert_not_awaited()
+
+
+async def _assert_policy_definition_uses_legacy_cleanup_for_ineligible_run(
+ monkeypatch: pytest.MonkeyPatch,
+ workflow_run: SimpleNamespace,
+ *,
+ block_scoped: bool,
+) -> None:
+ svc = WorkflowService()
+ workflow = _execute_workflow(retry_policy=WorkflowRetryPolicy(max_retries=1, retry_on=[{"status": "failed"}]))
+ attempt = SimpleNamespace(attempt_number=1, retry_decision=RETRY_DECISION_FINAL)
+ terminal_hook = AsyncMock()
+ delete_attachments = AsyncMock()
+ legacy_webhook = AsyncMock()
+ monkeypatch.setattr(
+ service_module.app,
+ "DATABASE",
+ SimpleNamespace(
+ workflow_run_attempts=SimpleNamespace(get_attempts=AsyncMock(return_value=[attempt])),
+ ),
+ )
+ monkeypatch.setattr(
+ service_module.app,
+ "AGENT_FUNCTION",
+ SimpleNamespace(
+ on_workflow_run_terminal=terminal_hook,
+ is_block_scoped_workflow_run=AsyncMock(return_value=block_scoped),
+ ),
+ )
+ monkeypatch.setattr(
+ service_module.app,
+ "WORKFLOW_CONTEXT_MANAGER",
+ SimpleNamespace(remove_workflow_run_context=Mock(), has_workflow_run_context=lambda _workflow_run_id: False),
+ )
+ monkeypatch.setattr(service_module.skyvern_context, "current", lambda: None)
+ monkeypatch.setattr(service_module.app.STORAGE, "save_downloaded_files", AsyncMock())
+ monkeypatch.setattr(service_module.app.ARTIFACT_MANAGER, "wait_for_upload_aiotasks", AsyncMock())
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", delete_attachments)
+ monkeypatch.setattr(svc, "execute_workflow_webhook", legacy_webhook)
+ policy_effects = AsyncMock()
+ monkeypatch.setattr(svc, "run_terminal_side_effects", policy_effects)
+
+ await svc.clean_up_workflow(
+ workflow=workflow,
+ workflow_run=workflow_run,
+ browser_cleanup_result=WorkflowBrowserCleanupResult(
+ browser_state=None,
+ tasks=[],
+ all_workflow_task_ids=[],
+ child_workflow_run_ids=[],
+ close_browser_on_completion=True,
+ ),
+ schedule_credential_fallback_retry=False,
+ )
+
+ terminal_hook.assert_awaited_once_with(
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=workflow_run.organization_id,
+ status=workflow_run.status,
+ is_final_attempt=True,
+ )
+ delete_attachments.assert_awaited_once_with(run_id=workflow_run.workflow_run_id)
+ legacy_webhook.assert_awaited_once_with(workflow_run, None)
+ policy_effects.assert_not_awaited()
+
+
+async def test_block_scoped_policy_run_uses_legacy_cleanup(monkeypatch: pytest.MonkeyPatch) -> None:
+ workflow_run = _execute_workflow_run(WorkflowRunStatus.completed)
+ await _assert_policy_definition_uses_legacy_cleanup_for_ineligible_run(
+ monkeypatch,
+ workflow_run,
+ block_scoped=True,
+ )
+
+
+async def test_child_policy_run_uses_legacy_cleanup(monkeypatch: pytest.MonkeyPatch) -> None:
+ workflow_run = _execute_workflow_run(WorkflowRunStatus.completed)
+ workflow_run.parent_workflow_run_id = "parent_run"
+ await _assert_policy_definition_uses_legacy_cleanup_for_ineligible_run(
+ monkeypatch,
+ workflow_run,
+ block_scoped=False,
+ )
+
+
+async def test_retry_decision_rejects_non_terminal_status() -> None:
+ with pytest.raises(ValueError, match="non-terminal status: running"):
+ await service_module.on_terminal_transition(
+ SimpleNamespace(workflow_run_id="wr_test"),
+ WorkflowRunStatus.running,
+ None,
+ None,
+ )
+
+
+async def test_filter_downloaded_files_keeps_identical_redownload_touched_in_current_attempt() -> None:
+ svc = WorkflowService()
+ attempt_started_at = datetime(2026, 9, 7, 12, 0, 0, tzinfo=UTC)
+ files = [
+ FileInfo(
+ url="https://example.test/old.pdf",
+ checksum="old",
+ filename="only-attempt-1.pdf",
+ modified_at=attempt_started_at.replace(hour=11, minute=59),
+ artifact_id="a_old",
+ ),
+ FileInfo(
+ url="https://example.test/report.pdf",
+ checksum="same",
+ filename="report.pdf",
+ modified_at=attempt_started_at,
+ artifact_id="a_report",
+ ),
+ ]
+
+ filtered = svc._filter_downloaded_files_to_attempt(
+ files,
+ attempt_rows=[SimpleNamespace(attempt_number=2, started_at=attempt_started_at)],
+ attempt_number=2,
+ artifact_ids={"a_report"},
+ )
+
+ assert [file_info.filename for file_info in filtered] == ["report.pdf"]
+
+
+def test_filter_downloaded_files_bounds_an_unstarted_attempt_by_its_creation() -> None:
+ svc = WorkflowService()
+ prepared_at = datetime(2026, 9, 7, 12, 0, 0, tzinfo=UTC)
+ files = [
+ FileInfo(
+ url="https://example.test/old.pdf",
+ checksum="old",
+ filename="attempt-1.pdf",
+ modified_at=prepared_at.replace(hour=11),
+ artifact_id="a_old",
+ ),
+ FileInfo(
+ url="https://example.test/claimed.pdf",
+ checksum="claimed",
+ filename="claimed.pdf",
+ modified_at=prepared_at.replace(hour=11, minute=30),
+ artifact_id="a_claimed",
+ ),
+ FileInfo(url="https://example.test/unknown.pdf", checksum="unknown", filename="unknown.pdf"),
+ ]
+ attempt_rows = [
+ SimpleNamespace(
+ attempt_number=1, started_at=prepared_at.replace(hour=10), created_at=prepared_at.replace(hour=9)
+ ),
+ SimpleNamespace(attempt_number=2, started_at=None, created_at=prepared_at),
+ ]
+
+ filtered = svc._filter_downloaded_files_to_attempt(
+ files, attempt_rows=attempt_rows, attempt_number=2, artifact_ids={"a_claimed"}
+ )
+
+ assert [file_info.filename for file_info in filtered] == ["claimed.pdf"]
+ # The live attempt keeps the permissive rule for a file whose timestamp is unknown.
+ live = svc._filter_downloaded_files_to_attempt(
+ files[2:], attempt_rows=attempt_rows[:1], attempt_number=1, artifact_ids=set()
+ )
+ assert [file_info.filename for file_info in live] == ["unknown.pdf"]
+
+
@pytest.mark.asyncio
async def test_execute_workflow_persists_profile_when_only_finally_block_fails(
monkeypatch: pytest.MonkeyPatch,
@@ -621,6 +1518,8 @@ async def test_execute_workflow_rechecks_terminal_winner_before_healthy_writebac
prefinal_browser_cleanup.assert_not_awaited()
persist_browser_session.assert_not_awaited()
finalize.assert_awaited_once()
+ assert finalize.await_args is not None
+ assert finalize.await_args.kwargs["workflow"] is workflow
clean_up.assert_awaited_once()
assert clean_up.await_args is not None
assert clean_up.await_args.kwargs["browser_persistence_status"] == WorkflowRunStatus.timed_out
@@ -841,3 +1740,664 @@ async def test_execute_workflow_does_not_close_human_interaction_session(
assert result is completed_run
close_session.assert_not_awaited()
+
+
+@pytest_asyncio.fixture
+async def forced_session_setup(
+ monkeypatch: pytest.MonkeyPatch,
+ sqlite_engine: AsyncEngine,
+) -> tuple[AgentDB, WorkflowService, Workflow]:
+ database = AgentDB("sqlite+aiosqlite://", db_engine=sqlite_engine)
+ await database.organizations.create_organization("Test", organization_id="o_test")
+ async with database.Session() as session:
+ session.add(
+ WorkflowModel(
+ workflow_id="wf_1",
+ workflow_permanent_id="wpid_test",
+ organization_id="o_test",
+ title="Workflow",
+ workflow_definition={
+ "parameters": [],
+ "blocks": [],
+ "retry_policy": {"retry_on": [{"status": "failed"}], "delay_seconds": 0},
+ },
+ )
+ )
+ await session.commit()
+ workflow = await database.workflows.get_workflow("wf_1", organization_id="o_test")
+ assert workflow is not None
+ monkeypatch.setattr(app, "DATABASE", database)
+ monkeypatch.setattr(app.WORKFLOW_CONTEXT_MANAGER, "remove_workflow_run_context", Mock())
+ monkeypatch.setattr(app.AGENT_FUNCTION, "is_block_scoped_workflow_run", AsyncMock(return_value=False))
+ monkeypatch.setattr(
+ app.EXPERIMENTATION_PROVIDER,
+ "is_feature_enabled_cached",
+ AsyncMock(side_effect=lambda flag, *args, **kwargs: flag == "FORCE_BROWSER_SESSION"),
+ )
+ create_session = AsyncMock(return_value=SimpleNamespace(persistent_browser_session_id="pbs_forced"))
+ monkeypatch.setattr(app.PERSISTENT_SESSIONS_MANAGER, "create_session", create_session)
+ service = WorkflowService()
+ monkeypatch.setattr(service, "_resolve_managed_browser_profile_for_run_request", AsyncMock(return_value=None))
+ return database, service, workflow
+
+
[email protected]("forced_session", [True, False])
+async def test_block_scoped_setup_does_not_enroll_a_retry_attempt(
+ monkeypatch: pytest.MonkeyPatch,
+ forced_session_setup: tuple[AgentDB, WorkflowService, Workflow],
+ forced_session: bool,
+) -> None:
+ """A block run creates its block-run rows only after setup, so enrolment must trust the
+ caller's block-scoped intent; a policy definition alone must not enroll it."""
+ database, service, workflow = forced_session_setup
+ monkeypatch.setattr(
+ app.EXPERIMENTATION_PROVIDER,
+ "is_feature_enabled_cached",
+ AsyncMock(side_effect=lambda flag, *args, **kwargs: forced_session and flag == "FORCE_BROWSER_SESSION"),
+ )
+ block_run = await service.create_workflow_run(
+ workflow_request=WorkflowRequestBody(),
+ workflow_permanent_id="wpid_test",
+ workflow_id="wf_1",
+ organization_id="o_test",
+ workflow=workflow,
+ block_scoped=True,
+ )
+ full_run = await service.create_workflow_run(
+ workflow_request=WorkflowRequestBody(),
+ workflow_permanent_id="wpid_test",
+ workflow_id="wf_1",
+ organization_id="o_test",
+ workflow=workflow,
+ )
+ assert await database.workflow_run_attempts.get_attempts(block_run.workflow_run_id) == []
+ enrolled = await database.workflow_run_attempts.get_attempts(full_run.workflow_run_id)
+ assert [attempt.attempt_number for attempt in enrolled] == [1]
+
+
+@pytest_asyncio.fixture(params=["sequential", "browser_reuse"])
+async def retry_gate_setup(
+ monkeypatch: pytest.MonkeyPatch,
+ forced_session_setup: tuple[AgentDB, WorkflowService, Workflow],
+ request: pytest.FixtureRequest,
+) -> tuple[AgentDB, WorkflowService, WorkflowRun]:
+ database, service, _ = forced_session_setup
+ async with database.Session() as session:
+ workflow_model = await session.get(WorkflowModel, "wf_1")
+ assert workflow_model is not None
+ workflow_model.run_sequentially = request.param == "sequential"
+ workflow_model.reuse_browser_session = request.param == "browser_reuse"
+ workflow_model.workflow_definition = {
+ "parameters": [],
+ "blocks": [],
+ "retry_policy": {"retry_on": [{"status": "timed_out"}], "delay_seconds": 0, "max_retries": 1},
+ }
+ await session.commit()
+ workflow = await database.workflows.get_workflow("wf_1", organization_id="o_test")
+ assert workflow is not None
+ monkeypatch.setattr(app.EXPERIMENTATION_PROVIDER, "is_feature_enabled_cached", AsyncMock(return_value=False))
+ monkeypatch.setattr(app, "WORKFLOW_SERVICE", service)
+ monkeypatch.setattr(service, "_run_interim_side_effects_with_retries", AsyncMock(return_value="released"))
+ monkeypatch.setattr(service, "_run_terminal_side_effects_with_retries", AsyncMock(return_value="released"))
+ run = await service.create_workflow_run(
+ workflow_request=WorkflowRequestBody(start_fresh_browser=False),
+ workflow_permanent_id="wpid_test",
+ workflow_id="wf_1",
+ organization_id="o_test",
+ workflow=workflow,
+ max_elapsed_time_minutes=1,
+ )
+ expired_start = datetime.now(UTC).replace(tzinfo=None) - timedelta(minutes=2)
+ run = await database.workflow_runs.update_workflow_run(
+ run.workflow_run_id, status=WorkflowRunStatus.running, started_at=expired_start
+ )
+ async with database.Session() as session:
+ attempt = await session.get(WorkflowRunAttemptModel, (run.workflow_run_id, 1))
+ assert attempt is not None
+ attempt.started_at = expired_start
+ await session.commit()
+
+ async def mark_timed_out(workflow_run_id: str, failure_reason: str) -> WorkflowRun:
+ return await database.workflow_runs.update_workflow_run(
+ workflow_run_id,
+ status=WorkflowRunStatus.timed_out,
+ failure_reason=failure_reason,
+ finished_at=datetime.now(UTC).replace(tzinfo=None),
+ )
+
+ monkeypatch.setattr(service, "mark_workflow_run_as_timed_out", mark_timed_out)
+ return database, service, run
+
+
[email protected]("blocked", [False, True])
[email protected]("escaped_exception", [False, True])
+async def test_timed_out_retry_gets_fresh_admission_budget(
+ monkeypatch: pytest.MonkeyPatch,
+ retry_gate_setup: tuple[AgentDB, WorkflowService, WorkflowRun],
+ blocked: bool,
+ escaped_exception: bool,
+) -> None:
+ database, service, run = retry_gate_setup
+ executed_attempts: list[int] = []
+ admission_budgets: list[float] = []
+ gate_sleeps: list[float] = []
+
+ async def execute_attempt(*, attempt_number: int, **kwargs: Any) -> WorkflowRun:
+ executed_attempts.append(attempt_number)
+ result = await database.workflow_runs.update_workflow_run(
+ run.workflow_run_id,
+ status=WorkflowRunStatus.timed_out if attempt_number == 1 else WorkflowRunStatus.completed,
+ )
+ if attempt_number == 1 and escaped_exception:
+ raise RuntimeError("attempt timed out")
+ return result
+
+ def scaled_timeout(seconds: float) -> asyncio.Timeout:
+ admission_budgets.append(seconds)
+ return asyncio.timeout(seconds / 60)
+
+ async def fast_sleep(seconds: float) -> None:
+ if seconds:
+ gate_sleeps.append(seconds)
+ await asyncio.sleep(0.01 if seconds else 0)
+
+ monkeypatch.setattr(service, "execute_workflow", execute_attempt)
+ monkeypatch.setattr(
+ database.workflow_runs, "get_blocking_sequential_workflow_run", AsyncMock(return_value=run if blocked else None)
+ )
+ monkeypatch.setattr(service_module, "asyncio", ScopedAsyncio(timeout=scaled_timeout, sleep=fast_sleep))
+
+ result = await service.execute_workflow_with_retries(
+ run.workflow_run_id, api_key=None, organization=SimpleNamespace(organization_id="o_test")
+ )
+
+ assert len(admission_budgets) == 1
+ assert 55 < admission_budgets[0] <= 60
+ attempts = await database.workflow_run_attempts.get_attempts(run.workflow_run_id)
+ assert attempts[0].status == "timed_out"
+ assert attempts[0].retry_decision == RETRY_DECISION_RETRY
+ if blocked:
+ assert gate_sleeps
+ assert executed_attempts == [1]
+ assert result.status == WorkflowRunStatus.timed_out
+ assert attempts[1].started_at is None
+ assert attempts[1].decision_reason == "sequential_gate_stopped"
+ else:
+ assert not gate_sleeps
+ assert executed_attempts == [1, 2]
+ assert result.status == WorkflowRunStatus.completed
+ assert attempts[1].started_at is not None
+
+
+async def test_prepared_retry_recovery_keeps_its_admission_deadline(
+ monkeypatch: pytest.MonkeyPatch,
+ retry_gate_setup: tuple[AgentDB, WorkflowService, WorkflowRun],
+) -> None:
+ database, service, run = retry_gate_setup
+ admission_deadlines: list[datetime] = []
+ admission_budgets: list[float] = []
+ elapsed_timeout = service_module._get_workflow_run_max_elapsed_timeout_seconds
+
+ class WorkerLost(BaseException):
+ pass
+
+ def record_budget(gate_run: WorkflowRun) -> float:
+ assert gate_run.started_at is not None
+ admission_deadlines.append(gate_run.started_at.replace(tzinfo=UTC) + timedelta(minutes=1))
+ remaining = elapsed_timeout(gate_run)
+ admission_budgets.append(remaining)
+ return remaining
+
+ async def execute_attempt(**kwargs: Any) -> WorkflowRun:
+ return await database.workflow_runs.update_workflow_run(run.workflow_run_id, status=WorkflowRunStatus.timed_out)
+
+ execute = AsyncMock(side_effect=execute_attempt)
+ monkeypatch.setattr(service, "execute_workflow", execute)
+ monkeypatch.setattr(service_module, "_get_workflow_run_max_elapsed_timeout_seconds", record_budget)
+ monkeypatch.setattr(
+ database.workflow_runs, "get_blocking_sequential_workflow_run", AsyncMock(side_effect=WorkerLost)
+ )
+
+ with pytest.raises(WorkerLost):
+ await service.execute_workflow_with_retries(
+ run.workflow_run_id, api_key=None, organization=SimpleNamespace(organization_id="o_test")
+ )
+
+ attempts = await database.workflow_run_attempts.get_attempts(run.workflow_run_id)
+ prepared_at = attempts[1].created_at.replace(tzinfo=UTC)
+ assert attempts[1].started_at is None
+ assert 55 < admission_budgets[0] <= 60
+ current_time = prepared_at + timedelta(seconds=30)
+
+ class RecoveryClock(datetime):
+ @classmethod
+ def now(cls, tz: tzinfo | None = None) -> datetime:
+ return current_time.astimezone(tz) if tz is not None else current_time.replace(tzinfo=None)
+
+ monkeypatch.setattr(service_module, "datetime", RecoveryClock)
+ with pytest.raises(WorkerLost):
+ await service.execute_workflow_with_retries(
+ run.workflow_run_id, api_key=None, organization=SimpleNamespace(organization_id="o_test"), attempt_number=2
+ )
+
+ assert admission_budgets[1] == 30
+ current_time = prepared_at + timedelta(minutes=1)
+ result = await service.execute_workflow_with_retries(
+ run.workflow_run_id, api_key=None, organization=SimpleNamespace(organization_id="o_test"), attempt_number=2
+ )
+
+ assert admission_deadlines == [prepared_at + timedelta(minutes=1)] * 3
+ assert admission_budgets[2] == 0
+ assert result.status == WorkflowRunStatus.timed_out
+ assert [call.kwargs["attempt_number"] for call in execute.await_args_list] == [1]
+ attempts = await database.workflow_run_attempts.get_attempts(run.workflow_run_id)
+ assert attempts[1].started_at is None
+ assert attempts[1].decision_reason == "sequential_gate_stopped"
+
+
[email protected]("escaped_exception", [False, True])
+async def test_forced_session_is_pinned_for_first_and_prepared_retry_attempt(
+ monkeypatch: pytest.MonkeyPatch,
+ forced_session_setup: tuple[AgentDB, WorkflowService, Workflow],
+ escaped_exception: bool,
+) -> None:
+ database, service, workflow = forced_session_setup
+
+ run = await service.create_workflow_run(
+ workflow_request=WorkflowRequestBody(),
+ workflow_permanent_id="wpid_test",
+ workflow_id="wf_1",
+ organization_id="o_test",
+ workflow=workflow,
+ )
+
+ assert run.browser_session_id == "pbs_forced"
+ attempts = await database.workflow_run_attempts.get_attempts(run.workflow_run_id)
+ assert len(attempts) == 1
+ assert attempts[0].attempt_number == 1
+ assert attempts[0].pinned_browser_session_id == "pbs_forced"
+
+ context = skyvern_context.SkyvernContext(workflow_run_id=run.workflow_run_id, organization_id="o_test")
+ monkeypatch.setattr(skyvern_context, "current", lambda: context)
+ monkeypatch.setattr(skyvern_context, "ensure_context", lambda: context)
+ monkeypatch.setattr(app, "BROWSER_MANAGER", RealBrowserManager())
+ generations: list[str] = []
+ released_generations: list[str] = []
+ browser_accesses: list[tuple[int, str | None]] = []
+ owned_generation: str | None = None
+
+ async def begin_session(**kwargs: Any) -> str:
+ nonlocal owned_generation
+ assert kwargs["browser_session_id"] == "pbs_forced"
+ assert kwargs["runnable_id"] == run.workflow_run_id
+ assert owned_generation is None
+ owned_generation = f"lease_{len(generations) + 1}"
+ generations.append(owned_generation)
+ return owned_generation
+
+ async def release_session(**kwargs: Any) -> bool:
+ nonlocal owned_generation
+ assert kwargs["expected_runnable_id"] == run.workflow_run_id
+ assert kwargs["expected_runnable_generation_id"] == owned_generation
+ assert owned_generation is not None
+ released_generations.append(owned_generation)
+ owned_generation = None
+ return True
+
+ async def execute_attempt(*, attempt_number: int, browser_session_id: str | None, **kwargs: Any) -> WorkflowRun:
+ current_run = await database.workflow_runs.get_workflow_run(run.workflow_run_id, "o_test")
+ assert current_run is not None
+ session_id = browser_session_id or current_run.browser_session_id
+ assert session_id == "pbs_forced"
+ if attempt_number > 1:
+ assert context.browser_session_id == session_id
+ await service._ensure_browser_session_lease(
+ organization_id="o_test", workflow_run_id=run.workflow_run_id, browser_session_id=session_id
+ )
+ generation = context.browser_session_runnable_generation_id
+ browser_accesses.append((attempt_number, generation))
+ owns_session = (
+ context.browser_session_runnable_id == run.workflow_run_id
+ and generation == owned_generation
+ and generation not in released_generations
+ )
+ if owns_session:
+ await service._clean_up_workflow_browser(
+ workflow_run=current_run, close_browser_on_completion=False, browser_session_id=session_id
+ )
+ status = WorkflowRunStatus.completed if attempt_number == 2 and owns_session else WorkflowRunStatus.failed
+ current_run = await database.workflow_runs.update_workflow_run(run.workflow_run_id, status=status)
+ async with database.Session() as session:
+ attempt = await session.scalar(
+ select(WorkflowRunAttemptModel).where(
+ WorkflowRunAttemptModel.workflow_run_id == run.workflow_run_id,
+ WorkflowRunAttemptModel.attempt_number == attempt_number,
+ )
+ )
+ assert attempt is not None
+ attempt.status = status.value
+ attempt.retry_decision = RETRY_DECISION_RETRY if attempt_number == 1 else RETRY_DECISION_FINAL
+ await session.commit()
+ if attempt_number == 1 and escaped_exception:
+ raise RuntimeError("escaped after browser cleanup")
+ return current_run
+
+ monkeypatch.setattr(app.PERSISTENT_SESSIONS_MANAGER, "begin_session", begin_session)
+ monkeypatch.setattr(app.PERSISTENT_SESSIONS_MANAGER, "release_browser_session", release_session)
+ monkeypatch.setattr(service, "execute_workflow", execute_attempt)
+ monkeypatch.setattr(service, "_wait_for_retry_sequential_clearance", AsyncMock(return_value=None))
+ monkeypatch.setattr(service, "_run_interim_side_effects_with_retries", AsyncMock(return_value="released"))
+ monkeypatch.setattr(service, "_run_terminal_side_effects_with_retries", AsyncMock(return_value="released"))
+
+ result = await service.execute_workflow_with_retries(
+ run.workflow_run_id, api_key=None, organization=SimpleNamespace(organization_id="o_test")
+ )
+
+ assert browser_accesses == [(1, "lease_1"), (2, "lease_2")]
+ assert generations == released_generations == ["lease_1", "lease_2"]
+ assert result.status == WorkflowRunStatus.completed
+ assert context.browser_session_id == "pbs_forced"
+ attempts = await database.workflow_run_attempts.get_attempts(run.workflow_run_id)
+ assert [(attempt.attempt_number, attempt.pinned_browser_session_id) for attempt in attempts] == [
+ (1, "pbs_forced"),
+ (2, "pbs_forced"),
+ ]
+ prepared_run = await database.workflow_runs.get_workflow_run(run.workflow_run_id, "o_test")
+ assert prepared_run is not None
+ assert prepared_run.browser_session_id == "pbs_forced"
+
+
[email protected]("session_source", ["forced", "explicit", "unpinned"])
+async def test_retry_preparation_preserves_session_after_transient_forced_pin_failure(
+ monkeypatch: pytest.MonkeyPatch,
+ forced_session_setup: tuple[AgentDB, WorkflowService, Workflow],
+ session_source: str,
+) -> None:
+ database, service, workflow = forced_session_setup
+ pin_session = database.workflow_run_attempts.pin_first_attempt_browser_session_if_unset
+ pin_calls = 0
+
+ async def fail_first_pin(**kwargs: Any) -> None:
+ nonlocal pin_calls
+ pin_calls += 1
+ if pin_calls == 1:
+ raise RuntimeError("pin failed")
+ await pin_session(**kwargs)
+
+ monkeypatch.setattr(database.workflow_run_attempts, "pin_first_attempt_browser_session_if_unset", fail_first_pin)
+ if session_source != "forced":
+ monkeypatch.setattr(app.EXPERIMENTATION_PROVIDER, "is_feature_enabled_cached", AsyncMock(return_value=False))
+ if session_source == "explicit":
+ monkeypatch.setattr(
+ database.browser_sessions,
+ "get_persistent_browser_session",
+ AsyncMock(return_value=SimpleNamespace(browser_profile_id=None, runnable_id="wr_other")),
+ )
+ run = await service.create_workflow_run(
+ workflow_request=WorkflowRequestBody(
+ browser_session_id="pbs_explicit" if session_source == "explicit" else None
+ ),
+ workflow_permanent_id="wpid_test",
+ workflow_id="wf_1",
+ organization_id="o_test",
+ workflow=workflow,
+ )
+ await database.workflow_runs.update_workflow_run(
+ run.workflow_run_id,
+ status=WorkflowRunStatus.failed,
+ browser_session_id="pbs_leased" if session_source == "unpinned" else run.browser_session_id,
+ )
+ async with database.Session() as session:
+ attempt = await session.get(WorkflowRunAttemptModel, (run.workflow_run_id, 1))
+ assert attempt is not None
+ attempt.status = WorkflowRunStatus.failed.value
+ attempt.retry_decision = RETRY_DECISION_RETRY
+ await session.commit()
+
+ preparation = await service_module.prepare_next_attempt_result(run.workflow_run_id, "o_test", 1)
+
+ expected_session_id = {"forced": "pbs_forced", "explicit": "pbs_explicit", "unpinned": None}[session_source]
+ assert preparation.status == "inserted"
+ assert preparation.pinned_browser_session_id == expected_session_id
+ attempts = await database.workflow_run_attempts.get_attempts(run.workflow_run_id)
+ assert [attempt.pinned_browser_session_id for attempt in attempts] == [expected_session_id, expected_session_id]
+ reopened = await database.workflow_runs.get_workflow_run(run.workflow_run_id, "o_test")
+ assert reopened is not None
+ assert reopened.browser_session_id == expected_session_id
+ assert pin_calls == (2 if session_source == "forced" else 0)
+
+
[email protected]("failure_point", ["assignment", "pin"])
+async def test_forced_session_assignment_precedes_required_pin(
+ monkeypatch: pytest.MonkeyPatch,
+ forced_session_setup: tuple[AgentDB, WorkflowService, Workflow],
+ failure_point: str,
+) -> None:
+ database, service, workflow = forced_session_setup
+ close_session = AsyncMock()
+ monkeypatch.setattr(app.PERSISTENT_SESSIONS_MANAGER, "close_session", close_session)
+ if failure_point == "assignment":
+ monkeypatch.setattr(
+ database.workflow_runs, "update_workflow_run", AsyncMock(side_effect=RuntimeError("assignment failed"))
+ )
+ else:
+ monkeypatch.setattr(
+ database.workflow_run_attempts,
+ "pin_first_attempt_browser_session_if_unset",
+ AsyncMock(side_effect=RuntimeError("pin failed")),
+ )
+
+ if failure_point == "pin":
+ with pytest.raises(RuntimeError, match="pin failed"):
+ await service.create_workflow_run(
+ workflow_request=WorkflowRequestBody(),
+ workflow_permanent_id="wpid_test",
+ workflow_id="wf_1",
+ workflow_run_id="wr_pin_failure",
+ organization_id="o_test",
+ workflow=workflow,
+ )
+ run = await database.workflow_runs.get_workflow_run("wr_pin_failure", "o_test")
+ assert run is not None
+ assert run.status == WorkflowRunStatus.failed
+ assert run.finished_at is not None
+ assert run.failure_reason == "Failed to pin forced browser session for workflow retry"
+ close_session.assert_awaited_once_with("o_test", "pbs_forced", reason=BrowserSessionCloseReason.aborted)
+ assert database.workflow_run_attempts.pin_first_attempt_browser_session_if_unset.await_count == 2
+ else:
+ run = await service.create_workflow_run(
+ workflow_request=WorkflowRequestBody(),
+ workflow_permanent_id="wpid_test",
+ workflow_id="wf_1",
+ organization_id="o_test",
+ workflow=workflow,
+ )
+
+ persisted_run = await database.workflow_runs.get_workflow_run(run.workflow_run_id, "o_test")
+ assert persisted_run is not None
+ expected_session_id = None if failure_point == "assignment" else "pbs_forced"
+ assert run.browser_session_id == persisted_run.browser_session_id == expected_session_id
+ attempts = await database.workflow_run_attempts.get_attempts(run.workflow_run_id)
+ assert len(attempts) == 1
+ assert attempts[0].pinned_browser_session_id is None
+ if failure_point == "pin":
+ assert attempts[0].status == WorkflowRunStatus.failed.value
+ assert attempts[0].retry_decision == "abandoned"
+
+
[email protected]("deleted_version", [False, True])
[email protected]("seed_source", [BrowserSeedSource.credential, BrowserSeedSource.own_memory])
+async def test_retry_execution_resolves_rotated_seed_before_browser_creation(
+ monkeypatch: pytest.MonkeyPatch,
+ sqlite_engine: AsyncEngine,
+ deleted_version: bool,
+ seed_source: BrowserSeedSource,
+) -> None:
+ database = AgentDB("sqlite+aiosqlite:///:memory:", db_engine=sqlite_engine)
+ now = datetime.now(UTC)
+ credential_parameter = {
+ "parameter_type": "credential",
+ "key": "login",
+ "credential_parameter_id": "cp_login",
+ "workflow_id": "wf_1",
+ "credential_id": "cred_a",
+ "credential_ids": ["cred_a", "cred_b"],
+ "created_at": now.isoformat(),
+ "modified_at": now.isoformat(),
+ }
+ own_memory = seed_source == BrowserSeedSource.own_memory
+ async with database.Session() as session:
+ session.add_all(
+ [
+ WorkflowModel(
+ workflow_id="wf_1",
+ workflow_permanent_id="wpid_test",
+ organization_id="o_test",
+ title="Workflow",
+ persist_browser_session=own_memory,
+ browser_profile_key="{{ login }}" if own_memory else None,
+ workflow_definition={
+ "parameters": [credential_parameter],
+ "blocks": [
+ {
+ "block_type": "login",
+ "label": "login",
+ "parameters": [credential_parameter],
+ "output_parameter": {
+ "parameter_type": "output",
+ "key": "login_output",
+ "output_parameter_id": "op_login",
+ "workflow_id": "wf_1",
+ "created_at": now.isoformat(),
+ "modified_at": now.isoformat(),
+ },
+ }
+ ],
+ "retry_policy": {"max_retries": 1, "retry_on": [{"status": "failed"}]},
+ },
+ ),
+ WorkflowRunModel(
+ workflow_run_id="wr_test",
+ workflow_id="wf_1",
+ workflow_permanent_id="wpid_test",
+ organization_id="o_test",
+ status="failed",
+ browser_profile_id="bp_a",
+ browser_seed_source=seed_source,
+ browser_sink_profile_id="bp_a" if own_memory else None,
+ max_elapsed_time_minutes=1,
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id="wr_test",
+ organization_id="o_test",
+ attempt_number=1,
+ status="failed",
+ retry_decision="retry",
+ ),
+ WorkflowRunCredentialSelectionModel(
+ workflow_run_id="wr_test",
+ organization_id="o_test",
+ workflow_permanent_id="wpid_test",
+ parameter_key="login",
+ credential_id="cred_a",
+ ),
+ *[
+ CredentialModel(
+ credential_id=f"cred_{suffix}",
+ organization_id="o_test",
+ name=f"Credential {suffix}",
+ credential_type="password",
+ item_id=f"item_{suffix}",
+ run_sequentially=False,
+ browser_profile_id=None if own_memory else f"bp_{suffix}",
+ )
+ for suffix in ("a", "b")
+ ],
+ *[
+ BrowserProfileModel(
+ browser_profile_id=f"bp_{suffix}",
+ organization_id="o_test",
+ name=f"Profile {suffix}",
+ is_managed=own_memory,
+ workflow_permanent_id="wpid_test" if own_memory else None,
+ browser_profile_key_digest=(
+ build_browser_profile_key_digest(f"cred_{suffix}") if own_memory else None
+ ),
+ )
+ for suffix in ("a", "b")
+ ],
+ ]
+ )
+ await session.commit()
+ workflow = await database.workflows.get_workflow("wf_1", organization_id="o_test")
+ assert workflow is not None
+ if deleted_version:
+ async with database.Session() as session:
+ row = await session.get(WorkflowModel, "wf_1")
+ assert row is not None
+ row.deleted_at = now
+ await session.commit()
+ assert await database.workflows.get_workflow("wf_1", organization_id="o_test") is None
+
+ svc = WorkflowService()
+ _patch_execute_workflow_deps(monkeypatch, svc, workflow, _execute_workflow_run(WorkflowRunStatus.completed))
+ monkeypatch.setattr(app, "DATABASE", database)
+ monkeypatch.setattr(svc, "get_workflow_run", WorkflowService.get_workflow_run.__get__(svc))
+ monkeypatch.setattr(svc, "get_workflow", WorkflowService.get_workflow.__get__(svc))
+ monkeypatch.setattr(
+ svc, "get_workflow_by_workflow_run_id", WorkflowService.get_workflow_by_workflow_run_id.__get__(svc)
+ )
+ monkeypatch.setattr(app.AGENT_FUNCTION, "is_browser_memory_engine_enabled", AsyncMock(return_value=True))
+ monkeypatch.setattr(svc, "_managed_browser_profile_has_content", AsyncMock(return_value=True))
+ monkeypatch.setattr(svc, "_reconcile_managed_browser_profile_proxy_pin", AsyncMock())
+ monkeypatch.setattr(svc, "_maybe_pin_credential_profile_ip", AsyncMock(side_effect=lambda **kw: kw["workflow_run"]))
+ monkeypatch.setattr(svc, "clean_up_workflow", AsyncMock())
+ monkeypatch.setattr(svc, "_clean_up_workflow_browser", AsyncMock(return_value=_browser_cleanup_result()))
+ monkeypatch.setattr(svc, "_finalize_workflow_run_status", AsyncMock(side_effect=lambda **kw: kw["workflow_run"]))
+ monkeypatch.setattr(svc, "_run_terminal_side_effects_with_retries", AsyncMock())
+ monkeypatch.setattr(
+ service_module, "get_recorded_decision", AsyncMock(return_value=RetryDecision(False, 2, 0, True, "no_match"))
+ )
+
+ async def mark_running(workflow_run_id: str) -> WorkflowRun:
+ return await database.workflow_runs.update_workflow_run(
+ workflow_run_id, status=WorkflowRunStatus.running, started_at=datetime.now(UTC).replace(tzinfo=None)
+ )
+
+ monkeypatch.setattr(svc, "mark_workflow_run_as_running", mark_running)
+ browser_seeds: list[str | None] = []
+
+ async def execute_blocks(**kwargs: Any) -> tuple[WorkflowRun, set[str]]:
+ browser_seeds.append(kwargs["browser_profile_id"])
+ return await database.workflow_runs.update_workflow_run("wr_test", status=WorkflowRunStatus.completed), set()
+
+ monkeypatch.setattr(svc, "_execute_workflow_blocks", execute_blocks)
+ preparation = await database.workflow_runs.prepare_next_attempt_atomic(
+ workflow_run_id="wr_test",
+ organization_id="o_test",
+ from_attempt=1,
+ expected_status=WorkflowRunStatus.failed,
+ browser_session_id=None,
+ )
+ assert preparation.status == "inserted"
+
+ result = await svc.execute_workflow_with_retries(
+ workflow_run_id="wr_test",
+ api_key=None,
+ organization=SimpleNamespace(organization_id="o_test"),
+ attempt_number=2,
+ )
+
+ assert result.status == WorkflowRunStatus.completed
+ assert browser_seeds == ["bp_b"]
+ assert result.browser_profile_id == "bp_b"
+ assert result.browser_seed_source == seed_source
+ assert result.browser_sink_profile_id == ("bp_b" if own_memory else None)
+ assert await database.workflow_run_credential_selections.get_selection("wr_test", "login") == "cred_b"
diff --git a/tests/unit/test_workflow_webhook_delivery.py b/tests/unit/test_workflow_webhook_delivery.py
index e08cd3253..86a13c100 100644
--- a/tests/unit/test_workflow_webhook_delivery.py
+++ b/tests/unit/test_workflow_webhook_delivery.py
@@ -1,24 +1,47 @@
from __future__ import annotations
+import asyncio
import hashlib
import hmac
import json
-from datetime import datetime, timezone
+from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
+from typing import Any, Literal
from unittest.mock import AsyncMock, MagicMock
import httpx
import pytest
+from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker
from structlog.testing import capture_logs
from skyvern.forge.sdk.core.security import generate_skyvern_webhook_signature
+from skyvern.forge.sdk.db.models import WorkflowModel, WorkflowRunAttemptModel, WorkflowRunModel
+from skyvern.forge.sdk.db.repositories.workflow_run_attempts import WorkflowRunAttemptsRepository
+from skyvern.forge.sdk.db.repositories.workflows import WorkflowsRepository
+from skyvern.forge.sdk.executor.background_task_executor import BackgroundTaskExecutor
from skyvern.forge.sdk.workflow import service as service_module
+from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowDefinition, WorkflowRun, WorkflowRunStatus
+from skyvern.forge.sdk.workflow.retry_policy import (
+ LEASE_SAFETY_MARGIN_SECONDS,
+ LEASE_TAKEOVER_SECONDS,
+ RETRY_DECISION_FINAL,
+ RETRY_DECISION_REVOKED,
+ WEBHOOK_FALLBACK_GRACE_SECONDS,
+ RetryDecision,
+ _attempt_from_record,
+ _get_retry_policy,
+ evaluate_retry_policy,
+ on_terminal_transition,
+)
from skyvern.forge.sdk.workflow.service import WorkflowService
+from skyvern.schemas.workflows import WorkflowRetryPolicy
+from skyvern.services import webhook_delivery as webhook_delivery_module
+from tests.unit.scoped_asyncio import ScopedAsyncio
class _StatusResponse:
def __init__(self, extra_payload: dict | None = None) -> None:
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
self.status = "completed"
self.outputs: dict = {}
self.downloaded_files: list = []
@@ -36,6 +59,10 @@ class _StatusResponse:
self.queued_at = now
self.started_at = now
self.finished_at = now
+ self.attempt = 1
+ self.retry_pending = False
+ self.next_attempt_at = None
+ self.attempts: list = []
def model_dump_json(self) -> str:
return json.dumps({"workflow_run_id": "wr_abc", "status": "completed", **self.extra_payload})
@@ -89,6 +116,51 @@ def webhook_service(monkeypatch: pytest.MonkeyPatch) -> tuple[WorkflowService, A
)
monkeypatch.setattr(service_module.app.DATABASE.workflow_runs, "update_workflow_run", update_run)
+ async def save_progress(
+ workflow_run_id: str,
+ attempt_number: int,
+ *,
+ kind: str,
+ expected_claim_at: datetime,
+ progress: dict[str, Any],
+ ) -> bool:
+ rows = await service_module.app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ row = next((row for row in rows if row.attempt_number == attempt_number), None)
+ if row is None or row.side_effects_released_at != expected_claim_at:
+ return False
+ checkpoint = getattr(row, f"{kind}_side_effects_progress", None) or {}
+ setattr(row, f"{kind}_side_effects_progress", {**checkpoint, **progress})
+ return True
+
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts, "save_side_effect_progress", save_progress, raising=False
+ )
+
+ async def reserve_delivery(
+ workflow_run_id: str,
+ attempt_number: int,
+ *,
+ kind: str,
+ expected_claim_at: datetime | None,
+ max_attempts: int,
+ ) -> int | None:
+ rows = await service_module.app.DATABASE.workflow_run_attempts.get_attempts(workflow_run_id)
+ row = next((row for row in rows if row.attempt_number == attempt_number), None)
+ if row is None or getattr(row, "side_effects_released_at", None) != expected_claim_at:
+ return None
+ checkpoint = getattr(row, f"{kind}_side_effects_progress", None) or {}
+ attempts = checkpoint.get("webhook_delivery_attempts", 0) + 1
+ assert attempts <= max_attempts
+ setattr(row, f"{kind}_side_effects_progress", {**checkpoint, "webhook_delivery_attempts": attempts})
+ return attempts
+
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "reserve_attempt_webhook_delivery",
+ reserve_delivery,
+ raising=False,
+ )
+
return svc, build_response, update_run
@@ -251,3 +323,1673 @@ async def test_execute_workflow_webhook_records_exception_type_for_empty_message
update_run.assert_awaited_once()
assert "ReadTimeout" in update_run.await_args.kwargs["webhook_failure_reason"]
+
+
+async def test_policy_webhook_retries_delivery_when_process_stops_before_recording_claim(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ attempt = SimpleNamespace(attempt_number=1, webhook_sent_at=None, interim_webhook_sent_at=None)
+ get_attempts = AsyncMock(return_value=[attempt])
+ claim = AsyncMock(return_value=True)
+ monkeypatch.setattr(service_module.app.DATABASE.workflow_run_attempts, "get_attempts", get_attempts)
+ monkeypatch.setattr(service_module.app.DATABASE.workflow_run_attempts, "claim_attempt_webhook", claim)
+
+ deliver = AsyncMock(side_effect=asyncio.CancelledError)
+ monkeypatch.setattr(svc, "deliver_prepared_workflow_webhook", deliver)
+ with pytest.raises(asyncio.CancelledError):
+ await svc.execute_workflow_webhook(_workflow_run())
+ claim.assert_not_awaited()
+
+ deliver.side_effect = None
+ await svc.execute_workflow_webhook(_workflow_run())
+
+ assert deliver.await_count == 2
+ claim.assert_awaited_once_with("wr_abc", 1, kind="final", delivery_attempted=True)
+
+
+async def test_policy_webhook_skips_when_claim_was_already_recorded(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ webhook_sent_at=datetime.now(UTC),
+ interim_webhook_sent_at=None,
+ )
+ get_attempts = AsyncMock(return_value=[attempt])
+ claim = AsyncMock(return_value=True)
+ deliver = AsyncMock()
+ monkeypatch.setattr(service_module.app.DATABASE.workflow_run_attempts, "get_attempts", get_attempts)
+ monkeypatch.setattr(service_module.app.DATABASE.workflow_run_attempts, "claim_attempt_webhook", claim)
+ monkeypatch.setattr(svc, "deliver_prepared_workflow_webhook", deliver)
+
+ await svc.execute_workflow_webhook(_workflow_run())
+
+ deliver.assert_not_awaited()
+ claim.assert_not_awaited()
+
+
+async def test_policy_release_records_final_marker_when_no_webhook_url(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ workflow_run = _workflow_run()
+ workflow_run.status = WorkflowRunStatus.failed
+ workflow_run.webhook_callback_url = None
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ webhook_sent_at=None,
+ interim_webhook_sent_at=None,
+ side_effects_released_at=None,
+ )
+ claim_side_effects = AsyncMock(return_value=True)
+ claim_webhook = AsyncMock(return_value=True)
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts, "get_attempts", AsyncMock(return_value=[attempt])
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ claim_side_effects,
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_webhook",
+ claim_webhook,
+ )
+ monkeypatch.setattr(svc, "_apply_completion_run_tags_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "_schedule_workflow_run_terminal_hooks", MagicMock())
+ monkeypatch.setattr(svc, "_schedule_credential_fallback_retry", MagicMock())
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", AsyncMock())
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "on_workflow_run_final", AsyncMock())
+
+ await svc.run_terminal_side_effects(workflow_run, RetryDecision(False, 1, 0, True, "budget_exhausted"))
+
+ claim_webhook.assert_awaited_once_with("wr_abc", 1, kind="final")
+
+
[email protected]("retry_decision", [RETRY_DECISION_REVOKED, RETRY_DECISION_FINAL])
+async def test_final_release_skips_credential_fallback_for_a_canceled_retry(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+ retry_decision: str,
+) -> None:
+ """A cancel during the retry delay keeps the last attempt's failed status, so only the
+ revoked decision can stop the credential fallback from starting a new run."""
+ svc, _build_response, _update_run = webhook_service
+ workflow_run = _workflow_run()
+ workflow_run.status = WorkflowRunStatus.failed
+ workflow_run.webhook_callback_url = None
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ retry_decision=retry_decision,
+ webhook_sent_at=None,
+ interim_webhook_sent_at=None,
+ side_effects_released_at=None,
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts, "get_attempts", AsyncMock(return_value=[attempt])
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts, "claim_attempt_side_effects", AsyncMock(return_value=True)
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts, "claim_attempt_webhook", AsyncMock(return_value=True)
+ )
+ credential_fallback = AsyncMock()
+ monkeypatch.setattr(svc, "_start_credential_fallback_retry_best_effort", credential_fallback)
+ monkeypatch.setattr(svc, "_apply_completion_run_tags_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "_run_workflow_run_terminal_hooks", AsyncMock())
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", AsyncMock())
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "on_workflow_run_final", AsyncMock())
+ reason = "cancel" if retry_decision == RETRY_DECISION_REVOKED else "no_match"
+
+ outcome = await svc.run_terminal_side_effects(workflow_run, RetryDecision(False, 1, 0, True, reason))
+
+ assert outcome == "released"
+ assert credential_fallback.await_count == (0 if retry_decision == RETRY_DECISION_REVOKED else 1)
+
+
+async def test_policy_final_webhook_retries_after_retry_after_and_records_marker(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ workflow_run = _workflow_run()
+ workflow_run.status = WorkflowRunStatus.failed
+ claim_at = datetime.now(UTC).replace(tzinfo=None)
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ webhook_sent_at=None,
+ interim_webhook_sent_at=None,
+ side_effects_released_at=claim_at,
+ )
+
+ async def record_webhook_marker(
+ _workflow_run_id: str,
+ _attempt_number: int,
+ *,
+ kind: str,
+ expected_claim_at: datetime | None = None,
+ delivery_attempted: bool = False,
+ ) -> bool:
+ assert kind == "final"
+ assert expected_claim_at == claim_at
+ attempt.webhook_sent_at = datetime.now(UTC)
+ return True
+
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "get_attempts",
+ AsyncMock(return_value=[attempt]),
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ AsyncMock(return_value=claim_at),
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_webhook",
+ record_webhook_marker,
+ )
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", AsyncMock())
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "on_workflow_run_final", AsyncMock())
+ monkeypatch.setattr(svc, "_apply_completion_run_tags_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "_run_workflow_run_terminal_hooks", AsyncMock())
+ monkeypatch.setattr(svc, "_start_credential_fallback_retry_best_effort", AsyncMock())
+
+ responses = [
+ httpx.Response(503, headers={"Retry-After": "0"}),
+ httpx.Response(200, content=b"ok"),
+ ]
+ deliver = AsyncMock(side_effect=responses)
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "deliver_webhook", deliver)
+ original_fenced_effect = svc._run_fenced_terminal_side_effect
+ effect_timeouts: dict[str, float | None] = {}
+
+ async def record_fenced_effect(**kwargs: Any) -> bool:
+ effect_timeouts[kwargs["effect_name"]] = kwargs.get("timeout_seconds")
+ return await original_fenced_effect(**kwargs)
+
+ monkeypatch.setattr(svc, "_run_fenced_terminal_side_effect", record_fenced_effect)
+
+ await svc.run_terminal_side_effects(workflow_run, RetryDecision(False, 1, 0, True, "budget_exhausted"))
+
+ assert deliver.await_count == 2
+ assert attempt.webhook_sent_at is not None
+ assert effect_timeouts["final workflow webhook"] == WEBHOOK_FALLBACK_GRACE_SECONDS
+
+
+async def test_final_tail_restart_does_not_repeat_once_only_hook_after_early_refusal(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ workflow_run = _workflow_run()
+ workflow_run.status = WorkflowRunStatus.failed
+ owner_token = datetime(2026, 9, 7, 16, 0, 1, tzinfo=UTC)
+ takeover_token = datetime(2026, 9, 7, 16, 0, 2, tzinfo=UTC)
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ retry_decision="final",
+ webhook_sent_at=None,
+ interim_webhook_sent_at=None,
+ side_effects_released_at=None,
+ )
+ claim_count = 0
+
+ async def claim_side_effects(*_args: Any, expected_claim_at: datetime | None = None, **_kwargs: Any) -> datetime:
+ nonlocal claim_count
+ claim_count += 1
+ if claim_count == 1:
+ assert expected_claim_at is None
+ token = owner_token
+ else:
+ assert expected_claim_at == owner_token
+ token = takeover_token
+ attempt.side_effects_released_at = token
+ return token
+
+ async def record_final_webhook(*_args: Any, **_kwargs: Any) -> None:
+ attempt.webhook_sent_at = datetime.now(UTC)
+
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "get_attempts",
+ AsyncMock(return_value=[attempt]),
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ claim_side_effects,
+ )
+ delete_attachments = AsyncMock()
+ credential_fallback = AsyncMock()
+ completion_tags = AsyncMock()
+ terminal_hooks = AsyncMock()
+ final_hook = AsyncMock()
+ final_webhook = AsyncMock(side_effect=record_final_webhook)
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", delete_attachments)
+ monkeypatch.setattr(svc, "_start_credential_fallback_retry_best_effort", credential_fallback)
+ monkeypatch.setattr(svc, "_apply_completion_run_tags_best_effort", completion_tags)
+ monkeypatch.setattr(svc, "_run_workflow_run_terminal_hooks", terminal_hooks)
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "on_workflow_run_final", final_hook)
+ monkeypatch.setattr(svc, "execute_workflow_webhook", final_webhook)
+ lease_checks = AsyncMock(side_effect=[True, True, True, True, False, True, True, True, True, True])
+ monkeypatch.setattr(svc, "_side_effects_lease_is_current", lease_checks)
+ monkeypatch.setattr(svc, "_terminal_side_effect_outcome_after_fence", AsyncMock(return_value="fenced_out"))
+
+ decision = RetryDecision(False, 1, 0, True, "budget_exhausted")
+ first_outcome = await svc.run_terminal_side_effects(workflow_run, decision)
+ second_outcome = await svc.run_terminal_side_effects(
+ workflow_run,
+ decision,
+ side_effects_claim_at=owner_token,
+ side_effects_stale_before=owner_token + timedelta(seconds=1),
+ )
+
+ assert first_outcome == "fenced_out"
+ assert second_outcome == "released"
+ assert final_hook.await_count == 1
+ final_webhook.assert_awaited_once()
+ assert attempt.webhook_sent_at is not None
+ assert lease_checks.await_count == 6
+ assert delete_attachments.await_count == 1
+ assert credential_fallback.await_count == 1
+ assert completion_tags.await_count == 1
+ assert terminal_hooks.await_count == 1
+
+
+async def test_final_tail_guard_prevents_refusal_between_hook_and_webhook(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ workflow_run = _workflow_run()
+ workflow_run.status = WorkflowRunStatus.failed
+ claim_at = datetime(2026, 9, 7, 16, 0, 1, tzinfo=UTC)
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ retry_decision="final",
+ webhook_sent_at=None,
+ interim_webhook_sent_at=None,
+ side_effects_released_at=claim_at,
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "get_attempts",
+ AsyncMock(return_value=[attempt]),
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ AsyncMock(return_value=claim_at),
+ )
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", AsyncMock())
+ monkeypatch.setattr(svc, "_start_credential_fallback_retry_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "_apply_completion_run_tags_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "_run_workflow_run_terminal_hooks", AsyncMock())
+ final_hook = AsyncMock()
+ final_webhook = AsyncMock()
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "on_workflow_run_final", final_hook)
+ monkeypatch.setattr(svc, "execute_workflow_webhook", final_webhook)
+ lease_checks = AsyncMock(side_effect=[True, True, True, True, True])
+ monkeypatch.setattr(svc, "_side_effects_lease_is_current", lease_checks)
+
+ outcome = await svc.run_terminal_side_effects(
+ workflow_run,
+ RetryDecision(False, 1, 0, True, "budget_exhausted"),
+ )
+
+ assert outcome == "released"
+ final_hook.assert_awaited_once()
+ final_webhook.assert_awaited_once()
+ assert lease_checks.await_count == 5
+
+
+async def test_final_tail_fences_owner_before_once_only_hook_after_takeover(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ workflow_run = _workflow_run()
+ workflow_run.status = WorkflowRunStatus.failed
+ claim_at = datetime.now(UTC)
+ takeover_token = claim_at + timedelta(seconds=1)
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ retry_decision="final",
+ webhook_sent_at=None,
+ interim_webhook_sent_at=None,
+ side_effects_released_at=claim_at,
+ )
+ get_attempts = AsyncMock(return_value=[attempt])
+ monkeypatch.setattr(service_module.app.DATABASE.workflow_run_attempts, "get_attempts", get_attempts)
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ AsyncMock(return_value=claim_at),
+ )
+ claim_webhook = AsyncMock()
+ monkeypatch.setattr(service_module.app.DATABASE.workflow_run_attempts, "claim_attempt_webhook", claim_webhook)
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", AsyncMock())
+ monkeypatch.setattr(svc, "_start_credential_fallback_retry_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "_apply_completion_run_tags_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "_run_workflow_run_terminal_hooks", AsyncMock())
+ final_hook = AsyncMock()
+ final_webhook = AsyncMock()
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "on_workflow_run_final", final_hook)
+ monkeypatch.setattr(svc, "execute_workflow_webhook", final_webhook)
+
+ # The owner passes the total-tail bound check. The fresh row read immediately before the
+ # once-only hook observes the takeover token and fences the paused owner out.
+ async def take_over_at_tail(**_kwargs: Any) -> bool:
+ if lease_checks.await_count == 5:
+ attempt.side_effects_released_at = takeover_token
+ return True
+
+ lease_checks = AsyncMock(side_effect=take_over_at_tail)
+ monkeypatch.setattr(svc, "_side_effects_lease_is_current", lease_checks)
+
+ outcome = await svc.run_terminal_side_effects(
+ workflow_run,
+ RetryDecision(False, 1, 0, True, "budget_exhausted"),
+ )
+
+ assert outcome == "lease_held_by_other_young"
+ final_hook.assert_not_awaited()
+ final_webhook.assert_not_awaited()
+ claim_webhook.assert_not_awaited()
+ assert lease_checks.await_count == 5
+ assert get_attempts.await_count == 8
+
+
+async def test_policy_release_reports_a_foreign_young_lease_as_retryable(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ workflow_run = _workflow_run()
+ workflow_run.status = WorkflowRunStatus.failed
+ now = datetime(2026, 9, 7, 16, 0, tzinfo=UTC).replace(tzinfo=None)
+ foreign_claim = now - timedelta(seconds=400)
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ retry_decision="final",
+ webhook_sent_at=None,
+ interim_webhook_sent_at=None,
+ side_effects_released_at=foreign_claim,
+ )
+ monkeypatch.setattr(service_module, "naive_utc_now", lambda: now)
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "get_attempts",
+ AsyncMock(return_value=[attempt]),
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ AsyncMock(return_value=None),
+ )
+
+ outcome = await svc.run_terminal_side_effects(
+ workflow_run,
+ RetryDecision(False, 1, 0, True, "budget_exhausted"),
+ side_effects_claim_at=foreign_claim,
+ side_effects_stale_before=now - timedelta(seconds=LEASE_TAKEOVER_SECONDS),
+ )
+
+ assert outcome == "lease_held_by_other_young"
+
+
+async def test_policy_retry_without_webhook_records_interim_marker(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ workflow_run = _workflow_run()
+ workflow_run.status = WorkflowRunStatus.failed
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ webhook_sent_at=None,
+ interim_webhook_sent_at=None,
+ side_effects_released_at=None,
+ )
+ claim_side_effects = AsyncMock(return_value=True)
+ claim_webhook = AsyncMock(return_value=True)
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts, "get_attempts", AsyncMock(return_value=[attempt])
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ claim_side_effects,
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_webhook",
+ claim_webhook,
+ )
+
+ await svc.run_terminal_side_effects(workflow_run, RetryDecision(True, 1, 0, False, "matched"))
+
+ claim_side_effects.assert_awaited_once_with(
+ "wr_abc",
+ 1,
+ kind="interim",
+ expected_retry_decision="retry",
+ )
+ claim_webhook.assert_awaited_once_with("wr_abc", 1, kind="interim")
+
+
+async def test_interim_payload_preparation_failure_is_not_recorded_as_release(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ workflow_run = _workflow_run()
+ workflow_run.status = WorkflowRunStatus.failed
+ claim_at = datetime.now(UTC).replace(tzinfo=None)
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ retry_decision="retry",
+ next_attempt_prepared_at=None,
+ webhook_sent_at=None,
+ interim_webhook_sent_at=None,
+ side_effects_released_at=claim_at,
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "get_attempts",
+ AsyncMock(return_value=[attempt]),
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ AsyncMock(return_value=claim_at),
+ )
+ clear_lease = AsyncMock()
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "clear_failed_interim_side_effect_lease",
+ clear_lease,
+ raising=False,
+ )
+ monkeypatch.setattr(svc, "prepare_workflow_webhook", AsyncMock(side_effect=RuntimeError("payload unavailable")))
+ claim_webhook = AsyncMock()
+ monkeypatch.setattr(service_module.app.DATABASE.workflow_run_attempts, "claim_attempt_webhook", claim_webhook)
+
+ outcome = await svc.run_terminal_side_effects(
+ workflow_run,
+ RetryDecision(True, 1, 0, True, "matched"),
+ )
+
+ assert outcome == "effect_failed"
+ assert attempt.interim_webhook_sent_at is None
+ assert attempt.next_attempt_prepared_at is None
+ claim_webhook.assert_not_awaited()
+ clear_lease.assert_awaited_once_with("wr_abc", 1, claim_at)
+
+
+async def test_failed_interim_release_is_retried_before_preparing_next_attempt(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ workflow_run = _workflow_run()
+ workflow_run.status = WorkflowRunStatus.failed
+ now = datetime.now(UTC).replace(tzinfo=None)
+ claim_tokens = [now, now + timedelta(seconds=1)]
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ retry_decision="retry",
+ next_attempt_prepared_at=None,
+ webhook_sent_at=None,
+ interim_webhook_sent_at=None,
+ side_effects_released_at=None,
+ )
+
+ async def claim_side_effects(*_args: Any, **_kwargs: Any) -> datetime:
+ token = claim_tokens.pop(0)
+ attempt.side_effects_released_at = token
+ return token
+
+ async def clear_lease(*_args: Any, **_kwargs: Any) -> bool:
+ attempt.side_effects_released_at = None
+ return True
+
+ async def claim_webhook(
+ _workflow_run_id: str,
+ _attempt_number: int,
+ *,
+ kind: str,
+ expected_claim_at: datetime | None = None,
+ delivery_attempted: bool = False,
+ ) -> bool:
+ assert kind == "interim"
+ assert expected_claim_at == attempt.side_effects_released_at
+ attempt.interim_webhook_sent_at = datetime.now(UTC)
+ return True
+
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "get_attempts",
+ AsyncMock(return_value=[attempt]),
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ claim_side_effects,
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "clear_failed_interim_side_effect_lease",
+ clear_lease,
+ raising=False,
+ )
+ monkeypatch.setattr(service_module.app.DATABASE.workflow_run_attempts, "claim_attempt_webhook", claim_webhook)
+ monkeypatch.setattr(
+ svc,
+ "prepare_workflow_webhook",
+ AsyncMock(side_effect=[RuntimeError("payload unavailable"), object()]),
+ )
+ deliver = AsyncMock()
+ monkeypatch.setattr(svc, "deliver_prepared_workflow_webhook", deliver)
+
+ monkeypatch.setattr(svc, "execute_workflow", AsyncMock(return_value=workflow_run))
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_runs,
+ "get_workflow_run",
+ AsyncMock(return_value=workflow_run),
+ )
+ decisions = iter(
+ [
+ RetryDecision(True, 1, 0, True, "matched"),
+ RetryDecision(True, 1, 0, True, "matched"),
+ RetryDecision(False, 2, 0, True, "budget_exhausted"),
+ ]
+ )
+ monkeypatch.setattr(service_module, "get_recorded_decision", AsyncMock(side_effect=decisions))
+ workflow_run.depends_on_workflow_run_id = None
+ prepare = AsyncMock(
+ return_value=SimpleNamespace(status="inserted", pinned_browser_session_id=None, serialized_identity=False)
+ )
+ monkeypatch.setattr(service_module, "prepare_next_attempt_result", prepare)
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_prepared_attempt_execution",
+ AsyncMock(return_value=True),
+ raising=False,
+ )
+ original_terminal_effects = svc.run_terminal_side_effects
+ final_effects = AsyncMock()
+
+ async def run_terminal_effects(*args: Any, **kwargs: Any) -> Any:
+ decision_arg = args[1]
+ if decision_arg.retry:
+ return await original_terminal_effects(*args, **kwargs)
+ await final_effects(*args, **kwargs)
+ return "released"
+
+ monkeypatch.setattr(svc, "run_terminal_side_effects", run_terminal_effects)
+
+ result = await svc.execute_workflow_with_retries(
+ workflow_run_id="wr_abc",
+ api_key="api-key",
+ organization=SimpleNamespace(organization_id="o_abc"),
+ )
+
+ assert result is workflow_run
+ assert attempt.interim_webhook_sent_at is not None
+ assert deliver.await_count == 1
+ prepare.assert_awaited_once_with(
+ workflow_run_id="wr_abc",
+ organization_id="o_abc",
+ from_attempt=1,
+ clear_browser_address=False,
+ )
+ final_effects.assert_awaited_once()
+
+
+async def test_concurrent_policy_terminal_releasers_deliver_final_webhook_once(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ workflow_run = _workflow_run()
+ workflow_run.status = WorkflowRunStatus.failed
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ webhook_sent_at=None,
+ interim_webhook_sent_at=None,
+ side_effects_released_at=None,
+ )
+ get_attempts = AsyncMock(return_value=[attempt])
+ claim_call_count = 0
+ both_claimers_entered = asyncio.Event()
+ release_claimers = asyncio.Event()
+
+ async def claim_side_effects(_workflow_run_id: str, _attempt_number: int) -> bool:
+ nonlocal claim_call_count
+ claim_call_count += 1
+ claim_number = claim_call_count
+ if claim_call_count == 2:
+ both_claimers_entered.set()
+ await release_claimers.wait()
+ return claim_number == 1
+
+ async def claim_webhook(
+ _workflow_run_id: str, _attempt_number: int, *, kind: str, delivery_attempted: bool = False
+ ) -> bool:
+ assert kind == "final"
+ attempt.webhook_sent_at = datetime.now(UTC)
+ return True
+
+ monkeypatch.setattr(service_module.app.DATABASE.workflow_run_attempts, "get_attempts", get_attempts)
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ claim_side_effects,
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_webhook",
+ claim_webhook,
+ )
+ monkeypatch.setattr(svc, "_apply_completion_run_tags_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "_schedule_workflow_run_terminal_hooks", MagicMock())
+ monkeypatch.setattr(svc, "_schedule_credential_fallback_retry", MagicMock())
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", AsyncMock())
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "on_workflow_run_final", AsyncMock())
+ monkeypatch.setattr(svc, "prepare_workflow_webhook", AsyncMock(return_value=object()))
+ deliver = AsyncMock()
+ monkeypatch.setattr(svc, "deliver_prepared_workflow_webhook", deliver)
+
+ decision = RetryDecision(False, 1, 0, True, "budget_exhausted")
+ releasers = asyncio.gather(
+ svc.run_terminal_side_effects(workflow_run, decision),
+ svc.run_terminal_side_effects(workflow_run, decision),
+ )
+ await asyncio.wait_for(both_claimers_entered.wait(), timeout=1)
+ release_claimers.set()
+ await releasers
+
+ assert claim_call_count == 2
+ deliver.assert_awaited_once()
+
+
+async def test_terminal_side_effect_owner_stops_before_recovery_grace_expires(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ workflow_run = _workflow_run()
+ workflow_run.status = WorkflowRunStatus.failed
+ now = datetime(2026, 9, 7, 16, 0, tzinfo=UTC).replace(tzinfo=None)
+ claim_at = now - timedelta(seconds=LEASE_TAKEOVER_SECONDS - LEASE_SAFETY_MARGIN_SECONDS)
+ monkeypatch.setattr(service_module, "naive_utc_now", lambda: now)
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ webhook_sent_at=None,
+ interim_webhook_sent_at=None,
+ side_effects_released_at=claim_at,
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "get_attempts",
+ AsyncMock(return_value=[attempt]),
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ AsyncMock(return_value=claim_at),
+ )
+ delete_attachments = AsyncMock()
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", delete_attachments)
+
+ await svc.run_terminal_side_effects(workflow_run, RetryDecision(False, 1, 0, True, "budget_exhausted"))
+
+ delete_attachments.assert_not_awaited()
+
+
+ ("lease_age_seconds", "webhook_starts"),
+ [(539, False), (300, True)],
+)
+async def test_final_webhook_owner_must_have_room_for_its_delivery_window(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+ lease_age_seconds: int,
+ webhook_starts: bool,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ workflow_run = _workflow_run()
+ workflow_run.status = WorkflowRunStatus.failed
+ now = datetime(2026, 9, 7, 16, 0, tzinfo=UTC).replace(tzinfo=None)
+ claim_at = now - timedelta(seconds=lease_age_seconds)
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ webhook_sent_at=None,
+ interim_webhook_sent_at=None,
+ side_effects_released_at=claim_at,
+ )
+ monkeypatch.setattr(service_module, "naive_utc_now", lambda: now)
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "get_attempts",
+ AsyncMock(return_value=[attempt]),
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ AsyncMock(return_value=claim_at),
+ )
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", AsyncMock())
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "on_workflow_run_final", AsyncMock())
+ monkeypatch.setattr(svc, "_apply_completion_run_tags_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "_run_workflow_run_terminal_hooks", AsyncMock())
+ monkeypatch.setattr(svc, "_start_credential_fallback_retry_best_effort", AsyncMock())
+ final_webhook = AsyncMock()
+ monkeypatch.setattr(svc, "execute_workflow_webhook", final_webhook)
+
+ outcome = await svc.run_terminal_side_effects(
+ workflow_run,
+ RetryDecision(False, 1, 0, True, "budget_exhausted"),
+ )
+
+ assert (final_webhook.await_count > 0) is webhook_starts
+ if not webhook_starts:
+ assert outcome == "fenced_out"
+ assert attempt.webhook_sent_at is None
+
+
+async def test_policy_interim_webhook_keeps_full_delivery_window_and_records_marker(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ workflow_run = _workflow_run()
+ workflow_run.status = WorkflowRunStatus.failed
+ claim_at = datetime.now(UTC).replace(tzinfo=None)
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ retry_decision="retry",
+ webhook_sent_at=None,
+ interim_webhook_sent_at=None,
+ side_effects_released_at=claim_at,
+ )
+
+ async def record_interim_marker(
+ _workflow_run_id: str,
+ _attempt_number: int,
+ *,
+ kind: str,
+ expected_claim_at: datetime | None = None,
+ delivery_attempted: bool = False,
+ ) -> bool:
+ assert kind == "interim"
+ assert expected_claim_at == claim_at
+ attempt.interim_webhook_sent_at = datetime.now(UTC)
+ return True
+
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "get_attempts",
+ AsyncMock(return_value=[attempt]),
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ AsyncMock(return_value=claim_at),
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_webhook",
+ record_interim_marker,
+ )
+ deliver = AsyncMock(
+ side_effect=[
+ httpx.Response(503, headers={"Retry-After": "30"}),
+ httpx.Response(200, content=b"ok"),
+ ]
+ )
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "deliver_webhook", deliver)
+ monkeypatch.setattr(webhook_delivery_module, "asyncio", ScopedAsyncio(sleep=AsyncMock()))
+ original_fenced_effect = svc._run_fenced_terminal_side_effect
+ effect_timeouts: dict[str, float | None] = {}
+
+ async def record_fenced_effect(**kwargs: Any) -> bool:
+ effect_timeouts[kwargs["effect_name"]] = kwargs.get("timeout_seconds")
+ return await original_fenced_effect(**kwargs)
+
+ monkeypatch.setattr(svc, "_run_fenced_terminal_side_effect", record_fenced_effect)
+
+ outcome = await svc.run_terminal_side_effects(
+ workflow_run,
+ RetryDecision(True, 1, 0, True, "matched"),
+ )
+
+ assert outcome == "released"
+ assert deliver.await_count == 2
+ assert attempt.interim_webhook_sent_at is not None
+ assert effect_timeouts["interim workflow webhook"] == WEBHOOK_FALLBACK_GRACE_SECONDS
+
+
+ ("lease_age_seconds", "expected_fallback_ready"),
+ [(400, False), (601, True)],
+)
+async def test_webhook_fallback_waits_for_the_shared_lease_takeover_bound(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+ lease_age_seconds: int,
+ expected_fallback_ready: bool,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ claim_at = datetime.now(UTC).replace(tzinfo=None) - timedelta(seconds=lease_age_seconds)
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ webhook_sent_at=None,
+ side_effects_released_at=claim_at,
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "get_attempts",
+ AsyncMock(return_value=[attempt]),
+ )
+
+ fallback_ready = await svc._workflow_webhook_fallback_is_current(
+ workflow_run_id="wr_abc",
+ attempt_number=1,
+ expected_claim_at=claim_at,
+ )
+
+ assert fallback_ready is expected_fallback_ready
+
+
+async def test_stale_terminal_side_effect_owner_is_fenced_after_recovery_takeover(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ workflow_run = _workflow_run()
+ workflow_run.status = WorkflowRunStatus.failed
+ owner_a_token = datetime.now(UTC)
+ takeover_token = datetime.now(UTC)
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ webhook_sent_at=None,
+ interim_webhook_sent_at=None,
+ side_effects_released_at=None,
+ )
+ delete_calls = 0
+ delete_owners: list[str] = []
+ active_owner = "A"
+ first_effect_started = asyncio.Event()
+ allow_owner_a_to_resume = asyncio.Event()
+ marker_tokens: list[datetime | None] = []
+
+ async def claim_side_effects(
+ _workflow_run_id: str,
+ _attempt_number: int,
+ *,
+ kind: str = "final",
+ expected_claim_at: datetime | None = None,
+ stale_before: datetime | None = None,
+ ) -> datetime | None:
+ assert kind == "final"
+ if expected_claim_at is None:
+ assert attempt.side_effects_released_at is None
+ attempt.side_effects_released_at = owner_a_token
+ return owner_a_token
+ assert expected_claim_at == owner_a_token
+ if attempt.side_effects_released_at != expected_claim_at:
+ return None
+ assert stale_before is not None
+ attempt.side_effects_released_at = takeover_token
+ return takeover_token
+
+ async def delete_attachments(*, run_id: str, timeout_seconds: float) -> None:
+ nonlocal delete_calls
+ assert run_id == workflow_run.workflow_run_id
+ assert timeout_seconds > 0
+ delete_calls += 1
+ delete_owners.append(active_owner)
+ if active_owner == "A" and delete_calls == 1:
+ first_effect_started.set()
+ await allow_owner_a_to_resume.wait()
+
+ async def claim_webhook(
+ _workflow_run_id: str,
+ _attempt_number: int,
+ *,
+ kind: str,
+ expected_claim_at: datetime | None = None,
+ delivery_attempted: bool = False,
+ ) -> bool:
+ assert kind == "final"
+ assert expected_claim_at == takeover_token
+ marker_tokens.append(expected_claim_at)
+ if attempt.webhook_sent_at is not None:
+ return False
+ attempt.webhook_sent_at = datetime.now(UTC)
+ return True
+
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "get_attempts",
+ AsyncMock(return_value=[attempt]),
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_side_effects",
+ claim_side_effects,
+ )
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_run_attempts,
+ "claim_attempt_webhook",
+ claim_webhook,
+ )
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", delete_attachments)
+ on_final = AsyncMock()
+ on_completed = AsyncMock()
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "on_workflow_run_final", on_final)
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "on_workflow_run_completed", on_completed)
+ monkeypatch.setattr(svc, "_apply_completion_run_tags_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "_start_credential_fallback_retry_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "prepare_workflow_webhook", AsyncMock(return_value=object()))
+ deliver = AsyncMock()
+ monkeypatch.setattr(svc, "deliver_prepared_workflow_webhook", deliver)
+
+ decision = RetryDecision(False, 1, 0, True, "budget_exhausted")
+ # Owner A pauses inside its first effect. Recovery takes over while it is paused; the fresh
+ # fence must stop A before any later effect after it resumes.
+ owner_a = asyncio.create_task(svc.run_terminal_side_effects(workflow_run, decision))
+ await asyncio.wait_for(first_effect_started.wait(), timeout=1)
+
+ active_owner = "B"
+ takeover = asyncio.create_task(
+ svc.run_terminal_side_effects(
+ workflow_run,
+ decision,
+ side_effects_claim_at=owner_a_token,
+ side_effects_stale_before=owner_a_token + timedelta(seconds=1),
+ )
+ )
+ await asyncio.wait_for(takeover, timeout=1)
+ active_owner = "A"
+ allow_owner_a_to_resume.set()
+ await asyncio.wait_for(owner_a, timeout=1)
+
+ assert delete_calls == 2
+ assert delete_owners == ["A", "B"]
+ on_final.assert_awaited_once()
+ on_completed.assert_awaited_once()
+ deliver.assert_awaited_once()
+ assert marker_tokens == [takeover_token]
+ assert attempt.webhook_sent_at is not None
+ assert attempt.side_effects_released_at == takeover_token
+
+
[email protected]("competing_owner", [False, True])
[email protected]("failed_effect", ["attachments", "hook", "webhook"])
+async def test_final_release_retries_keep_own_claim_and_completed_hook(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+ competing_owner: bool,
+ failed_effect: str,
+) -> None:
+ svc, build_response, _update_run = webhook_service
+ workflow_run = _workflow_run()
+ workflow_run.status = WorkflowRunStatus.canceled
+ owner_token = datetime.now(UTC).replace(tzinfo=None)
+ competing_token = owner_token + timedelta(seconds=1)
+ attempt = SimpleNamespace(
+ attempt_number=1,
+ retry_decision="revoked",
+ webhook_sent_at=None,
+ interim_webhook_sent_at=owner_token - timedelta(seconds=1),
+ side_effects_released_at=None,
+ )
+ claims: list[datetime | None] = []
+
+ async def claim(*_args: Any, expected_claim_at: datetime | None = None, **_kwargs: Any) -> datetime | None:
+ claims.append(expected_claim_at)
+ if attempt.side_effects_released_at != expected_claim_at:
+ return None
+ attempt.side_effects_released_at = owner_token
+ return owner_token
+
+ async def mark_webhook(*_args: Any, expected_claim_at: datetime | None = None, **_kwargs: Any) -> bool:
+ if attempt.side_effects_released_at != expected_claim_at:
+ return False
+ attempt.webhook_sent_at = owner_token
+ return True
+
+ preparation_calls = 0
+
+ async def prepare(*_args: Any, **_kwargs: Any) -> _StatusResponse:
+ nonlocal preparation_calls
+ preparation_calls += 1
+ if preparation_calls == 1 and failed_effect == "webhook":
+ if competing_owner:
+ attempt.side_effects_released_at = competing_token
+ raise RuntimeError("transient webhook preparation failure")
+ return _StatusResponse()
+
+ build_response.side_effect = prepare
+ repository = service_module.app.DATABASE.workflow_run_attempts
+ monkeypatch.setattr(repository, "get_attempts", AsyncMock(return_value=[attempt]))
+ monkeypatch.setattr(repository, "claim_attempt_side_effects", claim)
+ monkeypatch.setattr(repository, "claim_attempt_webhook", mark_webhook)
+ effects = [AsyncMock() for _ in range(5)]
+
+ async def delete_attachments(**_kwargs: Any) -> None:
+ if effects[0].await_count == 1 and failed_effect == "attachments":
+ if competing_owner:
+ attempt.side_effects_released_at = competing_token
+ raise RuntimeError("transient attachment cleanup failure")
+
+ effects[0].side_effect = delete_attachments
+ if failed_effect == "hook":
+ effects[4].side_effect = RuntimeError("final hook failed after emitting an effect")
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", effects[0])
+ monkeypatch.setattr(svc, "_start_credential_fallback_retry_best_effort", effects[1])
+ monkeypatch.setattr(svc, "_apply_completion_run_tags_best_effort", effects[2])
+ monkeypatch.setattr(svc, "_run_workflow_run_terminal_hooks", effects[3])
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "on_workflow_run_final", effects[4])
+ deliver = AsyncMock(return_value=httpx.Response(200))
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "deliver_webhook", deliver)
+
+ outcome = await svc._run_terminal_side_effects_with_retries(
+ workflow_run, RetryDecision(False, 1, 0, True, "canceled")
+ )
+
+ assert claims == ([None] if failed_effect == "hook" else [None, owner_token])
+ assert effects[0].await_count == (2 if failed_effect == "attachments" and not competing_owner else 1)
+ # The attempt is revoked (canceled during its retry delay), so the credential fallback is the
+ # one final effect that must stay silent.
+ assert effects[1].await_count == 0
+ for effect in effects[2:]:
+ assert effect.await_count == (0 if failed_effect == "attachments" and competing_owner else 1)
+ if failed_effect == "hook":
+ assert outcome == "effect_failed"
+ assert attempt.webhook_sent_at is None
+ deliver.assert_not_awaited()
+ elif competing_owner:
+ assert outcome in {"fenced_out", "lease_held_by_other_young"}
+ assert attempt.webhook_sent_at is None
+ deliver.assert_not_awaited()
+ else:
+ assert outcome == "released"
+ assert preparation_calls == (2 if failed_effect == "webhook" else 1)
+ assert attempt.webhook_sent_at is not None
+ deliver.assert_awaited_once()
+
+
+ "status, rule_status, rule_codes, errors, retries_used, expected",
+ [
+ ("canceled", "canceled", None, set(), 0, (False, "canceled")),
+ ("failed", "failed", None, set(), 1, (True, "matched")),
+ ("failed", "failed", None, set(), 2, (False, "budget_exhausted")),
+ ("failed", "failed", None, set(), 3, (False, "budget_exhausted")),
+ ("failed", "failed", [], {"ANY"}, 0, (True, "matched")),
+ ("failed", "failed", ["A", "B"], {"B", "C"}, 0, (True, "matched")),
+ ("failed", "failed", ["A", "B"], {"C"}, 0, (False, "no_match")),
+ ("failed", "failed", ["A"], set(), 0, (False, "no_match")),
+ ("completed", "failed", None, set(), 0, (False, "no_match")),
+ ],
+)
+def test_evaluate_retry_policy_decisions(status, rule_status, rule_codes, errors, retries_used, expected) -> None:
+ policy = WorkflowRetryPolicy.model_validate(
+ {"max_retries": 2, "retry_on": [{"status": rule_status, "error_codes": rule_codes}]}
+ )
+ assert evaluate_retry_policy(policy, WorkflowRunStatus(status), errors, retries_used) == expected
+
+
[email protected]("version_exists", [True, False], ids=["soft_deleted", "missing"])
+async def test_terminal_retry_resolves_deleted_pinned_workflow(
+ sqlite_engine: AsyncEngine, monkeypatch: pytest.MonkeyPatch, version_exists: bool
+) -> None:
+ now = datetime.now(UTC).replace(tzinfo=None)
+ run = WorkflowRun(
+ workflow_run_id="wr_deleted_policy",
+ workflow_id="w_deleted_policy",
+ workflow_permanent_id="wpid_deleted_policy",
+ organization_id="o_test",
+ status=WorkflowRunStatus.failed,
+ created_at=now,
+ modified_at=now,
+ )
+ policy = WorkflowRetryPolicy(max_retries=2, delay_seconds=7, retry_on=[{"status": "failed"}])
+ session_factory = async_sessionmaker(sqlite_engine, expire_on_commit=False)
+ workflows = WorkflowsRepository(session_factory)
+ attempts = WorkflowRunAttemptsRepository(session_factory)
+ async with session_factory() as session:
+ session.add(
+ WorkflowRunModel(
+ workflow_run_id=run.workflow_run_id,
+ workflow_id=run.workflow_id,
+ workflow_permanent_id=run.workflow_permanent_id,
+ organization_id=run.organization_id,
+ status="failed",
+ )
+ )
+ session.add(
+ WorkflowRunAttemptModel(
+ workflow_run_id=run.workflow_run_id,
+ organization_id=run.organization_id,
+ attempt_number=1,
+ status="failed",
+ )
+ )
+ if version_exists:
+ session.add(
+ WorkflowModel(
+ workflow_id=run.workflow_id,
+ workflow_permanent_id=run.workflow_permanent_id,
+ organization_id=run.organization_id,
+ title="Deleted pinned policy",
+ version=1,
+ is_saved_task=False,
+ deleted_at=now,
+ workflow_definition=WorkflowDefinition(parameters=[], blocks=[], retry_policy=policy).model_dump(
+ mode="json"
+ ),
+ )
+ )
+ await session.commit()
+
+ monkeypatch.setattr(service_module.app.DATABASE, "workflows", workflows)
+ monkeypatch.setattr(service_module.app.DATABASE, "workflow_run_attempts", attempts)
+ monkeypatch.setattr(service_module.app, "WORKFLOW_SERVICE", WorkflowService())
+ monkeypatch.setattr(service_module.app.DATABASE.tasks, "get_tasks_by_workflow_run_id", AsyncMock(return_value=[]))
+ monkeypatch.setattr(service_module.app.DATABASE.observer, "get_workflow_run_blocks", AsyncMock(return_value=[]))
+
+ assert await _get_retry_policy(run) == (policy if version_exists else None)
+ decision = await on_terminal_transition(run, WorkflowRunStatus.failed, None, None)
+ assert decision.retry is version_exists
+ assert decision.delay_seconds == (7 if version_exists else 0)
+ recorded_attempts = await attempts.get_attempts(run.workflow_run_id)
+ assert recorded_attempts[0].retry_decision == ("retry" if version_exists else "final")
+
+
+async def test_second_terminal_transition_refreshes_attempt_finished_at_but_keeps_the_decision(
+ sqlite_engine: AsyncEngine, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # A finally block reopens the run and terminalizes it again; compute cost is priced through the
+ # attempt's finished_at, so the frozen decision must keep its verdict while the end time moves.
+ first_finish = datetime.now(UTC).replace(tzinfo=None) - timedelta(minutes=5)
+ run = WorkflowRun(
+ workflow_run_id="wr_finally",
+ workflow_id="w_finally",
+ workflow_permanent_id="wpid_finally",
+ organization_id="o_test",
+ status=WorkflowRunStatus.failed,
+ created_at=first_finish,
+ modified_at=first_finish,
+ )
+ session_factory = async_sessionmaker(sqlite_engine, expire_on_commit=False)
+ attempts = WorkflowRunAttemptsRepository(session_factory)
+ async with session_factory() as session:
+ session.add(
+ WorkflowRunModel(
+ workflow_run_id=run.workflow_run_id,
+ workflow_id=run.workflow_id,
+ workflow_permanent_id=run.workflow_permanent_id,
+ organization_id=run.organization_id,
+ status="failed",
+ )
+ )
+ session.add(
+ WorkflowRunAttemptModel(
+ workflow_run_id=run.workflow_run_id,
+ organization_id=run.organization_id,
+ attempt_number=1,
+ status="failed",
+ retry_decision="final",
+ decision_reason="no_match",
+ finished_at=first_finish,
+ )
+ )
+ await session.commit()
+ monkeypatch.setattr(service_module.app.DATABASE, "workflows", WorkflowsRepository(session_factory))
+ monkeypatch.setattr(service_module.app.DATABASE, "workflow_run_attempts", attempts)
+ monkeypatch.setattr(service_module.app.DATABASE.tasks, "get_tasks_by_workflow_run_id", AsyncMock(return_value=[]))
+ monkeypatch.setattr(service_module.app.DATABASE.observer, "get_workflow_run_blocks", AsyncMock(return_value=[]))
+
+ decision = await on_terminal_transition(run, WorkflowRunStatus.failed, None, None, attempt_number=1)
+
+ assert decision.retry is False
+ recorded = (await attempts.get_attempts(run.workflow_run_id))[0]
+ assert (recorded.retry_decision, recorded.decision_reason) == ("final", "no_match")
+ assert recorded.finished_at > first_finish
+
+
[email protected]("webhook_on_retry", ["every_attempt", "final_only"])
[email protected]("delivery", ["sent", "no_url", "no_signing_key", "rejected"])
+async def test_webhook_producer_to_projection(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ sqlite_engine: AsyncEngine,
+ monkeypatch: pytest.MonkeyPatch,
+ webhook_on_retry: Literal["every_attempt", "final_only"],
+ delivery: str,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ now = datetime.now(UTC).replace(tzinfo=None)
+ run = WorkflowRun(
+ workflow_run_id="wr_abc",
+ workflow_id="w_abc",
+ workflow_permanent_id="wpid_abc",
+ organization_id="o_abc",
+ status=WorkflowRunStatus.failed,
+ webhook_callback_url=None if delivery == "no_url" else "https://example.com/hook",
+ created_at=now,
+ modified_at=now,
+ finished_at=now,
+ )
+ repository = WorkflowRunAttemptsRepository(async_sessionmaker(sqlite_engine, expire_on_commit=False))
+ monkeypatch.setattr(service_module.app.DATABASE, "workflow_run_attempts", repository)
+ if delivery == "no_signing_key":
+ monkeypatch.setattr(
+ service_module.app.DATABASE.organizations, "get_valid_org_auth_token", AsyncMock(return_value=None)
+ )
+ deliver = AsyncMock(return_value=_response(400 if delivery == "rejected" else 200))
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "deliver_webhook", deliver)
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", AsyncMock())
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "on_workflow_run_final", AsyncMock())
+ monkeypatch.setattr(svc, "_start_credential_fallback_retry_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "_apply_completion_run_tags_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "_run_workflow_run_terminal_hooks", AsyncMock())
+
+ for number, retry in [(1, True), (2, False)]:
+ run.status = WorkflowRunStatus.failed if retry else WorkflowRunStatus.completed
+ async with repository.Session() as session:
+ session.add(
+ WorkflowRunAttemptModel(
+ workflow_run_id=run.workflow_run_id,
+ organization_id=run.organization_id,
+ attempt_number=number,
+ status=run.status.value,
+ retry_decision="retry" if retry else "final",
+ finished_at=now,
+ next_attempt_prepared_at=None if not retry else now,
+ )
+ )
+ await session.commit()
+ outcome = await svc.run_terminal_side_effects(
+ run, RetryDecision(retry, number, 0, not retry or webhook_on_retry == "every_attempt", "matched")
+ )
+ failed_delivery = delivery == "rejected" and (not retry or webhook_on_retry == "every_attempt")
+ assert outcome == ("effect_failed" if failed_delivery else "released")
+
+ attempts = await repository.get_attempts(run.workflow_run_id)
+ assert (attempts[0].interim_webhook_sent_at is None) == (
+ delivery == "rejected" and webhook_on_retry == "every_attempt"
+ )
+ assert (attempts[1].webhook_sent_at is None) == (delivery == "rejected")
+ attempted = delivery in {"sent", "rejected"}
+ assert deliver.await_count == ((2 if webhook_on_retry == "every_attempt" else 1) if attempted else 0)
+ expected = [
+ attempts[0].interim_webhook_sent_at if delivery == "sent" and webhook_on_retry == "every_attempt" else None,
+ attempts[1].webhook_sent_at if delivery == "sent" else None,
+ ]
+ monkeypatch.setattr(
+ svc, "build_workflow_run_status_response", WorkflowService.build_workflow_run_status_response.__get__(svc)
+ )
+ monkeypatch.setattr(svc, "get_recent_workflow_screenshot_urls", AsyncMock(return_value=[]))
+ monkeypatch.setattr(svc, "get_output_parameter_workflow_run_output_parameter_tuples", AsyncMock(return_value=[]))
+ monkeypatch.setattr(svc, "_fetch_recording_urls", AsyncMock(return_value=([], False)))
+ monkeypatch.setattr(svc, "_fetch_downloaded_files", AsyncMock(return_value=([], None)))
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_runs, "get_workflow_run_retried_by", AsyncMock(return_value=None)
+ )
+ monkeypatch.setattr(service_module.app.DATABASE.observer, "get_workflow_run_blocks", AsyncMock(return_value=[]))
+
+ for current_policy in [webhook_on_retry, "final_only", "every_attempt", None]:
+ workflow = Workflow(
+ workflow_id=run.workflow_id,
+ workflow_permanent_id=run.workflow_permanent_id,
+ organization_id=run.organization_id,
+ title="Webhook timestamps",
+ version=1,
+ is_saved_task=False,
+ workflow_definition=WorkflowDefinition(
+ parameters=[],
+ blocks=[],
+ retry_policy=WorkflowRetryPolicy(webhook_on_retry=current_policy, retry_on=[{"status": "failed"}])
+ if current_policy is not None
+ else None,
+ ),
+ created_at=now,
+ modified_at=now,
+ )
+ monkeypatch.setattr(
+ svc, "_gather_with_max_in_flight", AsyncMock(return_value=(workflow, run, None, [], [], attempts))
+ )
+ response = await svc.build_workflow_run_status_response(
+ run.workflow_permanent_id, run.workflow_run_id, run.organization_id
+ )
+ assert [attempt.webhook_sent_at for attempt in response.attempts] == expected
+
+
[email protected]("webhook_on_retry", ["final_only", "every_attempt", None])
+async def test_attempt_response_does_not_infer_delivery_from_legacy_completion_markers(
+ monkeypatch: pytest.MonkeyPatch, webhook_on_retry: Literal["final_only", "every_attempt"] | None
+) -> None:
+ interim_sent_at = datetime.now(UTC)
+ final_sent_at = interim_sent_at + timedelta(seconds=1)
+ run = WorkflowRun(
+ workflow_run_id="wr_webhook",
+ workflow_id="wf_webhook",
+ workflow_permanent_id="wpid_webhook",
+ organization_id="org_test",
+ status=WorkflowRunStatus.completed,
+ created_at=interim_sent_at,
+ modified_at=final_sent_at,
+ finished_at=final_sent_at,
+ )
+ policy = (
+ WorkflowRetryPolicy(webhook_on_retry=webhook_on_retry, retry_on=[{"status": "failed"}])
+ if webhook_on_retry is not None
+ else None
+ )
+ workflow = Workflow(
+ workflow_id=run.workflow_id,
+ workflow_permanent_id=run.workflow_permanent_id,
+ organization_id=run.organization_id,
+ title="Webhook timestamps",
+ version=1,
+ is_saved_task=False,
+ workflow_definition=WorkflowDefinition(parameters=[], blocks=[], retry_policy=policy),
+ created_at=interim_sent_at,
+ modified_at=final_sent_at,
+ )
+ attempts = [
+ WorkflowRunAttemptModel(
+ workflow_run_id=run.workflow_run_id,
+ organization_id=run.organization_id,
+ attempt_number=1,
+ status="failed",
+ retry_decision="retry",
+ finished_at=interim_sent_at,
+ interim_webhook_sent_at=interim_sent_at,
+ ),
+ WorkflowRunAttemptModel(
+ workflow_run_id=run.workflow_run_id,
+ organization_id=run.organization_id,
+ attempt_number=2,
+ status="completed",
+ retry_decision="final",
+ finished_at=final_sent_at,
+ interim_webhook_sent_at=interim_sent_at,
+ webhook_sent_at=final_sent_at,
+ ),
+ ]
+ svc = WorkflowService()
+ monkeypatch.setattr(
+ svc, "_gather_with_max_in_flight", AsyncMock(return_value=(workflow, run, None, [], [], attempts))
+ )
+ monkeypatch.setattr(svc, "get_recent_workflow_screenshot_urls", AsyncMock(return_value=[]))
+ monkeypatch.setattr(svc, "get_output_parameter_workflow_run_output_parameter_tuples", AsyncMock(return_value=[]))
+ monkeypatch.setattr(svc, "_fetch_recording_urls", AsyncMock(return_value=([], False)))
+ monkeypatch.setattr(svc, "_fetch_downloaded_files", AsyncMock(return_value=([], None)))
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_runs, "get_workflow_run_retried_by", AsyncMock(return_value=None)
+ )
+ monkeypatch.setattr(service_module.app.DATABASE.observer, "get_workflow_run_blocks", AsyncMock(return_value=[]))
+
+ response = await svc.build_workflow_run_status_response(
+ run.workflow_permanent_id, run.workflow_run_id, run.organization_id
+ )
+
+ assert response.attempts[0].webhook_sent_at is None
+ assert response.attempts[1].webhook_sent_at is None
+ assert attempts[0].interim_webhook_sent_at == interim_sent_at
+
+
[email protected]("cap_output_values", [False, True])
+async def test_attempt_failure_reason_uses_response_text_cap(
+ monkeypatch: pytest.MonkeyPatch, cap_output_values: bool
+) -> None:
+ now = datetime.now(UTC)
+ reason = "failure " * (18 * 1024 * 1024 // 8)
+ run = WorkflowRun(
+ workflow_run_id="wr_reason",
+ workflow_id="wf_reason",
+ workflow_permanent_id="wpid_reason",
+ organization_id="org_test",
+ status=WorkflowRunStatus.failed,
+ failure_reason=reason,
+ created_at=now,
+ modified_at=now,
+ )
+ workflow = Workflow(
+ workflow_id=run.workflow_id,
+ workflow_permanent_id=run.workflow_permanent_id,
+ organization_id=run.organization_id,
+ title="Retry reason",
+ version=1,
+ is_saved_task=False,
+ workflow_definition=WorkflowDefinition(parameters=[], blocks=[]),
+ created_at=now,
+ modified_at=now,
+ )
+ attempt = WorkflowRunAttemptModel(
+ workflow_run_id=run.workflow_run_id,
+ organization_id=run.organization_id,
+ attempt_number=1,
+ status="failed",
+ retry_decision="final",
+ failure_reason=reason,
+ )
+ monkeypatch.setattr(
+ service_module.app,
+ "DATABASE",
+ SimpleNamespace(
+ workflows=SimpleNamespace(get_workflow_for_workflow_run=AsyncMock(return_value=workflow)),
+ observer=SimpleNamespace(
+ get_task_v2_by_workflow_run_id=AsyncMock(return_value=None),
+ get_workflow_run_blocks=AsyncMock(return_value=[]),
+ ),
+ tasks=SimpleNamespace(get_tasks_by_workflow_run_id=AsyncMock(return_value=[])),
+ workflow_runs=SimpleNamespace(
+ get_workflow_run_parameters=AsyncMock(return_value=[]),
+ get_workflow_run_block_errors=AsyncMock(return_value=[]),
+ get_workflow_run_retried_by=AsyncMock(return_value=None),
+ ),
+ workflow_run_attempts=SimpleNamespace(get_attempts=AsyncMock(return_value=[attempt])),
+ ),
+ )
+ svc = WorkflowService()
+ monkeypatch.setattr(svc, "get_workflow_run", AsyncMock(return_value=run))
+ monkeypatch.setattr(svc, "get_recent_workflow_screenshot_urls", AsyncMock(return_value=[]))
+ monkeypatch.setattr(svc, "get_output_parameter_workflow_run_output_parameter_tuples", AsyncMock(return_value=[]))
+ monkeypatch.setattr(svc, "_fetch_recording_urls", AsyncMock(return_value=([], False)))
+ monkeypatch.setattr(svc, "_fetch_downloaded_files", AsyncMock(return_value=([], None)))
+ response = await svc.build_workflow_run_status_response(
+ run.workflow_permanent_id,
+ run.workflow_run_id,
+ run.organization_id,
+ cap_output_values=cap_output_values,
+ )
+ assert response.attempts[0].failure_reason == response.failure_reason
+ if cap_output_values:
+ assert len(response.attempts[0].failure_reason.encode("utf-8")) <= service_module.RUN_RESPONSE_MAX_VALUE_BYTES
+ assert response.attempts[0].failure_reason != reason
+ else:
+ assert response.attempts[0].failure_reason == reason
+ assert attempt.failure_reason == reason
+
+
[email protected]("kind", ["interim", "final"])
[email protected]("failure", ["non_2xx", "exception", "none", "permanent"])
+async def test_webhook_claim_requires_successful_delivery(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ sqlite_engine: AsyncEngine,
+ monkeypatch: pytest.MonkeyPatch,
+ kind: str,
+ failure: str,
+) -> None:
+ svc, _build_response, _update_run = webhook_service
+ run = _workflow_run()
+ run.status = WorkflowRunStatus.failed
+ repository = WorkflowRunAttemptsRepository(async_sessionmaker(sqlite_engine, expire_on_commit=False))
+ monkeypatch.setattr(service_module.app.DATABASE, "workflow_run_attempts", repository)
+ async with repository.Session() as session:
+ session.add(
+ WorkflowRunAttemptModel(
+ workflow_run_id=run.workflow_run_id,
+ organization_id=run.organization_id,
+ attempt_number=1,
+ status="failed",
+ retry_decision="retry" if kind == "interim" else "final",
+ finished_at=datetime.now(UTC).replace(tzinfo=None),
+ next_attempt_prepared_at=datetime.now(UTC).replace(tzinfo=None) if kind == "interim" else None,
+ )
+ )
+ await session.commit()
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", AsyncMock())
+ final_hook = AsyncMock()
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "on_workflow_run_final", final_hook)
+ monkeypatch.setattr(svc, "_start_credential_fallback_retry_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "_apply_completion_run_tags_best_effort", AsyncMock())
+ monkeypatch.setattr(svc, "_run_workflow_run_terminal_hooks", AsyncMock())
+ monkeypatch.setattr(webhook_delivery_module, "asyncio", ScopedAsyncio(sleep=AsyncMock()))
+ delivery_calls = 0
+
+ async def deliver(**_kwargs: object) -> httpx.Response:
+ nonlocal delivery_calls
+ delivery_calls += 1
+ if failure != "none" and (
+ failure == "permanent" or delivery_calls <= webhook_delivery_module.WEBHOOK_DELIVERY_MAX_ATTEMPTS
+ ):
+ if failure == "exception":
+ raise httpx.ConnectError("endpoint unreachable")
+ return _response(503)
+ return _response(204)
+
+ monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "deliver_webhook", deliver)
+ decision = RetryDecision(kind == "interim", 1, 0, True, "matched")
+ outcome = await svc.run_terminal_side_effects(run, decision)
+ attempt = (await repository.get_attempts(run.workflow_run_id))[0]
+ marker = attempt.interim_webhook_sent_at if kind == "interim" else attempt.webhook_sent_at
+ progress = attempt.interim_side_effects_progress if kind == "interim" else attempt.final_side_effects_progress
+ if failure != "none":
+ assert outcome == "effect_failed"
+ assert marker is None
+ assert not (progress or {}).get("webhook_delivery_attempted")
+ assert f"{kind} workflow webhook" not in (progress or {}).get("completed_effects", [])
+ assert delivery_calls == webhook_delivery_module.WEBHOOK_DELIVERY_MAX_ATTEMPTS
+ outcome = await svc._run_terminal_side_effects_with_retries(
+ run,
+ decision,
+ side_effects_claim_at=attempt.side_effects_released_at,
+ side_effects_stale_before=datetime.now(UTC).replace(tzinfo=None),
+ )
+ attempt = (await repository.get_attempts(run.workflow_run_id))[0]
+ marker = attempt.interim_webhook_sent_at if kind == "interim" else attempt.webhook_sent_at
+ progress = attempt.interim_side_effects_progress if kind == "interim" else attempt.final_side_effects_progress
+ if failure == "permanent":
+ assert outcome == "released"
+ assert marker is not None
+ assert not (progress or {}).get("webhook_delivery_attempted")
+ assert progress["webhook_delivery_attempts"] == 15
+ assert progress["webhook_delivery_exhausted_at"]
+ assert delivery_calls == 45
+ assert _attempt_from_record(attempt).webhook_sent_at is None
+ aged = datetime.now(UTC).replace(tzinfo=None) - timedelta(seconds=LEASE_TAKEOVER_SECONDS + 1)
+ async with repository.Session() as session:
+ row = await session.get(WorkflowRunAttemptModel, (run.workflow_run_id, 1))
+ row.side_effects_released_at = aged
+ row.modified_at = aged
+ await session.commit()
+ monkeypatch.setattr(service_module.app, "WORKFLOW_SERVICE", svc)
+ await BackgroundTaskExecutor()._recover_pending_retries_once(resume_fresh=False)
+ assert await repository.list_attempts_needing_recovery(datetime.now(UTC).replace(tzinfo=None)) == []
+ await svc.execute_workflow_webhook(run, claim_kind=kind, attempt_number=1)
+ assert delivery_calls == 45
+ attempt = (await repository.get_attempts(run.workflow_run_id))[0]
+ assert _attempt_from_record(attempt).webhook_sent_at is None
+ else:
+ assert outcome == "released"
+ assert marker is not None
+ assert progress["webhook_delivery_attempted"] is True
+ assert delivery_calls == (1 if failure == "none" else webhook_delivery_module.WEBHOOK_DELIVERY_MAX_ATTEMPTS + 1)
+ assert final_hook.await_count == int(kind == "final")
+
+
[email protected]("later_attempt_delivered", ["final", "interim", None])
+async def test_interim_recovery_skips_delivery_once_a_later_attempt_finished(
+ monkeypatch: pytest.MonkeyPatch, later_attempt_delivered: str | None
+) -> None:
+ run = SimpleNamespace(workflow_run_id="wr_1", organization_id="o_1")
+ monkeypatch.setattr(service_module.app.DATABASE.workflow_runs, "get_workflow_run", AsyncMock(return_value=run))
+ monkeypatch.setattr(
+ service_module,
+ "get_recorded_decision",
+ AsyncMock(return_value=service_module.RetryDecision(True, 1, 0, True, "matched")),
+ )
+ delivered_at = datetime.now(UTC).replace(tzinfo=None)
+ rows = [
+ SimpleNamespace(attempt_number=1, webhook_sent_at=None, interim_webhook_sent_at=None),
+ SimpleNamespace(
+ attempt_number=2,
+ webhook_sent_at=delivered_at if later_attempt_delivered == "final" else None,
+ interim_webhook_sent_at=delivered_at if later_attempt_delivered == "interim" else None,
+ ),
+ ]
+ monkeypatch.setattr(service_module.app.DATABASE.workflow_run_attempts, "get_attempts", AsyncMock(return_value=rows))
+ claim = AsyncMock(return_value=True)
+ monkeypatch.setattr(service_module.app.DATABASE.workflow_run_attempts, "claim_attempt_webhook", claim)
+ monkeypatch.setattr(service_module, "_get_recovery_api_key", AsyncMock(return_value="token"))
+ release = AsyncMock(return_value="released")
+ monkeypatch.setattr(service_module.app.WORKFLOW_SERVICE, "_run_terminal_side_effects_with_retries", release)
+ pending = SimpleNamespace(
+ workflow_run_id="wr_1",
+ organization_id="o_1",
+ attempt_number=1,
+ side_effects_released_at=None,
+ decision_reason="matched",
+ )
+
+ await service_module._recover_unreleased_terminal_attempt(pending, interim=True)
+
+ if later_attempt_delivered:
+ release.assert_not_awaited()
+ claim.assert_awaited_once_with("wr_1", 1, "interim")
+ else:
+ release.assert_awaited_once()
+ claim.assert_not_awaited()
diff --git a/tests/unit/workflow/test_code_block_escalation.py b/tests/unit/workflow/test_code_block_escalation.py
index 74126225d..fa6ab94f3 100644
--- a/tests/unit/workflow/test_code_block_escalation.py
+++ b/tests/unit/workflow/test_code_block_escalation.py
@@ -675,7 +675,7 @@ def _install_db_fakes(
state["execute_step_kwargs"] = kwargs
return None, None, None
- async def _get_downloaded_files(*args: object, **kwargs: object) -> list[FileInfo]:
+ async def _get_current_attempt_downloaded_files(*args: object, **kwargs: object) -> list[FileInfo]:
return list(downloaded_files or [])
async def _create_action(action: Action) -> Action:
@@ -711,7 +711,11 @@ def _install_db_fakes(
monkeypatch.setattr(
app.DATABASE.observer, "update_workflow_run_block", AsyncMock(side_effect=_update_workflow_run_block)
)
- monkeypatch.setattr(app.STORAGE, "get_downloaded_files", AsyncMock(side_effect=_get_downloaded_files))
+ monkeypatch.setattr(
+ app.STORAGE,
+ "get_current_attempt_downloaded_files",
+ AsyncMock(side_effect=_get_current_attempt_downloaded_files),
+ )
monkeypatch.setattr(
app.DATABASE.workflow_runs, "create_or_update_workflow_run_output_parameter", AsyncMock(return_value=None)
)
diff --git a/tests/unit/workflow/test_code_block_recorder.py b/tests/unit/workflow/test_code_block_recorder.py
index c773a5689..e3e8f70df 100644
--- a/tests/unit/workflow/test_code_block_recorder.py
+++ b/tests/unit/workflow/test_code_block_recorder.py
@@ -1253,6 +1253,7 @@ class FakeWorkflowRunContext:
values: dict = {}
workflow_run_outputs: list = []
include_secrets_in_templates = False
+ organization_id: str | None = None
workflow_title = "Test Workflow"
workflow_id = "w_test"
workflow_permanent_id = "wpid_test"
diff --git a/tests/unit/workflow/test_enterprise_feature_gating.py b/tests/unit/workflow/test_enterprise_feature_gating.py
index b6e5e7e91..a2b2c613a 100644
--- a/tests/unit/workflow/test_enterprise_feature_gating.py
+++ b/tests/unit/workflow/test_enterprise_feature_gating.py
@@ -231,7 +231,7 @@ async def test_execute_workflow_cleans_up_after_enterprise_gate_failure(monkeypa
svc = WorkflowService()
monkeypatch.setattr(svc, "get_workflow_run", AsyncMock(return_value=workflow_run))
- monkeypatch.setattr(svc, "get_workflow", AsyncMock(return_value=workflow))
+ monkeypatch.setattr(svc, "get_workflow_by_workflow_run_id", AsyncMock(return_value=workflow))
mark_workflow_run_as_failed = AsyncMock(return_value=failed_workflow_run)
clean_up_workflow = AsyncMock()
monkeypatch.setattr(svc, "mark_workflow_run_as_failed", mark_workflow_run_as_failed)
@@ -256,4 +256,5 @@ async def test_execute_workflow_cleans_up_after_enterprise_gate_failure(monkeypa
browser_session_id=None,
close_browser_on_completion=True,
need_call_webhook=True,
+ attempt_number=1,
)
diff --git a/tests/unit/workflow/test_workflow_run_timeline_tree.py b/tests/unit/workflow/test_workflow_run_timeline_tree.py
index 10f091072..0d68e1868 100644
--- a/tests/unit/workflow/test_workflow_run_timeline_tree.py
+++ b/tests/unit/workflow/test_workflow_run_timeline_tree.py
@@ -2,13 +2,14 @@
from __future__ import annotations
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta, timezone
from unittest.mock import AsyncMock
import pytest
from skyvern.forge import app
-from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock
+from skyvern.forge.sdk.routes import agent_protocol
+from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock, WorkflowRunTimeline, WorkflowRunTimelineType
from skyvern.forge.sdk.workflow.service import WorkflowService
from skyvern.schemas.workflows import BlockType
from skyvern.webeye.actions.actions import ExtractAction
@@ -171,3 +172,45 @@ async def test_timeline_duplicate_block_ids_keep_last(mock_db: AsyncMock, caplog
assert len(timeline) == 1
assert any("Duplicate workflow_run_block_id" in record.message for record in caplog.records)
+
+
+async def test_flatten_task_v2_timeline_inherits_enclosing_attempt(monkeypatch: pytest.MonkeyPatch) -> None:
+ base = datetime(2026, 5, 4, 12, 0, tzinfo=UTC)
+ parent_block = _block("wrb_parent", created_at=base, block_type=BlockType.TaskV2).model_copy(
+ update={"block_workflow_run_id": "wr_child"}
+ )
+ parent = WorkflowRunTimeline(
+ type=WorkflowRunTimelineType.block,
+ attempt=2,
+ block=parent_block,
+ created_at=base,
+ modified_at=base,
+ )
+ leaf = WorkflowRunTimeline(
+ type=WorkflowRunTimelineType.block,
+ attempt=1,
+ block=_block("wrb_leaf", created_at=base),
+ created_at=base,
+ modified_at=base,
+ )
+ conditional = leaf.model_copy(
+ update={"block": _block("wrb_cond", created_at=base, block_type=BlockType.CONDITIONAL), "children": [leaf]}
+ )
+ loop = leaf.model_copy(
+ update={"block": _block("wrb_loop", created_at=base, block_type=BlockType.FOR_LOOP), "children": [conditional]}
+ )
+ thought = leaf.model_copy(update={"type": WorkflowRunTimelineType.thought, "block": None})
+ monkeypatch.setattr(agent_protocol, "_flatten_workflow_run_timeline", AsyncMock(return_value=[loop, thought]))
+
+ result = await agent_protocol._flatten_workflow_run_timeline_recursive(parent, organization_id="o_test")
+
+ assert len(result) == 2
+ assert len(result[0].children) == 1
+ assert len(result[0].children[0].children) == 1
+ flattened_items = [*result, result[0].children[0], result[0].children[0].children[0]]
+ assert [item.attempt for item in flattened_items] == [2, 2, 2, 2]
+ assert result[0].block == loop.block
+ assert result[1].type == WorkflowRunTimelineType.thought
+ assert result[0].children[0].children[0].block == leaf.block
+ assert [item.attempt for item in [loop, thought, conditional, leaf]] == [1, 1, 1, 1]