Skip to content

Automate browser based workflows with AI

Remember perception states for the whole run, not the last eight (SKY-14998) (#8440)

pedrohsdb7e6c631a4935
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotHistory.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotHistory.test.tsx
index f2520a15e..2c95ec85d 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotHistory.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotHistory.test.tsx
@@ -67,6 +67,47 @@ describe("WorkflowCopilotHistory", () => {
expect(screen.getByText("Scrape the news")).toBeTruthy();
});
+ it("marks only the chats the copilot is waiting on", async () => {
+ mockChats([
+ [
+ { ...chats[0]!, awaiting_user_input: true },
+ { ...chats[1]!, awaiting_user_input: false },
+ ],
+ ]);
+ render(
+ <WorkflowCopilotHistory
+ workflowPermanentId="wpid_a"
+ currentChatId={null}
+ onSelect={vi.fn()}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: /history/i }));
+
+ expect(await screen.findByText("Build a login flow")).toBeTruthy();
+ const badges = screen.getAllByText("Waiting on you");
+ expect(badges).toHaveLength(1);
+ expect(badges[0]!.closest("button")?.textContent).toContain(
+ "Build a login flow",
+ );
+ });
+
+ it("marks nothing for a backend that does not send the field", async () => {
+ mockChats([chats]);
+ render(
+ <WorkflowCopilotHistory
+ workflowPermanentId="wpid_a"
+ currentChatId={null}
+ onSelect={vi.fn()}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: /history/i }));
+
+ expect(await screen.findByText("Build a login flow")).toBeTruthy();
+ expect(screen.queryByText("Waiting on you")).toBeNull();
+ });
+
it("calls onSelect with the chosen chat", async () => {
mockChats([chats]);
const onSelect = vi.fn();
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotHistory.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotHistory.tsx
index 74f35b1cd..2bcec26bf 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotHistory.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotHistory.tsx
@@ -118,8 +118,19 @@ function WorkflowCopilotHistoryContent({
<span className="line-clamp-2 break-words [overflow-wrap:anywhere]">
{chat.title || "Untitled chat"}
</span>
- <span className="truncate text-xs text-muted-foreground">
- {compactLocalDateTime(chat.created_at)}
+ <span className="flex items-center gap-1.5 text-xs text-muted-foreground">
+ <span className="truncate">
+ {compactLocalDateTime(chat.created_at)}
+ </span>
+ {chat.awaiting_user_input ? (
+ <span className="inline-flex shrink-0 items-center gap-1 text-amber-700 dark:text-amber-300">
+ <span
+ aria-hidden="true"
+ className="inline-block h-1.5 w-1.5 rounded-full bg-amber-400"
+ />
+ Waiting on you
+ </span>
+ ) : null}
</span>
</div>
{isCurrent && (
diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
index 678af7a4e..86c1821d4 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
@@ -109,6 +109,8 @@ export interface WorkflowCopilotChatSummary {
title: string;
created_at: string;
modified_at: string;
+ // Absent on responses from a backend that predates the marker.
+ awaiting_user_input?: boolean;
}
export interface WorkflowCopilotClearProposedWorkflowRequest {
diff --git a/skyvern/forge/sdk/copilot/terminal_envelope.py b/skyvern/forge/sdk/copilot/terminal_envelope.py
index d5d3dd940..0ce23ec86 100644
--- a/skyvern/forge/sdk/copilot/terminal_envelope.py
+++ b/skyvern/forge/sdk/copilot/terminal_envelope.py
@@ -12,6 +12,7 @@ from skyvern.forge.sdk.copilot.context import ProposalDisposition
from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome, RunOutcomeRole
from skyvern.forge.sdk.copilot.secret_redaction import redact_raw_secrets_for_prompt
from skyvern.forge.sdk.schemas.copilot_turn_outcome import CopilotCancelSource
+from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotChatSender
TerminalNextState = Literal["completed", "proposal_pending", "awaiting_user_input", "stopped"]
TerminalResponseKind = Literal["question", "update", "answer", "stopped"]
@@ -156,6 +157,23 @@ class TerminalOutcomeEnvelope(BaseModel):
return self
+def chat_awaits_user_input(*, sender: str, narrative_payload: object) -> bool:
+ """Whether a chat is blocked on the user, given its most recent message row.
+
+ Keyed on the tail of the conversation, not on the last assistant turn: a user reply
+ answers the ask. The cancel path persists the pre-cancel envelope verbatim, so a stop
+ still carries ``awaiting_user_input`` and must not read as a question.
+ """
+ if sender != WorkflowCopilotChatSender.AI:
+ return False
+ if not isinstance(narrative_payload, dict) or narrative_payload.get("cancelled") is True:
+ return False
+ envelope = narrative_payload.get("terminalEnvelope")
+ if not isinstance(envelope, dict):
+ return False
+ return envelope.get("rendered_from_envelope") is True and envelope.get("next_state") == "awaiting_user_input"
+
+
def assemble_terminal_envelope(
*,
response_type: str,
diff --git a/skyvern/forge/sdk/db/repositories/workflow_parameters.py b/skyvern/forge/sdk/db/repositories/workflow_parameters.py
index 3b1fd9db8..e84589c3c 100644
--- a/skyvern/forge/sdk/db/repositories/workflow_parameters.py
+++ b/skyvern/forge/sdk/db/repositories/workflow_parameters.py
@@ -13,6 +13,7 @@ from sqlalchemy.orm import defer
from skyvern.config import settings
from skyvern.forge.sdk.copilot.completion_criteria_store import criteria_from_json, criterion_authority_projection
from skyvern.forge.sdk.copilot.context import TurnNarrativePayload
+from skyvern.forge.sdk.copilot.terminal_envelope import chat_awaits_user_input
from skyvern.forge.sdk.db._error_handling import db_operation
from skyvern.forge.sdk.db._sentinels import _UNSET
from skyvern.forge.sdk.db.base_repository import BaseRepository
@@ -1004,6 +1005,30 @@ class WorkflowParametersRepository(BaseRepository):
)
rows = (await session.execute(query)).all()
+ # The chats-list indexes are (organization_id, workflow_copilot_chat_id) with no
+ # created_at, so the tail lookup is scoped to this page's chats rather than joined
+ # as a DISTINCT ON over the org's whole message history.
+ chat_ids = [chat.workflow_copilot_chat_id for chat, _ in rows]
+ awaiting: dict[str, bool] = {}
+ if chat_ids:
+ latest_message = (
+ select(
+ WorkflowCopilotChatMessageModel.workflow_copilot_chat_id,
+ WorkflowCopilotChatMessageModel.sender,
+ WorkflowCopilotChatMessageModel.narrative_payload,
+ )
+ .where(WorkflowCopilotChatMessageModel.organization_id == organization_id)
+ .where(WorkflowCopilotChatMessageModel.workflow_copilot_chat_id.in_(chat_ids))
+ .distinct(WorkflowCopilotChatMessageModel.workflow_copilot_chat_id)
+ .order_by(
+ WorkflowCopilotChatMessageModel.workflow_copilot_chat_id,
+ WorkflowCopilotChatMessageModel.created_at.desc(),
+ WorkflowCopilotChatMessageModel.workflow_copilot_chat_message_id.desc(),
+ )
+ )
+ for chat_id, sender, narrative_payload in (await session.execute(latest_message)).all():
+ awaiting[chat_id] = chat_awaits_user_input(sender=sender, narrative_payload=narrative_payload)
+
workflow_titles: dict[str, str] = {}
permanent_ids = {chat.workflow_permanent_id for chat, _ in rows}
if permanent_ids:
@@ -1027,6 +1052,7 @@ class WorkflowParametersRepository(BaseRepository):
title=summarize_copilot_chat_title(content),
created_at=chat.created_at,
modified_at=chat.modified_at,
+ awaiting_user_input=awaiting.get(chat.workflow_copilot_chat_id, False),
)
for chat, content in rows
]
diff --git a/skyvern/forge/sdk/db/repositories/workflow_runs.py b/skyvern/forge/sdk/db/repositories/workflow_runs.py
index c73191797..948f8e6ff 100644
--- a/skyvern/forge/sdk/db/repositories/workflow_runs.py
+++ b/skyvern/forge/sdk/db/repositories/workflow_runs.py
@@ -1,8 +1,9 @@
from __future__ import annotations
-from collections.abc import Sequence
+from collections.abc import AsyncIterator, Callable, Sequence
+from contextlib import asynccontextmanager
from datetime import datetime, timedelta
-from typing import TYPE_CHECKING, Any, Callable
+from typing import TYPE_CHECKING, Any
from typing import cast as typing_cast
import structlog
@@ -603,6 +604,21 @@ class WorkflowRunsRepository(BaseRepository):
await session.refresh(refreshed)
return convert_to_workflow_run(refreshed)
+ @asynccontextmanager
+ async def admit_workflow_run_block_dispatch(self, workflow_run_id: str) -> AsyncIterator[WorkflowRun]:
+ """Hold the workflow-run row lock through the caller's scheduler handoff."""
+ async with self.Session() as session:
+ workflow_run_model = (
+ await session.scalars(
+ select(WorkflowRunModel).filter_by(workflow_run_id=workflow_run_id).with_for_update()
+ )
+ ).one_or_none()
+ if workflow_run_model is None:
+ raise WorkflowRunNotFound(workflow_run_id)
+
+ yield convert_to_workflow_run(workflow_run_model)
+ await session.commit()
+
@db_operation("finish_preexisting_timed_out_workflow_run")
async def finish_preexisting_timed_out_workflow_run(
self,
diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.py
index 2f84013ad..8d4411b29 100644
--- a/skyvern/forge/sdk/schemas/workflow_copilot.py
+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py
@@ -251,6 +251,10 @@ class WorkflowCopilotChatSummary(BaseModel):
title: str = Field(..., description="Single-line preview derived from the chat's first message")
created_at: datetime = Field(..., description="When the chat was created")
modified_at: datetime = Field(..., description="When the chat was last modified")
+ awaiting_user_input: bool = Field(
+ False,
+ description="Whether the chat's most recent message is a copilot turn that asked the user a question",
+ )
class WorkflowCopilotAudioUploadResponse(BaseModel):
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index 63238b999..39db59780 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -14,6 +14,7 @@ import unicodedata
import uuid
from collections import deque
from collections.abc import Awaitable, Callable, Iterable, Sequence
+from contextlib import suppress
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from hashlib import sha256
@@ -1194,6 +1195,15 @@ class ScriptBlockAttempt:
script_exception: Exception | None
+@dataclass(frozen=True)
+class WorkflowRunDispatchStopped:
+ workflow_run: WorkflowRun
+
+
+class _WorkflowRunDispatchScopeError(RuntimeError):
+ pass
+
+
@dataclass
class WorkflowBrowserCleanupResult:
browser_state: BrowserState | None
@@ -5439,7 +5449,12 @@ class WorkflowService:
organization=organization,
browser_session_id=browser_session_id,
)
- if finally_block_execution is not None:
+ if isinstance(finally_block_execution, WorkflowRunDispatchStopped):
+ workflow_run = finally_block_execution.workflow_run
+ pre_finally_status = workflow_run.status
+ pre_finally_failure_reason = workflow_run.failure_reason
+ pre_finally_failure_category = workflow_run.failure_category
+ elif finally_block_execution is not None:
finally_block, finally_block_result = finally_block_execution
assert pre_finally_status is not None
status_before_finally_result = pre_finally_status
@@ -6523,7 +6538,7 @@ class WorkflowService:
browser_session_id=browser_session_id,
)
- attempt = await self._try_execute_block_with_script(
+ attempt_or_stop = await self._try_execute_block_with_script(
workflow=workflow,
workflow_run=workflow_run,
block=block,
@@ -6533,12 +6548,15 @@ class WorkflowService:
loaded_script_module=loaded_script_module,
is_script_run=is_script_run,
)
+ if isinstance(attempt_or_stop, WorkflowRunDispatchStopped):
+ return attempt_or_stop.workflow_run, blocks_to_update, None, True, branch_metadata
+ attempt = attempt_or_stop
workflow_run_block_result = attempt.block_result
block_executed_with_code = attempt.executed_with_code
block_requires_agent = attempt.block_requires_agent
if not block_executed_with_code:
- workflow_run_block_result, block_requires_agent = await self._execute_block_via_agent_if_allowed(
+ agent_execution = await self._execute_block_via_agent_if_allowed(
block=block,
workflow_run=workflow_run,
workflow_run_id=workflow_run_id,
@@ -6549,6 +6567,9 @@ class WorkflowService:
script_blocks_by_label=script_blocks_by_label,
attempt=attempt,
)
+ if isinstance(agent_execution, WorkflowRunDispatchStopped):
+ return agent_execution.workflow_run, blocks_to_update, None, True, branch_metadata
+ workflow_run_block_result, block_requires_agent = agent_execution
if attempt.fallback_episode_id and workflow_run_block_result:
await self._enrich_fallback_episode_with_agent_actions(
block=block,
@@ -6596,9 +6617,12 @@ class WorkflowService:
no_block_result_reason = f"Script error ({type(attempt.script_exception).__name__}): {exc_message}"
else:
no_block_result_reason = "Block result is None"
- workflow_run = await self.mark_workflow_run_as_failed(
+ updated_workflow_run = await self.mark_workflow_run_as_failed_if_not_final(
workflow_run_id=workflow_run_id, failure_reason=no_block_result_reason
)
+ workflow_run = updated_workflow_run or await self._current_row_after_lost_finalize(
+ workflow_run_id, workflow_run
+ )
return workflow_run, blocks_to_update, workflow_run_block_result, True, branch_metadata
self._track_blocks_for_script_generation(
@@ -6627,6 +6651,8 @@ class WorkflowService:
return workflow_run, blocks_to_update, workflow_run_block_result, should_stop, branch_metadata
+ except _WorkflowRunDispatchScopeError:
+ raise
except Exception as e:
LOG.exception(
f"Error while executing workflow run {workflow_run_id}",
@@ -6639,11 +6665,44 @@ class WorkflowService:
exception_message = get_user_facing_exception_message(e)
failure_reason = f"{block.block_type} block failed. failure reason: {exception_message}"
- workflow_run = await self.mark_workflow_run_as_failed(
+ updated_workflow_run = await self.mark_workflow_run_as_failed_if_not_final(
workflow_run_id=workflow_run_id, failure_reason=failure_reason
)
+ workflow_run = updated_workflow_run or await self._current_row_after_lost_finalize(
+ workflow_run_id, workflow_run
+ )
return workflow_run, blocks_to_update, workflow_run_block_result, True, branch_metadata
+ async def _dispatch_workflow_run_block(
+ self,
+ workflow_run_id: str,
+ execute: Callable[[], Awaitable[_T1]],
+ ) -> _T1 | WorkflowRunDispatchStopped:
+ start_gate = asyncio.Event()
+ executor_task: asyncio.Task[_T1] | None = None
+
+ async def execute_after_admission() -> _T1:
+ await start_gate.wait()
+ return await execute()
+
+ try:
+ async with app.DATABASE.workflow_runs.admit_workflow_run_block_dispatch(workflow_run_id) as workflow_run:
+ if workflow_run.status.is_final():
+ return WorkflowRunDispatchStopped(workflow_run=workflow_run)
+ executor_task = asyncio.create_task(execute_after_admission())
+ except BaseException as exc:
+ if executor_task is not None:
+ executor_task.cancel()
+ with suppress(asyncio.CancelledError):
+ await executor_task
+ if not isinstance(exc, Exception):
+ raise
+ raise _WorkflowRunDispatchScopeError(str(exc)) from exc
+
+ start_gate.set()
+ assert executor_task is not None
+ return await executor_task
+
async def _record_conditional_agent_episode(
self,
*,
@@ -6796,7 +6855,7 @@ class WorkflowService:
script_blocks_by_label: dict[str, Any],
loaded_script_module: Any,
is_script_run: bool,
- ) -> ScriptBlockAttempt:
+ ) -> ScriptBlockAttempt | WorkflowRunDispatchStopped:
workflow_run_block_result: BlockResult | None = None
block_executed_with_code = False
valid_to_run_code = (
@@ -6892,7 +6951,13 @@ class WorkflowService:
try:
exec_code = compile(wrapper_code, "<run_signature>", "exec")
exec(exec_code, exec_globals)
- output_value = await exec_globals["__run_signature_wrapper"]()
+ script_execution = await self._dispatch_workflow_run_block(
+ workflow_run_id,
+ exec_globals["__run_signature_wrapper"],
+ )
+ if isinstance(script_execution, WorkflowRunDispatchStopped):
+ return script_execution
+ output_value = script_execution
except ScriptTerminationException as e:
LOG.warning(
"Script termination",
@@ -6967,6 +7032,8 @@ class WorkflowService:
duration_ms=block_exec_duration_ms,
)
block_executed_with_code = False
+ except _WorkflowRunDispatchScopeError:
+ raise
except Exception as e:
block_exec_duration_ms = round((time.monotonic() - block_exec_start) * 1000, 1)
script_exception = e
@@ -7014,7 +7081,7 @@ class WorkflowService:
is_script_run: bool,
script_blocks_by_label: dict[str, Any],
attempt: ScriptBlockAttempt,
- ) -> tuple[BlockResult | None, bool]:
+ ) -> tuple[BlockResult | None, bool] | WorkflowRunDispatchStopped:
workflow_run_block_result = attempt.block_result
# Check if this block is designated as requires_agent by the script reviewer.
# These blocks must execute via agent even when ai_fallback=False.
@@ -7069,12 +7136,18 @@ class WorkflowService:
block_type=block.block_type,
agent_reason=agent_reason,
)
- workflow_run_block_result = await block.execute_safe(
- workflow_run_id=workflow_run_id,
- parent_workflow_run_block_id=parent_workflow_run_block_id,
- organization_id=organization_id,
- browser_session_id=browser_session_id,
+ agent_execution = await self._dispatch_workflow_run_block(
+ workflow_run_id,
+ lambda: block.execute_safe(
+ workflow_run_id=workflow_run_id,
+ parent_workflow_run_block_id=parent_workflow_run_block_id,
+ organization_id=organization_id,
+ browser_session_id=browser_session_id,
+ ),
)
+ if isinstance(agent_execution, WorkflowRunDispatchStopped):
+ return agent_execution
+ workflow_run_block_result = agent_execution
# Record that this run experienced a script → AI fallback if
# the agent execution we just ran was a consequence of a failed
# script attempt. The gate correctly excludes:
@@ -8005,17 +8078,23 @@ class WorkflowService:
return workflow_run, False
if target_status == WorkflowRunStatus.failed:
- workflow_run = await self.mark_workflow_run_as_failed(
+ updated_workflow_run = await self.mark_workflow_run_as_failed_if_not_final(
workflow_run_id=workflow_run_id,
failure_reason=failure_reason,
failure_category=task_failure_category,
)
+ workflow_run = updated_workflow_run or await self._current_row_after_lost_finalize(
+ workflow_run_id, workflow_run
+ )
elif target_status == WorkflowRunStatus.terminated:
- workflow_run = await self.mark_workflow_run_as_terminated(
+ updated_workflow_run = await self.mark_workflow_run_as_terminated_if_not_final(
workflow_run_id=workflow_run_id,
failure_reason=failure_reason,
failure_category=task_failure_category,
)
+ workflow_run = updated_workflow_run or await self._current_row_after_lost_finalize(
+ workflow_run_id, workflow_run
+ )
else:
LOG.warning(
"Block terminal outcome did not map to a workflow terminal status",
@@ -8124,7 +8203,7 @@ class WorkflowService:
workflow_run: WorkflowRun,
organization: Organization,
browser_session_id: str | None,
- ) -> tuple[BlockTypeVar, BlockResult] | None:
+ ) -> tuple[BlockTypeVar, BlockResult] | WorkflowRunDispatchStopped | None:
finally_block_label = workflow.workflow_definition.finally_block_label
if not finally_block_label:
return None
@@ -8145,11 +8224,17 @@ class WorkflowService:
await app.WORKFLOW_CONTEXT_MANAGER.register_block_parameters_for_workflow_run(
workflow_run.workflow_run_id, parameters, organization
)
- block_result = await block.execute_safe(
- workflow_run_id=workflow_run.workflow_run_id,
- organization_id=organization.organization_id,
- browser_session_id=browser_session_id,
+ finally_execution = await self._dispatch_workflow_run_block(
+ workflow_run.workflow_run_id,
+ lambda: block.execute_safe(
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=organization.organization_id,
+ browser_session_id=browser_session_id,
+ ),
)
+ if isinstance(finally_execution, WorkflowRunDispatchStopped):
+ return finally_execution
+ block_result = finally_execution
return block, block_result
except Exception as e:
LOG.warning(
@@ -10053,6 +10138,35 @@ class WorkflowService:
)
return workflow_run
+ async def mark_workflow_run_as_terminated_if_not_final(
+ self,
+ workflow_run_id: str,
+ failure_reason: str | None,
+ failure_category: list[dict] | None = None,
+ ) -> WorkflowRun | None:
+ if failure_category is None:
+ failure_category = self._classify_workflow_terminal_failure(
+ WorkflowRunStatus.terminated,
+ failure_reason,
+ )
+
+ workflow_run = await self._update_workflow_run_status_if_not_final(
+ workflow_run_id=workflow_run_id,
+ status=WorkflowRunStatus.terminated,
+ failure_reason=failure_reason,
+ failure_category=failure_category,
+ )
+ if workflow_run is None:
+ return None
+
+ otel_trace.get_current_span().set_attribute("task.completion_status", WorkflowRunStatus.terminated)
+ LOG.info(
+ f"Marked workflow run {workflow_run_id} as terminated (conditional)",
+ workflow_run_id=workflow_run_id,
+ failure_category=failure_category,
+ )
+ return workflow_run
+
async def mark_workflow_run_as_canceled(self, workflow_run_id: str) -> WorkflowRun:
"""Cancel a workflow run, rejecting the transition if the run has already
reached a terminal state.
diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.py
index 1cd360e02..70156ee71 100644
--- a/skyvern/forge/taskv3/loop.py
+++ b/skyvern/forge/taskv3/loop.py
@@ -317,6 +317,69 @@ def _content_only_perception(content: str) -> str:
# be recognised, so it is a detection limit and not a memory tuning knob.
PERCEPTION_RING = 8
+# Run-scoped revisit memory (SKY-14998). The ring above is a DETECTION LIMIT: a run that cycles with
+# a period longer than it returns to states the ring has already evicted, so every ring-bounded guard
+# is structurally blind to the loop rather than judging it wrongly. Measured production case: a
+# macro-cycle of period ~44 billable touches, against a ring of 8 and a canonical window of 10.
+# This remembers perception states for the WHOLE run instead, which is what makes a long cycle
+# visible at all. It is a memory, not a verdict: LOG-ONLY, nothing reads it for control flow.
+PERCEPTION_REVISIT_EVENT = "taskv3 perception state revisited"
+# Two returns to a state is a panel toggling; the third is the earliest a cycle is worth reporting.
+PERCEPTION_REVISIT_LOG_AFTER = 3
+# Bounded storage: one 64-char digest per DISTINCT perception state, so the worst case is ~32KB of digests per
+# run. At the cap the memory stops admitting NEW states and keeps counting the ones it already
+# holds — it degrades to a smaller memory rather than growing without bound, and every emission says
+# whether it was capped so a truncated run is never read as a complete one.
+PERCEPTION_REVISIT_CAP = 512
+
+
+@dataclass
+class _RevisitMemory:
+ """How many times each perception state has been seen this run, unbounded in time and bounded in
+ size. Distinct from _ProbeStreak's ring, which only remembers the last PERCEPTION_RING states and
+ therefore cannot see a cycle longer than that."""
+
+ cap: int = PERCEPTION_REVISIT_CAP
+ # digest -> (times seen, novel-state count at its last sighting)
+ _seen: dict[str, tuple[int, int]] = field(default_factory=dict)
+ capped: bool = False
+ distinct_states: int = 0
+ peak_revisits: int = 0
+ # Revisits that had fresh ground covered since the last sighting, so they were not reported.
+ # Kept as a count so the healthy population stays measurable in aggregate without a line each.
+ progressed_revisits: int = 0
+ _novel_states: int = 0
+
+ def record(self, digest: str) -> tuple[int, int]:
+ """Returns (times this state has now been seen, distinct NEW states seen since it was last
+ seen). Zero new states between two sightings is a replay; a drill-down that opens a fresh
+ page between returns to its list is not, and that difference is what makes the signal
+ filterable rather than firing on healthy and stuck runs alike.
+
+ Novelty is measured against the WHOLE run, not the probe's ring: the ring is bounded at
+ PERCEPTION_RING, so a cycle longer than it reads as fresh content there — the exact
+ blindness this memory exists to lift, and reusing that derivation would reintroduce it.
+ """
+ entry = self._seen.get(digest)
+ if entry is None:
+ if len(self._seen) >= self.cap:
+ # Refused, not evicted: dropping a known state to admit a new one would reset a
+ # streak that is the whole point of the memory.
+ self.capped = True
+ return 0, 0
+ self._novel_states += 1
+ self._seen[digest] = (1, self._novel_states)
+ self.distinct_states = len(self._seen)
+ return 1, 0
+ seen, novel_at_last_sighting = entry
+ seen += 1
+ new_states_since = self._novel_states - novel_at_last_sighting
+ self._seen[digest] = (seen, self._novel_states)
+ self.peak_revisits = max(self.peak_revisits, seen)
+ if new_states_since:
+ self.progressed_revisits += 1
+ return seen, new_states_since
+
@dataclass
class _ProbeStreak:
@@ -1414,6 +1477,7 @@ async def run_agent_tool_loop(
# Net-progress ledger (additive shadow); None disables it, mirroring the guard's *_after knobs.
progress = _ProgressLedger(window=progress_window) if progress_window is not None else None
canonical = _CanonicalProgressTracker()
+ revisit_memory = _RevisitMemory()
# The action-loop counter: (repeat count, first turn of the streak) per billable action
# identity, cleared whenever evidence of page change arrives. action_warned holds the streaks
# whose warning was actually DELIVERED — termination is gated on it, so the model always gets
@@ -2208,6 +2272,25 @@ async def run_agent_tool_loop(
content_digest = hashlib.sha256(_canonical_perception_content(result.content).encode()).hexdigest()
attribution["snapshot_digest"] = telemetry_hash(telemetry_salt, content_digest)
attribution["probe_first_time"] = perception.first_time(action_key)
+ # Emitted on its own record, never folded into the one above: the tool-call record's
+ # fields are a stable contract and this signal must not perturb them.
+ seen_count, new_states_since = revisit_memory.record(content_digest)
+ # A revisit with fresh ground covered in between is a drill-down returning to its
+ # list, not a replay. Reporting those too would fire the signal identically on
+ # healthy and stuck runs and leave the precision read it exists to feed unable to
+ # tell them apart.
+ if seen_count >= PERCEPTION_REVISIT_LOG_AFTER and not new_states_since:
+ LOG.info(
+ PERCEPTION_REVISIT_EVENT,
+ revisit_count=seen_count,
+ distinct_states=revisit_memory.distinct_states,
+ peak_revisits=revisit_memory.peak_revisits,
+ progressed_revisits=revisit_memory.progressed_revisits,
+ capped=revisit_memory.capped,
+ tool=tool_name,
+ turn=turns,
+ **attribution,
+ )
# The only per-tool-call timing the engine has: tool execution is the majority of a v3
# run's wall-clock and otherwise emits nothing at all. Names, sizes and booleans only —
# argument values and result content carry end-user data and must not be logged.
diff --git a/tests/unit/force_stub_app.py b/tests/unit/force_stub_app.py
index ff5809994..8e0369ba2 100644
--- a/tests/unit/force_stub_app.py
+++ b/tests/unit/force_stub_app.py
@@ -1,10 +1,12 @@
from contextlib import nullcontext
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
from skyvern.config import settings
from skyvern.forge import set_force_app_instance
from skyvern.forge.agent_functions import AgentFunction
from skyvern.forge.forge_app import ForgeApp
+from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
def create_forge_stub_app() -> ForgeApp:
@@ -88,6 +90,11 @@ def create_forge_stub_app() -> ForgeApp:
fake_app_module.DATABASE.workflow_runs.create_or_update_workflow_run_output_parameter = AsyncMock()
fake_app_module.DATABASE.tasks.get_last_task_for_workflow_run = AsyncMock()
fake_app_module.DATABASE.workflow_runs.get_workflow_run = AsyncMock()
+ fake_app_module.DATABASE.workflow_runs.admit_workflow_run_block_dispatch = MagicMock(
+ side_effect=lambda workflow_run_id: nullcontext(
+ SimpleNamespace(workflow_run_id=workflow_run_id, status=WorkflowRunStatus.running)
+ )
+ )
fake_app_module.DATABASE.workflow_runs.get_secure_runner_pin = AsyncMock(return_value=None)
fake_app_module.DATABASE.observer.get_workflow_run_block = AsyncMock()
fake_app_module.DATABASE.tasks.get_task = AsyncMock()
diff --git a/tests/unit/test_copilot_terminal_envelope.py b/tests/unit/test_copilot_terminal_envelope.py
index 6d1cfb113..7e3282eb2 100644
--- a/tests/unit/test_copilot_terminal_envelope.py
+++ b/tests/unit/test_copilot_terminal_envelope.py
@@ -38,6 +38,7 @@ from skyvern.forge.sdk.copilot.terminal_envelope import (
TerminalOutcomeEnvelope,
admit_question_parts,
assemble_terminal_envelope,
+ chat_awaits_user_input,
finalize_applied_state,
interim_run_start_outcome,
is_interim_run_outcome,
@@ -1762,3 +1763,50 @@ def test_admission_keeps_only_parts_the_server_can_vouch_for() -> None:
("p2", "Which email?", []),
("p3", "Which day?", ["Monday"]),
]
+
+
+def _asking_row(**overrides: Any) -> dict[str, Any]:
+ payload: dict[str, Any] = {
+ "cancelled": False,
+ "terminalEnvelope": {
+ "next_state": "awaiting_user_input",
+ "response_kind": "question",
+ "user_action_required": True,
+ "rendered_from_envelope": True,
+ },
+ }
+ payload.update(overrides)
+ return payload
+
+
+def test_the_last_message_asking_marks_the_chat_awaiting() -> None:
+ assert chat_awaits_user_input(sender="ai", narrative_payload=_asking_row()) is True
+
+
+def test_a_user_reply_after_the_ask_clears_it() -> None:
+ # The user answered; the tail of the chat is theirs, so nothing is pending.
+ assert chat_awaits_user_input(sender="user", narrative_payload=_asking_row()) is False
+
+
+def test_a_stop_is_not_an_ask() -> None:
+ # The cancel path persists the pre-cancel envelope verbatim.
+ assert chat_awaits_user_input(sender="ai", narrative_payload=_asking_row(cancelled=True)) is False
+
+
+def test_an_unstamped_envelope_is_not_display_authority() -> None:
+ row = _asking_row()
+ row["terminalEnvelope"]["rendered_from_envelope"] = False
+ assert chat_awaits_user_input(sender="ai", narrative_payload=row) is False
+
+
+def test_a_terminal_state_other_than_awaiting_is_not_an_ask() -> None:
+ row = _asking_row()
+ row["terminalEnvelope"]["next_state"] = "completed"
+ assert chat_awaits_user_input(sender="ai", narrative_payload=row) is False
+
+
+def test_rows_without_an_envelope_are_not_asks() -> None:
+ assert chat_awaits_user_input(sender="ai", narrative_payload=None) is False
+ assert chat_awaits_user_input(sender="ai", narrative_payload={}) is False
+ assert chat_awaits_user_input(sender="ai", narrative_payload={"terminalEnvelope": None}) is False
+ assert chat_awaits_user_input(sender="ai", narrative_payload={"terminalEnvelope": "nonsense"}) is False
diff --git a/tests/unit/test_finally_block_status.py b/tests/unit/test_finally_block_status.py
index d5811f0ea..c9adaa44a 100644
--- a/tests/unit/test_finally_block_status.py
+++ b/tests/unit/test_finally_block_status.py
@@ -1,3 +1,5 @@
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
@@ -5,7 +7,7 @@ import pytest
from skyvern.forge.sdk.workflow import service as service_module
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
-from skyvern.forge.sdk.workflow.service import WorkflowService
+from skyvern.forge.sdk.workflow.service import WorkflowRunDispatchStopped, WorkflowService
from skyvern.schemas.workflows import BlockResult, BlockStatus
@@ -42,6 +44,55 @@ def _workflow_run(
)
[email protected](autouse=True)
+def _allow_dispatch(monkeypatch: pytest.MonkeyPatch) -> None:
+ @asynccontextmanager
+ async def admit_dispatch(_: str) -> AsyncIterator[SimpleNamespace]:
+ yield _workflow_run(WorkflowRunStatus.running)
+
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_runs,
+ "admit_workflow_run_block_dispatch",
+ admit_dispatch,
+ )
+
+
+async def test_cancellation_before_finally_handoff_prevents_dispatch(monkeypatch: pytest.MonkeyPatch) -> None:
+ canceled_run = _workflow_run(WorkflowRunStatus.canceled)
+ block = _block()
+ block.get_all_parameters = Mock(return_value=[])
+ block.execute_safe = AsyncMock()
+ workflow = SimpleNamespace(
+ workflow_definition=SimpleNamespace(finally_block_label=block.label, blocks=[block]),
+ )
+
+ @asynccontextmanager
+ async def deny_dispatch(_: str) -> AsyncIterator[SimpleNamespace]:
+ yield canceled_run
+
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_runs,
+ "admit_workflow_run_block_dispatch",
+ deny_dispatch,
+ )
+ monkeypatch.setattr(
+ service_module.app,
+ "WORKFLOW_CONTEXT_MANAGER",
+ SimpleNamespace(register_block_parameters_for_workflow_run=AsyncMock()),
+ )
+
+ result = await WorkflowService()._execute_finally_block_if_configured(
+ workflow=workflow,
+ workflow_run=_workflow_run(WorkflowRunStatus.running),
+ organization=SimpleNamespace(organization_id="org_test"),
+ browser_session_id=None,
+ )
+
+ assert result == WorkflowRunDispatchStopped(workflow_run=canceled_run)
+ block.execute_safe.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_execute_finally_block_returns_block_result(monkeypatch: pytest.MonkeyPatch) -> None:
block_result = _block_result(BlockStatus.failed, failure_reason="upload failed")
@@ -75,8 +126,10 @@ async def test_execute_finally_block_returns_block_result(monkeypatch: pytest.Mo
@pytest.mark.asyncio
[email protected]("failure_phase", ["executor", "admission", "commit"])
async def test_execute_finally_block_converts_exception_to_failed_result(
monkeypatch: pytest.MonkeyPatch,
+ failure_phase: str,
) -> None:
block = _block()
block.get_all_parameters = Mock(return_value=[])
@@ -87,7 +140,7 @@ async def test_execute_finally_block_converts_exception_to_failed_result(
blocks=[block],
)
)
- workflow_run = _workflow_run(WorkflowRunStatus.completed)
+ workflow_run = _workflow_run(WorkflowRunStatus.running)
organization = SimpleNamespace(organization_id="org_test")
monkeypatch.setattr(
service_module.app,
@@ -95,7 +148,23 @@ async def test_execute_finally_block_converts_exception_to_failed_result(
SimpleNamespace(register_block_parameters_for_workflow_run=AsyncMock()),
)
- result = await WorkflowService()._execute_finally_block_if_configured(
+ if failure_phase != "executor":
+
+ @asynccontextmanager
+ async def fail_admission(_: str) -> AsyncIterator[SimpleNamespace]:
+ if failure_phase == "admission":
+ raise RuntimeError("upload exploded")
+ yield workflow_run
+ raise RuntimeError("upload exploded")
+
+ monkeypatch.setattr(
+ service_module.app.DATABASE.workflow_runs,
+ "admit_workflow_run_block_dispatch",
+ fail_admission,
+ )
+
+ service = WorkflowService()
+ result = await service._execute_finally_block_if_configured(
workflow=workflow,
workflow_run=workflow_run,
organization=organization,
@@ -109,6 +178,18 @@ async def test_execute_finally_block_converts_exception_to_failed_result(
assert block_result.success is False
assert block_result.status == BlockStatus.failed
assert block_result.failure_reason == "Unexpected error: upload exploded"
+ if failure_phase != "executor":
+ block.execute_safe.assert_not_awaited()
+
+ _, terminal_intent, _ = await service._apply_finally_block_result(
+ block=block,
+ block_result=block_result,
+ workflow_run=workflow_run,
+ pre_finally_status=workflow_run.status,
+ pre_finally_failure_reason=None,
+ defer_status_write=True,
+ )
+ assert terminal_intent == WorkflowRunStatus.failed
@pytest.mark.asyncio
diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.py
index 7a76ba94c..c6048c8e9 100644
--- a/tests/unit/test_taskv3_loop.py
+++ b/tests/unit/test_taskv3_loop.py
@@ -38,6 +38,9 @@ from skyvern.forge.taskv3.loop import (
PAGE_REFRESH_EXHAUSTED_REASON_PREFIX,
PAGE_STATE_STALL_SHADOW_EVENT,
PAGE_UNAVAILABLE_ERROR,
+ PERCEPTION_REVISIT_EVENT,
+ PERCEPTION_REVISIT_LOG_AFTER,
+ PERCEPTION_RING,
PERCEPTION_STALL_NUDGE_AFTER,
PERCEPTION_STALL_REASON_PREFIX,
PERCEPTION_STALL_SHADOW_EVENT,
@@ -56,6 +59,7 @@ from skyvern.forge.taskv3.loop import (
_canonical_perception_content,
_PerceptionLedger,
_ProgressLedger,
+ _RevisitMemory,
make_finish_tool,
run_agent_tool_loop,
)
@@ -6205,6 +6209,22 @@ async def test_staged_download_stays_excluded_for_the_rest_of_the_run() -> None:
# --- SKY-15020 Lever C: net-progress _ProgressLedger (additive shadow) ---
+def _cycling_observe(name: str, period: int) -> ToolSpec:
+ """Observe fake whose content REPEATS with the given period: call i returns state (i % period).
+ A period longer than PERCEPTION_RING is invisible to the ring-bounded revisit guards, which is
+ the detection limit the run-scoped memory exists to lift."""
+ calls = {"n": 0}
+
+ async def handler(args: dict[str, Any]) -> ToolResult:
+ state = calls["n"] % period
+ calls["n"] += 1
+ return ToolResult.ok(f"url=x state={state}", data={"summary": {"invalid_fields": 0}})
+
+ return ToolSpec(
+ name=name, description=name, parameters={"type": "object", "properties": {}}, handler=handler, compactable=True
+ )
+
+
def _form_observe(name: str, invalid_seq: list[int]) -> ToolSpec:
"""Observe fake: call i returns UNIQUE content plus summary.invalid_fields=invalid_seq[i] (last
value repeats). Unique content each call keeps the perception-stall / oscillation guards from
@@ -6448,6 +6468,98 @@ async def test_progress_ledger_emits_terminal_survival_record() -> None:
assert final[0]["would_fire"] is True
+async def test_revisit_memory_sees_a_cycle_longer_than_the_perception_ring() -> None:
+ # The detection limit this exists to lift: PERCEPTION_RING is 8, and its own comment says that
+ # length IS the longest oscillation period that can be recognised. A run cycling with period 12
+ # returns to states the ring has already evicted, so every ring-bounded guard is structurally
+ # blind to it. The run-scoped memory is not.
+ period = PERCEPTION_RING + 4
+ rounds = period * PERCEPTION_REVISIT_LOG_AFTER + period
+ tools = [_cycling_observe("observe", period), make_finish_tool()]
+ script: list[list[tuple[str, dict[str, Any]]]] = [[("observe", {})] for _ in range(rounds)]
+ script.append([("finish", {"status": "completed", "reason": "done"})])
+ with capture_logs() as logs:
+ outcome, _ = await _run(script, tools, max_turns=200, max_tool_calls=500)
+
+ assert outcome.status == "completed"
+ revisits = [e for e in logs if e.get("event") == PERCEPTION_REVISIT_EVENT]
+ assert revisits, "a cycle longer than the ring must still be seen"
+ assert max(e["revisit_count"] for e in revisits) >= PERCEPTION_REVISIT_LOG_AFTER
+ # Log-only: the run is not terminated and no verdict is taken on this signal.
+ assert outcome.status == "completed"
+
+
+def test_revisit_memory_refuses_new_states_at_the_cap_without_evicting_known_ones() -> None:
+ # The storage bound, pinned rather than asserted in a comment. Evicting a held state to admit a
+ # new one would reset the very streak the memory exists to keep, so at the cap it REFUSES new
+ # states and keeps counting the ones it holds — degrading to a smaller memory, never to none.
+ memory = _RevisitMemory(cap=2)
+ assert memory.record("a") == (1, 0)
+ assert memory.record("b") == (1, 0)
+ assert memory.capped is False
+
+ assert memory.record("c") == (0, 0), "a refused state must not report a count"
+ assert memory.capped is True, "a truncated run must never read as a complete one"
+
+ # "b" was the only state admitted after "a" was last seen, so returning to "a" has one new
+ # state behind it; returning again straight away has none.
+ assert memory.record("a") == (2, 1)
+ assert memory.record("a") == (3, 0)
+ assert memory.peak_revisits == 3
+ assert memory.distinct_states == 2
+
+
+async def test_revisit_memory_stays_quiet_on_a_healthy_drill_down() -> None:
+ # The false-positive case that decides whether this signal is worth collecting. A drill-down
+ # returns to its list page over and over — a revisit every other touch — but opens a NEW item
+ # in between, so it is progressing. Reporting it would fire identically on healthy and stuck
+ # runs and leave the precision read this feeds unable to separate them.
+ items = 12
+ calls = {"n": 0}
+
+ async def handler(args: dict[str, Any]) -> ToolResult:
+ # list, item-0, list, item-1, list, item-2, ... the list recurs, each item is new.
+ i = calls["n"]
+ calls["n"] += 1
+ content = "url=x list" if i % 2 == 0 else f"url=x item-{i // 2}"
+ return ToolResult.ok(content, data={"summary": {"invalid_fields": 0}})
+
+ observe = ToolSpec(
+ name="observe",
+ description="observe",
+ parameters={"type": "object", "properties": {}},
+ handler=handler,
+ compactable=True,
+ )
+ script: list[list[tuple[str, dict[str, Any]]]] = [[("observe", {})] for _ in range(items * 2)]
+ script.append([("finish", {"status": "completed", "reason": "done"})])
+ with capture_logs() as logs:
+ outcome, _ = await _run(script, [observe, make_finish_tool()], max_turns=200, max_tool_calls=500)
+
+ assert outcome.status == "completed"
+ assert not [e for e in logs if e.get("event") == PERCEPTION_REVISIT_EVENT], (
+ "a run covering fresh ground between returns to its list is progressing, not looping"
+ )
+
+
+async def test_revisit_memory_silent_when_every_perception_state_is_new() -> None:
+ # A run that never returns to a state has no revisit to report. This is the false-positive
+ # direction that matters: a shadow signal headed for a future verdict must stay quiet on a run
+ # that is genuinely moving through fresh pages.
+ rounds = 20
+ tools = [_form_observe("observe", [0] * rounds), make_finish_tool()]
+ script: list[list[tuple[str, dict[str, Any]]]] = [[("observe", {})] for _ in range(rounds)]
+ script.append([("finish", {"status": "completed", "reason": "done"})])
+ with capture_logs() as logs:
+ outcome, _ = await _run(script, tools, max_turns=200, max_tool_calls=500)
+
+ assert outcome.status == "completed"
+ assert not [e for e in logs if e.get("event") == PERCEPTION_REVISIT_EVENT]
+
+
@pytest.mark.asyncio
async def test_non_form_run_emits_its_own_survival_record_keyed_on_canonical_touches() -> None:
# The ledger's survival record is gated on ever_armed, so it covers only runs that saw a
diff --git a/tests/unit/test_workflow_service_cancel.py b/tests/unit/test_workflow_service_cancel.py
index 3bfb20de5..1f997861a 100644
--- a/tests/unit/test_workflow_service_cancel.py
+++ b/tests/unit/test_workflow_service_cancel.py
@@ -405,6 +405,63 @@ async def test_mark_canceled_raises_when_row_missing(
await svc.mark_workflow_run_as_canceled(workflow_run_id="wr_missing")
+async def test_cleanup_after_cancellation_emits_only_canceled_webhook(monkeypatch: pytest.MonkeyPatch) -> None:
+ from skyvern.forge.sdk.workflow import service as service_module
+ from skyvern.forge.sdk.workflow.service import WorkflowBrowserCleanupResult, WorkflowService
+
+ running_run = _make_updated_row()
+ running_run.workflow_run_id = "wr_canceled_during_cleanup"
+ running_run.status = WorkflowRunStatus.running
+ canceled_run = _make_updated_row()
+ canceled_run.workflow_run_id = running_run.workflow_run_id
+
+ svc = WorkflowService()
+ monkeypatch.setattr(svc, "_grade_completion_contract", AsyncMock(return_value=None))
+ conditional_finalize = AsyncMock(return_value=None)
+ monkeypatch.setattr(svc, "_update_workflow_run_status_if_not_final", conditional_finalize)
+ monkeypatch.setattr(svc, "get_workflow_run", AsyncMock(return_value=canceled_run))
+
+ webhook_statuses: list[WorkflowRunStatus] = []
+
+ async def record_webhook(workflow_run: MagicMock, _api_key: str | None = None) -> None:
+ webhook_statuses.append(workflow_run.status)
+
+ monkeypatch.setattr(svc, "execute_workflow_webhook", record_webhook)
+ monkeypatch.setattr(app.AGENT_FUNCTION, "on_workflow_run_terminal", AsyncMock())
+ monkeypatch.setattr(app.ARTIFACT_MANAGER, "wait_for_upload_aiotasks", AsyncMock())
+ monkeypatch.setattr(app.STORAGE, "save_downloaded_files", AsyncMock())
+ monkeypatch.setattr(service_module.uploaded_file_service, "delete_files_attached_to_run", AsyncMock())
+ monkeypatch.setattr(service_module.skyvern_context, "current", lambda: None)
+ monkeypatch.setattr(app.WORKFLOW_CONTEXT_MANAGER, "remove_workflow_run_context", MagicMock())
+
+ finalized_run = await svc._finalize_workflow_run_status(
+ workflow_run_id=running_run.workflow_run_id,
+ workflow_run=running_run,
+ pre_finally_status=WorkflowRunStatus.running,
+ pre_finally_failure_reason=None,
+ )
+ await svc.clean_up_workflow(
+ workflow=MagicMock(),
+ workflow_run=finalized_run,
+ browser_cleanup_result=WorkflowBrowserCleanupResult(
+ browser_state=None,
+ tasks=[],
+ all_workflow_task_ids=[],
+ child_workflow_run_ids=[],
+ close_browser_on_completion=True,
+ ),
+ schedule_credential_fallback_retry=False,
+ )
+
+ conditional_finalize.assert_awaited_once_with(
+ workflow_run_id=running_run.workflow_run_id,
+ status=WorkflowRunStatus.completed,
+ )
+ assert finalized_run is canceled_run
+ assert webhook_statuses == [WorkflowRunStatus.canceled]
+
+
@pytest.mark.asyncio
async def test_execute_workflow_webhook_tolerates_soft_deleted_workflow(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/workflow/test_execute_single_block_phases.py b/tests/unit/workflow/test_execute_single_block_phases.py
index b3dbcc886..004e89fbe 100644
--- a/tests/unit/workflow/test_execute_single_block_phases.py
+++ b/tests/unit/workflow/test_execute_single_block_phases.py
@@ -8,6 +8,9 @@ before and after every extraction.
from __future__ import annotations
+import asyncio
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
from datetime import UTC, datetime
from types import SimpleNamespace
from typing import Any
@@ -26,7 +29,11 @@ from skyvern.forge.sdk.workflow.models.block import (
)
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
-from skyvern.forge.sdk.workflow.service import DebugSessionProfileDecision, WorkflowService
+from skyvern.forge.sdk.workflow.service import (
+ DebugSessionProfileDecision,
+ WorkflowRunDispatchStopped,
+ WorkflowService,
+)
from skyvern.schemas.scripts import ScriptBlock
from skyvern.schemas.workflows import BlockResult, BlockStatus
from skyvern.services import script_service
@@ -154,6 +161,188 @@ def _stub_run_refresh(monkeypatch: pytest.MonkeyPatch) -> None:
# get_all_parameters needs a sync context object; the stub app's auto-AsyncMock returns a coroutine.
monkeypatch.setattr(app.WORKFLOW_CONTEXT_MANAGER, "get_workflow_run_context", MagicMock(return_value=MagicMock()))
+ @asynccontextmanager
+ async def admit_dispatch(_: str) -> AsyncIterator[MagicMock]:
+ yield _workflow_run()
+
+ monkeypatch.setattr(app.DATABASE.workflow_runs, "admit_workflow_run_block_dispatch", admit_dispatch)
+
+
+async def test_dispatch_waits_for_successful_admission_scope_exit(monkeypatch: pytest.MonkeyPatch) -> None:
+ scope_exiting = asyncio.Event()
+ release_scope = asyncio.Event()
+ executor_started = asyncio.Event()
+
+ @asynccontextmanager
+ async def admit_dispatch(_: str) -> AsyncIterator[MagicMock]:
+ yield _workflow_run()
+ scope_exiting.set()
+ await release_scope.wait()
+
+ async def execute() -> str:
+ executor_started.set()
+ return "executed"
+
+ monkeypatch.setattr(app.DATABASE.workflow_runs, "admit_workflow_run_block_dispatch", admit_dispatch)
+ dispatch_task = asyncio.create_task(WorkflowService()._dispatch_workflow_run_block("wr_test", execute))
+
+ await scope_exiting.wait()
+ next_turn = asyncio.get_running_loop().create_future()
+ asyncio.get_running_loop().call_soon(next_turn.set_result, None)
+ await next_turn
+ assert executor_started.is_set() is False
+
+ release_scope.set()
+ assert await dispatch_task == "executed"
+ assert executor_started.is_set() is True
+
+
+async def test_dispatch_cancellation_cancels_dormant_executor(monkeypatch: pytest.MonkeyPatch) -> None:
+ scope_exiting = asyncio.Event()
+ release_scope = asyncio.Event()
+ execute = AsyncMock()
+
+ @asynccontextmanager
+ async def admit_dispatch(_: str) -> AsyncIterator[MagicMock]:
+ yield _workflow_run()
+ scope_exiting.set()
+ await release_scope.wait()
+
+ monkeypatch.setattr(app.DATABASE.workflow_runs, "admit_workflow_run_block_dispatch", admit_dispatch)
+ dispatch_task = asyncio.create_task(WorkflowService()._dispatch_workflow_run_block("wr_test", execute))
+ await scope_exiting.wait()
+
+ dispatch_task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await dispatch_task
+ execute.assert_not_awaited()
+
+
+async def test_dispatch_propagates_executor_exception_once(monkeypatch: pytest.MonkeyPatch) -> None:
+ execute = AsyncMock(side_effect=RuntimeError("executor failed"))
+
+ with pytest.raises(RuntimeError, match="executor failed"):
+ await WorkflowService()._dispatch_workflow_run_block("wr_test", execute)
+
+ execute.assert_awaited_once_with()
+
+
+async def test_dispatch_scope_failure_cancels_dormant_executor(monkeypatch: pytest.MonkeyPatch) -> None:
+ execute = AsyncMock(return_value="must not run")
+
+ @asynccontextmanager
+ async def admit_dispatch(_: str) -> AsyncIterator[MagicMock]:
+ yield _workflow_run()
+ raise RuntimeError("commit failed")
+
+ monkeypatch.setattr(app.DATABASE.workflow_runs, "admit_workflow_run_block_dispatch", admit_dispatch)
+
+ with pytest.raises(RuntimeError, match="commit failed"):
+ await WorkflowService()._dispatch_workflow_run_block("wr_test", execute)
+
+ execute.assert_not_awaited()
+
+
+async def test_cancellation_after_initial_read_prevents_agent_dispatch(monkeypatch: pytest.MonkeyPatch) -> None:
+ canceled_run = _workflow_run()
+ canceled_run.status = WorkflowRunStatus.canceled
+
+ @asynccontextmanager
+ async def deny_dispatch(_: str) -> AsyncIterator[MagicMock]:
+ yield canceled_run
+
+ monkeypatch.setattr(app.DATABASE.workflow_runs, "admit_workflow_run_block_dispatch", deny_dispatch)
+ execute_safe = AsyncMock()
+ monkeypatch.setattr(NavigationBlock, "execute_safe", execute_safe)
+
+ workflow_run, _, block_result, should_stop, _ = await _run_single_block(WorkflowService(), _navigation_block("nav"))
+
+ assert workflow_run is canceled_run
+ assert block_result is None
+ assert should_stop is True
+ execute_safe.assert_not_awaited()
+
+
+async def test_cancellation_before_script_handoff_prevents_script_dispatch(monkeypatch: pytest.MonkeyPatch) -> None:
+ canceled_run = _workflow_run()
+ canceled_run.status = WorkflowRunStatus.canceled
+
+ @asynccontextmanager
+ async def deny_dispatch(_: str) -> AsyncIterator[MagicMock]:
+ yield canceled_run
+
+ script_calls: list[str] = []
+ monkeypatch.setattr(app.DATABASE.workflow_runs, "admit_workflow_run_block_dispatch", deny_dispatch)
+ observer_read = AsyncMock()
+ monkeypatch.setattr(app.DATABASE.observer, "get_workflow_run_blocks", observer_read)
+
+ workflow_run, _, block_result, should_stop, _ = await _run_single_block(
+ WorkflowService(),
+ _navigation_block("cached_nav"),
+ is_script_run=True,
+ script_blocks_by_label={"cached_nav": _script_block("cached_nav", "record_dispatch()")},
+ loaded_script_module=SimpleNamespace(record_dispatch=lambda: script_calls.append("called")),
+ )
+
+ assert workflow_run is canceled_run
+ assert block_result is None
+ assert should_stop is True
+ assert script_calls == []
+ observer_read.assert_not_awaited()
+
+
+async def test_cancellation_before_script_fallback_prevents_agent_dispatch(monkeypatch: pytest.MonkeyPatch) -> None:
+ running_run = _workflow_run()
+ canceled_run = _workflow_run()
+ canceled_run.status = WorkflowRunStatus.canceled
+ admissions = iter((running_run, canceled_run))
+
+ @asynccontextmanager
+ async def admit_then_deny(_: str) -> AsyncIterator[MagicMock]:
+ yield next(admissions)
+
+ monkeypatch.setattr(app.DATABASE.workflow_runs, "admit_workflow_run_block_dispatch", admit_then_deny)
+ execute_safe = AsyncMock()
+ monkeypatch.setattr(NavigationBlock, "execute_safe", execute_safe)
+
+ workflow_run, _, block_result, should_stop, _ = await _run_single_block(
+ WorkflowService(),
+ _navigation_block("cached_nav"),
+ is_script_run=True,
+ script_blocks_by_label={"cached_nav": _script_block("cached_nav", "1 / 0")},
+ loaded_script_module=SimpleNamespace(),
+ )
+
+ assert workflow_run is canceled_run
+ assert block_result is None
+ assert should_stop is True
+ execute_safe.assert_not_awaited()
+
+
+async def test_dispatch_denial_returns_typed_stop(monkeypatch: pytest.MonkeyPatch) -> None:
+ canceled_run = _workflow_run()
+ canceled_run.status = WorkflowRunStatus.canceled
+ execute = AsyncMock()
+
+ @asynccontextmanager
+ async def deny_dispatch(_: str) -> AsyncIterator[MagicMock]:
+ yield canceled_run
+
+ monkeypatch.setattr(app.DATABASE.workflow_runs, "admit_workflow_run_block_dispatch", deny_dispatch)
+
+ result = await WorkflowService()._dispatch_workflow_run_block("wr_test", execute)
+
+ assert result == WorkflowRunDispatchStopped(workflow_run=canceled_run)
+ execute.assert_not_awaited()
+
@pytest.mark.asyncio
async def test_returns_early_when_run_already_final(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -207,7 +396,7 @@ async def test_missing_block_result_marks_run_failed(monkeypatch: pytest.MonkeyP
monkeypatch.setattr(NavigationBlock, "execute_safe", AsyncMock(return_value=None))
failed_run = MagicMock()
mark_failed = AsyncMock(return_value=failed_run)
- monkeypatch.setattr(WorkflowService, "mark_workflow_run_as_failed", mark_failed)
+ monkeypatch.setattr(WorkflowService, "mark_workflow_run_as_failed_if_not_final", mark_failed)
workflow_run, _, block_result, should_stop, _ = await _run_single_block(service, _navigation_block("nav"))
@@ -217,13 +406,72 @@ async def test_missing_block_result_marks_run_failed(monkeypatch: pytest.MonkeyP
assert should_stop is True
+async def test_missing_result_cannot_overwrite_concurrent_cancellation(monkeypatch: pytest.MonkeyPatch) -> None:
+ service = WorkflowService()
+ canceled_run = _workflow_run()
+ canceled_run.status = WorkflowRunStatus.canceled
+ monkeypatch.setattr(NavigationBlock, "execute_safe", AsyncMock(return_value=None))
+ conditional_failure = AsyncMock(return_value=None)
+ monkeypatch.setattr(WorkflowService, "mark_workflow_run_as_failed_if_not_final", conditional_failure)
+ monkeypatch.setattr(service, "_current_row_after_lost_finalize", AsyncMock(return_value=canceled_run))
+
+ workflow_run, _, block_result, should_stop, _ = await _run_single_block(service, _navigation_block("nav"))
+
+ assert workflow_run is canceled_run
+ assert block_result is None
+ assert should_stop is True
+ conditional_failure.assert_awaited_once()
+
+
+ ("block_status", "conditional_method"),
+ [
+ (BlockStatus.failed, "mark_workflow_run_as_failed_if_not_final"),
+ (BlockStatus.terminated, "mark_workflow_run_as_terminated_if_not_final"),
+ ],
+)
+async def test_block_terminal_outcome_cannot_overwrite_concurrent_cancellation(
+ monkeypatch: pytest.MonkeyPatch,
+ block_status: BlockStatus,
+ conditional_method: str,
+) -> None:
+ service = WorkflowService()
+ block = _navigation_block("nav")
+ block_result = BlockResult(
+ success=False,
+ failure_reason="block stopped",
+ output_parameter=block.output_parameter,
+ status=block_status,
+ )
+ canceled_run = _workflow_run()
+ canceled_run.status = WorkflowRunStatus.canceled
+ conditional_terminal = AsyncMock(return_value=None)
+ monkeypatch.setattr(service, conditional_method, conditional_terminal)
+ monkeypatch.setattr(service, "_current_row_after_lost_finalize", AsyncMock(return_value=canceled_run))
+
+ workflow_run, should_stop = await service._handle_block_result_status(
+ block=block,
+ block_idx=0,
+ blocks_cnt=1,
+ block_result=block_result,
+ workflow_run=_workflow_run(),
+ workflow_run_id="wr_test",
+ )
+
+ assert workflow_run is canceled_run
+ assert should_stop is True
+ conditional_terminal.assert_awaited_once()
+
+
@pytest.mark.asyncio
async def test_block_exception_marks_run_failed_with_block_type_reason(monkeypatch: pytest.MonkeyPatch) -> None:
service = WorkflowService()
monkeypatch.setattr(NavigationBlock, "execute_safe", AsyncMock(side_effect=RuntimeError("boom")))
failed_run = MagicMock()
mark_failed = AsyncMock(return_value=failed_run)
- monkeypatch.setattr(WorkflowService, "mark_workflow_run_as_failed", mark_failed)
+ monkeypatch.setattr(WorkflowService, "mark_workflow_run_as_failed_if_not_final", mark_failed)
workflow_run, _, _, should_stop, _ = await _run_single_block(service, _navigation_block("nav"))
@@ -259,7 +507,7 @@ async def test_ai_fallback_disabled_keeps_script_failure(monkeypatch: pytest.Mon
monkeypatch.setattr(NavigationBlock, "_apply_workflow_system_prompt", lambda self, ctx: None)
failed_run = MagicMock()
mark_failed = AsyncMock(return_value=failed_run)
- monkeypatch.setattr(WorkflowService, "mark_workflow_run_as_failed", mark_failed)
+ monkeypatch.setattr(WorkflowService, "mark_workflow_run_as_failed_if_not_final", mark_failed)
workflow_run, _, _, should_stop, _ = await _run_single_block(
service,