Skip to content

Automate browser based workflows with AI

Stop a self-hosted run from starting or writing loop output when another server holds its lease (SKY-18224) (#8982)

LawyZheng00ad00f0dc5f
diff --git a/skyvern/forge/sdk/executor/background_task_executor.py b/skyvern/forge/sdk/executor/background_task_executor.py
index 0c24b16f6..2d9f84292 100644
--- a/skyvern/forge/sdk/executor/background_task_executor.py
+++ b/skyvern/forge/sdk/executor/background_task_executor.py
@@ -24,7 +24,7 @@ from skyvern.forge.sdk.db.repositories.workflow_run_attempts import (
ATTEMPT_RECOVERY_MAX_PAGES,
)
from skyvern.forge.sdk.executor.async_executor import AsyncExecutor
-from skyvern.forge.sdk.executor.run_liveness import acquire_run_lease, hold_run, track_run
+from skyvern.forge.sdk.executor.run_liveness import acquire_run_lease, hold_run, run_lease_lost, track_run
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.schemas.persistent_browser_sessions import FORCED_WORKFLOW_SESSION_RUNNABLE_TYPE
from skyvern.forge.sdk.schemas.task_v2 import TaskV2Status
@@ -381,6 +381,16 @@ class BackgroundTaskExecutor(AsyncExecutor):
return org_auth_token.token if org_auth_token else None
async def _initialize_retry_resume(self, attempt: Any, *, prepared: bool) -> tuple[Organization, str] | None:
+ with track_run(attempt.workflow_run_id, "workflow_run", attempt.attempt_number):
+ if not await acquire_run_lease(attempt.workflow_run_id):
+ # Without this key the sweep treats a stale retry decision as orphaned and abandons it.
+ self._retry_resumes_needing_recovery.add((attempt.workflow_run_id, attempt.attempt_number))
+ return None
+ return await self._initialize_admitted_retry_resume(attempt, prepared=prepared)
+
+ async def _initialize_admitted_retry_resume(
+ self, attempt: Any, *, prepared: bool
+ ) -> tuple[Organization, str] | None:
deadline = naive_utc_now() + timedelta(seconds=LEASE_TAKEOVER_SECONDS)
backoff_seconds = 1.0
previous_missing: str | None = None
@@ -613,6 +623,16 @@ class BackgroundTaskExecutor(AsyncExecutor):
return False
async def _dispatch_retry_resume(self, attempt: Any, execution_kwargs: dict[str, Any]) -> None:
+ with track_run(attempt.workflow_run_id, "workflow_run", execution_kwargs["attempt_number"]):
+ if not await acquire_run_lease(attempt.workflow_run_id):
+ # A prepared claim is already stamped; only stale-claim recovery could otherwise reach it.
+ key = (attempt.workflow_run_id, attempt.attempt_number)
+ self._retry_dispatches_needing_recovery[key] = (attempt, execution_kwargs)
+ self._retry_resumes_needing_recovery.add(key)
+ return
+ await self._dispatch_admitted_retry_resume(attempt, execution_kwargs)
+
+ async def _dispatch_admitted_retry_resume(self, attempt: Any, execution_kwargs: dict[str, Any]) -> None:
key = (attempt.workflow_run_id, attempt.attempt_number)
self._retry_dispatches_needing_recovery.pop(key, None)
execution_started = False
@@ -719,16 +739,17 @@ class BackgroundTaskExecutor(AsyncExecutor):
if organization is None:
raise OrganizationNotFound(organization_id)
- step = await app.DATABASE.tasks.create_step(
- task_id,
- order=0,
- retry_index=0,
- organization_id=organization_id,
- )
-
release_hold = hold_run(task_id, "task")
try:
- await acquire_run_lease(task_id)
+ if not await acquire_run_lease(task_id):
+ release_hold()
+ return
+ step = await app.DATABASE.tasks.create_step(
+ task_id,
+ order=0,
+ retry_index=0,
+ organization_id=organization_id,
+ )
task = await app.DATABASE.tasks.update_task(
task_id,
status=TaskStatus.running,
@@ -763,6 +784,8 @@ class BackgroundTaskExecutor(AsyncExecutor):
async def execute_registered_step(*args: Any, **kwargs: Any) -> None:
with track_run(task_id, "task"):
release_hold()
+ if await run_lease_lost(task_id):
+ return
await app.agent.execute_step(*args, **kwargs)
self._schedule(
@@ -957,28 +980,40 @@ class BackgroundTaskExecutor(AsyncExecutor):
if not task_v2 or not task_v2.workflow_run_id:
raise ValueError("No task v2 or no workflow run associated with task v2")
- # mark task v2 as queued
- await app.DATABASE.observer.update_task_v2(
- task_v2_id=task_v2_id,
- status=TaskV2Status.queued,
- organization_id=organization_id,
- )
- await app.DATABASE.workflow_runs.update_workflow_run(
- workflow_run_id=task_v2.workflow_run_id,
- status=WorkflowRunStatus.queued,
- )
+ workflow_run_id = task_v2.workflow_run_id
+ release_hold = hold_run(workflow_run_id, "workflow_run")
+ try:
+ if not await acquire_run_lease(workflow_run_id):
+ release_hold()
+ return
+ await app.DATABASE.observer.update_task_v2(
+ task_v2_id=task_v2_id,
+ status=TaskV2Status.queued,
+ organization_id=organization_id,
+ )
+ await app.DATABASE.workflow_runs.update_workflow_run(
+ workflow_run_id=workflow_run_id,
+ status=WorkflowRunStatus.queued,
+ )
- await initialize_skyvern_state_file(workflow_run_id=task_v2.workflow_run_id, organization_id=organization_id)
- await prepare_org_llm_runtime(app.DATABASE, organization_id, organization)
- self._schedule(
- background_tasks,
- task_v2_service.run_task_v2,
- organization=organization,
- task_v2_id=task_v2_id,
- max_steps_override=max_steps_override,
- max_iterations_override=max_iterations_override,
- browser_session_id=browser_session_id,
- )
+ await initialize_skyvern_state_file(workflow_run_id=workflow_run_id, organization_id=organization_id)
+ await prepare_org_llm_runtime(app.DATABASE, organization_id, organization)
+
+ async def execute_registered_task_v2() -> None:
+ with track_run(workflow_run_id, "workflow_run"):
+ release_hold()
+ await task_v2_service.run_task_v2(
+ organization=organization,
+ task_v2_id=task_v2_id,
+ max_steps_override=max_steps_override,
+ max_iterations_override=max_iterations_override,
+ browser_session_id=browser_session_id,
+ )
+
+ self._schedule(background_tasks, execute_registered_task_v2)
+ except BaseException:
+ release_hold()
+ raise
async def execute_script(
self,
diff --git a/skyvern/forge/sdk/executor/run_liveness.py b/skyvern/forge/sdk/executor/run_liveness.py
index 45ee46a1a..a9fa537ea 100644
--- a/skyvern/forge/sdk/executor/run_liveness.py
+++ b/skyvern/forge/sdk/executor/run_liveness.py
@@ -74,14 +74,9 @@ def _register(
return lambda cancelled: None
_kept_leases.discard(run_id)
entry = _registry.get(run_id)
- if entry is None:
+ if entry is None or entry.attempt_number != attempt_number:
entry = _Registration(run_type, attempt_number)
_registry[run_id] = entry
- elif entry.attempt_number != attempt_number:
- entry.attempt_number = attempt_number
- entry.acquired = False
- entry.lost = False
- entry.finalized = False
entry.count += 1
entry.task = task
_wake.set()
@@ -134,23 +129,29 @@ def note_run_finalized(run_id: str) -> None:
entry.finalized = True
-async def acquire_run_lease(run_id: str) -> None:
+async def acquire_run_lease(run_id: str) -> bool:
if not _enabled:
- return
+ return True
entry = _registry.get(run_id)
- if entry is None or entry.acquired or entry.lost:
- return
+ if entry is None:
+ return True
+ if entry.acquired or entry.lost:
+ return not entry.lost
attempt = entry.attempt_number
try:
async with _lease_write_lock:
- if _registry.get(run_id) is not entry or entry.attempt_number != attempt or entry.acquired or entry.lost:
- return
+ if _registry.get(run_id) is not entry or entry.attempt_number != attempt:
+ return False
+ if entry.acquired or entry.lost:
+ return not entry.lost
acquired = await app.DATABASE.run_execution_leases.acquire(
owner_id(),
{run_id: (entry.run_type, attempt)},
stale_before=naive_utc_now() - timedelta(minutes=effective_timeout_minutes()),
)
if run_id not in acquired:
+ entry.lost = True
+ entry.acquired = False
LOG.info(
"Run lease held by another process",
run_id=run_id,
@@ -158,12 +159,15 @@ async def acquire_run_lease(run_id: str) -> None:
attempt_number=attempt,
owner_id=owner_id(),
)
- return
+ return False
_held.add(run_id)
if _registry.get(run_id) is entry and entry.attempt_number == attempt:
entry.acquired = True
+ return True
+ return False
except Exception:
LOG.warning("Run lease acquire failed before run start", run_id=run_id, exc_info=True)
+ return _registry.get(run_id) is entry and entry.attempt_number == attempt and not entry.lost
async def run_lease_lost(run_id: str) -> bool:
@@ -191,6 +195,16 @@ async def run_lease_lost(run_id: str) -> bool:
return True
+def _cancel_lost_runs(entries: list[_Registration]) -> None:
+ # Repeated cancellation would interrupt the cleanup started by the first cancellation.
+ lost_targets = {entry.task for entry in entries if entry.task is not None and not entry.finalized}
+ for target in lost_targets:
+ if not target.done() and all(
+ entry.lost and not entry.finalized for entry in _registry.values() if entry.task is target
+ ):
+ target.cancel()
+
+
async def _heartbeat(repository: RunExecutionLeasesRepository) -> None:
last_renew = time.monotonic()
while True:
@@ -226,13 +240,7 @@ async def _heartbeat(repository: RunExecutionLeasesRepository) -> None:
attempt_number=attempt,
owner_id=owner_id(),
)
- # Repeated cancellation would interrupt the cleanup started by the first cancellation.
- lost_targets = {entry.task for entry in newly_lost if entry.task is not None and not entry.finalized}
- for target in lost_targets:
- if not target.done() and all(
- entry.lost and not entry.finalized for entry in _registry.values() if entry.task is target
- ):
- target.cancel()
+ _cancel_lost_runs(newly_lost)
async with _lease_write_lock:
acquiring = {
key: (entry, entry.attempt_number)
@@ -244,8 +252,14 @@ async def _heartbeat(repository: RunExecutionLeasesRepository) -> None:
{key: (entry.run_type, attempt) for key, (entry, attempt) in acquiring.items()},
stale_before=naive_utc_now() - timedelta(minutes=effective_timeout_minutes()),
)
+ acquisition_losses: list[_Registration] = []
for run_id, (entry, attempt) in acquiring.items():
if run_id not in acquired:
+ if _registry.get(run_id) is not entry or entry.attempt_number != attempt:
+ continue
+ entry.lost = True
+ entry.acquired = False
+ acquisition_losses.append(entry)
LOG.info(
"Run lease held by another process",
run_id=run_id,
@@ -257,6 +271,7 @@ async def _heartbeat(repository: RunExecutionLeasesRepository) -> None:
_held.add(run_id)
if _registry.get(run_id) is entry and entry.attempt_number == attempt:
entry.acquired = True
+ _cancel_lost_runs(acquisition_losses)
_kept_leases.intersection_update(_held)
except Exception:
LOG.exception("Run lease heartbeat failed", owner_id=owner_id())
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 117be7474..d95ae7719 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -3732,6 +3732,8 @@ class ForLoopBlock(Block):
cancellation) always persist since they are terminal."""
if not self.output_parameter:
return
+ if run_lease_tasks_enabled() and await run_lease_lost(workflow_run_id):
+ return
_maybe_truncate_loop_outputs(
outputs_with_loop_values,
workflow_run_id=workflow_run_id,
@@ -4443,6 +4445,8 @@ class WhileLoopBlock(Block):
"""
if not self.output_parameter:
return
+ if run_lease_tasks_enabled() and await run_lease_lost(workflow_run_id):
+ return
_maybe_truncate_loop_outputs(
outputs_with_loop_values,
workflow_run_id=workflow_run_id,
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index 5630adecd..167b43905 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -15,7 +15,7 @@ import unicodedata
import uuid
from collections import Counter, deque
from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Sequence
-from contextlib import asynccontextmanager, suppress
+from contextlib import ExitStack, asynccontextmanager, suppress
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from functools import partial
@@ -6551,52 +6551,59 @@ class WorkflowService:
if serialized_identity:
retry_gate_run = recovered_run
while True:
- if retry_gate_run is not None:
- try:
- stopped_run = await self._wait_for_retry_sequential_clearance(retry_gate_run, attempt_number)
- except asyncio.CancelledError:
- # Only shutdown cancels this owner; the prepared attempt stays queued for recovery.
- LOG.info(
- "Workflow retry owner stopped while waiting for sequential clearance; leaving the attempt for recovery",
- workflow_run_id=workflow_run_id,
- attempt_number=attempt_number,
- )
- raise
- if stopped_run is not None:
- final_decision = await finalize_abandoned_attempt(
- workflow_run_id=workflow_run_id,
- organization_id=organization_id,
- reason="sequential_gate_stopped",
- status=stopped_run.status,
- failure_reason=stopped_run.failure_reason,
- finished_at=stopped_run.finished_at,
- attempt_number=attempt_number,
- )
- await self._run_terminal_side_effects_with_retries(stopped_run, final_decision, api_key=api_key)
- return stopped_run
- retry_gate_run = None
- if not prepared_attempt_claimed and (attempt_number > 1 or claim_initial_attempt):
- claimed = await app.DATABASE.workflow_run_attempts.claim_prepared_attempt_execution(
- workflow_run_id, organization_id, attempt_number
- )
- if not claimed:
- LOG.info(
- "Workflow attempt is owned by another dispatch; skipping execution",
- workflow_run_id=workflow_run_id,
- attempt_number=attempt_number,
- )
+ with ExitStack() as attempt_scope:
+ # The previous attempt's registration exits at `continue` with no await before this one, so the
+ # lease never lapses between attempts; admission must precede the dispatch claim below.
+ attempt_scope.enter_context(track_run(workflow_run_id, "workflow_run", attempt_number))
+ if not await acquire_run_lease(workflow_run_id):
deny_finalization()
return await self.get_workflow_run(workflow_run_id, organization_id)
- dispatch_claim_started_at = claimed
- if attempt_number > 1:
- current_context = skyvern_context.current()
- if current_context and current_context.browser_session_runnable_id == workflow_run_id:
- # A pinned session survives retries, but its released ownership generation does not.
- current_context.browser_session_runnable_id = None
- current_context.browser_session_runnable_generation_id = None
- prepared_attempt_claimed = False
- execution_entered = False
- with skyvern_context.workflow_log_attempt(workflow_run_id, attempt_number):
+ if retry_gate_run is not None:
+ try:
+ stopped_run = await self._wait_for_retry_sequential_clearance(retry_gate_run, attempt_number)
+ except asyncio.CancelledError:
+ # Only shutdown cancels this owner; the prepared attempt stays queued for recovery.
+ LOG.info(
+ "Workflow retry owner stopped while waiting for sequential clearance; leaving the attempt for recovery",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ )
+ raise
+ if stopped_run is not None:
+ final_decision = await finalize_abandoned_attempt(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ reason="sequential_gate_stopped",
+ status=stopped_run.status,
+ failure_reason=stopped_run.failure_reason,
+ finished_at=stopped_run.finished_at,
+ attempt_number=attempt_number,
+ )
+ await self._run_terminal_side_effects_with_retries(stopped_run, final_decision, api_key=api_key)
+ return stopped_run
+ retry_gate_run = None
+ if not prepared_attempt_claimed and (attempt_number > 1 or claim_initial_attempt):
+ claimed = await app.DATABASE.workflow_run_attempts.claim_prepared_attempt_execution(
+ workflow_run_id, organization_id, attempt_number
+ )
+ if not claimed:
+ LOG.info(
+ "Workflow attempt is owned by another dispatch; skipping execution",
+ workflow_run_id=workflow_run_id,
+ attempt_number=attempt_number,
+ )
+ deny_finalization()
+ return await self.get_workflow_run(workflow_run_id, organization_id)
+ dispatch_claim_started_at = claimed
+ if attempt_number > 1:
+ current_context = skyvern_context.current()
+ if current_context and current_context.browser_session_runnable_id == workflow_run_id:
+ # A pinned session survives retries, but its released ownership generation does not.
+ current_context.browser_session_runnable_id = None
+ current_context.browser_session_runnable_generation_id = None
+ prepared_attempt_claimed = False
+ execution_entered = False
+ attempt_scope.enter_context(skyvern_context.workflow_log_attempt(workflow_run_id, attempt_number))
try:
if dispatch_claim_started_at is not None:
report_authority(attempt_number, dispatch_claim_started_at)
@@ -6837,7 +6844,10 @@ class WorkflowService:
if on_execution_authority is not None:
on_execution_authority(attempt_number, dispatch_claim_started_at)
with track_run(workflow_run_id, "workflow_run", attempt_number):
- await acquire_run_lease(workflow_run_id)
+ if not await acquire_run_lease(workflow_run_id):
+ if on_finalization_denied is not None:
+ on_finalization_denied()
+ return await self.get_workflow_run(workflow_run_id, organization.organization_id)
try:
return await self._execute_workflow(
workflow_run_id=workflow_run_id,
diff --git a/skyvern/services/task_v2_service.py b/skyvern/services/task_v2_service.py
index 2576c83a4..0655ec62f 100644
--- a/skyvern/services/task_v2_service.py
+++ b/skyvern/services/task_v2_service.py
@@ -645,7 +645,8 @@ async def run_task_v2(
track_run(task_v2.workflow_run_id, "workflow_run") if task_v2.workflow_run_id else nullcontext(),
):
if task_v2.workflow_run_id:
- await acquire_run_lease(task_v2.workflow_run_id)
+ if not await acquire_run_lease(task_v2.workflow_run_id) or await run_lease_lost(task_v2.workflow_run_id):
+ return task_v2
try:
workflow, workflow_run, task_v2 = await run_task_v2_helper(
organization=organization,