Skip to content

Automate browser based workflows with AI

Record which operation a copilot turn is awaiting and name it at deadline (SKY-14521) (#8240)

Andrew Neilson486c8975e986
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index 69a516cc8..dafd2c280 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -67,6 +67,11 @@ from skyvern.forge.sdk.copilot.output_utils import (
extract_final_text,
parse_final_response,
)
+from skyvern.forge.sdk.copilot.pending_operation import (
+ install_pending_operation_slot,
+ pending_operation,
+ pending_operation_fields,
+)
from skyvern.forge.sdk.copilot.request_policy import (
CompletionCriterion,
RequestPolicy,
@@ -536,6 +541,7 @@ def _mark_copilot_total_timeout(ctx: Any, *, elapsed_seconds: float, iteration:
"copilot_turn_deadline_expired",
elapsed_seconds=round(elapsed_seconds, 3),
iteration=iteration,
+ **pending_operation_fields(),
)
@@ -576,6 +582,7 @@ def _record_copilot_cancellation(ctx: Any, start_time: float, iteration: int) ->
elapsed_seconds=round(elapsed, 3),
iteration=iteration,
deadline_exceeded=ctx.copilot_total_timeout_exceeded is True,
+ **pending_operation_fields(),
)
except Exception:
LOG.exception("Failed to record a copilot turn cancellation", iteration=iteration)
@@ -1139,10 +1146,11 @@ async def _recover_from_context_overflow(session: Any, current_input: str | list
stripped_input = current_input
if session is not None:
- all_items = await session.get_items()
- pruned = aggressive_prune(all_items)
- await session.clear_session()
- await session.add_items(pruned)
+ with pending_operation("session.prune"):
+ all_items = await session.get_items()
+ pruned = aggressive_prune(all_items)
+ await session.clear_session()
+ await session.add_items(pruned)
return stripped_input, stripped_any
if isinstance(stripped_input, list):
return stripped_input, stripped_any
@@ -1225,15 +1233,16 @@ async def _run_streamed_with_deadline(
"""
elapsed = _elapsed_run_seconds(ctx, start_time)
remaining = max(MIN_DEADLINE_REMAINING_SECONDS, TOTAL_TIMEOUT_SECONDS - elapsed)
- result = Runner.run_streamed(agent, input=current_input, context=ctx, session=session, **runner_kwargs)
- try:
+ with pending_operation("turn.stream", span=True):
+ result = Runner.run_streamed(agent, input=current_input, context=ctx, session=session, **runner_kwargs)
try:
- await asyncio.wait_for(streaming_adapter.stream_to_sse(result, tracked_stream, ctx), timeout=remaining)
- finally:
- _accumulate_usage(result, ctx)
- except TimeoutError:
- _mark_copilot_total_timeout(ctx, elapsed_seconds=_elapsed_run_seconds(ctx, start_time), iteration=iteration)
- raise CopilotTotalTimeoutError() from None
+ try:
+ await asyncio.wait_for(streaming_adapter.stream_to_sse(result, tracked_stream, ctx), timeout=remaining)
+ finally:
+ _accumulate_usage(result, ctx)
+ except TimeoutError:
+ _mark_copilot_total_timeout(ctx, elapsed_seconds=_elapsed_run_seconds(ctx, start_time), iteration=iteration)
+ raise CopilotTotalTimeoutError() from None
return result
@@ -1755,6 +1764,7 @@ async def run_with_enforcement(
current_input: str | list = initial_input
start_time = time.monotonic()
ctx.copilot_run_start_monotonic = start_time
+ install_pending_operation_slot(ctx)
iteration = 0
pending_recovery_nudge: str | None = None
diff --git a/skyvern/forge/sdk/copilot/mcp_adapter.py b/skyvern/forge/sdk/copilot/mcp_adapter.py
index 409a3b361..ddae6687a 100644
--- a/skyvern/forge/sdk/copilot/mcp_adapter.py
+++ b/skyvern/forge/sdk/copilot/mcp_adapter.py
@@ -40,6 +40,7 @@ from skyvern.forge.sdk.copilot.enforcement import requested_output_paths_for_der
from skyvern.forge.sdk.copilot.hooks import _copilot_log_fields
from skyvern.forge.sdk.copilot.loop_detection import record_tool_step_result_for_ctx
from skyvern.forge.sdk.copilot.output_utils import mark_mcp_result_untrusted_for_llm, sanitize_tool_result_for_llm
+from skyvern.forge.sdk.copilot.pending_operation import pending_operation
from skyvern.forge.sdk.copilot.request_policy import RequestPolicy
from skyvern.forge.sdk.copilot.runtime import (
AgentContext,
@@ -912,7 +913,8 @@ class SkyvernOverlayMCPServer(MCPServer):
) -> CallToolResult:
propagated_error: BaseException
try:
- return await self._call_tool(tool_name, arguments, meta)
+ with pending_operation(f"mcp.call_tool:{tool_name}"):
+ return await self._call_tool(tool_name, arguments, meta)
except BaseException as exc:
if not app.AGENT_FUNCTION.prepare_codeblock_control_flow_exception(exc):
LOG.warning("MCP tool dispatch failed")
diff --git a/skyvern/forge/sdk/copilot/model_telemetry.py b/skyvern/forge/sdk/copilot/model_telemetry.py
index b2a853051..b711406ae 100644
--- a/skyvern/forge/sdk/copilot/model_telemetry.py
+++ b/skyvern/forge/sdk/copilot/model_telemetry.py
@@ -44,6 +44,7 @@ from skyvern.forge.sdk.copilot.cache_envelope import (
ExplicitCacheEnvelope,
build_explicit_cache_envelope,
)
+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}$")
@@ -181,7 +182,8 @@ def model_call_telemetry_scope(
telemetry = CopilotModelCallTelemetry(model_call_index=model_call_index)
token = _current_model_call_telemetry.set(telemetry)
try:
- yield telemetry
+ with pending_operation(f"model.call:{model}" if model else "model.call"):
+ yield telemetry
finally:
try:
if model is not None:
diff --git a/skyvern/forge/sdk/copilot/pending_operation.py b/skyvern/forge/sdk/copilot/pending_operation.py
new file mode 100644
index 000000000..194280a05
--- /dev/null
+++ b/skyvern/forge/sdk/copilot/pending_operation.py
@@ -0,0 +1,198 @@
+"""Names the operation a copilot turn is waiting on, for the log emitters only. Nothing branches on this state."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import contextvars
+import itertools
+import time
+from collections.abc import Iterator
+from dataclasses import dataclass, field
+from typing import Any
+
+import structlog
+
+LOG = structlog.get_logger()
+
+PENDING_OPERATION_LOG_THRESHOLD_SECONDS = 30.0
+
+CORRELATION_ATTRS = ("workflow_permanent_id", "turn_id", "workflow_copilot_chat_id")
+
+
+@dataclass(frozen=True)
+class PendingOperation:
+ name: str
+ started_monotonic: float
+ state: str
+ duration: float | None = None
+ span: bool = False
+
+ def outstanding_seconds(self, now: float) -> float:
+ """How long this operation ran, or has been running — never the age of a finished record."""
+ return self.duration if self.duration is not None else now - self.started_monotonic
+
+
+@dataclass
+class _TurnOperations:
+ open: dict[int, PendingOperation] = field(default_factory=dict)
+ last_unwound: PendingOperation | None = None
+ log_fields: dict[str, str] = field(default_factory=dict)
+
+
+_turn_operations: contextvars.ContextVar[_TurnOperations | None] = contextvars.ContextVar(
+ "_copilot_turn_operations",
+ default=None,
+)
+
+_operation_ids = itertools.count()
+
+
+def install_pending_operation_slot(ctx: Any = None) -> None:
+ """Must run in the task that starts the turn: the agents SDK runs model and tool calls in child
+ tasks, which copy the context but share this object, so a slot installed deeper is invisible to
+ the turn's own log emitters."""
+ try:
+ log_fields = _correlation_fields(ctx)
+ except Exception:
+ # An uncorrelated slot beats inheriting the previous turn's, which would file this turn's
+ # scopes under the previous turn's ids.
+ log_fields = {}
+ LOG.warning("copilot_pending_operation_correlation_failed")
+ _turn_operations.set(_TurnOperations(log_fields=log_fields))
+
+
+def _correlation_fields(ctx: Any) -> dict[str, str]:
+ """The ids that join a fingerprint to its request, read once per turn. Non-string values are
+ dropped: a bare ``MagicMock`` ctx returns a Mock from ``getattr`` rather than the default, and a
+ Mock is not a correlation key."""
+ fields: dict[str, str] = {}
+ for attr in CORRELATION_ATTRS:
+ value = getattr(ctx, attr, None)
+ if isinstance(value, str) and value:
+ fields[attr] = value
+ return fields
+
+
+def pending_operation(name: str, *, span: bool = False) -> Iterator[None]:
+ """Records ``name`` as the operation being awaited for the duration of the block.
+
+ ``span=True`` marks a scope that wraps a whole turn iteration rather than one operation. Such a
+ scope is always outstanding and always over the threshold, so it neither logs a slow line nor
+ claims the fingerprint while any real operation is known.
+ """
+ operations = _turn_operations.get()
+ if operations is None:
+ yield
+ return
+ if span:
+ _discard_abandoned(operations)
+ operation_id = next(_operation_ids)
+ operations.open[operation_id] = PendingOperation(
+ name=name,
+ started_monotonic=time.monotonic(),
+ state="open",
+ span=span,
+ )
+ try:
+ yield
+ except asyncio.CancelledError:
+ _retire(operations, operation_id, "unwound_by_cancellation")
+ raise
+ except BaseException:
+ _retire(operations, operation_id, "unwound_by_error")
+ raise
+ _retire(operations, operation_id, "returned")
+
+
+def _discard_abandoned(operations: _TurnOperations) -> None:
+ """Drops leaf scopes left open by a previous iteration.
+
+ A scope wrapping an async generator's ``yield`` never exits if the consumer walks away without
+ finalising it — ``LitellmModel.stream_response`` is one — and the record would then outrank
+ every later operation for the rest of the turn, naming a call that stopped minutes earlier as
+ the one still running. Leaves live inside an iteration, so any still open when the next one
+ starts was abandoned.
+ """
+ for operation_id, record in list(operations.open.items()):
+ if not record.span:
+ del operations.open[operation_id]
+
+
+def _retire(operations: _TurnOperations, operation_id: int, state: str) -> None:
+ """Moves a finished operation out of ``open`` and into the fallback slot the emitters read when
+ nothing is open — ``wait_for`` unwinds every inner scope before the deadline emitter runs, and
+ the blocked one unwinds last, so the most recently retired scope is the one that was stuck."""
+ record = operations.open.pop(operation_id, None)
+ if record is None:
+ return
+ duration = time.monotonic() - record.started_monotonic
+ retired = PendingOperation(
+ name=record.name,
+ started_monotonic=record.started_monotonic,
+ state=state,
+ duration=duration,
+ span=record.span,
+ )
+ if not record.span:
+ operations.last_unwound = retired
+ if not record.span and duration >= PENDING_OPERATION_LOG_THRESHOLD_SECONDS:
+ try:
+ LOG.warning(
+ "copilot_pending_operation_slow",
+ pending_operation=record.name,
+ pending_operation_started_monotonic=round(record.started_monotonic, 3),
+ pending_operation_seconds=round(duration, 3),
+ pending_operation_state=state,
+ **operations.log_fields,
+ )
+ except Exception:
+ pass
+
+
+def _best_candidate(operations: _TurnOperations) -> PendingOperation | None:
+ """Which scope best explains where the turn is.
+
+ An operation still outstanding outranks one that already finished, so a fast sibling that
+ started later and returned cannot blame itself for a hang — the SDK cancels concurrent tool
+ tasks without awaiting their cleanup, so the one that hung can still be open here. Among equals
+ the latest start wins, which for nesting is the innermost scope. Otherwise the scope that
+ retired most recently, which during a ``wait_for`` unwind is the one that was blocked. The
+ whole-iteration span is the last resort: it is always open, so ranking it with the rest would
+ let it mask every real answer.
+ """
+ open_operations = [record for record in operations.open.values() if not record.span]
+ if open_operations:
+ return max(open_operations, key=lambda record: record.started_monotonic)
+ if operations.last_unwound is not None:
+ return operations.last_unwound
+ spans = list(operations.open.values())
+ return max(spans, key=lambda record: record.started_monotonic) if spans else None
+
+
+def pending_operation_fields() -> dict[str, str | float | int]:
+ """The operation that best explains where the turn is — see ``_best_candidate``.
+
+ ``pending_operation_seconds`` is always that operation's own outstanding time, so a scope that
+ finished early in a long turn cannot read as though it hung for the whole budget.
+
+ Never raises, so a failed read cannot change what the emitters do.
+ """
+ try:
+ operations = _turn_operations.get()
+ if operations is None:
+ return {}
+ latest = _best_candidate(operations)
+ if latest is None:
+ return {}
+ return {
+ "pending_operation": latest.name,
+ "pending_operation_started_monotonic": round(latest.started_monotonic, 3),
+ "pending_operation_seconds": round(latest.outstanding_seconds(time.monotonic()), 3),
+ "pending_operation_state": latest.state,
+ "pending_operation_open_count": len(operations.open),
+ **operations.log_fields,
+ }
+ except Exception:
+ return {}
diff --git a/skyvern/forge/sdk/copilot/tools/__init__.py b/skyvern/forge/sdk/copilot/tools/__init__.py
index fe61d7db1..2dcadf606 100644
--- a/skyvern/forge/sdk/copilot/tools/__init__.py
+++ b/skyvern/forge/sdk/copilot/tools/__init__.py
@@ -30,6 +30,7 @@ from skyvern.forge.sdk.copilot.output_utils import (
from skyvern.forge.sdk.copilot.output_utils import (
sanitize_tool_result_for_llm,
)
+from skyvern.forge.sdk.copilot.pending_operation import pending_operation
from skyvern.forge.sdk.copilot.screenshot_utils import enqueue_screenshot_from_result
from skyvern.forge.sdk.copilot.secret_scrub import scrub_secrets_from_structure
from skyvern.forge.sdk.copilot.tracing_setup import copilot_span
@@ -779,13 +780,14 @@ async def run_blocks_tool(
copilot_ctx,
),
):
- result = await _run_blocks_and_collect_debug(
- arguments,
- copilot_ctx,
- labels_to_execute=labels_to_execute,
- block_outputs_to_seed=block_outputs_to_seed,
- frontier_start_label=frontier_start_label,
- )
+ with pending_operation("tool.run_blocks_and_collect_debug"):
+ result = await _run_blocks_and_collect_debug(
+ arguments,
+ copilot_ctx,
+ labels_to_execute=labels_to_execute,
+ block_outputs_to_seed=block_outputs_to_seed,
+ frontier_start_label=frontier_start_label,
+ )
await _verify_and_record_run_blocks_result(copilot_ctx, result, handler_start)
record_tool_step_result_for_ctx(copilot_ctx, "run_blocks_and_collect_debug", arguments, result)
_record_diagnosis_repair_contract(
@@ -1031,13 +1033,14 @@ async def _run_updated_workflow_blocks(
copilot_ctx,
),
):
- run_result = await _run_blocks_and_collect_debug(
- {"block_labels": block_labels, "parameters": parameters},
- copilot_ctx,
- labels_to_execute=labels_to_execute,
- block_outputs_to_seed=block_outputs_to_seed,
- frontier_start_label=frontier_start_label,
- )
+ with pending_operation("tool.update_and_run_blocks"):
+ run_result = await _run_blocks_and_collect_debug(
+ {"block_labels": block_labels, "parameters": parameters},
+ copilot_ctx,
+ labels_to_execute=labels_to_execute,
+ block_outputs_to_seed=block_outputs_to_seed,
+ frontier_start_label=frontier_start_label,
+ )
await _verify_and_record_run_blocks_result(copilot_ctx, run_result, handler_start)
carry_author_time_findings(update_result, run_result)
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, run_result)
diff --git a/tests/unit/test_cdp_download_interceptor.py b/tests/unit/test_cdp_download_interceptor.py
index 2eabef47a..f1e4fba7d 100644
--- a/tests/unit/test_cdp_download_interceptor.py
+++ b/tests/unit/test_cdp_download_interceptor.py
@@ -1229,7 +1229,7 @@ class TestCDPDownloadInterceptorProxyAuth:
stalled_session.detach.side_effect = stalled_detach
binding = asyncio.create_task(replacement.bind_to_context(browser_context))
try:
- await asyncio.wait_for(detach_started.wait(), timeout=0.1)
+ await asyncio.wait_for(detach_started.wait(), timeout=5)
await asyncio.wait_for(binding, timeout=0.7)
await asyncio.wait_for(detach_cancelled.wait(), timeout=0.1)
diff --git a/tests/unit/test_copilot_model_telemetry.py b/tests/unit/test_copilot_model_telemetry.py
index 75a96583e..5b89ba473 100644
--- a/tests/unit/test_copilot_model_telemetry.py
+++ b/tests/unit/test_copilot_model_telemetry.py
@@ -1,9 +1,12 @@
from __future__ import annotations
import asyncio
+import contextlib
import json
+from collections.abc import AsyncIterator, Iterator
from types import SimpleNamespace
from typing import Any, cast
+from unittest.mock import MagicMock
import pytest
from agents import ModelSettings, function_tool
@@ -15,6 +18,7 @@ from litellm.types.utils import ModelResponse as LiteLLMModelResponse
from litellm.types.utils import ModelResponseStream, StreamingChoices, Usage
from openai import AsyncStream
from openai.types.chat import ChatCompletionChunk
+from structlog.testing import capture_logs
from skyvern.forge.sdk.copilot import model_telemetry as model_telemetry_module
from skyvern.forge.sdk.copilot.cache_envelope import CacheableSystemInstructions
@@ -23,6 +27,21 @@ from skyvern.forge.sdk.copilot.model_telemetry import (
current_model_call_telemetry,
model_call_telemetry_scope,
)
+from skyvern.forge.sdk.copilot.pending_operation import (
+ _turn_operations,
+ install_pending_operation_slot,
+ pending_operation,
+ pending_operation_fields,
+)
+
+
[email protected](autouse=True)
+def _clear_pending_operation_slot() -> Iterator[None]:
+ """Tests here install a turn slot directly; without this it leaks into every later test in the
+ worker, and the suite runs under pytest-randomly."""
+ token = _turn_operations.set(None)
+ yield
+ _turn_operations.reset(token)
@function_tool
@@ -713,3 +732,211 @@ def test_otel_provider_name_detects_azure_hosts(base_url: str) -> None:
def test_otel_provider_name_rejects_lookalike_azure_urls(base_url: str) -> None:
# A bare substring check labelled all of these as Azure; the host check must not.
assert model_telemetry_module._otel_provider_name("some-model", base_url) is None
+
+
+def test_model_call_scope_names_the_open_operation_and_retires_it_on_exit() -> None:
+ install_pending_operation_slot()
+
+ with model_call_telemetry_scope(0, model="gpt-5.6-sol"):
+ while_open = pending_operation_fields()
+
+ after_exit = pending_operation_fields()
+
+ assert while_open["pending_operation"] == "model.call:gpt-5.6-sol"
+ assert isinstance(while_open["pending_operation_started_monotonic"], float)
+ assert while_open["pending_operation_state"] == "open"
+ assert while_open["pending_operation_open_count"] == 1
+ assert after_exit["pending_operation"] == "model.call:gpt-5.6-sol"
+ assert after_exit["pending_operation_state"] == "returned"
+ assert after_exit["pending_operation_open_count"] == 0
+
+
+def test_the_innermost_scope_wins_over_an_outer_one_that_is_still_open() -> None:
+ install_pending_operation_slot()
+
+ outer = pending_operation("turn.stream", span=True)
+ inner = pending_operation("mcp.call_tool:run_block")
+ outer.__enter__()
+ inner.__enter__()
+ while_both_open = pending_operation_fields()
+ inner.__exit__(None, None, None)
+ after_inner_returned = pending_operation_fields()
+ outer.__exit__(None, None, None)
+
+ assert while_both_open["pending_operation"] == "mcp.call_tool:run_block"
+ assert after_inner_returned["pending_operation"] == "mcp.call_tool:run_block"
+ assert after_inner_returned["pending_operation_state"] == "returned"
+ assert after_inner_returned["pending_operation_open_count"] == 1
+
+
+def test_a_scope_that_exits_by_exception_is_never_reported_as_still_open() -> None:
+ install_pending_operation_slot()
+
+ with pytest.raises(RuntimeError):
+ with pending_operation("mcp.call_tool:run_block"):
+ raise RuntimeError("tool blew up")
+
+ fields = pending_operation_fields()
+ assert fields["pending_operation"] == "mcp.call_tool:run_block"
+ assert fields["pending_operation_state"] == "unwound_by_error"
+ assert fields["pending_operation_open_count"] == 0
+
+
+def test_a_scope_slower_than_the_threshold_logs_itself_once(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.pending_operation.PENDING_OPERATION_LOG_THRESHOLD_SECONDS",
+ 0.0,
+ )
+ install_pending_operation_slot()
+
+ with capture_logs() as logs:
+ with pending_operation("mcp.call_tool:run_block"):
+ pass
+
+ slow = [entry for entry in logs if entry.get("event") == "copilot_pending_operation_slow"]
+ assert len(slow) == 1
+ assert slow[0]["pending_operation"] == "mcp.call_tool:run_block"
+ assert isinstance(slow[0]["pending_operation_started_monotonic"], float)
+
+
+def test_a_fingerprint_carries_the_turn_identifiers_that_join_it_to_its_request(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.pending_operation.PENDING_OPERATION_LOG_THRESHOLD_SECONDS",
+ 0.0,
+ )
+ install_pending_operation_slot(
+ SimpleNamespace(
+ workflow_permanent_id="wpid_1",
+ turn_id="turn_1",
+ workflow_copilot_chat_id="wcc_1",
+ )
+ )
+
+ with capture_logs() as logs:
+ with pending_operation("mcp.call_tool:run_block"):
+ fields = pending_operation_fields()
+
+ slow = [entry for entry in logs if entry.get("event") == "copilot_pending_operation_slow"]
+ assert len(slow) == 1
+ for key, value in (
+ ("workflow_permanent_id", "wpid_1"),
+ ("turn_id", "turn_1"),
+ ("workflow_copilot_chat_id", "wcc_1"),
+ ):
+ assert slow[0][key] == value
+ assert fields[key] == value
+
+
+def test_a_context_carrying_no_real_identifiers_adds_no_correlation_keys(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.pending_operation.PENDING_OPERATION_LOG_THRESHOLD_SECONDS",
+ 0.0,
+ )
+ install_pending_operation_slot(cast(Any, MagicMock()))
+
+ with pending_operation("mcp.call_tool:run_block"):
+ fields = pending_operation_fields()
+
+ assert not {"workflow_permanent_id", "turn_id", "workflow_copilot_chat_id"} & set(fields)
+
+
+def test_an_early_tool_error_does_not_pin_the_fingerprint_for_the_rest_of_the_turn() -> None:
+ install_pending_operation_slot()
+
+ # mcp_adapter raises for code-block control flow, so an ordinary turn retires an errored scope
+ # early. It must not outrank everything that runs afterwards.
+ with contextlib.suppress(RuntimeError):
+ with pending_operation("mcp.call_tool:codeblock_control_flow"):
+ raise RuntimeError("control flow")
+ with pending_operation("mcp.call_tool:later"):
+ pass
+
+ fields = pending_operation_fields()
+ assert fields["pending_operation"] == "mcp.call_tool:later"
+ assert fields["pending_operation_state"] == "returned"
+
+
+def test_a_sibling_still_hanging_outranks_a_later_one_that_already_returned() -> None:
+ install_pending_operation_slot()
+ turn = pending_operation("turn.stream", span=True)
+ turn.__enter__()
+
+ hung = pending_operation("mcp.call_tool:hung")
+ hung.__enter__()
+ # The SDK cancels concurrent tool tasks without awaiting cleanup, so a later-started sibling can
+ # retire while the one that hung is still open.
+ with pending_operation("mcp.call_tool:fast"):
+ pass
+
+ fields = pending_operation_fields()
+ hung.__exit__(None, None, None)
+ turn.__exit__(None, None, None)
+
+ assert fields["pending_operation"] == "mcp.call_tool:hung"
+ assert fields["pending_operation_state"] == "open"
+
+
+async def test_a_scope_abandoned_by_an_unfinalised_generator_does_not_own_the_next_iteration() -> None:
+ install_pending_operation_slot()
+
+ async def abandoned() -> AsyncIterator[int]:
+ with pending_operation("model.call:terra"):
+ for value in range(100):
+ yield value
+
+ iteration_one = pending_operation("turn.stream", span=True)
+ iteration_one.__enter__()
+ generator = abandoned()
+ async for _ in generator:
+ break
+ del generator
+ iteration_one.__exit__(None, None, None)
+
+ with pending_operation("turn.stream", span=True):
+ with pending_operation("mcp.call_tool:later"):
+ pass
+ fields = pending_operation_fields()
+
+ assert fields["pending_operation"] == "mcp.call_tool:later"
+ assert fields["pending_operation_state"] == "returned"
+
+
+def test_a_finished_scope_reports_its_own_duration_not_the_time_since_it_started(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ clock = {"now": 1000.0}
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.pending_operation.time.monotonic",
+ lambda: clock["now"],
+ )
+ install_pending_operation_slot()
+
+ with pending_operation("model.call:terra"):
+ clock["now"] = 1002.0
+ clock["now"] = 1900.0 # the turn then stalls for ~15 min somewhere uninstrumented
+
+ fields = pending_operation_fields()
+ assert fields["pending_operation"] == "model.call:terra"
+ assert fields["pending_operation_state"] == "returned"
+ assert fields["pending_operation_seconds"] == 2.0, "a 2s call must not read as though it hung for 900s"
+
+
+def test_a_scope_spanning_the_whole_iteration_does_not_emit_the_slow_line(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.pending_operation.PENDING_OPERATION_LOG_THRESHOLD_SECONDS",
+ 0.0,
+ )
+ install_pending_operation_slot()
+
+ with capture_logs() as logs:
+ with pending_operation("turn.stream", span=True):
+ pass
+
+ assert [entry for entry in logs if entry.get("event") == "copilot_pending_operation_slow"] == []
diff --git a/tests/unit/test_copilot_runner_deadline.py b/tests/unit/test_copilot_runner_deadline.py
index c7c204636..d43f0d0d3 100644
--- a/tests/unit/test_copilot_runner_deadline.py
+++ b/tests/unit/test_copilot_runner_deadline.py
@@ -3,8 +3,9 @@
from __future__ import annotations
import asyncio
+import contextlib
import time
-from typing import Any
+from typing import Any, cast
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -13,8 +14,14 @@ from structlog.testing import capture_logs
from skyvern.forge.sdk.copilot.enforcement import (
TOTAL_TIMEOUT_SECONDS,
CopilotTotalTimeoutError,
+ _mark_copilot_total_timeout,
run_with_enforcement,
)
+from skyvern.forge.sdk.copilot.pending_operation import (
+ _turn_operations,
+ pending_operation,
+ pending_operation_fields,
+)
def _fake_result() -> MagicMock:
@@ -284,3 +291,182 @@ async def test_a_broken_recorder_neither_masks_nor_delays_the_cancellation(
assert _cancellation_events(logs) == []
assert any(entry.get("event") == "Failed to record a copilot turn cancellation" for entry in logs)
+
+
+async def test_deadline_event_names_the_operation_still_open_when_the_budget_expires(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.TOTAL_TIMEOUT_SECONDS", 0.05)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.MIN_DEADLINE_REMAINING_SECONDS", 0.02)
+
+ stream = MagicMock()
+ stream.is_disconnected = AsyncMock(return_value=False)
+
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.enforcement.Runner.run_streamed",
+ lambda *a, **kw: _fake_result(),
+ )
+
+ async def hanging_stream(result: Any, s: Any, c: Any) -> None:
+ with pending_operation("mcp.call_tool:run_block"):
+ await asyncio.sleep(5.0)
+
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.streaming_adapter.stream_to_sse", hanging_stream)
+
+ ctx = MagicMock()
+ ctx.copilot_total_timeout_exceeded = False
+ with capture_logs() as logs:
+ with pytest.raises(CopilotTotalTimeoutError):
+ await run_with_enforcement(agent=MagicMock(), initial_input="hello", ctx=ctx, stream=stream)
+
+ events = _deadline_events(logs)
+ assert len(events) == 1
+ assert events[0]["pending_operation"] == "mcp.call_tool:run_block"
+ assert isinstance(events[0]["pending_operation_started_monotonic"], float)
+ assert events[0]["pending_operation_state"] == "unwound_by_cancellation"
+ assert events[0]["iteration"] == 0
+ assert events[0]["elapsed_seconds"] >= 0.05
+
+
+async def test_a_broken_fingerprint_reader_neither_masks_nor_delays_the_cancellation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def exploding_fields() -> dict[str, str | float | int]:
+ raise RuntimeError("fingerprint reader is broken")
+
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.enforcement.pending_operation_fields",
+ exploding_fields,
+ )
+ ctx = _cancellation_ctx()
+
+ logs, _ = await _cancel_at_boundary(monkeypatch, boundary="first", elapsed=588.0, ctx=ctx)
+
+ assert _cancellation_events(logs) == []
+ assert any(entry.get("event") == "Failed to record a copilot turn cancellation" for entry in logs)
+
+
+async def test_the_deadline_names_the_inner_operation_that_returned_over_the_outer_one_still_open(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.TOTAL_TIMEOUT_SECONDS", 0.05)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.MIN_DEADLINE_REMAINING_SECONDS", 0.02)
+
+ stream = MagicMock()
+ stream.is_disconnected = AsyncMock(return_value=False)
+
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.enforcement.Runner.run_streamed",
+ lambda *a, **kw: _fake_result(),
+ )
+
+ async def stream_stalling_after_a_tool_returned(result: Any, s: Any, c: Any) -> None:
+ with pending_operation("mcp.call_tool:run_block"):
+ await asyncio.sleep(0)
+ await asyncio.sleep(5.0)
+
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.streaming_adapter.stream_to_sse",
+ stream_stalling_after_a_tool_returned,
+ )
+
+ ctx = MagicMock()
+ ctx.copilot_total_timeout_exceeded = False
+ with capture_logs() as logs:
+ with pytest.raises(CopilotTotalTimeoutError):
+ await run_with_enforcement(agent=MagicMock(), initial_input="hello", ctx=ctx, stream=stream)
+
+ events = _deadline_events(logs)
+ assert len(events) == 1
+ assert events[0]["pending_operation"] == "mcp.call_tool:run_block"
+ assert events[0]["pending_operation_state"] == "returned"
+ assert events[0]["pending_operation_open_count"] == 1, "the outer turn.stream scope is still open"
+
+
+async def test_the_deadline_names_an_operation_that_exited_by_exception_and_never_calls_it_open(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.TOTAL_TIMEOUT_SECONDS", 0.05)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.MIN_DEADLINE_REMAINING_SECONDS", 0.02)
+
+ stream = MagicMock()
+ stream.is_disconnected = AsyncMock(return_value=False)
+
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.enforcement.Runner.run_streamed",
+ lambda *a, **kw: _fake_result(),
+ )
+
+ async def stream_stalling_after_a_tool_failed(result: Any, s: Any, c: Any) -> None:
+ with contextlib.suppress(RuntimeError):
+ with pending_operation("mcp.call_tool:run_block"):
+ raise RuntimeError("tool blew up")
+ await asyncio.sleep(5.0)
+
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.streaming_adapter.stream_to_sse",
+ stream_stalling_after_a_tool_failed,
+ )
+
+ ctx = MagicMock()
+ ctx.copilot_total_timeout_exceeded = False
+ with capture_logs() as logs:
+ with pytest.raises(CopilotTotalTimeoutError):
+ await run_with_enforcement(agent=MagicMock(), initial_input="hello", ctx=ctx, stream=stream)
+
+ events = _deadline_events(logs)
+ assert len(events) == 1
+ assert events[0]["pending_operation"] == "mcp.call_tool:run_block"
+ assert events[0]["pending_operation_state"] == "unwound_by_error"
+ assert events[0]["pending_operation_open_count"] == 1, "the outer turn.stream scope is still open"
+
+
+def test_the_fingerprint_reader_reports_nothing_rather_than_raising_on_an_unreadable_slot() -> None:
+ token = _turn_operations.set(cast(Any, object()))
+ try:
+ assert pending_operation_fields() == {}
+ finally:
+ _turn_operations.reset(token)
+
+
+async def test_the_deadline_path_is_unchanged_when_the_fingerprint_contributes_no_fields(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.TOTAL_TIMEOUT_SECONDS", 0.05)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.MIN_DEADLINE_REMAINING_SECONDS", 0.02)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.pending_operation_fields", dict)
+
+ stream = MagicMock()
+ stream.is_disconnected = AsyncMock(return_value=False)
+
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.enforcement.Runner.run_streamed",
+ lambda *a, **kw: _fake_result(),
+ )
+
+ async def hanging_stream(result: Any, s: Any, c: Any) -> None:
+ await asyncio.sleep(5.0)
+
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.streaming_adapter.stream_to_sse", hanging_stream)
+
+ ctx = MagicMock()
+ ctx.copilot_total_timeout_exceeded = False
+ with capture_logs() as logs:
+ with pytest.raises(CopilotTotalTimeoutError):
+ await run_with_enforcement(agent=MagicMock(), initial_input="hello", ctx=ctx, stream=stream)
+
+ events = _deadline_events(logs)
+ assert len(events) == 1
+ assert "pending_operation" not in events[0]
+ assert events[0]["iteration"] == 0
+ assert events[0]["elapsed_seconds"] >= 0.05
+ assert ctx.copilot_total_timeout_exceeded is True
+
+ with capture_logs() as already_marked:
+ _mark_copilot_total_timeout(ctx, elapsed_seconds=99.0, iteration=1)
+ assert _deadline_events(already_marked) == []