Skip to content

Automate browser based workflows with AI

Batch endpoint for workflow self-heal reliability (#7489)

pedrohsdb78b620b72ba3
diff --git a/skyvern/forge/sdk/db/repositories/self_heal.py b/skyvern/forge/sdk/db/repositories/self_heal.py
index 67bae738e..037f293e0 100644
--- a/skyvern/forge/sdk/db/repositories/self_heal.py
+++ b/skyvern/forge/sdk/db/repositories/self_heal.py
@@ -2,7 +2,7 @@ from __future__ import annotations
from typing import Literal
-from sqlalchemy import select, update
+from sqlalchemy import func, select, update
from skyvern.forge.sdk.db._error_handling import db_operation
from skyvern.forge.sdk.db.base_repository import BaseRepository
@@ -168,6 +168,53 @@ class SelfHealRepository(BaseRepository):
)
return list((await session.scalars(query)).all())
+ @db_operation("get_recent_terminal_workflow_run_ids_batch")
+ async def get_recent_terminal_workflow_run_ids_batch(
+ self,
+ organization_id: str,
+ workflow_permanent_ids: list[str],
+ limit: int = 20,
+ ) -> dict[str, list[str]]:
+ result: dict[str, list[str]] = {wpid: [] for wpid in workflow_permanent_ids}
+ if not workflow_permanent_ids:
+ return result
+ terminal_statuses = ("completed", "failed", "terminated", "timed_out")
+ bounded_limit = max(1, min(limit, 100))
+ row_number = (
+ func.row_number()
+ .over(
+ partition_by=WorkflowRunModel.workflow_permanent_id,
+ order_by=(WorkflowRunModel.created_at.desc(), WorkflowRunModel.workflow_run_id.desc()),
+ )
+ .label("rn")
+ )
+ subquery = (
+ select(
+ WorkflowRunModel.workflow_run_id,
+ WorkflowRunModel.workflow_permanent_id,
+ row_number,
+ )
+ .where(
+ WorkflowRunModel.organization_id == organization_id,
+ WorkflowRunModel.workflow_permanent_id.in_(workflow_permanent_ids),
+ WorkflowRunModel.status.in_(terminal_statuses),
+ WorkflowRunModel.parent_workflow_run_id.is_(None),
+ WorkflowRunModel.copilot_session_id.is_(None),
+ WorkflowRunModel.debug_session_id.is_(None),
+ )
+ .subquery()
+ )
+ async with self.Session() as session:
+ query = (
+ select(subquery.c.workflow_permanent_id, subquery.c.workflow_run_id)
+ .where(subquery.c.rn <= bounded_limit)
+ .order_by(subquery.c.workflow_permanent_id, subquery.c.rn)
+ )
+ rows = (await session.execute(query)).all()
+ for workflow_permanent_id, workflow_run_id in rows:
+ result[workflow_permanent_id].append(workflow_run_id)
+ return result
+
@db_operation("get_heal_episodes_for_runs")
async def get_heal_episodes_for_runs(self, organization_id: str, workflow_run_ids: list[str]) -> list[HealEpisode]:
if not workflow_run_ids:
diff --git a/skyvern/forge/sdk/routes/self_heal.py b/skyvern/forge/sdk/routes/self_heal.py
index d4715f543..3a8ca37c0 100644
--- a/skyvern/forge/sdk/routes/self_heal.py
+++ b/skyvern/forge/sdk/routes/self_heal.py
@@ -1,6 +1,6 @@
import structlog
from fastapi import Depends, Query
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from skyvern.forge import app
from skyvern.forge.sdk.routes.routers import base_router
@@ -13,7 +13,7 @@ from skyvern.schemas.self_heal import (
WorkflowReliability,
summarize_run_heals,
)
-from skyvern.services.self_heal_reliability_service import get_workflow_reliability
+from skyvern.services.self_heal_reliability_service import get_workflow_reliability, get_workflows_reliability
LOG = structlog.get_logger()
@@ -23,6 +23,14 @@ class RunHealEpisodesResponse(BaseModel):
summary: RunHealSummary
+class WorkflowsReliabilityRequest(BaseModel):
+ workflow_permanent_ids: list[str] = Field(default_factory=list, max_length=100)
+
+
+class WorkflowsReliabilityResponse(BaseModel):
+ reliabilities: dict[str, WorkflowReliability]
+
+
@base_router.get(
"/workflows/{workflow_permanent_id}/heal_episodes",
response_model=list[HealEpisodeView],
@@ -76,3 +84,17 @@ async def get_workflow_reliability_route(
organization: Organization = Depends(org_auth_service.get_current_org),
) -> WorkflowReliability:
return await get_workflow_reliability(organization.organization_id, workflow_permanent_id)
+
+
+@base_router.post(
+ "/workflows/reliability/batch",
+ response_model=WorkflowsReliabilityResponse,
+ include_in_schema=False,
+)
+async def get_workflows_reliability_route(
+ request: WorkflowsReliabilityRequest,
+ organization: Organization = Depends(org_auth_service.get_current_org),
+) -> WorkflowsReliabilityResponse:
+ workflow_permanent_ids = list(dict.fromkeys(request.workflow_permanent_ids))
+ reliabilities = await get_workflows_reliability(organization.organization_id, workflow_permanent_ids)
+ return WorkflowsReliabilityResponse(reliabilities=reliabilities)
diff --git a/skyvern/services/self_heal_reliability_service.py b/skyvern/services/self_heal_reliability_service.py
index f3fd552f7..b71f6d41d 100644
--- a/skyvern/services/self_heal_reliability_service.py
+++ b/skyvern/services/self_heal_reliability_service.py
@@ -28,3 +28,32 @@ async def get_workflow_reliability(organization_id: str, workflow_permanent_id:
groups = [RunHealGroup(workflow_run_id=run_id, episodes=episodes_by_run_id[run_id]) for run_id in run_ids]
return compute_workflow_reliability(groups)
+
+
+async def get_workflows_reliability(
+ organization_id: str, workflow_permanent_ids: list[str]
+) -> dict[str, WorkflowReliability]:
+ if not workflow_permanent_ids:
+ return {}
+ run_ids_by_wpid = await app.DATABASE.self_heal.get_recent_terminal_workflow_run_ids_batch(
+ organization_id=organization_id,
+ workflow_permanent_ids=workflow_permanent_ids,
+ limit=RELIABILITY_WINDOW,
+ )
+ all_run_ids = [run_id for run_ids in run_ids_by_wpid.values() for run_id in run_ids]
+ episodes = await app.DATABASE.self_heal.get_heal_episodes_for_runs(
+ organization_id=organization_id,
+ workflow_run_ids=all_run_ids,
+ )
+ episodes_by_run_id: dict[str, list[HealEpisode]] = {}
+ for episode in episodes:
+ episodes_by_run_id.setdefault(episode.workflow_run_id, []).append(episode)
+
+ reliabilities: dict[str, WorkflowReliability] = {}
+ for workflow_permanent_id in workflow_permanent_ids:
+ run_ids = run_ids_by_wpid.get(workflow_permanent_id, [])
+ groups = [
+ RunHealGroup(workflow_run_id=run_id, episodes=episodes_by_run_id.get(run_id, [])) for run_id in run_ids
+ ]
+ reliabilities[workflow_permanent_id] = compute_workflow_reliability(groups)
+ return reliabilities
diff --git a/tests/unit/forge/sdk/db/test_self_heal_repository.py b/tests/unit/forge/sdk/db/test_self_heal_repository.py
index 9f509b858..8309d15fa 100644
--- a/tests/unit/forge/sdk/db/test_self_heal_repository.py
+++ b/tests/unit/forge/sdk/db/test_self_heal_repository.py
@@ -427,6 +427,101 @@ async def test_get_recent_terminal_workflow_run_ids_filters_orders_and_limits(re
assert bounded == ["wr_newest_timed_out"]
+async def test_get_recent_terminal_workflow_run_ids_batch_filters_orders_limits_and_includes_empty(
+ repo_and_session,
+) -> None:
+ repo, session_factory = repo_and_session
+ now = datetime(2026, 5, 2, 0, 0, 0)
+ async with session_factory() as session:
+ session.add_all(
+ [
+ _workflow_run_model(
+ workflow_run_id="wr_a_old_completed",
+ workflow_permanent_id="wpid_a",
+ status="completed",
+ created_at=now,
+ ),
+ _workflow_run_model(
+ workflow_run_id="wr_a_mid_failed",
+ workflow_permanent_id="wpid_a",
+ status="failed",
+ created_at=now + timedelta(minutes=1),
+ ),
+ _workflow_run_model(
+ workflow_run_id="wr_a_new_terminated",
+ workflow_permanent_id="wpid_a",
+ status="terminated",
+ created_at=now + timedelta(minutes=2),
+ ),
+ _workflow_run_model(
+ workflow_run_id="wr_a_running",
+ workflow_permanent_id="wpid_a",
+ status="running",
+ created_at=now + timedelta(minutes=3),
+ ),
+ _workflow_run_model(
+ workflow_run_id="wr_a_child",
+ workflow_permanent_id="wpid_a",
+ status="completed",
+ created_at=now + timedelta(minutes=4),
+ parent_workflow_run_id="wr_a_old_completed",
+ ),
+ _workflow_run_model(
+ workflow_run_id="wr_a_copilot",
+ workflow_permanent_id="wpid_a",
+ status="completed",
+ created_at=now + timedelta(minutes=5),
+ copilot_session_id="cs_a",
+ ),
+ _workflow_run_model(
+ workflow_run_id="wr_a_debug",
+ workflow_permanent_id="wpid_a",
+ status="completed",
+ created_at=now + timedelta(minutes=6),
+ debug_session_id="ds_a",
+ ),
+ _workflow_run_model(
+ workflow_run_id="wr_b_old_completed",
+ workflow_permanent_id="wpid_b",
+ status="completed",
+ created_at=now,
+ ),
+ _workflow_run_model(
+ workflow_run_id="wr_b_new_timed_out",
+ workflow_permanent_id="wpid_b",
+ status="timed_out",
+ created_at=now + timedelta(minutes=2),
+ ),
+ _workflow_run_model(
+ workflow_run_id="wr_b_running",
+ workflow_permanent_id="wpid_b",
+ status="running",
+ created_at=now + timedelta(minutes=3),
+ ),
+ _workflow_run_model(
+ workflow_run_id="wr_b_other_org",
+ organization_id=ORG_B,
+ workflow_permanent_id="wpid_b",
+ status="failed",
+ created_at=now + timedelta(minutes=4),
+ ),
+ ]
+ )
+ await session.commit()
+
+ run_ids_by_wpid = await repo.get_recent_terminal_workflow_run_ids_batch(
+ organization_id=ORG_A,
+ workflow_permanent_ids=["wpid_a", "wpid_b", "wpid_empty"],
+ limit=2,
+ )
+ assert run_ids_by_wpid == {
+ "wpid_a": ["wr_a_new_terminated", "wr_a_mid_failed"],
+ "wpid_b": ["wr_b_new_timed_out", "wr_b_old_completed"],
+ "wpid_empty": [],
+ }
+
+
@pytest.mark.asyncio
async def test_get_heal_episodes_for_runs_batches_and_scopes_to_org(repo_and_session) -> None:
repo, session_factory = repo_and_session
diff --git a/tests/unit/forge/sdk/routes/test_self_heal_routes.py b/tests/unit/forge/sdk/routes/test_self_heal_routes.py
index a00ab5b53..a4b07f2a3 100644
--- a/tests/unit/forge/sdk/routes/test_self_heal_routes.py
+++ b/tests/unit/forge/sdk/routes/test_self_heal_routes.py
@@ -18,6 +18,7 @@ from skyvern.schemas.self_heal import (
OutputObligation,
ReliabilityState,
WorkflowReliability,
+ compute_workflow_reliability,
)
ORG_ID = "org_self_heal"
@@ -50,25 +51,27 @@ def _episode(
)
-def _build_client(monkeypatch) -> tuple[TestClient, AsyncMock, AsyncMock, AsyncMock]:
+def _build_client(monkeypatch) -> tuple[TestClient, AsyncMock, AsyncMock, AsyncMock, AsyncMock]:
async def _fake_org() -> SimpleNamespace:
return SimpleNamespace(organization_id=ORG_ID)
get_for_workflow = AsyncMock()
get_for_run = AsyncMock()
get_reliability = AsyncMock()
+ get_reliability_batch = AsyncMock()
monkeypatch.setattr(forge_app.DATABASE.self_heal, "get_heal_episodes_for_workflow", get_for_workflow)
monkeypatch.setattr(forge_app.DATABASE.self_heal, "get_heal_episodes_for_run", get_for_run)
monkeypatch.setattr(self_heal_routes, "get_workflow_reliability", get_reliability)
+ monkeypatch.setattr(self_heal_routes, "get_workflows_reliability", get_reliability_batch)
fastapi_app = FastAPI()
fastapi_app.dependency_overrides[org_auth_service.get_current_org] = _fake_org
fastapi_app.include_router(routers_module.base_router, prefix="/v1")
- return TestClient(fastapi_app), get_for_workflow, get_for_run, get_reliability
+ return TestClient(fastapi_app), get_for_workflow, get_for_run, get_reliability, get_reliability_batch
def test_get_workflow_heal_episodes_filters_to_caller_org_and_view_shape(monkeypatch) -> None:
- client, get_for_workflow, _, _ = _build_client(monkeypatch)
+ client, get_for_workflow, _, _, _ = _build_client(monkeypatch)
async def _repo_call(**kwargs):
assert kwargs["organization_id"] == ORG_ID
@@ -108,7 +111,7 @@ def test_get_workflow_heal_episodes_filters_to_caller_org_and_view_shape(monkeyp
def test_get_workflow_heal_episodes_invalid_status_returns_422(monkeypatch) -> None:
- client, get_for_workflow, _, _ = _build_client(monkeypatch)
+ client, get_for_workflow, _, _, _ = _build_client(monkeypatch)
response = client.get("/v1/workflows/wpid_target/heal_episodes", params={"status": "invalid_status"})
@@ -117,7 +120,7 @@ def test_get_workflow_heal_episodes_invalid_status_returns_422(monkeypatch) -> N
def test_get_run_heal_episodes_returns_episodes_and_summary(monkeypatch) -> None:
- client, _, get_for_run, _ = _build_client(monkeypatch)
+ client, _, get_for_run, _, _ = _build_client(monkeypatch)
get_for_run.return_value = [
_episode(
heal_episode_id="he_1",
@@ -153,7 +156,7 @@ def test_get_run_heal_episodes_returns_episodes_and_summary(monkeypatch) -> None
def test_get_workflow_reliability_is_org_scoped(monkeypatch) -> None:
- client, _, _, get_reliability = _build_client(monkeypatch)
+ client, _, _, get_reliability, _ = _build_client(monkeypatch)
get_reliability.return_value = WorkflowReliability(
state=ReliabilityState.watch,
outcome_risk=True,
@@ -182,3 +185,63 @@ def test_get_workflow_reliability_is_org_scoped(monkeypatch) -> None:
"outcome_risk_runs": 1,
}
get_reliability.assert_awaited_once_with(ORG_ID, "wpid_target")
+
+
+def test_get_workflows_reliability_batch_dedupes_and_matches_single(monkeypatch) -> None:
+ client, _, _, get_reliability, get_reliability_batch = _build_client(monkeypatch)
+
+ reliability_a = compute_workflow_reliability([])
+ reliability_b = WorkflowReliability(
+ state=ReliabilityState.watch,
+ outcome_risk=False,
+ scored=True,
+ window_runs=20,
+ healed_runs=3,
+ heal_rate=0.15,
+ consecutive_healed_runs=1,
+ floor_runs=0,
+ outcome_risk_runs=0,
+ )
+ reliability_map = {"wpid_a": reliability_a, "wpid_b": reliability_b}
+
+ async def _single_reliability(org_id: str, workflow_permanent_id: str) -> WorkflowReliability:
+ assert org_id == ORG_ID
+ return reliability_map[workflow_permanent_id]
+
+ async def _batch_reliability(org_id: str, workflow_permanent_ids: list[str]) -> dict[str, WorkflowReliability]:
+ assert org_id == ORG_ID
+ return {wpid: reliability_map[wpid] for wpid in workflow_permanent_ids}
+
+ get_reliability.side_effect = _single_reliability
+ get_reliability_batch.side_effect = _batch_reliability
+
+ single_a = client.get("/v1/workflows/wpid_a/reliability")
+ single_b = client.get("/v1/workflows/wpid_b/reliability")
+ assert single_a.status_code == 200
+ assert single_b.status_code == 200
+
+ response = client.post(
+ "/v1/workflows/reliability/batch",
+ json={"workflow_permanent_ids": ["wpid_a", "wpid_b", "wpid_a"]},
+ )
+ assert response.status_code == 200
+ body = response.json()
+
+ assert set(body.keys()) == {"reliabilities"}
+ assert set(body["reliabilities"].keys()) == {"wpid_a", "wpid_b"}
+ assert body["reliabilities"]["wpid_a"] == single_a.json()
+ assert body["reliabilities"]["wpid_b"] == single_b.json()
+
+ get_reliability_batch.assert_awaited_once_with(ORG_ID, ["wpid_a", "wpid_b"])
+
+
+def test_get_workflows_reliability_batch_rejects_over_cap(monkeypatch) -> None:
+ client, _, _, _, get_reliability_batch = _build_client(monkeypatch)
+
+ response = client.post(
+ "/v1/workflows/reliability/batch",
+ json={"workflow_permanent_ids": [f"wpid_{i}" for i in range(101)]},
+ )
+
+ assert response.status_code == 422
+ get_reliability_batch.assert_not_awaited()
diff --git a/tests/unit/services/test_self_heal_reliability_service.py b/tests/unit/services/test_self_heal_reliability_service.py
new file mode 100644
index 000000000..e730a06bc
--- /dev/null
+++ b/tests/unit/services/test_self_heal_reliability_service.py
@@ -0,0 +1,175 @@
+from __future__ import annotations
+
+from datetime import datetime
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from skyvern.schemas.self_heal import (
+ HealEpisode,
+ HealStatus,
+ ReliabilityState,
+ WorkflowReliability,
+ compute_workflow_reliability,
+)
+from skyvern.services import self_heal_reliability_service
+
+ORG_ID = "org_self_heal"
+
+
+def _episode(
+ *,
+ heal_episode_id: str,
+ workflow_run_block_id: str,
+ block_label: str,
+ status: HealStatus,
+ workflow_permanent_id: str,
+ workflow_run_id: str,
+) -> HealEpisode:
+ now = datetime(2026, 1, 1, 0, 0, 0)
+ return HealEpisode(
+ heal_episode_id=heal_episode_id,
+ organization_id=ORG_ID,
+ workflow_permanent_id=workflow_permanent_id,
+ workflow_id=f"w_{workflow_permanent_id}",
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ block_label=block_label,
+ engine="code",
+ status=status,
+ created_at=now,
+ modified_at=now,
+ )
+
+
+async def test_get_workflows_reliability_batch_matches_single_with_ordering_and_unseen(monkeypatch) -> None:
+ wpid_ordered = "wpid_ordered"
+ wpid_other = "wpid_other"
+ wpid_unseen = "wpid_unseen"
+
+ ordered_run_ids = [f"wr_ordered_{index:02d}" for index in range(20)]
+ other_run_ids = [f"wr_other_{index:02d}" for index in range(12)]
+
+ run_ids_by_wpid = {
+ wpid_ordered: ordered_run_ids,
+ wpid_other: other_run_ids,
+ wpid_unseen: [],
+ }
+
+ episodes = [
+ _episode(
+ heal_episode_id="he_ordered_0",
+ workflow_run_block_id="wrb_ordered_0",
+ block_label="block_ordered",
+ status=HealStatus.fired_completed,
+ workflow_permanent_id=wpid_ordered,
+ workflow_run_id=ordered_run_ids[0],
+ ),
+ _episode(
+ heal_episode_id="he_ordered_1",
+ workflow_run_block_id="wrb_ordered_1",
+ block_label="block_ordered",
+ status=HealStatus.fired_completed,
+ workflow_permanent_id=wpid_ordered,
+ workflow_run_id=ordered_run_ids[1],
+ ),
+ _episode(
+ heal_episode_id="he_ordered_2",
+ workflow_run_block_id="wrb_ordered_2",
+ block_label="block_ordered",
+ status=HealStatus.fired_completed,
+ workflow_permanent_id=wpid_ordered,
+ workflow_run_id=ordered_run_ids[2],
+ ),
+ _episode(
+ heal_episode_id="he_other_1",
+ workflow_run_block_id="wrb_other_1",
+ block_label="block_other",
+ status=HealStatus.fired_failed,
+ workflow_permanent_id=wpid_other,
+ workflow_run_id=other_run_ids[1],
+ ),
+ _episode(
+ heal_episode_id="he_other_7",
+ workflow_run_block_id="wrb_other_7",
+ block_label="block_other",
+ status=HealStatus.fired_unverified,
+ workflow_permanent_id=wpid_other,
+ workflow_run_id=other_run_ids[7],
+ ),
+ ]
+
+ get_recent_terminal_workflow_run_ids = AsyncMock(
+ side_effect=lambda organization_id, workflow_permanent_id, limit: run_ids_by_wpid[workflow_permanent_id][:limit]
+ )
+ get_recent_terminal_workflow_run_ids_batch = AsyncMock(
+ side_effect=lambda organization_id, workflow_permanent_ids, limit: {
+ workflow_permanent_id: run_ids_by_wpid.get(workflow_permanent_id, [])[:limit]
+ for workflow_permanent_id in workflow_permanent_ids
+ }
+ )
+ get_heal_episodes_for_runs = AsyncMock(
+ side_effect=lambda organization_id, workflow_run_ids: [
+ episode for episode in episodes if episode.workflow_run_id in set(workflow_run_ids)
+ ]
+ )
+
+ monkeypatch.setattr(
+ self_heal_reliability_service.app.DATABASE,
+ "self_heal",
+ SimpleNamespace(
+ get_recent_terminal_workflow_run_ids=get_recent_terminal_workflow_run_ids,
+ get_recent_terminal_workflow_run_ids_batch=get_recent_terminal_workflow_run_ids_batch,
+ get_heal_episodes_for_runs=get_heal_episodes_for_runs,
+ ),
+ )
+
+ batch = await self_heal_reliability_service.get_workflows_reliability(
+ ORG_ID,
+ [wpid_ordered, wpid_other, wpid_unseen],
+ )
+ single_ordered = await self_heal_reliability_service.get_workflow_reliability(ORG_ID, wpid_ordered)
+ single_other = await self_heal_reliability_service.get_workflow_reliability(ORG_ID, wpid_other)
+
+ assert batch[wpid_ordered] == single_ordered
+ assert batch[wpid_other] == single_other
+
+ assert batch[wpid_ordered].consecutive_healed_runs == 3
+ assert batch[wpid_ordered].state == ReliabilityState.action_needed
+
+ assert batch[wpid_unseen] == compute_workflow_reliability([])
+ assert batch[wpid_unseen] == WorkflowReliability(
+ state=ReliabilityState.healthy,
+ outcome_risk=False,
+ scored=False,
+ window_runs=0,
+ healed_runs=0,
+ heal_rate=0.0,
+ consecutive_healed_runs=0,
+ floor_runs=0,
+ outcome_risk_runs=0,
+ )
+
+
+async def test_get_workflows_reliability_empty_request_returns_empty_without_db_calls(monkeypatch) -> None:
+ get_recent_terminal_workflow_run_ids = AsyncMock()
+ get_recent_terminal_workflow_run_ids_batch = AsyncMock()
+ get_heal_episodes_for_runs = AsyncMock()
+
+ monkeypatch.setattr(
+ self_heal_reliability_service.app.DATABASE,
+ "self_heal",
+ SimpleNamespace(
+ get_recent_terminal_workflow_run_ids=get_recent_terminal_workflow_run_ids,
+ get_recent_terminal_workflow_run_ids_batch=get_recent_terminal_workflow_run_ids_batch,
+ get_heal_episodes_for_runs=get_heal_episodes_for_runs,
+ ),
+ )
+
+ assert await self_heal_reliability_service.get_workflows_reliability(ORG_ID, []) == {}
+ get_recent_terminal_workflow_run_ids.assert_not_awaited()
+ get_recent_terminal_workflow_run_ids_batch.assert_not_awaited()
+ get_heal_episodes_for_runs.assert_not_awaited()