Skip to content

Automate browser based workflows with AI

Add the engine discriminator and loop wall-clock to the task duration telemetry (SKY-15499) (#8404)

pedrohsdb52eef687e78d
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index fd3706a0c..12c0df8b7 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -380,6 +380,18 @@ def _redact_tool_arg(value: Any, secret_values: set[str]) -> Any:
# display; a runaway multi-paragraph turn must not become a per-row payload.
_TASKV3_REASONING_MAX_CHARS = 1000
+# Block-engine to run-type labels for the "Task duration metrics" discriminator (SKY-15499):
+# workflow-block tasks have no task_runs row, so the block's resolved engine stands in.
+_RUN_TYPE_BY_ENGINE: dict[RunEngine, str] = {
+ RunEngine.skyvern_v1: "task_v1",
+ RunEngine.skyvern_v2: "task_v2",
+ RunEngine.skyvern_v3: "task_v3",
+ RunEngine.openai_cua: "openai_cua",
+ RunEngine.anthropic_cua: "anthropic_cua",
+ RunEngine.ui_tars: "ui_tars",
+ RunEngine.yutori_navigator: "yutori_navigator",
+}
+
def _taskv3_action_for_tool_call(tool_name: str, args: dict[str, Any], **fields: Any) -> Action:
"""Build the Action a v3 tool call persists as, carrying the fields its typed subclass requires so
@@ -1983,6 +1995,7 @@ class ForgeAgent:
page_fingerprint=_page_fingerprint,
page_probe=_page_probe,
reload_page=_reload_page,
+ block_type=str(task_block.block_type) if task_block is not None else None,
# Unfenced across both populations, unlike the settle probe above: that fence exists
# to keep a RENDERING wait off the bare arm, and this asks a different question. The
# bare arm is where the measured specimen lives (SKY-14701 is what inheriting a fence
@@ -7160,6 +7173,21 @@ class ForgeAgent:
start_time = task.started_at.replace(tzinfo=UTC) if task.started_at else task.created_at.replace(tzinfo=UTC)
duration_seconds = (datetime.now(UTC) - start_time).total_seconds()
queued_seconds = (start_time - task.created_at.replace(tzinfo=UTC)).total_seconds()
+ # Best-effort engine discriminator (SKY-15499): a bare task's own task_runs row is exact;
+ # a workflow-block task has no task_runs row, so its block row's RESOLVED engine is the
+ # source. Telemetry only — a failed lookup must not touch the terminal update.
+ task_run_type: str | None = None
+ try:
+ if task.workflow_run_id is None:
+ run = await app.DATABASE.tasks.get_run(task.task_id, organization_id=task.organization_id)
+ task_run_type = str(run.task_run_type) if run else None
+ else:
+ block_engine = await app.DATABASE.observer.get_workflow_run_block_engine_by_task_id(
+ task.task_id, organization_id=task.organization_id
+ )
+ task_run_type = _RUN_TYPE_BY_ENGINE.get(block_engine) if block_engine else None
+ except Exception:
+ LOG.warning("task_run_type resolution for duration metrics failed", task_id=task.task_id, exc_info=True)
LOG.info(
"Task duration metrics",
task_id=task.task_id,
@@ -7169,6 +7197,7 @@ class ForgeAgent:
task_status=status,
organization_id=task.organization_id,
failure_reason=failure_reason,
+ task_run_type=task_run_type,
)
await save_task_logs(task.task_id)
LOG.info("Updating task in db", task_id=task.task_id, diff=update_comparison, sampling=True)
diff --git a/skyvern/forge/sdk/db/repositories/observer.py b/skyvern/forge/sdk/db/repositories/observer.py
index 308afc031..7c6ec17ca 100644
--- a/skyvern/forge/sdk/db/repositories/observer.py
+++ b/skyvern/forge/sdk/db/repositories/observer.py
@@ -688,6 +688,23 @@ class ObserverRepository(BaseRepository):
return convert_to_workflow_run_block(workflow_run_block, task=task)
raise NotFoundError(f"WorkflowRunBlock not found by {task_id}")
+ @db_operation("get_workflow_run_block_engine_by_task_id")
+ async def get_workflow_run_block_engine_by_task_id(
+ self,
+ task_id: str,
+ organization_id: str | None = None,
+ ) -> RunEngine | None:
+ """The block row's resolved engine only — no task hydration, one indexed point read."""
+ async with self.Session() as session:
+ engine = (
+ await session.scalars(
+ select(WorkflowRunBlockModel.engine)
+ .filter_by(task_id=task_id)
+ .filter_by(organization_id=organization_id)
+ )
+ ).first()
+ return RunEngine(engine) if engine else None
+
@db_operation("get_workflow_run_blocks")
async def get_workflow_run_blocks(
self,
diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.py
index 5c5683a46..17ad4a254 100644
--- a/skyvern/forge/taskv3/engine.py
+++ b/skyvern/forge/taskv3/engine.py
@@ -248,6 +248,7 @@ async def run_task_v3_agent_loop(
initial_navigation_status: int | None = None,
page_probe: Callable[[], Awaitable[str | None]] | None = None,
reload_page: Callable[[], Awaitable[None]] | None = None,
+ block_type: str | None = None,
) -> LoopOutcome:
"""Run one Task V3 task to completion against `page`, returning the loop outcome.
@@ -260,6 +261,7 @@ async def run_task_v3_agent_loop(
failure-evidence gate, which shares the sampler, intact. `page_probe` is a separate sampler (URL
plus fingerprint) the loop uses to detect whether a failed batched call moved the page; a
page-free run has no page to probe."""
+ loop_started_at = time.monotonic()
# Presigned file URLs in the payload carry an HMAC token the model would otherwise have to
# retype verbatim into a tool call; masking them here and resolving inside the tool handlers
# (the same boundary credential placeholders already use) avoids that. Page-free runs have no
@@ -417,5 +419,7 @@ async def run_task_v3_agent_loop(
auto_observe_arm=auto_observe_decision.arm,
tool_choice_requested=settings.TASK_V3_TOOL_CHOICE_REQUIRED,
tool_choice_in_effect=outcome.tool_choice_in_effect,
+ duration_seconds=time.monotonic() - loop_started_at,
+ block_type=block_type,
)
return outcome
diff --git a/tests/unit/test_taskv3_engine.py b/tests/unit/test_taskv3_engine.py
index caca418b9..48032a2e4 100644
--- a/tests/unit/test_taskv3_engine.py
+++ b/tests/unit/test_taskv3_engine.py
@@ -1330,3 +1330,33 @@ def test_caller_level_bridge_check_denies_openai_provider_with_custom_api_base()
openai_client=None, _custom_openrouter=False, llm_config=azure, original_llm_key="AZURE_OPENAI_GPT5_6_SOL"
)
assert LLMCaller.uses_openai_responses_bridge(azure_self) is True
+
+
+async def test_terminal_log_carries_duration_and_block_type() -> None:
+ # The v1-vs-v3 wall-time dashboard reads this log line; it needs the loop's own wall-clock and
+ # the block context to slice workflow-block runs (SKY-15499).
+ from structlog.testing import capture_logs
+
+ script = [[("finish", {"status": "completed", "reason": "ok"})]]
+ with capture_logs() as logs:
+ await run_task_v3_agent_loop(
+ page_provider=_fixed_page_provider(_FakePage()),
+ llm_caller=_ScriptedCaller(script),
+ goal="x",
+ block_type="navigation",
+ )
+ terminal = [e for e in logs if e.get("event") == "taskv3 engine loop finished"]
+ assert len(terminal) == 1
+ assert terminal[0]["block_type"] == "navigation"
+ assert isinstance(terminal[0]["duration_seconds"], float)
+ assert terminal[0]["duration_seconds"] >= 0.0
+
+ with capture_logs() as logs:
+ await run_task_v3_agent_loop(
+ page_provider=_fixed_page_provider(_FakePage()),
+ llm_caller=_ScriptedCaller(script),
+ goal="x",
+ )
+ terminal = [e for e in logs if e.get("event") == "taskv3 engine loop finished"]
+ assert terminal[0]["block_type"] is None # bare task: no block context
diff --git a/tests/unit/test_workflow_run_minutes_gate.py b/tests/unit/test_workflow_run_minutes_gate.py
index 7624a1d5b..95a4859c8 100644
--- a/tests/unit/test_workflow_run_minutes_gate.py
+++ b/tests/unit/test_workflow_run_minutes_gate.py
@@ -338,3 +338,103 @@ async def test_finally_block_re_finalization_records_only_the_minutes_it_added(
assert sum(call.kwargs["duration_seconds"] for call in record_run_duration.await_args_list) == pytest.approx(
wall_clock_seconds
)
+
+
+async def test_duration_metrics_log_carries_task_run_type_for_a_bare_task(
+ monkeypatch: pytest.MonkeyPatch,
+ record_run_duration: AsyncMock,
+) -> None:
+ # The v1-vs-v3 wall-time dashboard needs an engine discriminator on "Task duration metrics";
+ # a bare task resolves it from its own task_runs row (SKY-15499).
+ from structlog.testing import capture_logs
+
+ from skyvern.schemas.run_enums import RunType
+
+ now = datetime.now(UTC)
+ entry_task = _make_task(status=TaskStatus.running, started_at=now - timedelta(minutes=5))
+ claimed_task = _make_task(status=TaskStatus.completed, started_at=now - timedelta(minutes=5), finished_at=now)
+ monkeypatch.setattr(app.DATABASE.tasks, "get_task", AsyncMock(return_value=entry_task))
+ monkeypatch.setattr(
+ app.DATABASE.tasks, "update_task_and_claim_finish", AsyncMock(return_value=(claimed_task, True))
+ )
+ monkeypatch.setattr(app.DATABASE.tasks, "get_run", AsyncMock(return_value=MagicMock(task_run_type=RunType.task_v3)))
+ monkeypatch.setattr(agent_module, "save_task_logs", AsyncMock())
+
+ with capture_logs() as logs:
+ await ForgeAgent().update_task(entry_task, status=TaskStatus.completed)
+
+ duration_logs = [e for e in logs if e.get("event") == "Task duration metrics"]
+ assert len(duration_logs) == 1
+ assert duration_logs[0]["task_run_type"] == "task_v3"
+
+
+async def test_duration_metrics_log_resolves_engine_from_the_block_for_a_workflow_task(
+ monkeypatch: pytest.MonkeyPatch,
+ record_run_duration: AsyncMock,
+) -> None:
+ # Workflow-block tasks have no task_runs row; the block row's RESOLVED engine is the
+ # discriminator (task_runs cover bare tasks only).
+ from structlog.testing import capture_logs
+
+ from skyvern.schemas.run_enums import RunEngine
+
+ now = datetime.now(UTC)
+ entry_task = _make_task(status=TaskStatus.running, started_at=now - timedelta(minutes=5))
+ entry_task.workflow_run_id = "wr_gate"
+ claimed_task = _make_task(status=TaskStatus.terminated, started_at=now - timedelta(minutes=5), finished_at=now)
+ claimed_task.workflow_run_id = "wr_gate"
+ monkeypatch.setattr(app.DATABASE.tasks, "get_task", AsyncMock(return_value=entry_task))
+ monkeypatch.setattr(
+ app.DATABASE.tasks, "update_task_and_claim_finish", AsyncMock(return_value=(claimed_task, True))
+ )
+ monkeypatch.setattr(
+ app.DATABASE.observer,
+ "get_workflow_run_block_engine_by_task_id",
+ AsyncMock(return_value=RunEngine.skyvern_v1),
+ )
+ monkeypatch.setattr(agent_module, "save_task_logs", AsyncMock())
+
+ with capture_logs() as logs:
+ await ForgeAgent().update_task(entry_task, status=TaskStatus.terminated, failure_reason="blocked")
+
+ duration_logs = [e for e in logs if e.get("event") == "Task duration metrics"]
+ assert len(duration_logs) == 1
+ assert duration_logs[0]["task_run_type"] == "task_v1"
+
+
+async def test_duration_metrics_log_survives_a_failed_run_type_resolution(
+ monkeypatch: pytest.MonkeyPatch,
+ record_run_duration: AsyncMock,
+) -> None:
+ # The discriminator is best-effort telemetry: a DB error must neither drop the log nor fail the
+ # terminal update.
+ from structlog.testing import capture_logs
+
+ now = datetime.now(UTC)
+ entry_task = _make_task(status=TaskStatus.running, started_at=now - timedelta(minutes=5))
+ claimed_task = _make_task(status=TaskStatus.completed, started_at=now - timedelta(minutes=5), finished_at=now)
+ monkeypatch.setattr(app.DATABASE.tasks, "get_task", AsyncMock(return_value=entry_task))
+ monkeypatch.setattr(
+ app.DATABASE.tasks, "update_task_and_claim_finish", AsyncMock(return_value=(claimed_task, True))
+ )
+ monkeypatch.setattr(app.DATABASE.tasks, "get_run", AsyncMock(side_effect=RuntimeError("db down")))
+ monkeypatch.setattr(agent_module, "save_task_logs", AsyncMock())
+
+ with capture_logs() as logs:
+ await ForgeAgent().update_task(entry_task, status=TaskStatus.completed)
+
+ duration_logs = [e for e in logs if e.get("event") == "Task duration metrics"]
+ assert len(duration_logs) == 1
+ assert duration_logs[0]["task_run_type"] is None
+
+
+def test_run_type_by_engine_mapping_is_exhaustive() -> None:
+ # A new RunEngine member silently maps to None otherwise -- pin the dict to the enum.
+ from skyvern.forge.agent import _RUN_TYPE_BY_ENGINE
+ from skyvern.schemas.run_enums import RunEngine, RunType
+
+ assert set(_RUN_TYPE_BY_ENGINE) == set(RunEngine)
+ assert set(_RUN_TYPE_BY_ENGINE.values()) <= {t.value for t in RunType}