Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-11229 Fix request-policy classifier timeout under-claims (#6732)
Andrew Neilson01f35077977f
diff --git a/skyvern/config.py b/skyvern/config.pyindex 24e394921..a5092a0e3 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -158,7 +158,7 @@ class Settings(BaseSettings):LOG_SAMPLING_RATE: float = 1.0LOG_SAMPLING_ORG_IDS: list[str] = []COPILOT_FEASIBILITY_GATE_TIMEOUT_SECONDS: float = 12.0- COPILOT_REQUEST_POLICY_CLASSIFIER_TIMEOUT_SECONDS: float = 6.0+ COPILOT_REQUEST_POLICY_CLASSIFIER_TIMEOUT_SECONDS: float = 12.0COPILOT_TURN_INTENT_CLASSIFIER_TIMEOUT_SECONDS: float = 12.0COPILOT_COMPLETION_JUDGE_TIMEOUT_SECONDS: float = 12.0# Consecutive repair runs that make no newly-verified forward progress before thediff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.pyindex 11297ee4f..5acd8a8f9 100644--- a/skyvern/forge/sdk/copilot/request_policy.py+++ b/skyvern/forge/sdk/copilot/request_policy.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport asyncioimport jsonimport re+import timefrom dataclasses import dataclass, fieldfrom typing import Any, Literal, cast, get_argsfrom urllib.parse import urlparse@@ -43,7 +44,6 @@ _CLASSIFIER_FAILURE_KINDS = {"timeout","transient_error","provider_error",- "retry_exhausted",}_CLASSIFICATION_RESPONSE_FIELDS = {"testing_intent",@@ -620,27 +620,28 @@ def _apply_explicit_code_block_credential_draft_policy(policy: RequestPolicy, usasync def _run_request_policy_classifier(handler: Any, prompt: str) -> tuple[Any | None, str, int]:+ # Diverges from turn-intent on purpose: a retriable provider error (429/5xx) retries once+ # within the budget, while a timeout is never retried (retrying cannot beat the budget).+ deadline = time.monotonic() + settings.COPILOT_REQUEST_POLICY_CLASSIFIER_TIMEOUT_SECONDSretry_count = 0- last_failure_kind = "none"- for attempt in range(2):+ while True:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ # Only reachable after a retriable error consumed the budget before the retry ran.+ return None, "transient_error", retry_counttry:raw = await asyncio.wait_for(handler(prompt=prompt, prompt_name=PROMPT_NAME),- timeout=settings.COPILOT_REQUEST_POLICY_CLASSIFIER_TIMEOUT_SECONDS,+ timeout=remaining,)return raw, "none", retry_countexcept asyncio.TimeoutError:- last_failure_kind = "timeout" if attempt == 0 else "retry_exhausted"+ return None, "timeout", retry_countexcept Exception as exc:- if attempt == 0 and is_retriable_llm_error(exc):- last_failure_kind = "transient_error"- else:- failure_kind = "retry_exhausted" if retry_count and is_retriable_llm_error(exc) else "provider_error"- return None, failure_kind, retry_count- if attempt == 0:- retry_count += 1- continue- return None, last_failure_kind, retry_count+ if retry_count == 0 and is_retriable_llm_error(exc):+ retry_count += 1+ continue+ return None, "provider_error", retry_countasync def _classify_request(diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.pyindex c6ee768dc..7c95145da 100644--- a/tests/unit/test_copilot_agent_helpers.py+++ b/tests/unit/test_copilot_agent_helpers.py@@ -2525,17 +2525,16 @@ class TestNativeToolSurface:class TestRequestPolicyCredentialResolution:@pytest.mark.asyncio- async def test_request_policy_classifier_timeout_retries_once(self, monkeypatch) -> None:+ async def test_request_policy_classifier_timeout_does_not_retry(self, monkeypatch) -> None:from skyvern.config import settings- monkeypatch.setattr(settings, "COPILOT_REQUEST_POLICY_CLASSIFIER_TIMEOUT_SECONDS", 0.01)+ monkeypatch.setattr(settings, "COPILOT_REQUEST_POLICY_CLASSIFIER_TIMEOUT_SECONDS", 0.05)calls = 0async def handler(*, prompt: str, prompt_name: str) -> dict[str, object]:nonlocal callscalls += 1- if calls == 1:- await asyncio.sleep(0.05)+ await asyncio.sleep(0.5)return {"credential_input_kind": "none", "completion_contract": None}policy = await _classify_request(@@ -2546,10 +2545,43 @@ class TestRequestPolicyCredentialResolution:handler=handler,)- assert calls == 2+ assert calls == 1+ assert policy.classifier_status == "fallback"+ assert policy.classifier_failure_kind == "timeout"+ assert policy.classifier_retry_count == 0+ assert policy.completion_contract_status == "unknown"++ @pytest.mark.asyncio+ async def test_request_policy_classifier_slow_but_within_budget_returns_real_policy(self, monkeypatch) -> None:+ from skyvern.config import settings++ monkeypatch.setattr(settings, "COPILOT_REQUEST_POLICY_CLASSIFIER_TIMEOUT_SECONDS", 0.5)+ calls = 0++ async def handler(*, prompt: str, prompt_name: str) -> dict[str, object]:+ nonlocal calls+ calls += 1+ await asyncio.sleep(0.05)+ return {+ "credential_input_kind": "none",+ "completion_contract": "complete when the account page is visible",+ }++ policy = await _classify_request(+ user_message=(+ "Build a workflow for https://example.com/account. complete when the account page is visible"+ ),+ workflow_yaml="",+ chat_history=[],+ global_llm_context="",+ handler=handler,+ )++ assert calls == 1assert policy.classifier_status == "success"- assert policy.classifier_retry_count == 1- assert policy.completion_contract_status == "absent"+ assert policy.classifier_retry_count == 0+ assert policy.completion_contract_status == "present"+ assert policy.completion_contract@pytest.mark.asyncioasync def test_request_policy_classifier_malformed_payload_falls_back_without_retry(self) -> None:@@ -2575,7 +2607,7 @@ class TestRequestPolicyCredentialResolution:assert policy.completion_contract_status == "unknown"@pytest.mark.asyncio- async def test_request_policy_classifier_transient_provider_error_retries_once(self) -> None:+ async def test_request_policy_classifier_retries_transient_error_then_succeeds(self) -> None:class RateLimitError(Exception):__module__ = "openai"@@ -2606,6 +2638,89 @@ class TestRequestPolicyCredentialResolution:assert policy.classifier_retry_count == 1assert policy.completion_contract_status == "present"+ @pytest.mark.asyncio+ async def test_request_policy_classifier_retries_transient_error_then_falls_back(self) -> None:+ class RateLimitError(Exception):+ __module__ = "openai"++ calls = 0++ async def handler(*, prompt: str, prompt_name: str) -> dict[str, object]:+ nonlocal calls+ calls += 1+ raise RateLimitError("rate limit")++ policy = await _classify_request(+ user_message="Build a workflow for https://example.com/account.",+ workflow_yaml="",+ chat_history=[],+ global_llm_context="",+ handler=handler,+ )++ assert calls == 2+ assert policy.classifier_status == "fallback"+ assert policy.classifier_failure_kind == "provider_error"+ assert policy.classifier_retry_count == 1+ assert policy.completion_contract_status == "unknown"++ @pytest.mark.asyncio+ async def test_request_policy_classifier_non_retriable_error_does_not_retry(self) -> None:+ calls = 0++ async def handler(*, prompt: str, prompt_name: str) -> dict[str, object]:+ nonlocal calls+ calls += 1+ raise ValueError("bad request")++ policy = await _classify_request(+ user_message="Build a workflow for https://example.com/account.",+ workflow_yaml="",+ chat_history=[],+ global_llm_context="",+ handler=handler,+ )++ assert calls == 1+ assert policy.classifier_status == "fallback"+ assert policy.classifier_failure_kind == "provider_error"+ assert policy.classifier_retry_count == 0+ assert policy.completion_contract_status == "unknown"++ @pytest.mark.asyncio+ async def test_request_policy_classifier_transient_error_exhausting_budget_labels_transient(+ self, monkeypatch+ ) -> None:+ from skyvern.forge.sdk.copilot import request_policy as rp++ class RateLimitError(Exception):+ __module__ = "openai"++ # deadline calc, then iteration-1 remaining; every later call reads past the deadline so the+ # retry never starts and the budget-exhaustion path labels the prior retriable error.+ clock = iter([1000.0, 1000.0])+ monkeypatch.setattr(rp.time, "monotonic", lambda: next(clock, 1_000_000.0))+ calls = 0++ async def handler(*, prompt: str, prompt_name: str) -> dict[str, object]:+ nonlocal calls+ calls += 1+ raise RateLimitError("rate limit")++ policy = await _classify_request(+ user_message="Build a workflow for https://example.com/account.",+ workflow_yaml="",+ chat_history=[],+ global_llm_context="",+ handler=handler,+ )++ assert calls == 1+ assert policy.classifier_status == "fallback"+ assert policy.classifier_failure_kind == "transient_error"+ assert policy.classifier_retry_count == 1+ assert policy.completion_contract_status == "unknown"+@pytest.mark.asyncioasync def test_missing_user_supplied_credential_ids_ask_for_clarification(self, monkeypatch) -> None:from skyvern.forge.sdk.copilot import request_policy as policy_module