Skip to content

Automate browser based workflows with AI

Return every in-loop 404/410 to the Task V3 model, behind a run-arm flag (SKY-16206) (#9040)

pedrohsdb02e54f46e9d9
diff --git a/skyvern/config.py b/skyvern/config.py
index e278ed7ea..914e73387 100644
--- a/skyvern/config.py
+++ b/skyvern/config.py
@@ -590,6 +590,9 @@ class Settings(BaseSettings):
# Hold the first click or Enter after a password fill until 45 s after Task V3 started the block. Force-on term
# only: runs are randomized per run by the flag of the same name, read through run_arm_enabled(LOGIN_PACE_FLAG, ...).
TASK_V3_LOGIN_PACE: bool = False
+ # Return an in-loop navigate's 404/410 to the model as the navigate result instead of ending the run (SKY-16206).
+ # Force-on term only: runs are randomized per run by the flag of the same name (DEAD_END_RETURN_FLAG).
+ TASK_V3_DEAD_END_RETURN: bool = False
# Store the error code v3's model chose on finish instead of the post-run page guess. Off: the guess is stored
# as before. Retry policies match on stored codes, so turning this on can change which runs retry.
TASK_V3_ERROR_CODE_ON_FINISH: bool = False
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index d0c410011..2a4da4fc2 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -229,6 +229,7 @@ from skyvern.forge.taskv3.provider_downloads import (
)
from skyvern.forge.taskv3.run_arms import (
DATE_SEGMENT_AIM_FLAG,
+ DEAD_END_RETURN_FLAG,
LOGIN_PACE_FLAG,
resolve_run_arm,
)
@@ -2830,6 +2831,13 @@ class ForgeAgent:
forced=settings.TASK_V3_LOGIN_PACE,
properties={"workflow_permanent_id": task.workflow_permanent_id or context.workflow_permanent_id or ""},
)
+ await resolve_run_arm(
+ context,
+ DEAD_END_RETURN_FLAG,
+ distinct_id=task.workflow_run_id or task.task_id,
+ organization_id=task.organization_id,
+ forced=settings.TASK_V3_DEAD_END_RETURN,
+ )
page_free_validation = bool(
task_block is not None
and task.task_type == TaskType.validation
diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.py
index 53d35c497..01fa4e5fd 100644
--- a/skyvern/forge/taskv3/engine.py
+++ b/skyvern/forge/taskv3/engine.py
@@ -815,6 +815,7 @@ async def run_task_v3_agent_loop(
attempts_at_hold_gate=activity.attempts_at_hold_gate,
perceptions_at_hold_gate=activity.perceptions_at_hold_gate,
status_at_hold_gate=activity.status_at_hold_gate,
+ dead_ends_returned=activity.dead_ends_returned,
has_navigation_goal=has_navigation_goal,
age_default_rendered=bool(age_default_text),
age_default_reason=age_default_reason,
diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.py
index 0d9080551..f76f17aba 100644
--- a/skyvern/forge/taskv3/loop.py
+++ b/skyvern/forge/taskv3/loop.py
@@ -30,6 +30,7 @@ from urllib.parse import urlsplit
import structlog
+from skyvern.config import settings
from skyvern.errors.errors import resolve_error_code_mapping_key
from skyvern.exceptions import (
CompletionGateTerminationError,
@@ -51,6 +52,7 @@ from skyvern.forge.taskv3.goal_check import (
)
from skyvern.forge.taskv3.handoff_redaction import MAX_HANDOFF_URL_CHARS, normalized_url, sanitize_published_url
from skyvern.forge.taskv3.intercepted_submission import InterceptedSubmission, SubmissionOutcome
+from skyvern.forge.taskv3.run_arms import DEAD_END_RETURN_FLAG, run_arm_enabled
from skyvern.forge.taskv3.target_label import describe_target
from skyvern.schemas.workflows import ERROR_CODE_MAPPING_MAX_ENTRIES, ERROR_CODE_MAPPING_MAX_UTF8_BYTES
from skyvern.webeye.navigation import clear_task_nav_error_code, redact_url_secrets
@@ -1785,6 +1787,8 @@ class ActivityRecency:
attempts_at_hold_gate: int | None = None
perceptions_at_hold_gate: int | None = None
status_at_hold_gate: str | None = None
+ # In-loop dead ends returned to the model as the navigate result instead of ending the run.
+ dead_ends_returned: int = 0
def armed(self, window: int = FAILURE_EVIDENCE_WINDOW_TURNS) -> bool:
return self.last_trigger_turn is not None and (self.turn - self.last_trigger_turn) <= window
@@ -5977,22 +5981,30 @@ async def run_agent_tool_loop(
# failed/terminated choice to the model's finish tool (which does not converge on this class).
if st.outcome is None and st.pending_nav_dead_end is not None:
dead = st.pending_nav_dead_end
+ # Not on the granted final turn: with no turn left to act on it, a return would end the run budget_exhausted.
+ returned = not (activity is not None and activity.final_turn_active) and run_arm_enabled(
+ DEAD_END_RETURN_FLAG, settings.TASK_V3_DEAD_END_RETURN
+ )
LOG.info(
"taskv3 loop navigation dead end",
http_status=dead.status,
turn=st.turns,
guard=NAV_DEAD_END_GUARD,
+ returned_to_model=returned,
**_dead_end_provenance((dead.url, dead.requested_url), task_target_urls, dead.revisit),
)
- st.outcome = _guard_verdict(
- NAV_DEAD_END_GUARD,
- _dead_end_reason(
- st.pending_nav_dead_end.status,
- st.pending_nav_dead_end.url,
- page_noun="The page the run opened",
- caller_known_urls=caller_known_urls,
- ),
- )
+ if returned:
+ # The navigate's own result already gave the model the status and the URL it landed on.
+ st.pending_nav_dead_end = None
+ if activity is not None:
+ activity.dead_ends_returned += 1
+ else:
+ st.outcome = _guard_verdict(
+ NAV_DEAD_END_GUARD,
+ _dead_end_reason(
+ dead.status, dead.url, page_noun="The page the run opened", caller_known_urls=caller_known_urls
+ ),
+ )
# Page-state stall detector (SKY-15265): tool-independent — any batch of billable work that
# leaves the rendered document byte-identical ticks the counter, whatever tools produced it.
diff --git a/skyvern/forge/taskv3/run_arms.py b/skyvern/forge/taskv3/run_arms.py
index 0179d8281..b519990b1 100644
--- a/skyvern/forge/taskv3/run_arms.py
+++ b/skyvern/forge/taskv3/run_arms.py
@@ -18,6 +18,7 @@ LOG = structlog.get_logger()
DATE_SEGMENT_AIM_FLAG = "TASK_V3_DATE_SEGMENT_AIM"
LOGIN_PACE_FLAG = "TASK_V3_LOGIN_PACE"
+DEAD_END_RETURN_FLAG = "TASK_V3_DEAD_END_RETURN"
# Person properties a flag is evaluated with beyond organization_id; resolve_run_arm drops any other key. The
# PostHog preflight (scripts/check_run_arm_flags.py) reads this mapping to accept release conditions on them.
diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.py
index 36d84b079..6ef788db0 100644
--- a/tests/unit/test_agent_task_v3.py
+++ b/tests/unit/test_agent_task_v3.py
@@ -100,6 +100,7 @@ from skyvern.forge.taskv3.loop import (
)
from skyvern.forge.taskv3.run_arms import (
DATE_SEGMENT_AIM_FLAG,
+ DEAD_END_RETURN_FLAG,
LOGIN_PACE_FLAG,
run_arm_enabled,
)
@@ -459,11 +460,9 @@ async def test_execute_task_v3_buckets_the_date_segment_aim_arm_per_run(monkeypa
assert loop_mock.date_segment_aim_enabled_during_loop is True
assert loop_mock.context.run_arms[DATE_SEGMENT_AIM_FLAG] == (task.workflow_run_id, "treatment")
- provider.assert_any_await(
- DATE_SEGMENT_AIM_FLAG,
- task.workflow_run_id,
- properties={"organization_id": task.organization_id},
- )
+ assert loop_mock.context.run_arms[DEAD_END_RETURN_FLAG] == (task.workflow_run_id, "treatment")
+ for flag in (DATE_SEGMENT_AIM_FLAG, DEAD_END_RETURN_FLAG):
+ provider.assert_any_await(flag, task.workflow_run_id, properties={"organization_id": task.organization_id})
@pytest.mark.asyncio
diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.py
index 398e03c3e..3baef98a7 100644
--- a/tests/unit/test_taskv3_loop.py
+++ b/tests/unit/test_taskv3_loop.py
@@ -29,6 +29,7 @@ import pytest
from structlog.testing import capture_logs
import skyvern.webeye.cdp_download_interceptor as cdp_module
+from skyvern.config import settings
from skyvern.exceptions import (
CompletionGateTerminationError,
MissingBrowserStatePage,
@@ -126,6 +127,7 @@ from skyvern.forge.taskv3.loop import (
submissions_since,
)
from skyvern.forge.taskv3.opaque_refs import mask_opaque_urls
+from skyvern.forge.taskv3.run_arms import DEAD_END_RETURN_FLAG
from skyvern.forge.taskv3.tools import build_browser_tools
from skyvern.utils.url_validators import validate_fetch_url
@@ -649,26 +651,177 @@ async def test_navigate_without_dead_end_does_not_terminate() -> None:
assert outcome.reason == "applied"
+_DEAD = "https://jobs.example.test/acme/closed"
+_DEAD_TOO = "https://jobs.example.test/acme/gone"
+_DEAD_THREE = "https://jobs.example.test/acme/removed"
+_LIVE = "https://jobs.example.test/acme/open"
+
+
+def _url_navigate_tool(dead: frozenset[str] = frozenset({_DEAD, _DEAD_TOO, _DEAD_THREE})) -> ToolSpec:
+ # Like the real tool: ok either way, the dead end in its data, and the move inside its action outcome.
+ async def handler(args: dict[str, Any]) -> ToolResult:
+ url = args["url"]
+ data: dict[str, Any] = {"page_state_changed": True, ACTION_OUTCOME_DATA_KEY: {"page_transitioned": True}}
+ if url in dead:
+ return ToolResult.ok(
+ f"navigated to {url} (HTTP 404)",
+ data={**data, "navigation_dead_end": 404, "navigation_dead_end_url": url},
+ )
+ return ToolResult.ok(f"navigated to {url}", data=data)
+
+ return ToolSpec(
+ name="navigate",
+ description="navigate",
+ parameters={"type": "object", "properties": {"url": {"type": "string"}}},
+ handler=handler,
+ )
+
+
+def _page_text_tool() -> ToolSpec:
+ async def handler(args: dict[str, Any]) -> ToolResult:
+ return ToolResult.ok("page text")
+
+ return ToolSpec(name="observe", description="observe", parameters={}, handler=handler, compactable=True)
+
+
+async def _run_dead_end(
+ script: list[list[tuple[str, dict[str, Any]]]], *, activity: ActivityRecency | None = None, **kwargs: Any
+) -> tuple[LoopOutcome, list[ToolResult]]:
+ activity = activity or ActivityRecency()
+ finish = make_finish_tool(activity=activity)
+ finishes: list[ToolResult] = []
+
+ async def recording_finish(args: dict[str, Any]) -> ToolResult:
+ finishes.append(result := await finish.handler(args))
+ return result
+
+ tools = [_url_navigate_tool(), _page_text_tool(), dataclasses.replace(finish, handler=recording_finish)]
+ outcome, _ = await _run(script, tools, activity=activity, **kwargs)
+ return outcome, finishes
+
+
@pytest.mark.asyncio
-async def test_batched_dead_end_then_live_navigate_recovers() -> None:
- # The system prompt tells the model to batch aggressively. A turn that batches a speculative
- # navigate that 404s WITH a fallback navigate to a live page must NOT be terminated on the first
- # of the batch — the fallback runs and the run proceeds to the model's own verdict.
- live = _navigate_tool(dead_end_status=None)
- dead = _navigate_tool(dead_end_status=404)
- tools = [
- ToolSpec(name="navigate_dead", description="d", parameters=dead.parameters, handler=dead.handler),
- ToolSpec(name="navigate_live", description="l", parameters=live.parameters, handler=live.handler),
- make_finish_tool(),
[email protected]("arm", ["forced", "treatment"])
+async def test_every_in_loop_dead_end_goes_back_to_the_model_under_the_arm(
+ monkeypatch: pytest.MonkeyPatch, arm: str
+) -> None:
+ if arm == "forced":
+ monkeypatch.setattr(settings, "TASK_V3_DEAD_END_RETURN", True)
+ script = [
+ [("navigate", {"url": _DEAD})],
+ [("navigate", {"url": _DEAD_TOO}), ("observe", {})],
+ [("navigate", {"url": _DEAD_THREE})],
+ [("navigate", {"url": _LIVE})],
+ [("finish", {"status": "completed", "reason": "posting is open"})],
]
+ context = SkyvernContext(run_arms={DEAD_END_RETURN_FLAG: ("wr_1", "treatment")} if arm == "treatment" else {})
+ activity = ActivityRecency()
+ with skyvern_context.scoped(context), capture_logs() as logs:
+ outcome, _ = await _run_dead_end(script, activity=activity)
+
+ assert (outcome.status, outcome.reason) == ("completed", "posting is open")
+ lines = [entry for entry in logs if entry["event"] == "taskv3 loop navigation dead end"]
+ assert [(line["returned_to_model"], line["provenance"]) for line in lines] == [(True, "undecided")] * 3
+ assert activity.dead_ends_returned == 3
+
+
[email protected]("status", ["completed", "failed", "terminated"])
+async def test_any_verdict_is_accepted_on_a_returned_dead_end(monkeypatch: pytest.MonkeyPatch, status: str) -> None:
+ # A goal can be met by confirming a link is dead; the model, which sees the goal and the page, decides.
+ monkeypatch.setattr(settings, "TASK_V3_DEAD_END_RETURN", True)
+ script = [[("navigate", {"url": _DEAD})], [("finish", {"status": status, "reason": "the posting is gone"})]]
+ outcome, finishes = await _run_dead_end(script)
+
+ assert [result.status for result in finishes] == ["ok"]
+ assert (outcome.status, outcome.reason) == (status, "the posting is gone")
+
+
[email protected]("arm_on", [False, True])
+async def test_batched_dead_end_then_live_navigate_recovers(monkeypatch: pytest.MonkeyPatch, arm_on: bool) -> None:
+ # The model is told to batch aggressively: a fallback navigate in the same batch recovers, under either arm.
+ monkeypatch.setattr(settings, "TASK_V3_DEAD_END_RETURN", arm_on)
script = [
- [("navigate_dead", {"url": "https://jobs.example.test/acme/closed"}), ("navigate_live", {"url": "x"})],
+ [("navigate", {"url": _DEAD}), ("navigate", {"url": _LIVE})],
+ [("navigate", {"url": _DEAD_TOO}), ("observe", {})],
+ [("navigate", {"url": _LIVE})],
[("finish", {"status": "completed", "reason": "applied to the live one"})],
]
- outcome, _ = await _run(script, tools)
+ with capture_logs() as logs:
+ outcome, _ = await _run_dead_end(script)
- assert outcome.status == "completed"
- assert outcome.reason == "applied to the live one"
+ if arm_on:
+ assert (outcome.status, outcome.reason) == ("completed", "applied to the live one")
+ else:
+ assert (outcome.status, outcome.guard) == ("terminated", NAV_DEAD_END_GUARD)
+ # Only the second batch's dead end reaches the settle site.
+ assert len([entry for entry in logs if entry["event"] == "taskv3 loop navigation dead end"]) == 1
+
+
+async def test_a_failed_call_after_a_task_url_dead_end_behaves_the_same_under_either_arm(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def stale_click(args: dict[str, Any]) -> ToolResult:
+ return ToolResult.error("stale ref", data={"page_state_changed": True})
+
+ click = ToolSpec(name="click", description="click", parameters={}, handler=stale_click, billable=True)
+ script = [
+ [("navigate", {"url": _DEAD}), ("click", {"ref": 3})],
+ [("finish", {"status": "failed", "reason": "gone"})],
+ ]
+ outcomes = []
+ for arm_on in (False, True):
+ monkeypatch.setattr(settings, "TASK_V3_DEAD_END_RETURN", arm_on)
+ activity = ActivityRecency()
+ tools = [_url_navigate_tool(), click, make_finish_tool(activity=activity)]
+ outcome, _ = await _run(
+ script, tools, activity=activity, task_target_urls=caller_known_published_urls(_DEAD, keep_query=True)
+ )
+ outcomes.append((outcome.status, outcome.guard))
+
+ # The failed click reports a page change, which clears the pending dead end as on main, so the model's verdict stands.
+ assert outcomes == [("failed", None), ("failed", None)]
+
+
+async def test_a_dead_end_on_the_granted_final_turn_still_ends_the_run(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "TASK_V3_DEAD_END_RETURN", True)
+ activity = ActivityRecency(final_turn_active=True)
+ script = [[("navigate", {"url": _DEAD})], [("finish", {"status": "completed", "reason": "never"})]]
+ outcome, _ = await _run(script, [_url_navigate_tool(), make_finish_tool(activity=activity)], activity=activity)
+
+ assert (outcome.status, outcome.guard) == ("terminated", NAV_DEAD_END_GUARD)
+
+
[email protected]("arm_on", [False, True])
+async def test_a_dead_end_on_the_tasks_own_url_is_the_models_evidence_under_the_arm(
+ monkeypatch: pytest.MonkeyPatch, arm_on: bool
+) -> None:
+ # The goal can be to confirm the link it supplies is dead; under the arm the model judges that from the status.
+ monkeypatch.setattr(settings, "TASK_V3_DEAD_END_RETURN", arm_on)
+ script = [
+ [("navigate", {"url": _DEAD})],
+ [("finish", {"status": "completed", "reason": "the supplied link is dead"})],
+ ]
+ with capture_logs() as logs:
+ outcome, finishes = await _run_dead_end(
+ script, task_target_urls=caller_known_published_urls(_DEAD, keep_query=True)
+ )
+
+ if arm_on:
+ assert (outcome.status, outcome.reason) == ("completed", "the supplied link is dead")
+ assert [result.status for result in finishes] == ["ok"]
+ else:
+ assert (outcome.status, outcome.guard) == ("terminated", NAV_DEAD_END_GUARD)
+ (line,) = (entry for entry in logs if entry["event"] == "taskv3 loop navigation dead end")
+ assert (line["provenance"], line["returned_to_model"]) == ("task_supplied", arm_on)
+
+ # The pre-loop initial navigation is not in-loop: it ends the run under either arm.
+ initial, _ = await _run_dead_end(script[1:], initial_navigation_status=404, initial_navigation_url=_DEAD)
+ assert (initial.status, initial.guard) == ("terminated", NAV_DEAD_END_GUARD)
@pytest.mark.parametrize("status", sorted(NAVIGATION_DEAD_END_STATUSES))