Skip to content

Automate browser based workflows with AI

Move four DataDragon schedules off Redshift maintenance and the 09:00 ET pile-up (SKY-18010) (#8895)

Shuchang Zheng8d4c8818c092
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.presentation.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.presentation.test.tsx
index 3934f658c..1cc0bc8a7 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.presentation.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.presentation.test.tsx
@@ -159,6 +159,83 @@ describe("NarrativeView structured turn presentation", () => {
const card = screen.getByRole("button", { name: /Stopped Open Site/ });
expect(card.getAttribute("aria-expanded")).toBeNull();
});
+
+ it.each([
+ [["wr_left"], "deadline"],
+ [[], "deadline"],
+ [[], "max_turns"],
+ ] as const)(
+ "names the runs left running (%j) after the %s limit",
+ (leftRunIds, source) => {
+ render(
+ <NarrativeView
+ turn={structuredTurn({
+ blocks: [{ ...completedBlock(), state: "unfinished" }],
+ budgetExpiry: {
+ budgetExpired: true,
+ source,
+ reportProduced: true,
+ stagedDraftId: null,
+ drainFingerprint: null,
+ leftRunIds: [...leftRunIds],
+ },
+ turnFacts: {
+ factsAvailable: true,
+ evaluationState: null,
+ runId: "wr_left",
+ runCompleted: false,
+ terminalCause: null,
+ blocksRunThisTurn: 1,
+ ranCleanOnCurrentSource: false,
+ authoredBlockCount: 1,
+ matchingSourceBlockCount: 1,
+ },
+ })}
+ />,
+ );
+
+ expect(
+ screen.getByRole("button", { name: /Unfinished Open Site/ }),
+ ).toBeTruthy();
+ expect(
+ screen.getByText(/the turn ended before this block finished/),
+ ).toBeTruthy();
+ expect(screen.queryByText(/Passed|Stopped|Failed/)).toBeNull();
+ const runPage = screen.queryByRole("link", { name: /its run page/ });
+ if (leftRunIds.length) {
+ expect(screen.getByText(/may still be going/)).toBeTruthy();
+ expect(runPage?.getAttribute("href")).toBe("/runs/wr_left");
+ } else {
+ expect(screen.queryByText(/may still be going/)).toBeNull();
+ expect(runPage).toBeNull();
+ }
+ },
+ );
+
+ it("links each run the time limit left", () => {
+ render(
+ <NarrativeView
+ turn={structuredTurn({
+ blocks: [{ ...completedBlock(), state: "unfinished" }],
+ budgetExpiry: {
+ budgetExpired: true,
+ source: "deadline",
+ reportProduced: true,
+ stagedDraftId: null,
+ drainFingerprint: null,
+ leftRunIds: ["wr_a", "wr_b"],
+ },
+ })}
+ />,
+ );
+
+ expect(screen.getByText(/test runs may still be going/)).toBeTruthy();
+ expect(
+ screen
+ .getAllByRole("link", { name: /wr_/ })
+ .map((link) => link.getAttribute("href")),
+ ).toEqual(["/runs/wr_a", "/runs/wr_b"]);
+ });
});
// codegen_progress frames are live-only and never persisted: the backend
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
index bd1218abe..7e3ed5dfd 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
@@ -43,6 +43,7 @@ describe("terminalNarrativeText — budget expiry", () => {
reportProduced: true,
stagedDraftId: "wf_draft",
drainFingerprint: "drain-1",
+ leftRunIds: [],
},
};
expect(terminalNarrativeText(turn)).toBe("I saved the useful draft.");
@@ -78,6 +79,7 @@ describe("terminalNarrativeText — budget expiry", () => {
reportProduced: false,
stagedDraftId,
drainFingerprint: "drain-2",
+ leftRunIds: [],
},
};
expect(terminalNarrativeText(turn)).toBe(expected);
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
index 4d0705767..39a95ff4b 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
@@ -68,6 +68,7 @@ import {
toolCallKind,
} from "./narrativeState";
import { useShimmerText } from "../workflowRun/useShimmerText";
+import { workflowRunDetailPath } from "../studioNavigation";
// Row flashes green/red for 600ms once revealed — must match the tailwind
// copilot-row-flash-* animation duration.
@@ -134,6 +135,8 @@ function isQuestionTurn(turn: TurnNarrativeState): boolean {
);
}
+const UNFINISHED_BLOCK_NOTE = "the turn ended before this block finished";
+
function blockIdentity(block: BlockState): string {
return block.workflowRunBlockId || block.label;
}
@@ -154,7 +157,11 @@ function outcomeNotConfirmedOwnerKey(turn: TurnNarrativeState): string | null {
for (let i = turn.blocks.length - 1; i >= 0; i -= 1) {
const block = turn.blocks[i]!;
- if (block.state === "failed" || block.state === "stopped") {
+ if (
+ block.state === "failed" ||
+ block.state === "stopped" ||
+ block.state === "unfinished"
+ ) {
return blockIdentity(block);
}
}
@@ -543,6 +550,7 @@ function FBlockRun({
const isOk = isBlockOk(block);
const isFail = block.state === "failed";
const isStopped = block.state === "stopped";
+ const isUnfinished = block.state === "unfinished";
const isDraft = block.state === "drafted";
const collapsedOutcomeReason =
isOutcomeNotShown || ownsOutcomeNotConfirmed
@@ -603,7 +611,8 @@ function FBlockRun({
ownsOutcomeReason ||
isVerifying ||
isRanNeutral ||
- isStopped);
+ isStopped ||
+ isUnfinished);
useTick(isRunning);
const elapsed = formatElapsed(block.startedAt, block.endedAt);
const live = isRunning ? liveElapsed(block.startedAt) : null;
@@ -619,9 +628,11 @@ function FBlockRun({
? "halted"
: isStopped
? `stopped${elapsed ? ` · ${elapsed}` : ""}`
- : isDraft
- ? "drafted"
- : "queued";
+ : isUnfinished
+ ? UNFINISHED_BLOCK_NOTE
+ : isDraft
+ ? "drafted"
+ : "queued";
const stateGlyph = isOk ? (
"✓"
) : isOutcomeNotShown ? (
@@ -632,6 +643,8 @@ function FBlockRun({
"✕"
) : isStopped ? (
"■"
+ ) : isUnfinished ? (
+ "○"
) : isRunning ? (
<Spinner />
) : (
@@ -1149,6 +1162,13 @@ function testCardStatus(block: BlockState, turnEnded: boolean): TestCardStatus {
note: null,
glyph: <StopIcon aria-hidden="true" className="size-3" />,
};
+ case "unfinished":
+ return {
+ tone: "neutral",
+ word: "Unfinished",
+ note: UNFINISHED_BLOCK_NOTE,
+ glyph: "○",
+ };
case "skipped":
return { tone: "neutral", word: "Skipped", note: null, glyph: "–" };
case "queued":
@@ -2344,6 +2364,35 @@ function FBudgetLimitNote({ budget }: { budget: BudgetExpiryState }) {
);
}
+function FUnfinishedRunNote({ runIds }: { runIds: string[] }) {
+ const single = runIds.length === 1;
+ return (
+ <div
+ data-testid="copilot-unfinished-run"
+ className={`text-[12px] leading-[1.5] ${STEP_TEXT}`}
+ >
+ {single
+ ? "The test run may still be going. You can open or cancel it from "
+ : "The test runs may still be going. You can open or cancel them from their run pages: "}
+ {runIds.map((runId, index) => (
+ <Fragment key={runId}>
+ {index > 0 ? ", " : null}
+ <a
+ className="underline underline-offset-2"
+ href={workflowRunDetailPath(runId)}
+ target="_blank"
+ rel="noreferrer"
+ >
+ {single ? "its run page" : runId}
+ <span className="sr-only"> (opens in new tab)</span>
+ </a>
+ </Fragment>
+ ))}
+ .
+ </div>
+ );
+}
+
// Something that happened during a turn and renders where it happened: after the activity row
// holding its tool call. When that row is not on screen (a long turn keeps only its newest
// activity), `at` places it among the rows by time; without it, it sits above the reply.
@@ -2564,6 +2613,10 @@ function DetailView({
<FBudgetLimitNote budget={turn.budgetExpiry} />
) : null}
+ {turn.terminal !== null && turn.budgetExpiry?.leftRunIds.length ? (
+ <FUnfinishedRunNote runIds={turn.budgetExpiry.leftRunIds} />
+ ) : null}
+
{/* terminalProseTone's question branch without its evidence gate: an
ask that followed a run keeps the rail here, beside the evidence,
rather than replacing the card with prose-only chrome. */}
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.runOutcome.test.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.runOutcome.test.ts
index 8a6fc6b27..e683de9ed 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.runOutcome.test.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.runOutcome.test.ts
@@ -42,6 +42,7 @@ describe("budget expiry narrative", () => {
reportProduced: false,
stagedDraftId: "wf_draft",
drainFingerprint: "drain-1",
+ leftRunIds: [],
});
});
@@ -712,28 +713,44 @@ describe("canonical turn facts — pill and prose over one bundle", () => {
expect(pill).toBe("untested");
});
- it("settles a block still running at the deadline as stopped, not failed", () => {
- const turn = hydrateNarrativeFromPayload({
- ...(bundles["deadline-after-one-clean-run"] as unknown as Record<
- string,
- unknown
- >),
- blocks: [
- {
- workflowRunBlockId: "wrb_1",
- label: "append_star_count_to_sheet",
- blockType: "code",
- state: "running",
- lastSeenIteration: 0,
- activity: [],
+ it.each([
+ [false, "unfinished", "unfinished"],
+ [false, "running", "stopped"],
+ [true, "running", "stopped"],
+ ])(
+ "keeps a block saved at the deadline (cancelled: %s, saved as %s) as %s, not failed",
+ (cancelled, savedState, expected) => {
+ const turn = hydrateNarrativeFromPayload({
+ ...(bundles["deadline-after-one-clean-run"] as unknown as Record<
+ string,
+ unknown
+ >),
+ cancelled,
+ budgetExpiry: {
+ budgetExpired: true,
+ source: "deadline",
+ reportProduced: true,
+ stagedDraftId: null,
+ drainFingerprint: null,
+ leftRunIds: ["wr_left"],
},
- ],
- });
- if (!turn) throw new Error("fixture did not hydrate");
-
- expect(turn.blocks.map((block) => block.state)).toEqual(["stopped"]);
- expect(isDeadlineHalt(turn)).toBe(true);
- });
+ blocks: [
+ {
+ workflowRunBlockId: "wrb_1",
+ label: "append_star_count_to_sheet",
+ blockType: "code",
+ state: savedState,
+ lastSeenIteration: 0,
+ activity: [],
+ },
+ ],
+ });
+ if (!turn) throw new Error("fixture did not hydrate");
+
+ expect(turn.blocks.map((block) => block.state)).toEqual([expected]);
+ expect(isDeadlineHalt(turn)).toBe(true);
+ },
+ );
it("keeps a failed block a failure even when the deadline expired", () => {
const turn = hydrateNarrativeFromPayload({
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
index e1114fc03..6ee889178 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
@@ -36,6 +36,8 @@ export interface BudgetExpiryState {
reportProduced: boolean | null;
stagedDraftId: string | null;
drainFingerprint: string | null;
+ // Test runs the turn's hard time limit left to their worker; the backend saves only their blocks as unfinished.
+ leftRunIds: string[];
}
function parseBudgetExpiry(raw: unknown): BudgetExpiryState | null {
@@ -58,6 +60,9 @@ function parseBudgetExpiry(raw: unknown): BudgetExpiryState | null {
typeof value.drainFingerprint === "string"
? value.drainFingerprint
: null,
+ leftRunIds: Array.isArray(value.leftRunIds)
+ ? value.leftRunIds.filter((id): id is string => typeof id === "string")
+ : [],
};
}
@@ -77,6 +82,7 @@ function budgetExpiryFromOutcome(
reportProduced: outcome.budget_expiry_report_produced ?? null,
stagedDraftId: outcome.budget_expiry_staged_draft_id ?? null,
drainFingerprint: outcome.drain_fingerprint ?? null,
+ leftRunIds: [],
};
}
@@ -131,7 +137,8 @@ export type NarrativeEvent =
// failed-style states (failed, terminated, timed_out) under one chip and
// treats `skipped` and `stopped` as separate neutral states. `stopped` is a
// user cancel: it ran and was interrupted, which is not a failure and must
-// never be rendered as one.
+// never be rendered as one. `unfinished` is a block still running when a turn
+// limit ended the turn; its run may still be going, so it is neither.
export type BlockUIState =
| "queued"
| "drafted"
@@ -139,6 +146,7 @@ export type BlockUIState =
| "completed"
| "failed"
| "stopped"
+ | "unfinished"
| "skipped";
// Recorded per-run outcome verdict, distinct from lifecycle state: a row can
@@ -1945,6 +1953,7 @@ export function hydrateNarrativeFromPayload(
s === "completed" ||
s === "failed" ||
s === "stopped" ||
+ s === "unfinished" ||
s === "skipped"
)
return s;
@@ -1973,23 +1982,21 @@ export function hydrateNarrativeFromPayload(
typeof payload.endedAt === "string" ? (payload.endedAt as string) : null;
const cancelled = payload.cancelled === true;
const turnFacts = parseTurnFacts(payload.turnFacts);
- // A deadline cuts a running block off; that is a stop, so it must not be swept
- // to failed and then read back as the turn having failed.
+ // The backend saves a left run's blocks as unfinished; any other block
+ // cut off by a turn limit is a stop, never a failure.
const budgetExpiry = parseBudgetExpiry(payload.budgetExpiry);
- const halted =
- cancelled ||
- turnFacts?.terminalCause === "deadline_expired" ||
- budgetExpiry !== null;
+ const halted = budgetHalted({ turnFacts, budgetExpiry });
const sweptBlocks: BlockState[] = terminal
? blocks.map((b) =>
b.state === "running"
? {
...b,
- state: halted
- ? "stopped"
- : terminal === "error"
- ? "failed"
- : "completed",
+ state:
+ cancelled || halted
+ ? "stopped"
+ : terminal === "error"
+ ? "failed"
+ : "completed",
endedAt: b.endedAt ?? endedAtIso,
}
: b,
@@ -2211,8 +2218,16 @@ export function notConfirmedOutcome(
// not a block failure, so no surface may give it failure's treatment.
export function isDeadlineHalt(turn: TurnNarrativeState): boolean {
return (
- (turn.turnFacts?.terminalCause === "deadline_expired" ||
- turn.budgetExpiry !== null) &&
+ budgetHalted(turn) &&
!latestBlocksByLabel(turn.blocks).some((b) => b.state === "failed")
);
}
+
+type TurnLimitFacts = Pick<TurnNarrativeState, "turnFacts" | "budgetExpiry">;
+
+function budgetHalted(turn: TurnLimitFacts): boolean {
+ return (
+ turn.turnFacts?.terminalCause === "deadline_expired" ||
+ turn.budgetExpiry !== null
+ );
+}
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index 3b463f9f2..2f339dda5 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -2209,12 +2209,16 @@ def _build_narrative_payload(
if not isinstance(label, str) or not label:
continue
block_labels.append(label)
+ left_run_ids = ctx.budget_expiry_state.leavable_run_ids if ctx.budget_expiry_state.hard_backstop_reached else []
for attempt in ctx.narrative_block_attempts.values():
+ block_state = _block_ui_state(attempt["rawStatus"], drafted_fallback=False)
+ if block_state == "running" and attempt["workflowRunId"] in left_run_ids:
+ block_state = "unfinished"
block_entry: NarrativeBlock = {
"label": attempt["label"],
"workflowRunBlockId": attempt["workflowRunBlockId"],
"blockType": attempt["blockType"],
- "state": _block_ui_state(attempt["rawStatus"], drafted_fallback=False),
+ "state": block_state,
"lastSeenIteration": attempt["lastSeenIteration"],
"activity": list(block_activity.get(attempt["workflowRunBlockId"], [])),
"startedAt": attempt["startedAt"],
@@ -2263,6 +2267,7 @@ def _build_narrative_payload(
"reportProduced": budget_state.report_produced,
"stagedDraftId": budget_state.staged_draft_id,
"drainFingerprint": budget_state.drain_fingerprint,
+ "leftRunIds": list(budget_state.leavable_run_ids) if budget_state.hard_backstop_reached else [],
}
if ctx.google_connection_notices:
payload["googleConnectionNotices"] = [notice.to_payload() for notice in ctx.google_connection_notices]
diff --git a/skyvern/forge/sdk/copilot/budget_expiry.py b/skyvern/forge/sdk/copilot/budget_expiry.py
index 2cef51c2c..25b40ef84 100644
--- a/skyvern/forge/sdk/copilot/budget_expiry.py
+++ b/skyvern/forge/sdk/copilot/budget_expiry.py
@@ -3,7 +3,7 @@
from __future__ import annotations
import json
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from typing import Literal, TypedDict
from uuid import uuid4
@@ -23,6 +23,8 @@ class BudgetExpiryState:
report_produced: bool | None = None
staged_draft_id: str | None = None
hard_backstop_reached: bool = False
+ # Set by the build tool before its poll, so the persisted reply reads it without waiting on the tool's cleanup.
+ leavable_run_ids: list[str] = field(default_factory=list)
def begin_drain(self) -> None:
self.drain_attempted = True
@@ -60,6 +62,7 @@ class RecordedRunState(BaseModel):
failure_reason: str | None = None
blocks: list[RecordedBlockState] = []
earlier_blocks_not_shown: int = 0
+ left_running: bool = False
class BudgetExpiredReplyObservation(BaseModel):
@@ -74,8 +77,12 @@ class BudgetExpiredReplyObservation(BaseModel):
"This turn's time is spent and nothing more can run in it. Call `reply` now with your final response for "
"this turn; any other tool call will not run. staged_draft is the draft this turn holds. "
"stopped_waiting means the turn stopped waiting for the step still in progress: that step's model response "
- "and tool results are not in your history, and the result of a browser action in it is unknown. The time "
- "limit does not stop runs: runs_not_in_history lists each run that step started, as its record reads now."
+ "and tool results are not in your history, and the result of a browser action in it is unknown. "
+ "runs_not_in_history lists each run that step started, as its record reads now. left_running is true for a "
+ "run the time limit left going on its own browser. A final or paused status in a record is what happened. "
+ "When stopped_waiting is true, any other run whose record still shows it starting or running was cancelled "
+ "because it used this chat's browser, carried secret inputs, or had not finished starting, and its record "
+ "may not show the cancel yet."
)
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index 6d41b0d00..70c654f8d 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -248,6 +248,7 @@ class NarrativeBudgetExpiry(TypedDict):
reportProduced: bool | None
stagedDraftId: str | None
drainFingerprint: str | None
+ leftRunIds: NotRequired[list[str]]
# Mirror of the FE TurnNarrativeState; camelCase keys match the wire shape.
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index bb8088f75..2ec2d2f61 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -42,7 +42,12 @@ from skyvern.forge.sdk.copilot.authoring_parameter_binding import _literal_locat
from skyvern.forge.sdk.copilot.blocker_signal import (
stash_blocker_signal,
)
-from skyvern.forge.sdk.copilot.budget_expiry import RecordedBlockState, RecordedRunState, budget_run_denial
+from skyvern.forge.sdk.copilot.budget_expiry import (
+ BudgetExpiryState,
+ RecordedBlockState,
+ RecordedRunState,
+ budget_run_denial,
+)
from skyvern.forge.sdk.copilot.build_test_connect_failure import (
SUPERSEDED_BY_NEWER_TEST_REASON,
BuildTestConnectFailure,
@@ -990,6 +995,8 @@ async def recorded_open_step_runs(ctx: CopilotContext) -> list[RecordedRunState]
failure_reason=run.failure_reason if run is not None else None,
blocks=shown,
earlier_blocks_not_shown=len(blocks) - len(shown),
+ left_running=ctx.budget_expiry_state.hard_backstop_reached
+ and workflow_run_id in ctx.budget_expiry_state.leavable_run_ids,
)
# The same scrub a run tool's own result gets before the model reads it.
runs.append(
@@ -2820,6 +2827,18 @@ def _origin_run_secrets_unregistered(registry: OriginRunRedactionRegistry | None
)
+def _unmark_leavable_run(ctx: CopilotContext, workflow_run_id: str) -> None:
+ marks = ctx.budget_expiry_state.leavable_run_ids
+ marks[:] = [run_id for run_id in marks if run_id != workflow_run_id]
+
+
+def _backstop_may_leave_run_running(
+ turn_deadline: asyncio.Timeout | None, budget_state: BudgetExpiryState, workflow_run_id: str
+) -> bool:
+ """Whether the turn's own backstop, not a Stop, ended the wait on the run the poll marked leavable."""
+ return turn_deadline is not None and turn_deadline.expired() and workflow_run_id in budget_state.leavable_run_ids
+
+
def _sensitive_parameter_keys_requiring_resolved_values(workflow: Workflow) -> list[str]:
return [
parameter.key
@@ -4708,15 +4727,8 @@ async def _run_blocks_and_collect_debug(
)
)
except BaseException:
- # Run setup / submission failed OR the tool was cancelled after the dispatch version was
- # created. The watchdog cleanup below never runs on this path, so soft-delete the version
- # here so it does not linger as the latest-by-permanent-id pointer. Catch BaseException so
- # asyncio.CancelledError (the SDK tool timeout) also cleans the draft up. The turn's own deadline
- # leaves a submitted run's version in place, since the worker may already be loading it (ADR-0025).
- deadline_left_run = run_submission_attempted and turn_deadline is not None and turn_deadline.expired()
- if dispatch_draft_workflow_id is not None and not deadline_left_run:
- await _delete_dispatch_draft(dispatch_draft_workflow_id, ctx.organization_id)
- dispatch_draft_workflow_id = None
+ # Setup or submission failed or was cancelled, and the poll cleanup below never runs on this path.
+ # BaseException so a cancellation also releases the lock, cancels a submitted run and retires its draft.
if secret_run_session_lock is not None:
if run_submission_attempted:
# The start may have landed before this raised, so the run can still be filling secrets.
@@ -4725,6 +4737,13 @@ async def _run_blocks_and_collect_debug(
secret_run_session_lock = None
if interim_run_id is not None and not run_submission_attempted:
_forget_interim_run_start(ctx, interim_run_id)
+ # The submission had not returned, so no worker owns the run yet, even at the backstop; cancel before
+ # retiring the draft so a start that did land sees a canceled row.
+ if run_submission_attempted:
+ await asyncio.shield(_cooperative_cancel_dispatched_run(workflow_run.workflow_run_id))
+ if dispatch_draft_workflow_id is not None:
+ await _delete_dispatch_draft(dispatch_draft_workflow_id, ctx.organization_id)
+ dispatch_draft_workflow_id = None
raise
finally:
if secret_run_session_lock is not None and not run_submission_attempted:
@@ -4737,53 +4756,51 @@ async def _run_blocks_and_collect_debug(
active_run_association: ActiveRunSessionAssociation | None = None
run_paused = False
- run_left_running = False
+ leave_run_to_owner = False
+ left_by_backstop = False
+ final_status: str | None = None
+ run_cancelled_by_watchdog = False
try:
- # Inside this try so a cancellation while publishing still reaches the browser lock release below.
- if run_detached_from_chat and debug_session_id and run_session_id:
- try:
- active_run_association = await publish_active_run_session(
- organization_id=ctx.organization_id,
- workflow_permanent_id=ctx.workflow_permanent_id,
- debug_browser_session_id=debug_session_id,
- run_browser_session_id=run_session_id,
- workflow_run_id=workflow_run.workflow_run_id,
- turn_id=ctx.turn_id,
- )
- except Exception:
- LOG.warning(
- "Failed to publish active Copilot run session",
- organization_id=ctx.organization_id,
- workflow_permanent_id=ctx.workflow_permanent_id,
- workflow_run_id=workflow_run.workflow_run_id,
- debug_browser_session_id=debug_session_id,
- run_browser_session_id=run_session_id,
- exc_info=True,
- )
-
- # The OpenAI Agents SDK wraps this tool in
- # ``asyncio.wait_for(..., timeout=RUN_BLOCKS_SAFETY_CEILING_SECONDS)``, so
- # the poll loop leaves 10 s of headroom for the cancel-drain and
- # post-drain reconcile to finish before the SDK's own cancel fires.
- #
- # Do NOT short-circuit on client disconnect: the agent loop runs to
- # completion after the SSE stream is gone so its reply persists
- # (SKY-8986); aborting mid-block would strand the run without debug
- # output for the final chat message.
- initial_run, initial_block_ts = await _read_progress_sources(ctx, workflow_run.workflow_run_id)
- started_monotonic = time.monotonic()
- final_status: str | None = None
- run: Any = initial_run
- exit_reason: WatchdogExitReason | None = None
- run_cancelled_by_watchdog = False
- budget_seconds = max(1, RUN_BLOCKS_SAFETY_CEILING_SECONDS - 10)
-
- narrator_state: NarratorState | None = ctx.narrator_state
- progress_enabled = narrator_state is not None and ctx.stream is not None
- seen_block_states: dict[str, str] = {}
- prior_block_ts: datetime | None = initial_block_ts
- last_block_fetch_monotonic = 0.0
try:
+ # A run on the chat's browser or carrying secrets cannot outlive the turn: only this turn guards that
+ # browser and the scrubber. The mark is cleared once the run is final or the watchdog cancels it.
+ if run_detached_from_chat and not origin_registry.contains_sensitive_values:
+ ctx.budget_expiry_state.leavable_run_ids.append(workflow_run.workflow_run_id)
+ # Inside this try so a cancellation while publishing still reaches the browser lock release below.
+ if run_detached_from_chat and debug_session_id and run_session_id:
+ try:
+ active_run_association = await publish_active_run_session(
+ organization_id=ctx.organization_id,
+ workflow_permanent_id=ctx.workflow_permanent_id,
+ debug_browser_session_id=debug_session_id,
+ run_browser_session_id=run_session_id,
+ workflow_run_id=workflow_run.workflow_run_id,
+ turn_id=ctx.turn_id,
+ )
+ except Exception:
+ LOG.warning(
+ "Failed to publish active Copilot run session",
+ organization_id=ctx.organization_id,
+ workflow_permanent_id=ctx.workflow_permanent_id,
+ workflow_run_id=workflow_run.workflow_run_id,
+ debug_browser_session_id=debug_session_id,
+ run_browser_session_id=run_session_id,
+ exc_info=True,
+ )
+
+ # The SDK's tool timeout is RUN_BLOCKS_SAFETY_CEILING_SECONDS, so the poll keeps 10 s for the cancel
+ # drain and reconcile. A client disconnect does not end the poll: the turn finishes and persists its reply.
+ initial_run, initial_block_ts = await _read_progress_sources(ctx, workflow_run.workflow_run_id)
+ started_monotonic = time.monotonic()
+ run: WorkflowRun | None = initial_run
+ exit_reason: WatchdogExitReason | None = None
+ budget_seconds = max(1, RUN_BLOCKS_SAFETY_CEILING_SECONDS - 10)
+
+ narrator_state: NarratorState | None = ctx.narrator_state
+ progress_enabled = narrator_state is not None and ctx.stream is not None
+ seen_block_states: dict[str, str] = {}
+ prior_block_ts: datetime | None = initial_block_ts
+ last_block_fetch_monotonic = 0.0
while True:
await asyncio.sleep(RUN_BLOCKS_POLL_INTERVAL_SECONDS)
@@ -4810,6 +4827,7 @@ async def _run_blocks_and_collect_debug(
if run and WorkflowRunStatus(run.status).is_final():
final_status = run.status
+ _unmark_leavable_run(ctx, workflow_run.workflow_run_id)
exit_reason = "success"
break
@@ -4840,6 +4858,7 @@ async def _run_blocks_and_collect_debug(
# has to exclude. Then cancel + reread +
# ``_trusted_post_drain_status`` applies SKY-9167's success-race
# recovery uniformly to both non-success exit reasons.
+ _unmark_leavable_run(ctx, workflow_run.workflow_run_id)
pre_cancel_run = await _safe_read_workflow_run(
workflow_run.workflow_run_id, ctx.organization_id, context="pre-cancel"
)
@@ -4972,21 +4991,26 @@ async def _run_blocks_and_collect_debug(
result["data"]["authored_locator_observations"] = watchdog_locator_observations
return _ExecutionResult(result, execution)
except asyncio.CancelledError:
- # A pause is detected several awaits before the result is returned, so a tool timeout
- # landing in that window reaches here with the run alive and waiting on a person.
- # Cancelling it would destroy the state the person was asked to act on, so leave the
- # run to the ``finally`` below, which adopts the executor instead.
- if run_paused:
- raise
- # The turn's hard deadline ends the turn's wait for the run, never the run (ADR-0025): the
- # run stays with its executor and the turn's final reply reads its record.
- if turn_deadline is not None and turn_deadline.expired():
- run_left_running = True
+ # A paused run waits on a person, and a live run the backstop may leave is its owner's to finish, so the
+ # finally adopts either instead of cancelling it. Stop, shutdown and this tool's timeout still cancel.
+ left_by_backstop = _backstop_may_leave_run_running(
+ turn_deadline, ctx.budget_expiry_state, workflow_run.workflow_run_id
+ )
+ leave_run_to_owner = run_paused or left_by_backstop
+ LOG.info(
+ "copilot_build_test_cancellation_disposition",
+ left_to_owner=leave_run_to_owner,
+ run_paused=run_paused,
+ backstop_expired=turn_deadline is not None and turn_deadline.expired(),
+ run_detached_from_chat=run_detached_from_chat,
+ contains_sensitive_values=origin_registry.contains_sensitive_values,
+ dispatched=run_task is None,
+ workflow_run_id=workflow_run.workflow_run_id,
+ )
+ if leave_run_to_owner:
raise
- # The SDK's @function_tool(timeout=...) cancelled us mid-poll. Shield
- # the cleanup so the parent cancellation can't interrupt it mid-await.
- # If the shield itself is cancelled, fall back to a detached task
- # that outlives tool teardown and still reconciles workflow state.
+ # Shielded so the cancellation cannot interrupt the cancel write; a second cancellation hands it to a
+ # detached task that outlives tool teardown.
cancel_cleanup = (
_cancel_run_task_if_not_final(run_task, workflow_run.workflow_run_id)
if run_task is not None
@@ -5007,13 +5031,13 @@ async def _run_blocks_and_collect_debug(
fallback.add_done_callback(_log_detached_cleanup_failure)
raise
finally:
- # If any exit path above missed a cancel — e.g. an unexpected exception bubbling out of the
- # poll loop — signal the run_task so we don't leak it. Dispatched runs have no in-process
- # task, so there is nothing to signal.
+ leave_run_to_owner = leave_run_to_owner or run_paused
+ # Only the backstop's own leave stays marked: a paused run that returned normally was not left by it.
+ if not left_by_backstop:
+ _unmark_leavable_run(ctx, workflow_run.workflow_run_id)
if run_task is not None and not run_task.done():
- if run_paused or run_left_running:
- # The inline executor coroutine is the run itself (and what observes a pause's
- # approval), so it has to outlive this tool call instead of being cancelled.
+ if leave_run_to_owner:
+ # The inline executor coroutine is what finishes the run, so it outlives this tool call.
detached_task = asyncio.create_task(
_retire_snapshot_after_execution(
run_task,
@@ -5121,9 +5145,9 @@ async def _run_blocks_and_collect_debug(
if execution.reused_origin_input_keys:
result_data["reused_origin_input_keys"] = list(execution.reused_origin_input_keys)
_attach_reused_origin_outputs(result_data, execution)
- if not run_ok and run and getattr(run, "failure_reason", None):
+ if not run_ok and run and run.failure_reason:
result_data["failure_reason"] = redact_totp_runtime_values(run.failure_reason)
- if not run_ok and run and getattr(run, "failure_category", None):
+ if not run_ok and run and run.failure_category:
failure_category = without_output_only_categories(run.failure_category)
if failure_category:
result_data["failure_category"] = failure_category
@@ -5268,9 +5292,8 @@ async def _run_blocks_and_collect_debug(
return response
finally:
- # A paused or still-running run keeps its association so the pane still follows it; the next
- # run's generation replaces it.
- if active_run_association is not None and not (run_paused or run_left_running):
+ # A run left to its owner keeps its association so the pane still follows it; the next run replaces it.
+ if active_run_association is not None and not leave_run_to_owner:
try:
await clear_active_run_session(
organization_id=active_run_association.organization_id,
diff --git a/tests/unit/copilot_test_helpers.py b/tests/unit/copilot_test_helpers.py
index f43005bb4..0ef834a56 100644
--- a/tests/unit/copilot_test_helpers.py
+++ b/tests/unit/copilot_test_helpers.py
@@ -61,6 +61,7 @@ from skyvern.forge.sdk.copilot.request_policy import CompletionCriterion
from skyvern.forge.sdk.copilot.review_gate import build_review_projection, workflow_block_fingerprints
from skyvern.forge.sdk.copilot.runtime import (
AgentContext,
+ OriginRunRedactionRegistry,
)
from skyvern.forge.sdk.copilot.session_factory import (
copilot_call_model_input_filter,
@@ -654,6 +655,99 @@ async def install_run_blocks_harness(
return captured
+_REAL_CANCEL_RUN_TASK_IF_NOT_FINAL = run_execution_module._cancel_run_task_if_not_final
+_REAL_COOPERATIVE_CANCEL_DISPATCHED_RUN = run_execution_module._cooperative_cancel_dispatched_run
+_REAL_DELETE_DISPATCH_DRAFT_IF_RUN_FINAL = run_execution_module._delete_dispatch_draft_if_run_final
+
+OWNED_RUN_ID = "wr_build_test"
+
+
+class OwnedRunRow:
+ """One run row shared by the build tool's poll, the real conditional cancel and draft-retire paths and its
+ worker, installed over ``install_run_blocks_harness`` so a write lands on the row a later read reports."""
+
+ def __init__(
+ self, monkeypatch: pytest.MonkeyPatch, *, block_first_read: bool = False, block_first_cancel: bool = False
+ ) -> None:
+ self.row = _fake_workflow_run(status="running").model_copy(update={"workflow_run_id": OWNED_RUN_ID})
+ self.cancel_writes: list[str] = []
+ self.draft_deletes = AsyncMock()
+ self.polled = asyncio.Event()
+ self.cancel_started = asyncio.Event()
+ self._block_first_read = block_first_read
+ self._block_first_cancel = block_first_cancel
+ monkeypatch.setattr(workflow_service_module, "prepare_workflow", AsyncMock(return_value=self.row.model_copy()))
+ monkeypatch.setattr(run_execution_module, "_cancel_run_task_if_not_final", _REAL_CANCEL_RUN_TASK_IF_NOT_FINAL)
+ monkeypatch.setattr(
+ run_execution_module, "_cooperative_cancel_dispatched_run", _REAL_COOPERATIVE_CANCEL_DISPATCHED_RUN
+ )
+ monkeypatch.setattr(
+ run_execution_module, "_delete_dispatch_draft_if_run_final", _REAL_DELETE_DISPATCH_DRAFT_IF_RUN_FINAL
+ )
+ monkeypatch.setattr(
+ forge_app.WORKFLOW_SERVICE, "mark_workflow_run_as_canceled_if_not_final", self._cancel_if_not_final
+ )
+ monkeypatch.setattr(forge_app.DATABASE.workflow_runs, "get_workflow_run", self._get_workflow_run)
+ monkeypatch.setattr(forge_app.DATABASE.workflows, "soft_delete_workflow_by_id", self.draft_deletes)
+ monkeypatch.setattr(run_execution_module, "_read_progress_sources", self._read_progress_sources)
+
+ def finish(self, status: str) -> None:
+ if not self.row.status.is_final():
+ self.row.status = WorkflowRunStatus(status)
+
+ async def _cancel_if_not_final(self, workflow_run_id: str) -> None:
+ self.cancel_started.set()
+ if self._block_first_cancel:
+ self._block_first_cancel = False
+ await asyncio.Event().wait()
+ if not self.row.status.is_final():
+ self.cancel_writes.append(workflow_run_id)
+ self.finish("canceled")
+
+ async def _get_workflow_run(self, **_kwargs: object) -> WorkflowRun:
+ return self.row
+
+ async def _read_progress_sources(self, _ctx: CopilotContext, _run_id: str) -> tuple[WorkflowRun, datetime]:
+ self.polled.set()
+ if self._block_first_read:
+ await asyncio.Event().wait()
+ return self.row, datetime.now(UTC)
+
+
+def make_build_test_ctx(
+ harness: dict[str, Any], monkeypatch: pytest.MonkeyPatch, *, on_chat_browser: bool = False, **overrides: object
+) -> CopilotContext:
+ ctx = make_copilot_ctx(browser_session_id="pbs_chat", **overrides)
+ ctx.staged_workflow = harness["workflow"]
+ ctx.frontier_resume_session_id = "pbs_chat" if on_chat_browser else "pbs_run"
+ if on_chat_browser:
+ monkeypatch.setattr(run_execution_module, "acquire_build_test_browser_session", AsyncMock(return_value=None))
+ return ctx
+
+
+def install_secret_carrying_run_registry(monkeypatch: pytest.MonkeyPatch, *, all_registered: bool = False) -> None:
+ async def _secret_carrying_registry(
+ _ctx: CopilotContext, *, workflow_run_id: str, **_kwargs: object
+ ) -> OriginRunRedactionRegistry:
+ return OriginRunRedactionRegistry(
+ workflow_run_id=workflow_run_id,
+ parameters={},
+ contains_sensitive_values=True,
+ contains_all_sensitive_values=all_registered,
+ )
+
+ monkeypatch.setattr(run_execution_module, "_bind_origin_run_redaction_registry", _secret_carrying_registry)
+
+
+def adopted_detached_tasks(before: set[asyncio.Task]) -> list[asyncio.Task]:
+ return [task for task in run_execution_module._DETACHED_CLEANUP_TASKS if task not in before]
+
+
+async def settle_cancelled_tools() -> None:
+ for _ in range(10):
+ await asyncio.sleep(0.01)
+
+
HANDBACK_WORKFLOW_YAML = """
title: extraction example
workflow_definition:
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 035178370..45d7fdcda 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -7630,6 +7630,7 @@ class TestCopilotConfig:
{"label": "download_invoice", "status": "running", "failure_reason": None},
],
"earlier_blocks_not_shown": 0,
+ "left_running": False,
}
],
id="hard_backstop",
diff --git a/tests/unit/test_copilot_budget_drain.py b/tests/unit/test_copilot_budget_drain.py
index cfac729b7..c40db957b 100644
--- a/tests/unit/test_copilot_budget_drain.py
+++ b/tests/unit/test_copilot_budget_drain.py
@@ -9,41 +9,60 @@ from typing import Any
from unittest.mock import AsyncMock, MagicMock
import pytest
-from agents import ModelSettings, function_tool
+from agents import Agent, ModelSettings, RunContextWrapper, SQLiteSession, function_tool
from agents.exceptions import MaxTurnsExceeded
from agents.run_config import RunConfig
+from skyvern.forge import app as forge_app
from skyvern.forge.sdk.copilot import tools as tools_module
from skyvern.forge.sdk.copilot.agent import (
+ _build_narrative_payload,
_build_timeout_exit_result,
_format_chat_history,
_translate_to_agent_result,
)
from skyvern.forge.sdk.copilot.ask_user import QuestionInteraction, QuestionPart, QuestionResponse
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal
+from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.copilot.enforcement import (
BUDGET_DRAIN_HEADROOM,
EXPIRED_TURN_REPLY_SECONDS,
HARD_BACKSTOP_ALLOWANCE_SECONDS,
TOTAL_TIMEOUT_SECONDS,
+ CopilotTotalTimeoutError,
run_final_reply_drain,
run_with_enforcement,
)
+from skyvern.forge.sdk.copilot.hooks import CopilotRunHooks
from skyvern.forge.sdk.copilot.output_utils import extract_final_text, parse_final_response
-from skyvern.forge.sdk.copilot.tools.run_execution import _run_blocks_and_collect_debug
+from skyvern.forge.sdk.copilot.tools.run_execution import (
+ _run_blocks_and_collect_debug,
+ hydrate_prior_run_packet,
+ recorded_open_step_runs,
+)
from skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind, TurnOutcome
from skyvern.forge.sdk.schemas.workflow_copilot import (
WorkflowCopilotChatHistoryMessage,
WorkflowCopilotChatSender,
WorkflowCopilotStreamMessageType,
)
+from skyvern.forge.sdk.workflow.models.workflow import Workflow
from skyvern.utils.yaml_loader import safe_load_no_dates
from tests.unit.copilot_test_helpers import (
+ HANDBACK_WORKFLOW_YAML,
+ OWNED_RUN_ID,
REPLY_ARGUMENTS,
+ FakeCopilotStream,
+ OwnedRunRow,
ScriptedModel,
+ install_run_blocks_harness,
+ install_secret_carrying_run_registry,
+ make_build_test_ctx,
make_copilot_ctx,
run_scripted_turn,
scripted_call,
+ scripted_text,
+ settle_cancelled_tools,
tool_outputs_for,
)
@@ -700,3 +719,165 @@ async def test_unknown_tool_recovery_keeps_the_budget_drain_within_its_headroom(
await run_scripted_turn(model, tools=[probe], max_turns=1)
assert len(model.inputs) == 1 + BUDGET_DRAIN_HEADROOM
+
+
+async def _build_test_turn(
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ dispatch_to_worker: bool,
+ block_first_read: bool = False,
+ on_chat_browser: bool = False,
+) -> tuple[dict[str, Any], OwnedRunRow, CopilotContext, ScriptedModel]:
+ harness = await install_run_blocks_harness(
+ monkeypatch,
+ workflow_yaml=HANDBACK_WORKFLOW_YAML,
+ polled_status="running",
+ dispatch_to_worker=dispatch_to_worker,
+ )
+ owned = OwnedRunRow(monkeypatch, block_first_read=block_first_read)
+ monkeypatch.setattr(forge_app, "CACHE", MagicMock(get=AsyncMock(return_value=None)))
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.steer.STEER_POLL_SECONDS", 0.01)
+ ctx = make_build_test_ctx(harness, monkeypatch, on_chat_browser=on_chat_browser, stream=FakeCopilotStream())
+ ctx.workflow_copilot_chat_id = "chat-1"
+ ctx.copilot_cancel_token = "cancel-token"
+ model = ScriptedModel(
+ [
+ [scripted_call("run_blocks_and_collect_debug", {"block_labels": ["extract_heading"]}, "call_run")],
+ [scripted_text("A model call after the build test was cancelled.")],
+ ]
+ )
+ return harness, owned, ctx, model
+
+
+@function_tool(name_override="run_blocks_and_collect_debug", strict_mode=False)
+async def _build_test_tool(ctx: RunContextWrapper[CopilotContext], block_labels: list[str]) -> str:
+ result = await _run_blocks_and_collect_debug({"block_labels": block_labels, "parameters": {}}, ctx.context)
+ return json.dumps(result, default=str)
+
+
+async def _run_build_test_turn(ctx: CopilotContext, model: ScriptedModel) -> None:
+ session = SQLiteSession("build-test-turn")
+ try:
+ await run_with_enforcement(
+ agent=Agent(
+ name="build-test-turn",
+ model=model,
+ tools=[_build_test_tool, tools_module.reply_tool],
+ tool_use_behavior=tools_module.reply_ends_turn,
+ ),
+ initial_input="Test the workflow.",
+ ctx=ctx,
+ stream=ctx.stream,
+ session=session,
+ hooks=CopilotRunHooks(ctx),
+ run_config=RunConfig(tracing_disabled=True),
+ )
+ finally:
+ session.close()
+
+
+def _saved_left_run_ids(ctx: CopilotContext) -> list[str]:
+ payload = _build_narrative_payload(ctx, terminal="response", terminal_message="", narrative_summary="")
+ return payload.get("budgetExpiry", {}).get("leftRunIds", [])
+
+
+def _expire_turn_soon(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.TOTAL_TIMEOUT_SECONDS", 0.2)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.HARD_BACKSTOP_ALLOWANCE_SECONDS", 0.3)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.MIN_DEADLINE_REMAINING_SECONDS", 0.1)
+
+
+def _make_prior_run_readable(monkeypatch: pytest.MonkeyPatch, workflow: Workflow) -> None:
+ monkeypatch.setattr(forge_app.DATABASE.workflows, "get_workflow_for_workflow_run", AsyncMock(return_value=workflow))
+ monkeypatch.setattr(forge_app.DATABASE.artifacts, "get_artifacts_for_run", AsyncMock(return_value=[]))
+ monkeypatch.setattr(forge_app.DATABASE.self_heal, "get_heal_episodes_for_run", AsyncMock(return_value=[]))
+
+
[email protected]("worker_outcome", ["completed", "failed", None])
+async def test_hard_backstop_leaves_the_active_dispatched_test_to_its_worker(
+ monkeypatch: pytest.MonkeyPatch, worker_outcome: str | None
+) -> None:
+ harness, owned, ctx, model = await _build_test_turn(monkeypatch, dispatch_to_worker=True)
+ _expire_turn_soon(monkeypatch)
+
+ with pytest.raises(CopilotTotalTimeoutError):
+ await _run_build_test_turn(ctx, model)
+ left_run_ids = _saved_left_run_ids(ctx)
+ reported = await recorded_open_step_runs(ctx)
+ await settle_cancelled_tools()
+ if worker_outcome is not None:
+ owned.finish(worker_outcome)
+
+ assert left_run_ids == [OWNED_RUN_ID]
+ assert [(run.workflow_run_id, run.left_running) for run in reported] == [(OWNED_RUN_ID, True)]
+
+ assert ctx.budget_expiry_state.hard_backstop_reached
+ assert owned.polled.is_set()
+ assert owned.cancel_writes == []
+ assert len(model.inputs) == 1
+ assert ctx.dispatched_run_ids_this_turn == {OWNED_RUN_ID}
+ owned.draft_deletes.assert_not_awaited()
+ harness["clear"].assert_not_awaited()
+ _make_prior_run_readable(monkeypatch, harness["workflow"])
+ packet = await hydrate_prior_run_packet(make_copilot_ctx(), workflow_run_id=OWNED_RUN_ID)
+ assert packet is not None
+ assert (packet["run"]["workflow_run_id"], packet["run"]["status"]) == (
+ OWNED_RUN_ID,
+ worker_outcome or "running",
+ )
+
+
[email protected]("run", ["on_chat_browser", "owes_secrets", "carries_registered_secrets"])
+async def test_hard_backstop_still_cancels_a_test_it_cannot_leave_running(
+ monkeypatch: pytest.MonkeyPatch, run: str
+) -> None:
+ harness, owned, ctx, model = await _build_test_turn(
+ monkeypatch, dispatch_to_worker=True, on_chat_browser=run == "on_chat_browser"
+ )
+ if run != "on_chat_browser":
+ install_secret_carrying_run_registry(monkeypatch, all_registered=run == "carries_registered_secrets")
+ _expire_turn_soon(monkeypatch)
+
+ with pytest.raises(CopilotTotalTimeoutError):
+ await _run_build_test_turn(ctx, model)
+ left_run_ids = _saved_left_run_ids(ctx)
+ reported = await recorded_open_step_runs(ctx)
+ await settle_cancelled_tools()
+
+ assert left_run_ids == []
+ assert [(run.workflow_run_id, run.left_running) for run in reported] == [(OWNED_RUN_ID, False)]
+ assert ctx.budget_expiry_state.hard_backstop_reached
+ assert owned.cancel_writes == [OWNED_RUN_ID]
+ assert owned.row.status == "canceled"
+ assert len(model.inputs) == 1
+ assert harness["clear"].await_count == (0 if run == "on_chat_browser" else 1)
+
+
[email protected]("dispatch_to_worker", [True, False])
[email protected]("elapsed_at_stop", [300.0, 950.0])
[email protected]("block_first_read", [False, True])
+async def test_stop_still_cancels_the_active_build_test(
+ monkeypatch: pytest.MonkeyPatch, dispatch_to_worker: bool, elapsed_at_stop: float, block_first_read: bool
+) -> None:
+ harness, owned, ctx, model = await _build_test_turn(
+ monkeypatch, dispatch_to_worker=dispatch_to_worker, block_first_read=block_first_read
+ )
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement._elapsed_run_seconds", lambda *_: elapsed_at_stop)
+
+ turn = asyncio.create_task(_run_build_test_turn(ctx, model))
+ await asyncio.wait_for(owned.polled.wait(), timeout=5)
+ turn.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await turn
+ left_run_ids = _saved_left_run_ids(ctx)
+ await settle_cancelled_tools()
+
+ assert left_run_ids == []
+ assert ctx.copilot_total_timeout_exceeded is (elapsed_at_stop >= 900)
+ assert owned.cancel_writes == [OWNED_RUN_ID]
+ assert owned.row.status == "canceled"
+ assert harness["executor_cancelled"] is not dispatch_to_worker
+ harness["clear"].assert_awaited_once()
diff --git a/tests/unit/test_copilot_cancel_helpers.py b/tests/unit/test_copilot_cancel_helpers.py
index 8376e8ae6..013301eb3 100644
--- a/tests/unit/test_copilot_cancel_helpers.py
+++ b/tests/unit/test_copilot_cancel_helpers.py
@@ -19,13 +19,28 @@ Covers:
from __future__ import annotations
import asyncio
+import itertools
from types import SimpleNamespace
from typing import Any
import pytest
-from skyvern.forge.sdk.copilot.tools import _cancel_run_task_if_not_final, _trusted_post_drain_status
+from skyvern.forge.sdk.copilot.context import CopilotContext
+from skyvern.forge.sdk.copilot.runtime import browser_session_lock
+from skyvern.forge.sdk.copilot.tools import _cancel_run_task_if_not_final, _trusted_post_drain_status, run_execution
+from skyvern.forge.sdk.copilot.tools.run_execution import _run_blocks_and_collect_debug
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
+from tests.unit.copilot_test_helpers import (
+ HANDBACK_WORKFLOW_YAML,
+ OWNED_RUN_ID,
+ OwnedRunRow,
+ adopted_detached_tasks,
+ install_run_blocks_harness,
+ install_secret_carrying_run_registry,
+ make_build_test_ctx,
+ make_copilot_ctx,
+ settle_cancelled_tools,
+)
class _FakeService:
@@ -223,3 +238,125 @@ def test_trusted_post_drain_handles_missing_row() -> None:
"""A missing row (DB read returned None) is treated the same as a
non-final row: no trusted status, caller emits the timeout error."""
assert _trusted_post_drain_status(None) is None
+
+
+async def _build_test_under_backstop(ctx: CopilotContext, fire_when: asyncio.Event) -> None:
+ """Expire the stream's real timeout once the tool reaches the phase under test, not after a wall-clock delay."""
+ async with asyncio.timeout(None) as deadline:
+ ctx.model_stream_deadline = deadline
+
+ async def _expire_when_reached() -> None:
+ await fire_when.wait()
+ deadline.reschedule(asyncio.get_running_loop().time())
+
+ trigger = asyncio.create_task(_expire_when_reached())
+ try:
+ await _run_blocks_and_collect_debug({"block_labels": ["extract_heading"], "parameters": {}}, ctx)
+ finally:
+ trigger.cancel()
+
+
+async def test_a_finished_sibling_does_not_unmark_a_concurrent_leavable_run() -> None:
+ ctx = make_copilot_ctx()
+ ctx.budget_expiry_state.leavable_run_ids.extend(["wr_left", "wr_sibling"])
+ with pytest.raises(TimeoutError):
+ async with asyncio.timeout(0) as deadline:
+ await asyncio.sleep(1)
+
+ run_execution._unmark_leavable_run(ctx, "wr_sibling")
+
+ assert run_execution._backstop_may_leave_run_running(deadline, ctx.budget_expiry_state, "wr_left")
+ assert not run_execution._backstop_may_leave_run_running(deadline, ctx.budget_expiry_state, "wr_sibling")
+
+
[email protected]("block_first_read", [False, True])
+async def test_backstop_detaches_an_inline_build_test_instead_of_cancelling_it(
+ monkeypatch: pytest.MonkeyPatch, block_first_read: bool
+) -> None:
+ harness = await install_run_blocks_harness(
+ monkeypatch, workflow_yaml=HANDBACK_WORKFLOW_YAML, polled_status="running"
+ )
+ owned = OwnedRunRow(monkeypatch, block_first_read=block_first_read)
+ ctx = make_build_test_ctx(harness, monkeypatch)
+ before = set(run_execution._DETACHED_CLEANUP_TASKS)
+
+ with pytest.raises(TimeoutError):
+ await _build_test_under_backstop(ctx, fire_when=owned.polled)
+ await settle_cancelled_tools()
+
+ adopted = adopted_detached_tasks(before)
+ try:
+ assert owned.polled.is_set()
+ assert owned.cancel_writes == []
+ assert harness["executor_cancelled"] is False
+ assert len(adopted) == 1 and not adopted[0].done()
+ harness["clear"].assert_not_awaited()
+ finally:
+ for task in adopted:
+ task.cancel()
+ await asyncio.gather(*adopted, return_exceptions=True)
+
+
[email protected]("run", ["detached", "detached_owes_secrets", "on_chat_browser"])
+async def test_backstop_during_submission_cancels_the_run(monkeypatch: pytest.MonkeyPatch, run: str) -> None:
+ harness = await install_run_blocks_harness(
+ monkeypatch, workflow_yaml=HANDBACK_WORKFLOW_YAML, polled_status="running", dispatch_to_worker=True
+ )
+ owned = OwnedRunRow(monkeypatch)
+ owned.row.status = WorkflowRunStatus.queued
+ if run == "detached_owes_secrets":
+ install_secret_carrying_run_registry(monkeypatch)
+ submitted = asyncio.Event()
+
+ async def _submit_forever(**_kwargs: object) -> None:
+ submitted.set()
+ await asyncio.Event().wait()
+
+ harness["worker_execute"].side_effect = _submit_forever
+ ctx = make_build_test_ctx(harness, monkeypatch, on_chat_browser=run == "on_chat_browser")
+
+ with pytest.raises(TimeoutError):
+ await _build_test_under_backstop(ctx, fire_when=submitted)
+
+ assert submitted.is_set()
+ assert owned.draft_deletes.await_count == 1
+ assert owned.cancel_writes == [OWNED_RUN_ID]
+ if run == "detached_owes_secrets":
+ assert not browser_session_lock(ctx, session_id="pbs_run").locked()
+ assert ("pbs_run", OWNED_RUN_ID) in ctx.awaited_run_secret_handoffs
+
+
[email protected]("ended_by", ["worker", "watchdog", "watchdog_cancel_in_flight"])
+async def test_backstop_after_the_run_ended_does_not_leave_it_to_an_owner(
+ monkeypatch: pytest.MonkeyPatch, ended_by: str
+) -> None:
+ harness = await install_run_blocks_harness(
+ monkeypatch, workflow_yaml=HANDBACK_WORKFLOW_YAML, polled_status="running", dispatch_to_worker=True
+ )
+ owned = OwnedRunRow(monkeypatch, block_first_cancel=ended_by == "watchdog_cancel_in_flight")
+ if ended_by == "worker":
+ owned.finish("completed")
+ else:
+ monkeypatch.setattr(run_execution, "time", SimpleNamespace(monotonic=itertools.count(step=600).__next__))
+ run_ended = asyncio.Event()
+
+ async def _park_after_the_run(*_args: object, **_kwargs: object) -> None:
+ run_ended.set()
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr(run_execution, "_halt_turn_if_superseded", _park_after_the_run)
+ ctx = make_build_test_ctx(harness, monkeypatch)
+
+ with pytest.raises(TimeoutError):
+ await _build_test_under_backstop(
+ ctx, fire_when=owned.cancel_started if ended_by == "watchdog_cancel_in_flight" else run_ended
+ )
+
+ assert owned.cancel_writes == ([] if ended_by == "worker" else [OWNED_RUN_ID])
+ assert owned.row.status == ("completed" if ended_by == "worker" else "canceled")
+ owned.draft_deletes.assert_awaited_once()
+ harness["clear"].assert_awaited_once()
diff --git a/tests/unit/test_copilot_narrative_activity.py b/tests/unit/test_copilot_narrative_activity.py
index c70f2942c..9186f0a9e 100644
--- a/tests/unit/test_copilot_narrative_activity.py
+++ b/tests/unit/test_copilot_narrative_activity.py
@@ -278,6 +278,33 @@ def test_build_narrative_payload_serializes_block_and_design_activity() -> None:
assert blocks_by_label["step_2"]["activity"] == []
+def test_build_narrative_payload_marks_only_the_left_runs_blocks_unfinished() -> None:
+ ctx = _ctx()
+ for workflow_run_block_id, workflow_run_id in (("wrb_left", "wr_left"), ("wrb_cancelled", "wr_cancelled")):
+ upsert_narrative_block_attempt(
+ ctx.narrative_block_attempts,
+ workflow_run_block_id=workflow_run_block_id,
+ workflow_run_id=workflow_run_id,
+ label=workflow_run_block_id,
+ block_type="task",
+ status="running",
+ iteration=1,
+ started_at=_TS.isoformat(),
+ ended_at=None,
+ )
+ ctx.budget_expiry_state.source = "deadline"
+ ctx.budget_expiry_state.hard_backstop_reached = True
+ ctx.budget_expiry_state.leavable_run_ids.append("wr_left")
+
+ payload = _build_narrative_payload(ctx, terminal="response", terminal_message="done", narrative_summary="done")
+
+ assert {block["label"]: block["state"] for block in payload["blocks"]} == {
+ "wrb_left": "unfinished",
+ "wrb_cancelled": "running",
+ }
+ assert payload["budgetExpiry"]["leftRunIds"] == ["wr_left"]
+
+
def test_build_narrative_payload_serializes_only_observed_attempts() -> None:
ctx = _ctx()
ctx.staged_workflow = _staged("step_1", "drafted_only") # type: ignore[assignment]
diff --git a/tests/unit/test_copilot_watchdog.py b/tests/unit/test_copilot_watchdog.py
index ea33a4ae8..d24a04197 100644
--- a/tests/unit/test_copilot_watchdog.py
+++ b/tests/unit/test_copilot_watchdog.py
@@ -45,7 +45,7 @@ from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock
from skyvern.schemas.workflows import BlockStatus, BlockType
from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.actions import ActionStatus
-from tests.unit.copilot_test_helpers import SEARCH_THEN_SELECT_WORKFLOW_YAML
+from tests.unit.copilot_test_helpers import SEARCH_THEN_SELECT_WORKFLOW_YAML, adopted_detached_tasks
from tests.unit.copilot_test_helpers import install_run_blocks_harness as _install_run_harness
from tests.unit.copilot_test_helpers import make_copilot_ctx, run_result_action_row, terminal_extraction_block
@@ -429,10 +429,6 @@ workflow_definition:
"""
-def _adopted_detached_tasks(before: set[Any]) -> list[Any]:
- return [task for task in run_execution._DETACHED_CLEANUP_TASKS if task not in before]
-
-
def _install_advancing_clock(monkeypatch: pytest.MonkeyPatch, step_seconds: float = 600.0) -> Callable[[], float]:
elapsed = 0.0
@@ -493,8 +489,9 @@ async def test_paused_run_is_reported_as_a_pause_and_left_running(monkeypatch: p
harness["cooperative_cancel"].assert_not_awaited()
harness["clear"].assert_not_awaited()
harness["publish"].assert_awaited_once()
+ assert ctx.budget_expiry_state.leavable_run_ids == []
- adopted = _adopted_detached_tasks(before)
+ adopted = adopted_detached_tasks(before)
assert len(adopted) == 1
await asyncio.sleep(0)
assert harness["executor_cancelled"] is False
@@ -530,7 +527,7 @@ async def test_tool_cancelled_while_paused_leaves_the_run_alive(monkeypatch: pyt
harness["cancel_run_task"].assert_not_awaited()
harness["cooperative_cancel"].assert_not_awaited()
- adopted = _adopted_detached_tasks(before)
+ adopted = adopted_detached_tasks(before)
assert len(adopted) == 1
await asyncio.sleep(0)
assert harness["executor_cancelled"] is False
@@ -607,7 +604,7 @@ async def test_non_paused_watchdog_exit_still_cancels_and_clears(monkeypatch: py
assert result["data"]["browser_start"]["kind"] == "separate_context_continued_from_earlier_test"
harness["cancel_run_task"].assert_awaited_once()
harness["clear"].assert_awaited_once()
- assert _adopted_detached_tasks(before) == []
+ assert adopted_detached_tasks(before) == []
for relayed in (
result["data"]["failure_reason"],
@@ -1064,7 +1061,7 @@ async def test_the_turn_deadline_ends_the_wait_and_leaves_the_run_with_its_execu
assert harness["executor_cancelled"] is False
assert ctx.open_step_run_ids == ["wr_paused"]
- adopted = _adopted_detached_tasks(before)
+ adopted = adopted_detached_tasks(before)
for task in adopted:
task.cancel()
await asyncio.gather(*adopted, return_exceptions=True)