Skip to content

Automate browser based workflows with AI

Merge the retention pod weekly report into the daily report (SKY-18314) (#8921)

Shuchang Zhenge4a9145287fd
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index 2adeeab05..7f023be6b 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -2174,13 +2174,15 @@ async def run_with_enforcement(
**runner_kwargs: Any,
) -> RunResultStreaming:
"""Run agent with enforcement nudges, preserving conversation history."""
- # A retry after a failed drain would otherwise restart the full tool set on a fresh clock.
+ # A retry after a failed drain would otherwise restart the full tool set.
if ctx.budget_expiry_state.drain_attempted:
raise MaxTurnsExceeded("Budget drain already attempted")
session = runner_kwargs.pop("session", None)
copilot_config = runner_kwargs.pop("copilot_config", None) or CopilotConfig()
current_input: str | list = initial_input
- start_time = time.monotonic()
+ # A fallback or model-lookup retry resumes the turn's clock, so the turn keeps one deadline and one backstop.
+ resumed = ctx.copilot_run_start_monotonic is not None
+ start_time = ctx.copilot_run_start_monotonic if resumed else time.monotonic()
ctx.copilot_run_start_monotonic = start_time
install_pending_operation_slot(ctx)
iteration = 0
@@ -2193,7 +2195,7 @@ async def run_with_enforcement(
# the agent keeps running so the reply can be persisted to the
# chat history on the server side (see SKY-8986).
elapsed = _elapsed_run_seconds(ctx, start_time)
- if iteration > 0 and elapsed >= TOTAL_TIMEOUT_SECONDS:
+ if (iteration > 0 or resumed) and elapsed >= TOTAL_TIMEOUT_SECONDS:
_mark_copilot_total_timeout(ctx, elapsed_seconds=elapsed, iteration=iteration)
return await _run_budget_drain(
agent,
diff --git a/skyvern/forge/sdk/copilot/model_telemetry.py b/skyvern/forge/sdk/copilot/model_telemetry.py
index 1f8602550..b8f6ad291 100644
--- a/skyvern/forge/sdk/copilot/model_telemetry.py
+++ b/skyvern/forge/sdk/copilot/model_telemetry.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import asyncio
import contextlib
import contextvars
import json
@@ -31,6 +32,7 @@ from litellm.litellm_core_utils.core_helpers import safe_deep_copy
from litellm.types.llms.openai import ResponsesAPIResponse
from litellm.types.utils import ModelResponse as LiteLLMModelResponse
from litellm.types.utils import Usage as LiteLLMUsage
+from litellm.utils import CustomStreamWrapper
from openai import AsyncStream, omit
from openai.types.chat import ChatCompletionChunk
from openai.types.completion_usage import CompletionUsage
@@ -58,6 +60,9 @@ from skyvern.forge.sdk.copilot.pending_operation import pending_operation
LOG = structlog.get_logger()
_DATED_MODEL_SUFFIX = re.compile(r"-\d{4}-\d{2}-\d{2}$")
+# Anthropic sends each tool argument in one piece after a silence as long as its generation, so this must stay
+# above the time to write the largest argument (~29k tokens at the slowest observed Sonnet rate).
+_STREAM_PROGRESS_TIMEOUT_SECONDS = 300.0
@dataclass(frozen=True, slots=True)
@@ -342,10 +347,73 @@ def _capture_responses_stop_metadata(telemetry: CopilotModelCallTelemetry, respo
telemetry.content_filter = False
-class _UsageCapturingStream:
+def _is_stream_progress(chunk: ChatCompletionChunk) -> bool:
+ for choice in chunk.choices:
+ delta = choice.delta
+ if choice.finish_reason or delta.content or delta.tool_calls:
+ return True
+ # Keep-alives arrive as empty deltas, and an empty thinking delta is not output. LiteLLM deletes unset
+ # reasoning fields from its Delta, so they are read with getattr.
+ if getattr(delta, "reasoning_content", None):
+ return True
+ for block in getattr(delta, "thinking_blocks", None) or ():
+ if block.get("thinking") or block.get("signature") or block.get("data"):
+ return True
+ return False
+
+
+class _ProgressGuardedStream:
def __init__(
self,
stream: AsyncStream[ChatCompletionChunk],
+ model: str,
+ telemetry: CopilotModelCallTelemetry | None,
+ ) -> None:
+ self._stream = stream
+ self._iterator = stream.__aiter__()
+ self._model = model
+ self._telemetry = telemetry
+ self._last_progress = asyncio.get_running_loop().time()
+ self._made_progress = False
+ self._chunks_seen = 0
+
+ def __aiter__(self) -> _ProgressGuardedStream:
+ return self
+
+ async def __anext__(self) -> ChatCompletionChunk:
+ timeout = asyncio.timeout_at(self._last_progress + _STREAM_PROGRESS_TIMEOUT_SECONDS)
+ try:
+ async with timeout:
+ chunk = await self._iterator.__anext__()
+ except TimeoutError:
+ if not timeout.expired():
+ raise
+ served_provider = self._telemetry.served_provider if self._telemetry is not None else None
+ if served_provider is None and isinstance(self._stream, CustomStreamWrapper):
+ served_provider = self._stream.custom_llm_provider
+ LOG.warning(
+ "Copilot model stream made no progress",
+ model=self._model,
+ served_provider=served_provider,
+ made_progress=self._made_progress,
+ chunks_seen=self._chunks_seen,
+ )
+ raise litellm.Timeout(
+ f"Copilot model stream made no progress for {_STREAM_PROGRESS_TIMEOUT_SECONDS:g} s",
+ model=self._model,
+ llm_provider=served_provider or "",
+ ) from None
+ self._chunks_seen += 1
+ if _is_stream_progress(chunk):
+ self._made_progress = True
+ self._last_progress = asyncio.get_running_loop().time()
+ return chunk
+
+
+class _UsageCapturingStream:
+ def __init__(
+ self,
+ stream: AsyncIterator[ChatCompletionChunk],
telemetry: CopilotModelCallTelemetry,
) -> None:
self._stream = stream
@@ -710,9 +778,10 @@ class CopilotLitellmModel(LitellmModel):
return result
response, response_stream = result
+ guarded_stream = _ProgressGuardedStream(response_stream, self.model, telemetry)
if telemetry is None:
- return result
- capturing_stream = _UsageCapturingStream(response_stream, telemetry)
+ return response, cast(AsyncStream[ChatCompletionChunk], guarded_stream)
+ capturing_stream = _UsageCapturingStream(guarded_stream, telemetry)
return response, cast(AsyncStream[ChatCompletionChunk], capturing_stream)
async def _fetch_explicit_responses(
diff --git a/tests/unit/test_copilot_budget_drain.py b/tests/unit/test_copilot_budget_drain.py
index 8d33f27ad..16d6559c9 100644
--- a/tests/unit/test_copilot_budget_drain.py
+++ b/tests/unit/test_copilot_budget_drain.py
@@ -14,6 +14,7 @@ from agents.exceptions import MaxTurnsExceeded
from agents.run_config import RunConfig
from litellm.exceptions import NotFoundError as LiteLLMNotFoundError
from litellm.exceptions import RateLimitError as LiteLLMRateLimitError
+from litellm.exceptions import Timeout as LiteLLMTimeout
from skyvern.forge import app as forge_app
from skyvern.forge.sdk.copilot import agent as agent_module
@@ -995,3 +996,61 @@ async def test_stop_still_cancels_the_active_build_test(
assert owned.row.status == "canceled"
assert harness["executor_cancelled"] is not dispatch_to_worker
harness["clear"].assert_awaited_once()
+
+
[email protected]("seconds_at_cut", [300.0, TOTAL_TIMEOUT_SECONDS + 50.0])
+async def test_a_model_call_cut_mid_turn_leaves_the_fallback_on_the_turns_clock(
+ monkeypatch: pytest.MonkeyPatch, seconds_at_cut: float
+) -> None:
+ offset = 0.0
+ attempts: list[dict[str, Any]] = []
+
+ def run_streamed(agent: Agent, **_kwargs: Any) -> MagicMock:
+ attempts.append({"model": str(agent.model), "tools": {tool.name for tool in agent.tools}})
+ return _result(json.dumps({"type": "REPLY", "user_response": "Here is where things stand."}))
+
+ async def stream_to_sse(_result: Any, _stream: Any, ctx: Any) -> None:
+ nonlocal offset
+ attempts[-1]["drained"] = ctx.budget_expiry_state.drain_active
+ attempts[-1]["allowance"] = ctx.model_stream_deadline.when() - asyncio.get_running_loop().time()
+ if len(attempts) == 1:
+ offset = seconds_at_cut
+ raise LiteLLMTimeout("Copilot model stream made no progress", model="m", llm_provider="anthropic")
+
+ stub_copilot_agent_loop(monkeypatch, run_with_enforcement)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.enforcement.time", SimpleNamespace(monotonic=lambda: time.monotonic() + offset)
+ )
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.Runner.run_streamed", run_streamed)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.streaming_adapter.stream_to_sse", stream_to_sse)
+
+ result = await agent_module.run_copilot_agent(
+ stream=MagicMock(send=AsyncMock(return_value=True)),
+ organization_id="org-1",
+ chat_request=WorkflowCopilotChatRequest(
+ message="build it",
+ workflow_id="wf-1",
+ workflow_permanent_id="wfp-1",
+ workflow_copilot_chat_id="chat-1",
+ workflow_yaml="",
+ ),
+ chat_history=[],
+ global_llm_context=None,
+ llm_api_handler=SimpleNamespace(llm_key="PRIMARY"),
+ raw_secret_safety_handler=AsyncMock(
+ return_value={"version": "1", "state": "clean", "handling": "none", "citations": []}
+ ),
+ api_key="sk-test",
+ config=CopilotConfig(fallback_llm_key="SECONDARY"),
+ )
+
+ budget_spent = seconds_at_cut >= TOTAL_TIMEOUT_SECONDS
+ (_, fallback) = attempts
+ assert fallback["model"] == "model-SECONDARY"
+ assert fallback["drained"] is budget_spent
+ assert ("update_workflow" in fallback["tools"]) is not budget_spent
+ assert fallback["allowance"] < TOTAL_TIMEOUT_SECONDS + HARD_BACKSTOP_ALLOWANCE_SECONDS - seconds_at_cut + 5
+ assert result.user_response == "Here is where things stand."
+ assert result.turn_outcome is not None
+ assert result.turn_outcome.budget_expired is budget_spent
diff --git a/tests/unit/test_copilot_model_telemetry.py b/tests/unit/test_copilot_model_telemetry.py
index f1fdcfa98..b40248f59 100644
--- a/tests/unit/test_copilot_model_telemetry.py
+++ b/tests/unit/test_copilot_model_telemetry.py
@@ -23,7 +23,7 @@ from agents.models.interface import ModelTracing
from litellm.integrations.anthropic_cache_control_hook import AnthropicCacheControlHook
from litellm.litellm_core_utils.fallback_utils import async_completion_with_fallbacks
from litellm.llms.vertex_ai.gemini.transformation import _gemini_convert_messages_with_history
-from litellm.types.llms.openai import ResponsesAPIResponse
+from litellm.types.llms.openai import GenericEvent, ResponsesAPIResponse
from litellm.types.utils import Delta
from litellm.types.utils import ModelResponse as LiteLLMModelResponse
from litellm.types.utils import ModelResponseStream, StreamingChoices, Usage
@@ -2150,6 +2150,73 @@ async def test_a_stream_that_drops_midway_raises_the_typed_error_copilot_retries
assert is_retriable_llm_error(raised.value) is True
+async def _silent_after_one_chunk() -> AsyncIterator[ChatCompletionChunk]:
+ yield _stream_chunks()[0]
+ await asyncio.Event().wait()
+
+
+async def _keepalives_forever() -> AsyncIterator[GenericEvent]:
+ while True:
+ await asyncio.sleep(0.05)
+ yield GenericEvent(type="keepalive")
+
+
+async def _slow_steady_chunks() -> AsyncIterator[ChatCompletionChunk]:
+ for _ in range(20):
+ await asyncio.sleep(0.05)
+ yield _stream_chunks()[0]
+ yield _stream_chunks()[1]
+
+
+ ("model_name", "upstream", "stalls"),
+ [
+ ("anthropic/claude-sonnet-5-5", _silent_after_one_chunk, True),
+ ("azure/gpt-5.6-terra", _keepalives_forever, True),
+ ("anthropic/claude-sonnet-5-5", _slow_steady_chunks, False),
+ ],
+)
+async def test_a_stream_without_progress_is_cut_as_a_retriable_timeout_but_slow_steady_output_is_not(
+ monkeypatch: pytest.MonkeyPatch,
+ model_name: str,
+ upstream: Callable[[], AsyncIterator[Any]],
+ stalls: bool,
+) -> None:
+ async def fake_call(**_kwargs: object) -> AsyncIterator[Any]:
+ return upstream()
+
+ monkeypatch.setattr(model_telemetry_module, "_STREAM_PROGRESS_TIMEOUT_SECONDS", 0.5)
+ monkeypatch.setattr("litellm.acompletion", fake_call)
+ monkeypatch.setattr("litellm.aresponses", fake_call)
+ model_settings = (
+ _gpt_route_settings(model_name, []) if model_name.startswith("azure/") else ModelSettings(include_usage=True)
+ )
+ events: list[Any] = []
+ with pytest.raises(litellm.Timeout) if stalls else contextlib.nullcontext() as raised:
+ async with asyncio.timeout(5):
+ async for event in CopilotLitellmModel(
+ model=model_name,
+ base_url=_AZURE_BASE if model_name.startswith("azure/") else None,
+ api_key="test-key",
+ next_model_call_index=lambda: 1,
+ ).stream_response(
+ system_instructions=_CACHED_PROMPT,
+ input=_GPT_TOOL_HISTORY,
+ model_settings=model_settings,
+ tools=[_lookup_number],
+ output_schema=None,
+ handoffs=[],
+ tracing=ModelTracing.DISABLED,
+ ):
+ events.append(event)
+
+ if stalls:
+ assert is_retriable_llm_error(raised.value) is True
+ else:
+ assert events[-1].type == "response.completed"
+
+
@pytest.mark.asyncio
async def test_every_failed_hop_is_logged_and_an_exhausted_chain_raises_litellms_fallback_error(
monkeypatch: pytest.MonkeyPatch,