Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
[oncall] Retry workflow webhooks after infra failures (#6062)
Marc Kelechava3212ca8d7fee
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 16c4ae9f6..737e4b027 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -38,7 +38,6 @@ from skyvern.exceptions import (BrowserProfileNotFound,BrowserSessionNotFound,BrowserSessionNotRenewable,- FailedToSendWebhook,InvalidCredentialId,MissingValueForParameter,ScriptTerminationException,@@ -129,7 +128,7 @@ from skyvern.schemas.workflows import (WorkflowStatus,)from skyvern.services import script_service, workflow_script_service-from skyvern.services.webhook_delivery import deliver_webhook_with_retries+from skyvern.services.webhook_delivery import PreparedWorkflowWebhook, deliver_webhook_with_retriesfrom skyvern.utils.css_selector import build_action_summaries_with_timing # shared with script_servicefrom skyvern.utils.url_validators import validate_url as validate_url_with_blocked_host_checkfrom skyvern.webeye.browser_state import BrowserState@@ -5374,11 +5373,11 @@ class WorkflowService:await self.execute_workflow_webhook(workflow_run, api_key)- async def execute_workflow_webhook(+ async def prepare_workflow_webhook(self,workflow_run: WorkflowRun,api_key: str | None = None,- ) -> None:+ ) -> PreparedWorkflowWebhook | None:workflow_id = workflow_run.workflow_id# Cleanup path: tolerate soft-deleted workflows. If the workflow row# has been deleted between run start and cleanup (common when an eval@@ -5399,14 +5398,14 @@ class WorkflowService:workflow_run_id=workflow_run.workflow_run_id,workflow_permanent_id=workflow_run.workflow_permanent_id,)- return+ return Noneif not workflow_run.webhook_callback_url:LOG.warning("Workflow has no webhook callback url. Not sending workflow response",workflow_id=workflow_id,workflow_run_id=workflow_run.workflow_run_id,)- return+ return None# Strip whitespace from the webhook URL to handle user input with leading/trailing spacesworkflow_run.webhook_callback_url = workflow_run.webhook_callback_url.strip()@@ -5427,7 +5426,7 @@ class WorkflowService:workflow_run_id=workflow_run.workflow_run_id,organization_id=workflow_run.organization_id,)- return+ return None# build new schema for backward compatible webhook payloadapp_url = f"{settings.SKYVERN_APP_URL.rstrip('/')}/runs/{workflow_run.workflow_run_id}"@@ -5468,53 +5467,115 @@ class WorkflowService:api_key=signing_api_key,)LOG.info(- "Sending webhook run status to webhook callback url",+ "Prepared webhook run status for webhook callback url",workflow_id=workflow_id,workflow_run_id=workflow_run.workflow_run_id,webhook_callback_url=workflow_run.webhook_callback_url,payload=signed_data.payload_for_log,headers=signed_data.headers,)+ return PreparedWorkflowWebhook(+ workflow_id=workflow_id,+ workflow_run_id=workflow_run.workflow_run_id,+ organization_id=workflow_run.organization_id,+ webhook_callback_url=workflow_run.webhook_callback_url,+ signed_payload=signed_data.signed_payload,+ headers=signed_data.headers,+ payload_for_log=signed_data.payload_for_log,+ )++ async def deliver_prepared_workflow_webhook(self, webhook: PreparedWorkflowWebhook) -> None:+ LOG.info(+ "Sending webhook run status to webhook callback url",+ workflow_id=webhook.workflow_id,+ workflow_run_id=webhook.workflow_run_id,+ webhook_callback_url=webhook.webhook_callback_url,+ payload=webhook.payload_for_log,+ headers=webhook.headers,+ )try:resp = await deliver_webhook_with_retries(- url=workflow_run.webhook_callback_url,- payload=signed_data.signed_payload,- headers=signed_data.headers,+ url=webhook.webhook_callback_url,+ payload=webhook.signed_payload,+ headers=webhook.headers,timeout_seconds=30.0,- organization_id=workflow_run.organization_id,- run_id=workflow_run.workflow_run_id,+ organization_id=webhook.organization_id,+ run_id=webhook.workflow_run_id,)- if resp.status_code >= 200 and resp.status_code < 300:- LOG.info(- "Webhook sent successfully",- workflow_id=workflow_id,- workflow_run_id=workflow_run.workflow_run_id,- resp_code=resp.status_code,- resp_text=resp.text,+ except Exception as e:+ LOG.warning(+ "Workflow webhook delivery failed after attempting delivery",+ workflow_id=webhook.workflow_id,+ workflow_run_id=webhook.workflow_run_id,+ error=str(e),+ exc_info=True,+ )+ try:+ await app.DATABASE.workflow_runs.update_workflow_run(+ workflow_run_id=webhook.workflow_run_id,+ webhook_failure_reason=f"Webhook delivery failed before receiving a response: {e}",+ )+ except Exception:+ LOG.warning(+ "Failed to record workflow webhook delivery error",+ workflow_id=webhook.workflow_id,+ workflow_run_id=webhook.workflow_run_id,+ exc_info=True,)+ return++ if resp.status_code >= 200 and resp.status_code < 300:+ LOG.info(+ "Webhook sent successfully",+ workflow_id=webhook.workflow_id,+ workflow_run_id=webhook.workflow_run_id,+ resp_code=resp.status_code,+ resp_text=resp.text,+ )+ try:await app.DATABASE.workflow_runs.update_workflow_run(- workflow_run_id=workflow_run.workflow_run_id,+ workflow_run_id=webhook.workflow_run_id,webhook_failure_reason="",)- else:- LOG.info(- "Webhook failed",- workflow_id=workflow_id,- workflow_run_id=workflow_run.workflow_run_id,- webhook_data=signed_data.payload_for_log,- resp=resp,- resp_code=resp.status_code,- resp_text=resp.text,+ except Exception:+ LOG.warning(+ "Failed to record successful workflow webhook delivery",+ workflow_id=webhook.workflow_id,+ workflow_run_id=webhook.workflow_run_id,+ exc_info=True,)+ else:+ LOG.info(+ "Webhook failed",+ workflow_id=webhook.workflow_id,+ workflow_run_id=webhook.workflow_run_id,+ webhook_data=webhook.payload_for_log,+ resp=resp,+ resp_code=resp.status_code,+ resp_text=resp.text,+ )+ try:await app.DATABASE.workflow_runs.update_workflow_run(- workflow_run_id=workflow_run.workflow_run_id,+ workflow_run_id=webhook.workflow_run_id,webhook_failure_reason=f"Webhook failed with status code {resp.status_code}, error message: {resp.text}",)- except Exception as e:- raise FailedToSendWebhook(- workflow_id=workflow_id,- workflow_run_id=workflow_run.workflow_run_id,- ) from e+ except Exception:+ LOG.warning(+ "Failed to record failed workflow webhook delivery",+ workflow_id=webhook.workflow_id,+ workflow_run_id=webhook.workflow_run_id,+ exc_info=True,+ )++ async def execute_workflow_webhook(+ self,+ workflow_run: WorkflowRun,+ api_key: str | None = None,+ ) -> None:+ webhook = await self.prepare_workflow_webhook(workflow_run, api_key)+ if webhook is None:+ return+ await self.deliver_prepared_workflow_webhook(webhook)async def persist_video_data(self,diff --git a/skyvern/services/webhook_delivery.py b/skyvern/services/webhook_delivery.pyindex aa0a98733..5ed3d7b53 100644--- a/skyvern/services/webhook_delivery.py+++ b/skyvern/services/webhook_delivery.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport random+from dataclasses import dataclassfrom datetime import datetime, timezonefrom email.utils import parsedate_to_datetime@@ -28,6 +29,23 @@ WEBHOOK_DELIVERY_RETRY_BASE_DELAY_SECONDS = 1.0WEBHOOK_DELIVERY_MAX_RETRY_AFTER_SECONDS = 30.0+@dataclass(frozen=True)+class PreparedWorkflowWebhook:+ """Process-local signed workflow webhook request.++ Do not return this object from Temporal activities or workflows; signed_payload+ can be large and must not be persisted in Temporal history.+ """++ workflow_id: str+ workflow_run_id: str+ organization_id: str+ webhook_callback_url: str+ signed_payload: str+ headers: dict[str, str]+ payload_for_log: str++def is_retryable_status(status_code: int) -> bool:return status_code in NON_5XX_RETRYABLE_STATUS_CODES or 500 <= status_code < 600diff --git a/tests/unit/test_workflow_webhook_delivery.py b/tests/unit/test_workflow_webhook_delivery.pynew file mode 100644index 000000000..81fe3a3e7--- /dev/null+++ b/tests/unit/test_workflow_webhook_delivery.py@@ -0,0 +1,174 @@+from __future__ import annotations++from datetime import datetime, timezone+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import httpx+import pytest++from skyvern.forge.sdk.workflow import service as service_module+from skyvern.forge.sdk.workflow.service import WorkflowService+++class _StatusResponse:+ def __init__(self) -> None:+ now = datetime.now(timezone.utc)+ self.status = "completed"+ self.outputs: dict = {}+ self.downloaded_files: list = []+ self.recording_url = None+ self.screenshot_urls: list = []+ self.failure_reason = None+ self.script_run = None+ self.workflow_title = "Workflow"+ self.parameters: dict = {}+ self.errors: list = []+ self.total_steps = 1+ self.created_at = now+ self.modified_at = now+ self.queued_at = now+ self.started_at = now+ self.finished_at = now++ def model_dump_json(self) -> str:+ return '{"workflow_run_id":"wr_abc","status":"completed"}'+++class _WebhookRunResponse:+ def __init__(self, **_kwargs: object) -> None:+ pass++ def model_dump_json(self) -> str:+ return '{"run_id":"wr_abc","run_type":"workflow_run"}'+++def _workflow_run() -> MagicMock:+ run = MagicMock()+ run.workflow_id = "w_abc"+ run.workflow_permanent_id = "wpid_abc"+ run.workflow_run_id = "wr_abc"+ run.organization_id = "o_abc"+ run.webhook_callback_url = " https://example.com/hook "+ run.proxy_location = "NONE"+ run.totp_verification_url = None+ run.totp_identifier = None+ return run+++def _response(status_code: int, body: str = "") -> httpx.Response:+ return httpx.Response(status_code=status_code, content=body.encode("utf-8"))+++def webhook_service(monkeypatch: pytest.MonkeyPatch) -> tuple[WorkflowService, AsyncMock, AsyncMock]:+ svc = WorkflowService()+ build_response = AsyncMock(return_value=_StatusResponse())+ update_run = AsyncMock()++ monkeypatch.setattr(svc, "build_workflow_run_status_response", build_response)+ monkeypatch.setattr(service_module, "WorkflowRunResponse", _WebhookRunResponse)+ monkeypatch.setattr(+ service_module,+ "generate_skyvern_webhook_signature",+ lambda payload, api_key: SimpleNamespace(+ payload_for_log='{"safe":true}',+ headers={"x-skyvern-signature": "sig"},+ signed_payload='{"signed":true}',+ ),+ )+ monkeypatch.setattr(+ service_module.app.DATABASE.organizations,+ "get_valid_org_auth_token",+ AsyncMock(return_value=SimpleNamespace(token="api-key")),+ )+ monkeypatch.setattr(service_module.app.DATABASE.workflow_runs, "update_workflow_run", update_run)++ return svc, build_response, update_run+++async def test_prepare_workflow_webhook_builds_request_without_delivery(+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ svc, _build_response, _update_run = webhook_service+ deliver = AsyncMock()+ monkeypatch.setattr(service_module, "deliver_webhook_with_retries", deliver)++ webhook = await svc.prepare_workflow_webhook(_workflow_run())++ assert webhook is not None+ assert webhook.workflow_id == "w_abc"+ assert webhook.workflow_run_id == "wr_abc"+ assert webhook.organization_id == "o_abc"+ assert webhook.webhook_callback_url == "https://example.com/hook"+ assert webhook.signed_payload == '{"signed":true}'+ deliver.assert_not_awaited()+++async def test_execute_workflow_webhook_records_customer_failure_without_raising(+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ svc, _build_response, update_run = webhook_service+ deliver = AsyncMock(return_value=_response(400, "bad request"))+ monkeypatch.setattr(service_module, "deliver_webhook_with_retries", deliver)++ await svc.execute_workflow_webhook(_workflow_run())++ deliver.assert_awaited_once()+ update_run.assert_awaited_once_with(+ workflow_run_id="wr_abc",+ webhook_failure_reason="Webhook failed with status code 400, error message: bad request",+ )+++async def test_execute_workflow_webhook_records_delivery_exception_without_raising(+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ svc, _build_response, update_run = webhook_service+ deliver = AsyncMock(side_effect=httpx.ConnectError("customer endpoint unreachable"))+ monkeypatch.setattr(service_module, "deliver_webhook_with_retries", deliver)++ await svc.execute_workflow_webhook(_workflow_run())++ deliver.assert_awaited_once()+ update_run.assert_awaited_once()+ assert "customer endpoint unreachable" in update_run.await_args.kwargs["webhook_failure_reason"]+++async def test_execute_workflow_webhook_does_not_raise_if_post_delivery_recording_fails(+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ svc, _build_response, update_run = webhook_service+ update_run.side_effect = RuntimeError("db pool exhausted after delivery")+ deliver = AsyncMock(return_value=_response(200, "ok"))+ monkeypatch.setattr(service_module, "deliver_webhook_with_retries", deliver)++ await svc.execute_workflow_webhook(_workflow_run())++ deliver.assert_awaited_once()+ update_run.assert_awaited_once_with(workflow_run_id="wr_abc", webhook_failure_reason="")+++async def test_execute_workflow_webhook_propagates_pre_delivery_infra_failure(+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ svc, build_response, update_run = webhook_service+ build_response.side_effect = RuntimeError("db pool exhausted before delivery")+ deliver = AsyncMock()+ monkeypatch.setattr(service_module, "deliver_webhook_with_retries", deliver)++ with pytest.raises(RuntimeError, match="db pool exhausted before delivery"):+ await svc.execute_workflow_webhook(_workflow_run())++ deliver.assert_not_awaited()+ update_run.assert_not_awaited()