Skip to content

Automate browser based workflows with AI

Persist a terminal decision row for budget-exhausted and loop-error Task V3 deaths (#8432)

pedrohsdb7e376a918921
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index da1b6740e..a545871ab 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -2108,12 +2108,16 @@ class ForgeAgent:
# its complete/terminate decision, and this row is the only step detail a click-free
# validation/extraction block has to show. Written HERE, after the verdict is
# final: a completion the gate or the extraction check rejects records as the FAILED attempt
- # it was, and a finish the loop rejected mid-run never persists at all.
- if outcome.status in ("completed", "terminated", "failed"):
+ # it was, and a finish the loop rejected mid-run never persists at all. A verdict-less death
+ # (budget_exhausted/loop_error) records as a FAILED terminate carrying the outcome reason —
+ # those are the runs users most need step details for. Cancellation persists nothing.
+ if outcome.status in ("completed", "terminated", "failed", "budget_exhausted", "loop_error"):
with contained_effect("task_v3 terminal decision persist", task_id=task.task_id):
decision_reason = outcome.reason or ""
decision_action_status = ActionStatus.completed
- if outcome.status == "completed" and (completion_vetoed or missing_extraction):
+ if outcome.status in ("budget_exhausted", "loop_error"):
+ decision_action_status = ActionStatus.failed
+ elif outcome.status == "completed" and (completion_vetoed or missing_extraction):
decision_action_status = ActionStatus.failed
rejection = (
"the completion gate rejected the verdict"
@@ -2132,10 +2136,13 @@ class ForgeAgent:
decision_screenshot_id: str | None = None
if not page_free_validation:
try:
- decision_shot = await browser_state.take_post_action_screenshot(scrolling_number=0)
- decision_screenshot_id = await app.ARTIFACT_MANAGER.create_artifact(
- step=step, artifact_type=ArtifactType.SCREENSHOT_ACTION, data=decision_shot
- )
+ # Bounded like the neighboring persists: the verdict-less death paths reach
+ # this on exactly the runs whose page is most likely stuck.
+ async with asyncio.timeout(30):
+ decision_shot = await browser_state.take_post_action_screenshot(scrolling_number=0)
+ decision_screenshot_id = await app.ARTIFACT_MANAGER.create_artifact(
+ step=step, artifact_type=ArtifactType.SCREENSHOT_ACTION, data=decision_shot
+ )
except Exception:
LOG.warning(
"task_v3 failed to capture decision screenshot", task_id=task.task_id, exc_info=True
diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.py
index 85c04afa0..9b144ecd0 100644
--- a/tests/unit/test_agent_task_v3.py
+++ b/tests/unit/test_agent_task_v3.py
@@ -2392,11 +2392,13 @@ async def test_execute_task_v3_actions_are_round_stamped(monkeypatch: pytest.Mon
monkeypatch, outcome, action_rounds=rounds, data_extraction_goal=None, extracted_information_schema=None
)
create_action = agent_module.app.DATABASE.workflow_params.create_action
- # The terminal decision row (appended last) is stamped separately; slice it off to check only
- # the per-action rows this test is about.
action_rows = create_action.await_args_list[:-1]
stamped = [(c.kwargs["action"].step_order, c.kwargs["action"].action_order) for c in action_rows]
assert stamped == [(0, 0), (0, 1), (1, 2)]
+ # The terminal decision row rides the LAST consumed billable index — a fresh index would read
+ # as a new distinct (task, step_order) pair to the workflow-run step budget.
+ decision = create_action.await_args_list[-1].kwargs["action"]
+ assert (decision.step_order, decision.action_order) == (1, 3)
@pytest.mark.asyncio
@@ -2835,6 +2837,69 @@ async def test_execute_task_v3_cap_tripped_loop_error_keeps_provider_category_an
assert loop_mock.update_task_kwargs.get("extracted_information") == {"rows": [8]}
+ ("status", "reason"),
+ [
+ ("budget_exhausted", "The run reached its turn budget before the model finished."),
+ ("loop_error", "llm_call_failed: RuntimeError: provider unavailable"),
+ ],
+)
+async def test_execute_task_v3_verdictless_death_persists_a_failed_decision_row(
+ monkeypatch: pytest.MonkeyPatch, status: str, reason: str
+) -> None:
+ # A death with no agent verdict is exactly the run a click-free block has no step details for:
+ # the terminal decision row is synthesized as a FAILED terminate carrying the outcome reason.
+ from skyvern.forge import agent as agent_mod
+
+ outcome = LoopOutcome(status=status, reason=reason, billable_actions=["click"])
+ _step, task, _loop, _post = await _run_execute_task_v3(
+ monkeypatch, outcome, data_extraction_goal=None, extracted_information_schema=None
+ )
+ assert task.status == TaskStatus.failed
+ persisted = agent_mod.app.DATABASE.workflow_params.create_action.await_args.kwargs["action"]
+ assert persisted.action_type == ActionType.TERMINATE
+ assert persisted.status == ActionStatus.failed
+ assert persisted.reasoning == reason
+
+
+async def test_execute_task_v3_verdictless_death_with_salvaged_output_still_fails_the_decision_row(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # The decision row records whether the agent gave a verdict, not whether data survived: a
+ # cap-tripped death still persists FAILED even though AC-2 carries the staged extraction
+ # through. Coupling the row's status to the salvage would hide these runs from the
+ # failed-decision-row taxonomy the docs point at.
+ from skyvern.forge import agent as agent_mod
+
+ outcome = LoopOutcome(
+ status="budget_exhausted",
+ reason="The run reached its turn budget before the model finished.",
+ cap_trip="max_turns (40) reached",
+ billable_actions=["click"],
+ extracted_output={"rows": [3]},
+ )
+ _step, task, loop_mock, _post = await _run_execute_task_v3(
+ monkeypatch, outcome, data_extraction_goal=None, extracted_information_schema=None
+ )
+ assert task.status == TaskStatus.failed
+ assert loop_mock.update_task_kwargs.get("extracted_information") == {"rows": [3]}
+ persisted = agent_mod.app.DATABASE.workflow_params.create_action.await_args.kwargs["action"]
+ assert persisted.action_type == ActionType.TERMINATE
+ assert persisted.status == ActionStatus.failed
+
+
+async def test_execute_task_v3_canceled_death_persists_no_decision_row(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Cancellation is the user's decision, not a run verdict — no synthesized row.
+ from skyvern.forge import agent as agent_mod
+
+ outcome = LoopOutcome(status="canceled", reason="run canceled", billable_actions=[])
+ await _run_execute_task_v3(monkeypatch, outcome, data_extraction_goal=None, extracted_information_schema=None)
+ assert agent_mod.app.DATABASE.workflow_params.create_action.await_args is None
+
+
def test_task_validate_update_allows_partial_extraction_on_failed_and_terminated() -> None:
# The budget-cap final turn persists PARTIAL extraction with a failed/terminated verdict. The
# execute harness stubs update_task, so the real contract is pinned here: failed/terminated
diff --git a/tests/unit/test_script_service_fallback_engine.py b/tests/unit/test_script_service_fallback_engine.py
index 6ee43476e..d855999b5 100644
--- a/tests/unit/test_script_service_fallback_engine.py
+++ b/tests/unit/test_script_service_fallback_engine.py
@@ -14,12 +14,15 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
+from skyvern.forge.sdk.schemas.tasks import TaskStatus
from skyvern.forge.sdk.workflow.models.block import TaskBlock
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, ParameterType
from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowDefinition
from skyvern.schemas.runs import RunEngine
from skyvern.schemas.workflows import BlockType
from skyvern.services import script_service
+from skyvern.webeye.actions.action_types import ActionType
+from skyvern.webeye.actions.actions import Action, ActionStatus
MODULE = "skyvern.services.script_service"
@@ -295,3 +298,47 @@ async def test_block_screenshot_without_browser_state_is_not_a_warning(monkeypat
log.warning.assert_not_called()
log.info.assert_called_once()
assert log.info.call_args.args[0] == "No browser state found when creating workflow_run_block"
+
+
+async def test_fallback_episode_excludes_decision_row_from_agent_action_count() -> None:
+ # Twin pin of the workflow/service.py count-filter test: _fallback_to_ai_run keeps its own copy
+ # of the decision-row exclusion, and a verdict row must not count as agent activity here either.
+ workflow = _make_workflow([_make_task_block("my_block", engine=RunEngine.skyvern_v1)])
+ workflow.run_with = "code"
+ workflow.code_version = 2
+ app = _make_app(workflow)
+ app.DATABASE.workflow_runs.get_workflow_run = AsyncMock(
+ return_value=SimpleNamespace(ai_fallback=True, run_with=None)
+ )
+ app.DATABASE.tasks.get_task = AsyncMock(
+ return_value=SimpleNamespace(url="https://example.com", status=TaskStatus.completed, failure_reason=None)
+ )
+ app.DATABASE.scripts.create_fallback_episode = AsyncMock(return_value=SimpleNamespace(episode_id="cep_1"))
+ update_episode = AsyncMock()
+ app.DATABASE.scripts.update_fallback_episode = update_episode
+ app.DATABASE.tasks.get_task_actions = AsyncMock(
+ return_value=[Action(action_type=ActionType.COMPLETE, status=ActionStatus.completed, step_id="stp_ai_1")]
+ )
+
+ # create_fallback_episode only fires when the context carries a workflow_permanent_id
+ # (is_adaptive_caching's gate); _make_context() leaves it unset for the other tests in
+ # this file, so this test needs its own context with it filled in.
+ context = _make_context()
+ context.workflow_permanent_id = "wpid_test"
+ with (
+ patch(f"{MODULE}.app", app),
+ patch(f"{MODULE}.skyvern_context.current", return_value=context),
+ ):
+ await script_service._fallback_to_ai_run(
+ block_type=BlockType.NAVIGATION,
+ cache_key="my_block",
+ prompt="do the thing",
+ )
+
+ update_episode.assert_awaited_once()
+ assert update_episode.await_args.kwargs["fallback_succeeded"] is False
+ assert (
+ update_episode.await_args.kwargs["agent_actions"]["failure_reason"]
+ == script_service.VERIFIER_SWAP_FAILURE_REASON
+ )
diff --git a/tests/unit/workflow/test_execute_single_block_phases.py b/tests/unit/workflow/test_execute_single_block_phases.py
index 28b82806f..b3dbcc886 100644
--- a/tests/unit/workflow/test_execute_single_block_phases.py
+++ b/tests/unit/workflow/test_execute_single_block_phases.py
@@ -31,6 +31,7 @@ from skyvern.schemas.scripts import ScriptBlock
from skyvern.schemas.workflows import BlockResult, BlockStatus
from skyvern.services import script_service
from skyvern.webeye.actions.action_types import ActionType
+from skyvern.webeye.actions.actions import Action
from skyvern.webeye.browser_artifacts import BrowserArtifacts
@@ -596,7 +597,7 @@ async def test_enrich_fallback_episode_excludes_decision_row_from_agent_action_c
monkeypatch.setattr(
app.DATABASE.tasks,
"get_task_actions",
- AsyncMock(return_value=[SimpleNamespace(action_type=ActionType.COMPLETE)]),
+ AsyncMock(return_value=[Action(action_type=ActionType.COMPLETE)]),
)
update_episode = AsyncMock()
monkeypatch.setattr(app.DATABASE.scripts, "update_fallback_episode", update_episode)
@@ -611,6 +612,10 @@ async def test_enrich_fallback_episode_excludes_decision_row_from_agent_action_c
update_episode.assert_awaited_once()
assert update_episode.await_args.kwargs["fallback_succeeded"] is False
+ # The happy-path summary must exist (a raising summarizer would fall into the except arm and
+ # leave this test unable to discriminate the count filter).
+ summarized = update_episode.await_args.kwargs["agent_actions"]["actions"]
+ assert [entry["action_type"] for entry in summarized] == [ActionType.COMPLETE]
assert (
update_episode.await_args.kwargs["agent_actions"]["failure_reason"]
== script_service.VERIFIER_SWAP_FAILURE_REASON