Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Hold a v3 give-up once for the one permitted retry after a typed site rejection (SKY-17487) (#9003)
LawyZhengf94b4f6376b9
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex 0d3bd220e..6de7213fc 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -215,6 +215,7 @@ from skyvern.forge.taskv3.loop import (DownloadWait,LoopOutcome,RoundAction,+ submissions_across_contexts,)from skyvern.forge.taskv3.pre_submit_capture import PreSubmitCaptureRing, is_run_sampled, pre_submit_screenshotfrom skyvern.forge.taskv3.provider_downloads import (@@ -3260,9 +3261,10 @@ class ForgeAgent:outcome = await run_task_v3_agent_loop(page_provider=_page_provider,- # Read through browser_state each time: a recovered browser brings a new context.- intercepted_submissions=lambda: app.AGENT_FUNCTION.task_v3_intercepted_submissions(- browser_state.browser_context+ # Read through browser_state each time: a recovered browser brings a new context, and the old+ # one's submissions still count.+ intercepted_submissions=submissions_across_contexts(+ app.AGENT_FUNCTION.task_v3_intercepted_submissions, lambda: browser_state.browser_context),resolve_typed_text=resolve_typed_text,credential_release_guard=release_guard,diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.pyindex e8173cff7..da1c65d7b 100644--- a/skyvern/forge/taskv3/loop.py+++ b/skyvern/forge/taskv3/loop.py@@ -15,6 +15,7 @@ core can be unit-tested with scripted fakes.from __future__ import annotationsimport asyncio+import dataclassesimport hashlibimport jsonimport re@@ -1713,6 +1714,10 @@ class ActivityRecency:# after it showing the old page); this batch's reads wait in `batch_read_started_at` until the next model turn.read_started_at: float | None = Nonebatch_read_started_at: float | None = None+ # Page reloads a page-level handler may still request before the run ends on the refresh cap.+ refresh_cycles_remaining: int | None = None+ # time.monotonic() at the dispatch of the newest submit-shaped action (`_may_submit`), whatever its result.+ last_submit_attempt_at: float | None = None# State at the FIRST failed/terminated finish past the failure-evidence gate, emitted once per run# by the engine's summary line. Not the run's first verdict: a zero-action `completed` refused by a# gate above reaches this point later as failed/terminated.@@ -1749,6 +1754,32 @@ def submissions_since(return read+def submissions_across_contexts(+ read: Callable[[Any], Sequence[InterceptedSubmission]], current_context: Callable[[], Any]+) -> Callable[[], tuple[InterceptedSubmission, ...]]:+ """Records from every browser context the run has read, oldest first, so a recovered browser cannot hide a+ submission made in the one it replaced. Ids are renumbered per (context, id), since a reader may restart them."""+ contexts: list[Any] = []+ ids: dict[tuple[int, int], int] = {}++ def track() -> None:+ context = current_context()+ if context is not None and not any(seen is context for seen in contexts):+ contexts.append(context)++ def records() -> tuple[InterceptedSubmission, ...]:+ track()+ out = []+ for index, context in enumerate(contexts):+ for record in read(context):+ record_id = ids.setdefault((index, record.record_id), len(ids) + 1)+ out.append(dataclasses.replace(record, record_id=record_id))+ return tuple(out)++ track()+ return records++def _names_submit_control(tool_name: str, args: dict[str, Any], ok: bool, data: dict[str, Any]) -> str | None:"""The selector of a control a successful action acted on directly, or None.@@ -2736,7 +2767,10 @@ def make_finish_tool(verdict is held once per submission whose response reached the page after the newest read the model receivedstarted: the verdict may describe the page before the response. One still held is waited on first (bounded) and,if still held, holds once on the wait; when it is released later its response can hold once more. The hold asks- for a re-observe and never implies the response was an acceptance."""+ for a re-observe and never implies the response was an acceptance. When the only submission the+ interceptor saw is the site's typed machine rejection, and no submit-shaped action followed the one that sent it,+ a failed or terminated verdict is held once more, funded like the give-up hold, so the one retry the prompt+ permits is not left unused; any other record or later submit-shaped action ends that."""error_code_mapping = _offered_error_codes(error_code_mapping)deferrals = 0stale_holds = 0@@ -2751,6 +2785,15 @@ def make_finish_tool(# The turn a submission hold fired in and its message: a later finish in that batch has not received it either.submission_hold_turn: int | None = Nonesubmission_hold_message = ""+ retry_offered = False+ retry_would_offer = False+ # What the retry hold was granted on; a submit later in its batch spends it, so a later finish there must not+ # repeat the permission.+ retry_granted_on: tuple[tuple[tuple[int, SubmissionOutcome], ...], float | None] | None = None++ def _submission_state() -> tuple[tuple[tuple[int, SubmissionOutcome], ...], float | None]:+ records = tuple((r.record_id, r.outcome) for r in _read_submissions())+ return records, activity.last_submit_attempt_at if activity is not None else Nonedef _read_submissions() -> list[InterceptedSubmission]:assert intercepted_submissions is not None@@ -2974,6 +3017,7 @@ def make_finish_tool(async def handler(args: dict[str, Any]) -> ToolResult:nonlocal deferrals, stale_holds, failure_deferrals, reask_asked, premise_checksnonlocal submission_hold_turn, submission_hold_message+ nonlocal retry_offered, retry_would_offer, retry_granted_onstatus = args.get("status")if status not in ("completed", "failed", "terminated"):return ToolResult.error(@@ -3131,6 +3175,11 @@ def make_finish_tool(return ToolResult.error(COMPLETION_GATE_REFUSAL)if status in ("failed", "terminated") and intercepted_submissions is not None and activity is not None:if submission_hold_turn == activity.turn:+ if retry_granted_on is not None and _submission_state() != retry_granted_on:+ return ToolResult.error(+ "verdict held: a submission was made after the retry offer in this same batch, so that "+ "offer is spent. Do not submit again; re-observe the page and finish on what it shows."+ )return ToolResult.error(submission_hold_message)unseen = _unseen_submissions(_read_submissions())can_hold = bool(unseen) and _has_hold_headroom(activity, deadline_at)@@ -3173,6 +3222,8 @@ def make_finish_tool()still_held = any(r.outcome is SubmissionOutcome.HELD for r in unseen)submission_hold_turn = activity.turn+ # A plain hold, not the retry offer: a later finish in this batch gets it unchanged.+ retry_granted_on = Nonesubmission_hold_message = ("verdict held once: a form submission on this page "+ (@@ -3186,6 +3237,54 @@ def make_finish_tool("confirmation of the goal; otherwise finish again with your verdict and it will stand.")return ToolResult.error(submission_hold_message)+ if status in ("failed", "terminated") and intercepted_submissions is not None and activity is not None:+ records = _read_submissions()+ rejection = (+ records[0] if len(records) == 1 and records[0].outcome is SubmissionOutcome.REJECTED_BY_SITE else None+ )+ # The ledger can miss a submit (another op, a frameless request), so the loop's own trail must agree that+ # the rejected request came from this block's latest submit-shaped action.+ if rejection is not None and (+ activity.last_submit_attempt_at is None or activity.last_submit_attempt_at > rejection.started_at+ ):+ rejection = None+ if rejection is not None and not retry_offered:+ can_retry = (+ _has_hold_headroom(+ activity,+ deadline_at,+ min_deadline_headroom_seconds=VERIFICATION_GIVEUP_MIN_DEADLINE_HEADROOM_SECONDS,+ )+ and (activity.action_steps_remaining is None or activity.action_steps_remaining > 0)+ and (activity.refresh_cycles_remaining is None or activity.refresh_cycles_remaining > 0)+ )+ if not can_retry:+ if not retry_would_offer:+ retry_would_offer = True+ LOG.info(+ "taskv3 finish would hold for the permitted retry of a typed site rejection",+ status=status,+ site_error_type=rejection.site_error_type,+ turn=activity.turn,+ )+ else:+ retry_offered = True+ if status == "failed":+ failure_deferrals = max_failure_deferrals+ LOG.info(+ "taskv3 finish held for the permitted retry of a typed site rejection",+ status=status,+ site_error_type=rejection.site_error_type,+ turn=activity.turn,+ )+ submission_hold_turn = activity.turn+ retry_granted_on = _submission_state()+ submission_hold_message = (+ "verdict held once: the only submission the page-level interceptor saw this block got the "+ f"site's own machine-typed rejection ({rejection.site_error_type}). Finish again with the "+ "verdict you decide on and it will stand."+ )+ return ToolResult.error(submission_hold_message)if (status == "failed"and activity is not None@@ -3832,6 +3931,8 @@ async def run_agent_tool_loop("""Clear the page-refresh signal and, unless dropped or past the cap, reload and void `remaining`."""ctx.refresh_working_page = Falsest.refresh_cycles += 1+ if activity is not None:+ activity.refresh_cycles_remaining = max_refresh_cycles - st.refresh_cyclesif drop:LOG.info("taskv3 loop refresh signal dropped", tool=tool_name, turn=st.turns)return False@@ -4335,6 +4436,7 @@ async def run_agent_tool_loop(st.turns += 1if activity is not None:activity.deliver_batch_reads()+ activity.refresh_cycles_remaining = max_refresh_cycles - st.refresh_cyclesactivity.turn = st.turnsactivity.turns_remaining = st.max_turns - st.turnsactivity.tool_calls_remaining = st.max_tool_calls - st.total_tool_calls@@ -5542,6 +5644,8 @@ async def run_agent_tool_loop(st.block_action_transitioned = Trueif activity is not None and _arms_failure_evidence(tool_name, args, result.status == "ok"):activity.last_trigger_turn = st.turns+ if activity is not None and _may_submit(tool_name, args):+ activity.last_submit_attempt_at = tool_started_atif submit_watch is not None:submit_selector = _names_submit_control(tool_name, args, result.status == "ok", result_data)if submit_selector is not None:diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.pyindex b899a2962..578b40d29 100644--- a/tests/unit/test_taskv3_loop.py+++ b/tests/unit/test_taskv3_loop.py@@ -110,6 +110,7 @@ from skyvern.forge.taskv3.loop import (record_resolve_seconds,record_text_delta,run_agent_tool_loop,+ submissions_across_contexts,submissions_since,)from skyvern.forge.taskv3.opaque_refs import mask_opaque_urls@@ -7018,7 +7019,15 @@ class _FakeSubmissions:at = time.monotonic() - agoself.records.append(InterceptedSubmission(- record_id=len(self.records) + 1, outcome=outcome, started_at=at - 0.5, released_at=at, delivered_at=at+ record_id=len(self.records) + 1,+ outcome=outcome,+ # A request sent now reaches the interceptor after the action that sent it was dispatched.+ started_at=at - min(ago, 0.5),+ released_at=at,+ delivered_at=at,+ site_error_type="RECAPTCHA_SCORE_BELOW_THRESHOLD"+ if outcome is SubmissionOutcome.REJECTED_BY_SITE+ else None,))@@ -7403,6 +7412,282 @@ def test_submissions_since_drops_an_earlier_blocks_settled_records() -> None:assert [r.record_id for r in read()] == [2, 3]+_RETRY_HELD = "taskv3 finish held for the permitted retry of a typed site rejection"+_RETRY_WOULD_HOLD = "taskv3 finish would hold for the permitted retry of a typed site rejection"+_REJECTED = SubmissionOutcome.REJECTED_BY_SITE+++async def _typed_rejection_run(+ submissions: _FakeSubmissions,+ script: list[list[tuple[str, dict[str, Any]]]],+ *,+ click_outcomes: list[SubmissionOutcome] | None = None,+ finish_kwargs: dict[str, Any] | None = None,+ **kwargs: Any,+) -> tuple[Any, list[dict[str, Any]]]:+ """Each click is a submit the interceptor records with the next outcome; once they run out it records nothing."""+ activity = ActivityRecency()+ tools = _submission_tools(submissions, activity, **(finish_kwargs or {}))+ pending = list(click_outcomes or [])++ async def click(args: dict[str, Any]) -> ToolResult:+ if pending:+ next_outcome = pending.pop(0)+ if next_outcome is SubmissionOutcome.HELD:+ submissions.hold()+ else:+ submissions.deliver(outcome=next_outcome)+ await asyncio.sleep(SUBMISSION_RENDER_MARGIN_SECONDS + 0.2)+ return ToolResult.ok("click done")++ tools[0] = ToolSpec(name="click", description="c", parameters={}, handler=click, billable=True)+ with capture_logs() as logs:+ outcome, _ = await _run(script, tools, activity=activity, **kwargs)+ return outcome, logs+++_SUBMIT_REJECTED_THEN_GIVE_UP = [+ [("observe", {})],+ [("click", {"selector": "#submit"})],+ [("observe", {})],+ [("finish", {"status": "terminated", "reason": "flagged as spam"})],+]+++async def test_a_lone_typed_rejection_holds_a_give_up_once_for_the_permitted_retry() -> None:+ script = [*_SUBMIT_REJECTED_THEN_GIVE_UP, [("finish", {"status": "terminated", "reason": "not retrying"})]]+ outcome, logs = await _typed_rejection_run(_FakeSubmissions(), script, click_outcomes=[_REJECTED])+ assert (outcome.status, outcome.reason) == ("terminated", "not retrying")+ assert [e["event"] for e in logs].count(_RETRY_HELD) == 1+++async def test_any_submit_after_the_typed_rejection_ends_the_offer() -> None:+ # The retry's own record, whatever it got back, or a resubmit the interceptor never saw: either way no offer.+ for retry in (_REJECTED, SubmissionOutcome.UNKNOWN, SubmissionOutcome.DELIVERED, None):+ script = [+ [("observe", {})],+ [("click", {"selector": "#submit"})],+ [("observe", {})],+ [("click", {"selector": "#submit"})],+ [("observe", {})],+ [("finish", {"status": "terminated", "reason": "rejected again"})],+ ]+ outcomes = [_REJECTED] if retry is None else [_REJECTED, retry]+ outcome, logs = await _typed_rejection_run(_FakeSubmissions(), script, click_outcomes=outcomes)+ assert (retry, outcome.status, outcome.turns) == (retry, "terminated", 6)+ assert _RETRY_HELD not in [e["event"] for e in logs]+++async def test_only_this_blocks_own_typed_rejection_offers_the_retry() -> None:+ for lone in (SubmissionOutcome.DELIVERED, SubmissionOutcome.UNKNOWN):+ script = [*_SUBMIT_REJECTED_THEN_GIVE_UP[:3], [("finish", {"status": "failed", "reason": "r"})]]+ outcome, logs = await _typed_rejection_run(_FakeSubmissions(), script, click_outcomes=[lone])+ assert (lone, outcome.status, outcome.turns) == (lone, "failed", 4)+ assert _RETRY_HELD not in [e["event"] for e in logs]+ # A rejection this block made no submit for: an earlier block's submission, settled while this one ran.+ submissions = _FakeSubmissions()+ submissions.deliver(ago=5.0, outcome=_REJECTED)+ outcome, logs = await _typed_rejection_run(+ submissions, [[("observe", {})], [("finish", {"status": "terminated", "reason": "nothing to submit"})]]+ )+ assert (outcome.status, outcome.turns) == ("terminated", 2)+ assert _RETRY_HELD not in [e["event"] for e in logs]+ submissions = _FakeSubmissions()+ submissions.hold()++ async def canceled() -> bool:+ return True++ activity = ActivityRecency()+ finish = make_finish_tool(activity=activity, intercepted_submissions=submissions, should_cancel=canceled)+ with capture_logs() as logs:+ await finish.handler({"status": "terminated", "reason": "r"})+ activity.turn += 1+ result = await finish.handler({"status": "terminated", "reason": "r"})+ assert result.status == "ok"+ assert _RETRY_HELD not in [e["event"] for e in logs]+++async def test_a_second_finish_in_the_batch_of_the_retry_hold_is_held_too() -> None:+ script = [+ *_SUBMIT_REJECTED_THEN_GIVE_UP[:3],+ [("finish", {"status": "terminated", "reason": "r1"}), ("finish", {"status": "terminated", "reason": "r2"})],+ [("finish", {"status": "terminated", "reason": "r3"})],+ ]+ outcome, logs = await _typed_rejection_run(_FakeSubmissions(), script, click_outcomes=[_REJECTED])+ assert (outcome.status, outcome.reason, outcome.turns) == ("terminated", "r3", 5)+ assert [e["event"] for e in logs].count(_RETRY_HELD) == 1+++_RETRY_HOLD = "verdict held once: the only submission the page-level interceptor saw"+# The hold reports the rejection as a fact; it must not tell the model what to do about it.+_STEERING = ("you may retry", "unused", "retry the submission")+++ "second", [None, SubmissionOutcome.HELD, SubmissionOutcome.DELIVERED, SubmissionOutcome.UNKNOWN, _REJECTED]+)+async def test_a_submit_queued_behind_the_retry_hold_spends_the_offer_for_the_rest_of_the_batch(+ second: SubmissionOutcome | None,+) -> None:+ # [finish, submit, finish] in one batch: the second finish must not repeat a permission the submit already used,+ # whether the interceptor recorded it (in flight, delivered, unknown, rejected) or never saw it (None).+ submissions = _FakeSubmissions()+ outcomes = [_REJECTED] if second is None else [_REJECTED, second]+ script = [+ *_SUBMIT_REJECTED_THEN_GIVE_UP[:3],+ [+ ("finish", {"status": "terminated", "reason": "r1"}),+ ("click", {"selector": "#submit"}),+ ("finish", {"status": "terminated", "reason": "r2"}),+ ],+ [("observe", {})],+ [("finish", {"status": "terminated", "reason": "r3"})],+ ]++ async def settle_held() -> None:+ while not any(r.outcome is SubmissionOutcome.HELD for r in submissions.records):+ await asyncio.sleep(0.01)+ submissions.release(next(r.record_id for r in submissions.records if r.outcome is SubmissionOutcome.HELD))++ releaser = asyncio.create_task(settle_held()) if second is SubmissionOutcome.HELD else None+ outcome, logs = await _typed_rejection_run(submissions, script, click_outcomes=outcomes)+ if releaser is not None:+ await releaser+ finishes = [+ str(m.get("content")) for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "finish"+ ]+ assert finishes[0].startswith(_RETRY_HOLD)+ assert finishes[1].startswith("verdict held") and not finishes[1].startswith(_RETRY_HOLD), finishes[1]+ assert all(not later.startswith(_RETRY_HOLD) for later in finishes[2:])+ assert (outcome.status, outcome.reason) == ("terminated", "r3")+ assert [e["event"] for e in logs].count(_RETRY_HELD) == 1+++async def test_a_submission_the_loop_did_not_send_also_spends_the_retry_offer_for_the_batch() -> None:+ # The page can send a submission on its own (a script re-submitting): a new record with no submit-shaped action.+ submissions, activity = _FakeSubmissions(), ActivityRecency()+ tools = _submission_tools(submissions, activity)+ reads = [0]++ async def click(args: dict[str, Any]) -> ToolResult:+ submissions.deliver(outcome=_REJECTED)+ await asyncio.sleep(SUBMISSION_RENDER_MARGIN_SECONDS + 0.2)+ return ToolResult.ok("click done")++ async def observe(args: dict[str, Any]) -> ToolResult:+ reads[0] += 1+ if reads[0] == 2:+ submissions.deliver(outcome=SubmissionOutcome.DELIVERED)+ return ToolResult.ok("url=x text: 'Submit application'")++ tools[0] = ToolSpec(name="click", description="c", parameters={}, handler=click, billable=True)+ tools[1] = ToolSpec(name="observe", description="o", parameters={}, handler=observe, compactable=True)+ script = [+ [("click", {"selector": "#submit"})],+ [("observe", {})],+ [+ ("finish", {"status": "terminated", "reason": "r1"}),+ ("observe", {}),+ ("finish", {"status": "terminated", "reason": "r2"}),+ ],+ ]+ outcome, _ = await _run(script, tools, activity=activity)+ finishes = [+ str(m.get("content")) for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "finish"+ ]+ assert finishes[0].startswith(_RETRY_HOLD)+ assert finishes[1].startswith("verdict held") and not finishes[1].startswith(_RETRY_HOLD), finishes[1]+++async def test_the_typed_rejection_hold_states_the_rejection_without_steering() -> None:+ script = [*_SUBMIT_REJECTED_THEN_GIVE_UP, [("finish", {"status": "terminated", "reason": "r2"})]]+ outcome, _ = await _typed_rejection_run(_FakeSubmissions(), script, click_outcomes=[_REJECTED])+ hold = next(m["content"] for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "finish")+ assert hold.startswith(_RETRY_HOLD) and "RECAPTCHA_SCORE_BELOW_THRESHOLD" in hold, hold+ assert not any(phrase in hold.lower() for phrase in _STEERING), hold+ assert (outcome.status, outcome.reason) == ("terminated", "r2")+++async def test_a_later_generic_hold_is_not_reported_as_a_spent_retry_offer() -> None:+ # Offer in one turn, a submission in the next, then a plain unseen-response hold: the second finish in that later+ # batch gets the same plain hold, not the claim that a submission followed the offer in this batch.+ script = [+ *_SUBMIT_REJECTED_THEN_GIVE_UP,+ [("click", {"selector": "#submit"})],+ [("finish", {"status": "terminated", "reason": "r1"}), ("finish", {"status": "terminated", "reason": "r2"})],+ [("observe", {})],+ [("finish", {"status": "terminated", "reason": "r3"})],+ ]+ outcome, _ = await _typed_rejection_run(+ _FakeSubmissions(), script, click_outcomes=[_REJECTED, SubmissionOutcome.DELIVERED]+ )+ finishes = [+ str(m.get("content")) for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "finish"+ ]+ assert finishes[0].startswith(_RETRY_HOLD)+ assert "got the site's response after your last look" in finishes[1], finishes[1]+ assert finishes[2] == finishes[1], finishes[2]+ assert (outcome.status, outcome.reason) == ("terminated", "r3")+++async def test_typed_rejection_retry_without_headroom_only_logs() -> None:+ reloads: list[None] = []++ async def reload_page() -> None:+ reloads.append(None)++ # The retry is a refill and a resubmit, so it is funded like the give-up hold, not like a re-observe.+ deadline = {"deadline_at": time.monotonic() + VERIFICATION_GIVEUP_MIN_DEADLINE_HEADROOM_SECONDS - 10}+ for limit, finish_kwargs in (+ ({"max_turns": 4}, None),+ ({"max_action_steps": 1}, None),+ ({"max_refresh_cycles": 1}, None),+ ({}, deadline),+ ):+ ctx = SkyvernContext(task_id="tsk_typed_rejection")+ skyvern_context.set(ctx)+ ctx.refresh_working_page = "max_refresh_cycles" in limit+ try:+ outcome, logs = await _typed_rejection_run(+ _FakeSubmissions(),+ _SUBMIT_REJECTED_THEN_GIVE_UP,+ click_outcomes=[_REJECTED],+ finish_kwargs=finish_kwargs,+ reload_page=reload_page,+ **limit,+ )+ finally:+ skyvern_context.reset()+ events = [e["event"] for e in logs]+ assert (str(limit), outcome.status, _RETRY_HELD in events) == (str(limit), "terminated", False)+ assert _RETRY_WOULD_HOLD in events+++def test_submissions_across_contexts_keeps_a_replaced_contexts_records_apart() -> None:+ first, second = object(), object()+ ledgers = {+ first: (InterceptedSubmission(1, _REJECTED, started_at=1.0, released_at=2.0, delivered_at=2.0),),+ second: (InterceptedSubmission(1, _REJECTED, started_at=3.0, released_at=4.0, delivered_at=4.0),),+ }+ current = [first]+ read = submissions_across_contexts(lambda context: ledgers.get(context, ()), lambda: current[0])+ current[0] = second+ records = read()+ assert [r.started_at for r in records] == [1.0, 3.0]+ assert len({r.record_id for r in records}) == 2+ assert [r.record_id for r in read()] == [r.record_id for r in records]++@pytest.mark.asyncioasync def test_failure_gate_off_without_activity_tracker() -> None:# Fenced like the completed-side probe: without an activity tracker (bare callers) the failure