Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Routines: try a scheduled run again when its cloud computer did not wake (#6545)

Milind Soni04ccd3dade0d
diff --git a/server/host/cloud-computer-run-gate.test.ts b/server/host/cloud-computer-run-gate.test.ts
index 1262e92f36..b209136c7e 100644
--- a/server/host/cloud-computer-run-gate.test.ts
+++ b/server/host/cloud-computer-run-gate.test.ts
@@ -7,14 +7,14 @@ import { createRunComputerGate, RUN_COMPUTER_WAIT_MS } from "./cloud-computer-ru
const RUN = { routineId: "routine-1", botId: "bot-1", target: "bot", runOn: "cloud" };
-function harness(over: { state?: string; answers?: (wait: number) => boolean; wakes?: boolean; disk?: (boxId: string, signal?: AbortSignal) => Promise<number | null | void>; remember?: { load(): string[]; save(ids: string[]): void } } = {}) {
+function harness(over: { state?: string; answers?: (wait: number) => boolean; wakes?: boolean; wakeThrows?: unknown; findThrows?: unknown; disk?: (boxId: string, signal?: AbortSignal) => Promise<number | null | void>; remember?: { load(): string[]; save(ids: string[]): void } } = {}) {
let at = 0;
const seen = { finds: 0, wakes: 0, waits: [] as boolean[], signals: [] as Array<AbortSignal | undefined>, used: 0 };
const world = { verdict: null as RecoveryVerdict | null, verdictAt: 0, routine: "routine-1" as string | null, recovery: null as CloudComputerRecoveryState | null, machine: { id: "bx_23456789", state: over.state ?? "idle" } as { id: string; state: string } | null };
const gate = createRunComputerGate({
computerOf: () => "bot-1",
- find: async () => { seen.finds++; return world.machine; },
- wake: async () => { seen.wakes++; return over.wakes === false ? null : { id: "bx_23456789", state: "idle" }; },
+ find: async () => { seen.finds++; if (over.findThrows !== undefined) throw over.findThrows; return world.machine; },
+ wake: async () => { seen.wakes++; if (over.wakeThrows !== undefined) throw over.wakeThrows; return over.wakes === false ? null : { id: "bx_23456789", state: "idle" }; },
awaitAnswer: async (_boxId, opts): Promise<BoatAnswer> => {
seen.waits.push(opts.woke);
seen.signals.push(opts.signal);
@@ -151,6 +151,37 @@ describe("an unattended run and its cloud computer", () => {
await expect(h.gate.prepare(RUN)).resolves.toBe(RUN_COMPUTER_LINES.noWake);
});
+ it("lets a run start when its computer cannot be looked up, unless it is a retry of a run whose computer did not wake", async () => {
+ const unreachable = Object.assign(new Error("could not list cloud computers"), { status: 503, transient: true });
+ const h = harness({ findThrows: unreachable });
+ h.used();
+ await expect(h.gate.prepare(RUN)).resolves.toBeNull();
+ await expect(h.gate.prepare({ ...RUN, wakeRetries: 1 })).resolves.toBe(RUN_COMPUTER_LINES.noWake);
+ // A run that started since its wake retries is an ordinary run again.
+ await expect(h.gate.prepare({ ...RUN, wakeRetries: 1, startedAt: 1, retried: "restarted" })).resolves.toBeNull();
+ expect(h.seen.wakes).toBe(0);
+ });
+
+ it("leaves a lookup the provider refused to the turn, even on a retry", async () => {
+ const h = harness({ findThrows: Object.assign(new Error("boat.dev rejected the Boat API key"), { status: 503 }) });
+ h.used();
+ await expect(h.gate.prepare({ ...RUN, wakeRetries: 1 })).resolves.toBeNull();
+ });
+
+ it("tells a provider that refused the wake from one that did not answer: only the second is worth another try", async () => {
+ const refusal = (status: number) => Object.assign(new Error("refused"), { boatStatus: status });
+ for (const [thrown, line] of [
+ [refusal(402), RUN_COMPUTER_LINES.wakeRefused], [refusal(403), RUN_COMPUTER_LINES.wakeRefused],
+ [refusal(429), RUN_COMPUTER_LINES.noWake], [refusal(503), RUN_COMPUTER_LINES.noWake],
+ [Object.assign(new Error("The operation was aborted due to timeout"), { name: "TimeoutError" }), RUN_COMPUTER_LINES.noWake],
+ [Object.assign(new Error("could not list cloud computers"), { status: 503, transient: true }), RUN_COMPUTER_LINES.noWake],
+ ] as const) {
+ const h = harness({ state: "archived", wakeThrows: thrown });
+ h.used();
+ await expect(h.gate.prepare(RUN)).resolves.toBe(line);
+ }
+ });
+
it("keeps waiting while the recovery works on a silent computer, and starts once it answers", async () => {
const h = harness({ answers: (wait) => wait >= 4 });
h.used();
diff --git a/server/host/cloud-computer-run-gate.ts b/server/host/cloud-computer-run-gate.ts
index d8c94e80fe..a5656210b6 100644
--- a/server/host/cloud-computer-run-gate.ts
+++ b/server/host/cloud-computer-run-gate.ts
@@ -18,7 +18,9 @@ const MAX_ROUTINES = 500;
const ENDED = new Set<CloudComputerRecoveryState>(["needs-person", "unreachable", "capped"]);
const SLEEPING = new Set(["archived", "archiving"]);
-interface RunLike { routineId: string; botId: string; target: string; runOn?: string }
+/** `wakeRetries`: how often the run was queued again because its computer did not wake (routine-wake-retry.ts); it counts
+ * only while the run has not started since (`startedAt`, `retried`). */
+interface RunLike { routineId: string; botId: string; target: string; runOn?: string; wakeRetries?: number; startedAt?: number; retried?: string }
interface Machine { id: string; state: string }
export interface RunComputerGateDeps {
@@ -44,6 +46,17 @@ export interface RunComputerGateDeps {
now?(): number;
}
+/** The provider answered the wake with a refusal a later try would meet too (a plan or start limit, a rejected key), not a
+ * timeout, a network failure, a rate limit or a fault on its side. */
+const refusedWake = (error: unknown): boolean => {
+ const status = (error as { boatStatus?: unknown } | null)?.boatStatus;
+ return typeof status === "number" && status >= 400 && status < 500 && status !== 408 && status !== 429;
+};
+
+/** The provider did not answer the lookup at all: a time-out, or no answer from it (findBoat marks that `transient`). */
+const unanswered = (error: unknown): boolean =>
+ (error as { transient?: unknown } | null)?.transient === true || (error instanceof Error && error.name === "TimeoutError");
+
const VERDICT_LINE: Record<RecoveryVerdict, string> = {
"restart-failed": RUN_COMPUTER_LINES.afterRestart, "person-busy": RUN_COMPUTER_LINES.personBusy,
"restart-limited": RUN_COMPUTER_LINES.restartLimited, shared: RUN_COMPUTER_LINES.shared,
@@ -59,14 +72,21 @@ export function createRunComputerGate(deps: RunComputerGateDeps) {
const startedFull = new Set<string>();
const fullThreads = new Set<string>();
- async function ready(owner: string, routineId: string, signal?: AbortSignal): Promise<string | null> {
+ async function ready(owner: string, routineId: string, retrying: boolean, signal?: AbortSignal): Promise<string | null> {
const began = now();
- let machine = await deps.find(owner).catch(() => null);
+ // A lookup that fails lets the run start, and its turn reports the trouble; but a run tried again because its computer
+ // did not wake already found it asleep, and a lookup the provider does not answer now is the same outage. A lookup
+ // it answered with a refusal (a rejected key) is the turn's to report.
+ const found = await deps.find(owner).then((machine) => machine, (error: unknown) => retrying && unanswered(error) ? RUN_COMPUTER_LINES.noWake : null);
+ if (typeof found === "string") return found;
+ let machine = found;
if (!machine || signal?.aborted) return null;
let woke = false;
if (SLEEPING.has(machine.state)) {
- machine = await deps.wake(owner, WAKE_BUDGET_MS).catch(() => null);
- if (!machine) return RUN_COMPUTER_LINES.noWake;
+ const woken = await deps.wake(owner, WAKE_BUDGET_MS).then((up) => up ?? RUN_COMPUTER_LINES.noWake,
+ (error: unknown) => refusedWake(error) ? RUN_COMPUTER_LINES.wakeRefused : RUN_COMPUTER_LINES.noWake);
+ if (typeof woken === "string") return woken;
+ machine = woken;
woke = true;
}
const deadline = now() + RUN_COMPUTER_WAIT_MS;
@@ -99,7 +119,7 @@ export function createRunComputerGate(deps: RunComputerGateDeps) {
const owner = deps.computerOf(run);
if (!owner) return null;
startedFull.delete(run.routineId);
- return ready(owner, run.routineId, signal).then((reason) => {
+ return ready(owner, run.routineId, (run.wakeRetries ?? 0) > 0 && run.startedAt == null && run.retried === undefined, signal).then((reason) => {
if (reason) deps.log(`routine ${run.routineId}: its cloud computer (${owner}) was not ready: ${reason}`);
return reason;
}, (error) => {
diff --git a/server/routine-execution.ts b/server/routine-execution.ts
index 554e26f337..1b95d56341 100644
--- a/server/routine-execution.ts
+++ b/server/routine-execution.ts
@@ -1,5 +1,6 @@
import { stopCause } from "./drivers/engine-errors.ts";
import { redactSecretsInText } from "./redact.ts";
+import { waitsToWakeAgain } from "./routine-wake-retry.ts";
import type { Routine, RoutineContextAttachment, RoutineRun, RoutineRunOn, RoutineRunTrigger } from "./routines.ts";
export interface RoutineContinuityCarry {
@@ -134,8 +135,10 @@ export function routineFailure(error: string | undefined, stopReason: string | n
export const ROUTINE_DEFERRAL_NOTICE_MS = 30 * 60_000;
export const ROUTINE_SUPERSEDED = "Stopped waiting: the next scheduled run of this routine started instead";
-/** Waiting since a notice window before its routine's next occurrence came due, with no hand-off still open: that occurrence starts instead. */
-export function supersededBy(dueAt: number, run: Pick<RoutineRun, "status" | "waitingSince" | "threadId">, handedOffWorkLive?: (threadId: string) => boolean): boolean {
+/** Waiting since a notice window before its routine's next occurrence came due, with no hand-off still open, or queued to
+ * wake its cloud computer again (routine-wake-retry.ts): that occurrence starts instead. */
+export function supersededBy(dueAt: number, run: Pick<RoutineRun, "status" | "waitingSince" | "threadId" | "wakeRetries" | "startedAt" | "retried">, handedOffWorkLive?: (threadId: string) => boolean): boolean {
+ if (waitsToWakeAgain(run)) return true;
return run.status === "waiting" && run.waitingSince !== undefined && run.waitingSince <= dueAt - ROUTINE_DEFERRAL_NOTICE_MS &&
!(run.threadId && handedOffWorkLive?.(run.threadId));
}
diff --git a/server/routine-lines.ts b/server/routine-lines.ts
index 8e944ba9cd..d2e8054890 100644
--- a/server/routine-lines.ts
+++ b/server/routine-lines.ts
@@ -49,6 +49,9 @@ export const ROUTINE_LINE = {
"routines.server.restored": "Not run again: this schedule was restored from a backup made before this run had its turn",
"routines.server.restoredMany": "Not run again: {count} scheduled runs from before this schedule was restored from a backup",
"routines.server.duplicate": "Not started: this scheduled run had already started once",
+ "routines.server.wakeRetry": "The cloud desktop did not wake, so this run has not started yet. It tries again at {resets}",
+ "routines.server.noWakeRetried": "The cloud desktop did not wake, even after more tries, so this run did not start. The next scheduled run tries again.",
+ "routines.server.noWakeRetriedLast": "The cloud desktop did not wake, even after more tries, so this run did not start.",
} as const;
export type RoutineLineKey = keyof typeof ROUTINE_LINE;
diff --git a/server/routine-load.ts b/server/routine-load.ts
index 41927253c7..51c3bb6ba5 100644
--- a/server/routine-load.ts
+++ b/server/routine-load.ts
@@ -12,6 +12,7 @@ import { isRoutineHoldCause } from "./routine-holds.ts";
import { MAX_DATE_MS } from "./routine-intervals.ts";
import { loadSchedule } from "./routine-schedules.ts";
import { loadSkips } from "./routine-skips.ts";
+import { loadWakeRetries } from "./routine-wake-retry.ts";
import type { Routine, RoutineGoalStatus, RoutinePackageStamp, RoutineRequestCommit, RoutineRequestReceipt, RoutineRun, RoutineTarget } from "./routines.ts";
const persistedSourceThreadId = z.string().trim().min(1).optional().catch(undefined);
@@ -137,8 +138,10 @@ export function loadRun(run: RoutineRun): RoutineRun {
busyMs: instant(run.busyMs),
workedMs: instant(run.workedMs),
skipped: loadSkips(run.skipped),
+ wakeRetries: loadWakeRetries(run.wakeRetries),
+ wakeRetryUntil: instant(run.wakeRetryUntil),
};
- return withoutUndefined(loaded, ["timeoutMinutes", "access", "deliver", "checkKey", "busyMs", "workedMs", "skipped"]);
+ return withoutUndefined(loaded, ["timeoutMinutes", "access", "deliver", "checkKey", "busyMs", "workedMs", "skipped", "wakeRetries", "wakeRetryUntil"]);
}
const REQUEST_ACTIONS = new Set<RoutineRequestOperation["action"]>(["create", "update", "pause", "resume", "run_now", "delete"]);
diff --git a/server/routine-recovery.ts b/server/routine-recovery.ts
index 57775f3f5a..6165d8e14e 100644
--- a/server/routine-recovery.ts
+++ b/server/routine-recovery.ts
@@ -140,7 +140,7 @@ function when(at: number): string {
return whenParams(at).resets;
}
-function whenParams(at: number): { resets: string; resetsAt?: number; timeZone?: string } {
+export function whenParams(at: number): { resets: string; resetsAt?: number; timeZone?: string } {
const timeZone = hostTimeZone();
try {
return { resets: `${new Date(at).toLocaleString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit", timeZone })} (${timeZone})`, resetsAt: at, timeZone };
diff --git a/server/routine-wake-retry.test.ts b/server/routine-wake-retry.test.ts
new file mode 100644
index 0000000000..0eb448aea6
--- /dev/null
+++ b/server/routine-wake-retry.test.ts
@@ -0,0 +1,238 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { RUN_COMPUTER_LINES } from "../shared/cloud-computer-recovery.ts";
+import { CATCH_UP_MS } from "./routine-catch-up.ts";
+import { WAKE_RETRY_AFTER_MS, WAKE_RETRY_LAST_MS, waitsToWakeAgain, wakeRetry } from "./routine-wake-retry.ts";
+import type { RoutineScheduleInput } from "./routine-schedules.ts";
+import { RoutineManager, type RoutineManagerOptions } from "./routines.ts";
+
+const MINUTE = 60_000;
+const START = new Date(2026, 10, 18, 8, 0, 0).getTime();
+const dirs: string[] = [];
+const managers: RoutineManager[] = [];
+afterEach(() => {
+ for (const manager of managers.splice(0)) manager.close();
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+/** A cloud bot's routine whose computer answers each wake from `wakes`, in order: a reason it did not start, or null. */
+function harness(wakes: Array<string | null | "hang">, everyMinutes = 60, schedule?: RoutineScheduleInput) {
+ const dir = mkdtempSync(join(tmpdir(), "omb-wake-retry-"));
+ dirs.push(dir);
+ const world = { at: START, started: [] as string[], prepared: [] as string[] };
+ let tasks = 0;
+ const options: RoutineManagerOptions = {
+ file: join(dir, "routines.json"), now: () => world.at, botState: () => "ready",
+ createTask: (botId) => ({ threadId: `${botId}-thread-${++tasks}` }),
+ startTurn: async (_botId, threadId) => { world.started.push(threadId); },
+ prepareRun: (run) => {
+ world.prepared.push(run.id);
+ const answer = wakes.shift() ?? null;
+ return answer === "hang" ? new Promise<string | null>(() => {}) : Promise.resolve(answer);
+ },
+ preparing: RUN_COMPUTER_LINES.waking,
+ };
+ const h = {
+ world, options,
+ manager: new RoutineManager(options),
+ restart() { h.manager.close(); h.manager = new RoutineManager(options); managers.push(h.manager); return h.manager; },
+ /** Until the computer's answer is in and the pass it set off has ended. */
+ async idle() {
+ do await new Promise((resolve) => setImmediate(resolve)); while (h.manager.isTicking);
+ },
+ /** A scheduler pass at `at`, then one more once the computer's answer is in. */
+ async passAt(at: number) {
+ world.at = at;
+ await h.manager.tick();
+ await h.idle();
+ await h.manager.tick();
+ await h.idle();
+ },
+ runs: () => h.manager.listRuns(),
+ };
+ managers.push(h.manager);
+ const routine = h.manager.create({ name: "Out of hours", prompt: "Check the inbox", botId: "cloud-bot", schedule: schedule ?? { type: "interval", everyMinutes, anchorAt: START } });
+ return { ...h, routine, due: routine.nextRunAt! };
+}
+
+describe("a scheduled run whose cloud computer did not wake", () => {
+ it("stays queued, says when it tries again, and starts on the second try", async () => {
+ const h = harness([RUN_COMPUTER_LINES.noWake, null]);
+ await h.passAt(h.due);
+ expect(h.world.started).toEqual([]);
+ const [run] = h.runs();
+ expect(run).toMatchObject({ status: "queued", scheduledFor: h.due, retryAt: h.due + WAKE_RETRY_AFTER_MS[0]!, wakeRetries: 1, attentionCode: "routines.server.wakeRetry" });
+ expect(run!.attention).toMatch(/^The cloud desktop did not wake, so this run has not started yet\. It tries again at /);
+ expect(run).not.toHaveProperty("error");
+
+ // Nothing is asked of the computer before the retry is due.
+ await h.passAt(h.due + WAKE_RETRY_AFTER_MS[0]! - MINUTE);
+ expect(h.world.prepared).toHaveLength(1);
+
+ await h.passAt(h.due + WAKE_RETRY_AFTER_MS[0]!);
+ expect(h.world.prepared).toEqual([run!.id, run!.id]);
+ expect(h.world.started).toHaveLength(1);
+ expect(h.runs()).toMatchObject([{ id: run!.id, status: "running", scheduledFor: h.due }]);
+ });
+
+ it("never starts the same occurrence twice: later passes leave it alone, and the next occurrence is a run of its own", async () => {
+ const h = harness([RUN_COMPUTER_LINES.noWake, null, null]);
+ await h.passAt(h.due);
+ await h.passAt(h.due + WAKE_RETRY_AFTER_MS[0]!);
+ for (const later of [1, 10, 25]) await h.passAt(h.due + WAKE_RETRY_AFTER_MS[0]! + later * MINUTE);
+ expect(h.world.started).toHaveLength(1);
+ const threadId = h.runs()[0]!.threadId!;
+ h.manager.handleRuntimeEvent({ eventId: `done-${threadId}`, provider: "fake", threadId, createdAt: new Date(h.world.at).toISOString(), type: "turn.completed", ok: true } as Parameters<RoutineManager["handleRuntimeEvent"]>[0]);
+ expect(h.runs()[0]).toMatchObject({ status: "completed" });
+ await h.passAt(h.due + 60 * MINUTE);
+ expect(h.world.started).toHaveLength(2);
+ expect(h.runs().map((run) => run.scheduledFor).sort()).toEqual([h.due, h.due + 60 * MINUTE]);
+ });
+
+ it("keeps its retry across a restart and starts it once", async () => {
+ const h = harness([RUN_COMPUTER_LINES.noWake, null]);
+ await h.passAt(h.due);
+ const [before] = h.runs();
+ h.restart();
+ expect(h.runs()).toMatchObject([{ id: before!.id, status: "queued", retryAt: before!.retryAt, wakeRetries: 1 }]);
+ await h.passAt(before!.retryAt!);
+ await h.passAt(before!.retryAt! + MINUTE);
+ expect(h.world.started).toHaveLength(1);
+ expect(h.runs()).toMatchObject([{ id: before!.id, status: "running" }]);
+ });
+
+ it("tries three more times at most, then fails saying the next scheduled run tries again", async () => {
+ const h = harness([RUN_COMPUTER_LINES.noWake, RUN_COMPUTER_LINES.noWake, RUN_COMPUTER_LINES.noWake, RUN_COMPUTER_LINES.noWake]);
+ await h.passAt(h.due);
+ for (const after of WAKE_RETRY_AFTER_MS) await h.passAt(h.due + after);
+ expect(h.world.prepared).toHaveLength(4);
+ expect(h.world.started).toEqual([]);
+ expect(h.runs()).toMatchObject([{ status: "failed", errorCode: "routines.server.noWakeRetried",
+ error: "The cloud desktop did not wake, even after more tries, so this run did not start. The next scheduled run tries again." }]);
+ expect(h.manager.listRoutines()[0]).toMatchObject({ enabled: true });
+ });
+
+ it("gives up before the next occurrence is due, which takes over", async () => {
+ // Every 15 minutes: one retry fits before the next occurrence, a second would not.
+ const h = harness([RUN_COMPUTER_LINES.noWake, RUN_COMPUTER_LINES.noWake, null], 15);
+ await h.passAt(h.due);
+ expect(h.runs()).toMatchObject([{ status: "queued", retryAt: h.due + WAKE_RETRY_AFTER_MS[0]! }]);
+ await h.passAt(h.due + WAKE_RETRY_AFTER_MS[0]!);
+ expect(h.runs()).toMatchObject([{ status: "failed", error: "The cloud desktop did not wake, even after more tries, so this run did not start. The next scheduled run tries again." }]);
+ await h.passAt(h.due + 15 * MINUTE);
+ expect(h.world.started).toHaveLength(1);
+ expect(h.runs().find((run) => run.status === "running")).toMatchObject({ scheduledFor: h.due + 15 * MINUTE });
+ });
+
+ it("gives way when a retry is still waiting for its computer as the next occurrence comes due", async () => {
+ const h = harness([RUN_COMPUTER_LINES.noWake, "hang", null], 15);
+ await h.passAt(h.due);
+ const [first] = h.runs();
+ await h.passAt(first!.retryAt!);
+ expect(h.runs()).toMatchObject([{ id: first!.id, status: "queued", attention: RUN_COMPUTER_LINES.waking }]);
+ await h.passAt(h.due + 15 * MINUTE);
+ expect(h.runs().find((run) => run.id === first!.id)).toMatchObject({ status: "failed", error: "The cloud desktop did not wake, even after more tries, so this run did not start. The next scheduled run tries again." });
+ const next = h.runs().find((run) => run.id !== first!.id)!;
+ expect(next).toMatchObject({ scheduledFor: h.due + 15 * MINUTE, status: "running" });
+ expect(next).not.toHaveProperty("skipped");
+ expect(h.world.started).toHaveLength(1);
+ });
+
+ it("never queues a try outside an interval schedule's hours, and gives one up that comes due outside them", async () => {
+ const window = { type: "interval", everyMinutes: 15, anchorAt: START, window: { start: "08:00", end: "09:00" } } as const;
+ // Three tries from 08:45: 08:50 and 08:57 are inside the window, 09:05 would not be.
+ const h = harness([RUN_COMPUTER_LINES.noWake, RUN_COMPUTER_LINES.noWake, RUN_COMPUTER_LINES.noWake, null], 15, window);
+ const last = START + 45 * MINUTE;
+ await h.passAt(last);
+ const [run] = h.runs().filter((candidate) => candidate.scheduledFor === last);
+ expect(run).toMatchObject({ status: "queued", retryAt: START + 50 * MINUTE });
+ await h.passAt(START + 50 * MINUTE);
+ expect(h.runs().find((candidate) => candidate.id === run!.id)).toMatchObject({ status: "queued", retryAt: START + 57 * MINUTE });
+ await h.passAt(START + 57 * MINUTE);
+ expect(h.runs().find((candidate) => candidate.id === run!.id)).toMatchObject({ status: "failed", error: "The cloud desktop did not wake, even after more tries, so this run did not start. The next scheduled run tries again." });
+ expect(h.manager.hasActiveRuns()).toBe(false);
+
+ // A try queued inside the window whose pass only comes after it ends is given up, not left waiting for tomorrow.
+ const late = harness([RUN_COMPUTER_LINES.noWake, RUN_COMPUTER_LINES.noWake, null], 15, window);
+ await late.passAt(last);
+ await late.passAt(START + 50 * MINUTE);
+ expect(late.runs().find((candidate) => candidate.scheduledFor === last)).toMatchObject({ status: "queued", retryAt: START + 57 * MINUTE });
+ await late.passAt(START + 62 * MINUTE);
+ expect(late.runs().find((candidate) => candidate.scheduledFor === last)).toMatchObject({ status: "failed", error: "The cloud desktop did not wake, even after more tries, so this run did not start. The next scheduled run tries again." });
+ expect(late.manager.hasActiveRuns()).toBe(false);
+ expect(late.world.started).toEqual([]);
+ });
+
+ it("tries a once-only routine's run again, though the routine turned itself off when the run was made", async () => {
+ const at = START + 30 * MINUTE;
+ const h = harness([RUN_COMPUTER_LINES.noWake, null], 60, { type: "once", at });
+ await h.passAt(at);
+ expect(h.manager.listRoutines()[0]).toMatchObject({ enabled: false, nextRunAt: null });
+ expect(h.runs()).toMatchObject([{ status: "queued", retryAt: at + WAKE_RETRY_AFTER_MS[0]!, wakeRetries: 1 }]);
+ await h.passAt(at + WAKE_RETRY_AFTER_MS[0]!);
+ expect(h.world.started).toHaveLength(1);
+ expect(h.runs()).toMatchObject([{ status: "running", scheduledFor: at }]);
+ });
+
+ it("gives up a try left waiting while the server slept past the next occurrence, which then runs in its place", async () => {
+ const h = harness([RUN_COMPUTER_LINES.noWake, null, null], 60, { type: "cron", expression: "0 * * * *", timeZone: "UTC" });
+ await h.passAt(h.due);
+ const [first] = h.runs();
+ expect(first).toMatchObject({ status: "queued", wakeRetryUntil: h.due + 60 * MINUTE });
+ await h.passAt(h.due + 14 * 60 * MINUTE);
+ expect(h.runs().find((run) => run.id === first!.id)).toMatchObject({ status: "failed", error: "The cloud desktop did not wake, even after more tries, so this run did not start. The next scheduled run tries again." });
+ expect(h.runs().some((run) => run.skipped?.behind === first!.id)).toBe(false);
+ expect(h.world.prepared.filter((id) => id === first!.id)).toHaveLength(1);
+ });
+
+ it("fails at once for any other reason it did not start: those are not tried again", async () => {
+ for (const reason of [RUN_COMPUTER_LINES.noAnswer, RUN_COMPUTER_LINES.afterRestart, RUN_COMPUTER_LINES.wakeRefused]) {
+ const h = harness([reason, null]);
+ await h.passAt(h.due);
+ await h.passAt(h.due + 30 * MINUTE);
+ expect(h.world.prepared).toHaveLength(1);
+ expect(h.world.started).toEqual([]);
+ expect(h.runs()).toMatchObject([{ status: "failed", error: reason }]);
+ expect(h.runs()[0]).not.toHaveProperty("wakeRetries");
+ }
+ });
+});
+
+describe("whether a run that did not wake is tried again", () => {
+ const run = () => ({ status: "queued" as const, target: "bot" as const, scheduledFor: START, attention: "x" as string | undefined });
+ const every = { type: "interval", everyMinutes: 60, anchorAt: START } as const;
+ const hourly = { enabled: true, nextRunAt: START + 60 * MINUTE, schedule: every };
+
+ it("is not for a run its schedule did not start, a paused routine, or a routine with no time left before the next occurrence", () => {
+ expect(wakeRetry(run(), RUN_COMPUTER_LINES.noWake, undefined, START + 4 * MINUTE)).toBe(RUN_COMPUTER_LINES.noWake);
+ expect(wakeRetry(run(), RUN_COMPUTER_LINES.noWake, { enabled: false, nextRunAt: null, schedule: every }, START + 4 * MINUTE)).toBe(RUN_COMPUTER_LINES.noWake);
+ expect(wakeRetry(run(), RUN_COMPUTER_LINES.noWake, { enabled: true, nextRunAt: START + 9 * MINUTE, schedule: every }, START + 4 * MINUTE)).toBe(RUN_COMPUTER_LINES.noWake);
+ // A run that already started once (a restart put it back) is not this run's to try again.
+ expect(wakeRetry({ ...run(), startedAt: START + MINUTE, retried: "restarted" as const }, RUN_COMPUTER_LINES.noWake, hourly, START + 4 * MINUTE)).toBe(RUN_COMPUTER_LINES.noWake);
+ });
+
+ it("waits at least a short gap after a try that ended late", () => {
+ const late = run();
+ expect(wakeRetry(late, RUN_COMPUTER_LINES.noWake, hourly, START + 30 * MINUTE)).toBe(true);
+ expect(late).toMatchObject({ retryAt: START + 32 * MINUTE, wakeRetries: 1 });
+ });
+
+ it("gives way to the next occurrence only while the run has not started since", () => {
+ expect(waitsToWakeAgain({ status: "queued", wakeRetries: 1 })).toBe(true);
+ expect(waitsToWakeAgain({ status: "queued" })).toBe(false);
+ expect(waitsToWakeAgain({ status: "queued", wakeRetries: 1, startedAt: START + 5 * MINUTE, retried: "restarted" })).toBe(false);
+ expect(waitsToWakeAgain({ status: "running", wakeRetries: 1, startedAt: START + 5 * MINUTE })).toBe(false);
+ });
+
+ it("ends a once-only routine's tries without promising a next run, and bounds them by how late a missed run still starts", () => {
+ const onceOnly = { enabled: false, nextRunAt: null, schedule: { type: "once", at: START } } as const;
+ const first = run();
+ expect(wakeRetry(first, RUN_COMPUTER_LINES.noWake, onceOnly, START + 4 * MINUTE)).toBe(true);
+ expect(first).toMatchObject({ wakeRetries: 1, wakeRetryUntil: START + WAKE_RETRY_LAST_MS });
+ expect(WAKE_RETRY_LAST_MS).toBe(CATCH_UP_MS);
+ expect(wakeRetry({ ...run(), wakeRetries: 3 }, RUN_COMPUTER_LINES.noWake, onceOnly, START + 25 * MINUTE)).toBe("The cloud desktop did not wake, even after more tries, so this run did not start.");
+ });
+});
diff --git a/server/routine-wake-retry.ts b/server/routine-wake-retry.ts
new file mode 100644
index 0000000000..f6be3f0e7f
--- /dev/null
+++ b/server/routine-wake-retry.ts
@@ -0,0 +1,94 @@
+// A scheduled run whose cloud computer did not wake never began: its turn did not start, so nothing of it can be
+// repeated by starting it again. A provider that stops answering for a few minutes would otherwise cost that whole
+// occurrence, so the same run row stays queued and asks for its computer again, a few times, a little later each time
+// (the run gate in cloud-computer-run-gate.ts wakes it afresh). The tries end as soon as one starts, after the last
+// of WAKE_RETRY_AFTER_MS, or once another try could still be under way when the routine's next occurrence is due: that
+// occurrence takes over. A try is never queued outside the hours or days an interval schedule allows. A routine whose
+// schedule has no next occurrence (a once-only one, an interval past its end) keeps its tries, up to the same count.
+// The row is saved queued with its `retryAt` and `wakeRetryUntil` like any other queued run, so a restart in between
+// keeps it, and a try still waiting at `wakeRetryUntil` (the server or the computer it runs on was asleep) is given up.
+// Only the plain "did not wake" reason is tried again: a computer that woke and did not answer was already waited for
+// and restarted, and the provider refusing the wake (a plan or start limit) answers the same way later.
+import { RUN_COMPUTER_LINES } from "../shared/cloud-computer-recovery.ts";
+import { runsOnce } from "../shared/limit-reset.ts";
+import { intervalAllowsOccurrence, isSameLocalDay } from "./routine-intervals.ts";
+import { codedLine } from "./routine-lines.ts";
+import { whenParams } from "./routine-recovery.ts";
+import { nextOccurrence } from "./routine-schedules.ts";
+import type { Routine, RoutineRun } from "./routines.ts";
+
+export interface WakeRetryMark {
+ /** How many times this run was queued again because its cloud computer did not wake. */
+ wakeRetries?: number;
+ /** A try still waiting at this time is given up: the routine's next occurrence, or for a schedule with none, the latest
+ * a missed occurrence is still started. */
+ wakeRetryUntil?: number;
+}
+
+/** When each try again comes, counted from the run's scheduled time: a try itself takes up to about four minutes
+ * (finding the computer, then the wake's own budget), so these leave a few minutes between tries. */
+export const WAKE_RETRY_AFTER_MS = [5, 12, 20].map((minutes) => minutes * 60_000);
+/** The least time between a try that did not wake and the next, for a run that started late. */
+export const WAKE_RETRY_GAP_MS = 2 * 60_000;
+/** The longest one try can still be waking its computer: a try is queued only if it ends before the next occurrence. */
+export const WAKE_TRY_MS = 5 * 60_000;
+/** For a schedule with no next occurrence: as late as the scheduler still starts a missed occurrence (CATCH_UP_MS in
+ * routine-catch-up.ts, which imports this module through routine-execution.ts, so the value is repeated here). */
+export const WAKE_RETRY_LAST_MS = 12 * 60 * 60_000;
+
+type Run = Pick<RoutineRun, "status" | "target" | "scheduledFor" | "retryAt" | "attention" | "error" | "startedAt" | "retried"> & WakeRetryMark
+ & Partial<Pick<RoutineRun, "attentionCode" | "attentionParams" | "errorCode" | "errorParams">>;
+type Scheduled = Pick<Routine, "enabled" | "nextRunAt" | "schedule">;
+
+/** The schedule itself has no occurrence after this run's: a once-only routine, or an interval past its end. A routine a
+ * person turned off is not this. */
+const lastOccurrence = (routine: Scheduled, run: Pick<RoutineRun, "scheduledFor">): boolean =>
+ runsOnce(routine.schedule) || (routine.schedule.type === "interval" && nextOccurrence(routine.schedule, run.scheduledFor) === null);
+
+/** An interval schedule with hours or weekdays starts a queued run only inside them, on its occurrence's day. */
+function allowedAt(routine: Scheduled, run: Pick<RoutineRun, "scheduledFor">, at: number): boolean {
+ const schedule = routine.schedule;
+ if (schedule.type !== "interval") return true;
+ const sameDay = schedule.weekdays === undefined && schedule.window === undefined ? true : isSameLocalDay(run.scheduledFor, at);
+ return sameDay && intervalAllowsOccurrence(schedule, at);
+}
+
+/** The run's tries are over: the line it fails with, its codes put on the run. */
+export function wakeGiveUp(run: Run, routine: Pick<Routine, "nextRunAt"> | undefined): string {
+ const line = codedLine("error", routine?.nextRunAt == null ? "routines.server.noWakeRetriedLast" : "routines.server.noWakeRetried");
+ Object.assign(run, line.codes, { attentionCode: undefined, attentionParams: undefined });
+ return line.text;
+}
+
+/** What a run whose start was refused for `reason` becomes. `routine` is its schedule's routine, only for a run its
+ * schedule started. true: queued again, with its `retryAt` and line. A string: the line to fail it with, its codes
+ * already on the run. */
+export function wakeRetry(run: Run, reason: string, routine: Scheduled | undefined, now: number): true | string {
+ if (reason !== RUN_COMPUTER_LINES.noWake || run.target !== "bot" || !routine || run.startedAt != null || run.retried !== undefined) return reason;
+ const tries = run.wakeRetries ?? 0;
+ const at = tries < WAKE_RETRY_AFTER_MS.length ? Math.max(run.scheduledFor + WAKE_RETRY_AFTER_MS[tries]!, now + WAKE_RETRY_GAP_MS) : null;
+ const next = routine.nextRunAt, last = next === null && lastOccurrence(routine, run);
+ const until = next !== null && routine.enabled ? next : last ? run.scheduledFor + WAKE_RETRY_LAST_MS : null;
+ if (at !== null && until !== null && at + WAKE_TRY_MS <= until && allowedAt(routine, run, at)) {
+ const line = codedLine("attention", "routines.server.wakeRetry", whenParams(at));
+ Object.assign(run, line.codes, { status: "queued", retryAt: at, wakeRetries: tries + 1, wakeRetryUntil: until, attention: line.text });
+ delete run.error;
+ return true;
+ }
+ return tries === 0 ? reason : wakeGiveUp(run, routine);
+}
+
+/** A run queued again by wakeRetry and not started since. A run that started and was queued again for another reason (a
+ * restart, a failure's one retry) keeps its own rules. */
+export const waitsToWakeAgain = (run: Pick<RoutineRun, "status" | "startedAt" | "retried"> & WakeRetryMark): boolean =>
+ run.status === "queued" && (run.wakeRetries ?? 0) > 0 && run.startedAt == null && run.retried === undefined;
+
+/** At each scheduler pass, before any routine comes due: a try still waiting at its `wakeRetryUntil` is given up, with
+ * the line to fail it with; null otherwise. */
+export function wakeRetryEnded(run: Run, now: number, routine: Pick<Routine, "nextRunAt"> | undefined): string | null {
+ return waitsToWakeAgain(run) && run.wakeRetryUntil !== undefined && now >= run.wakeRetryUntil ? wakeGiveUp(run, routine) : null;
+}
+
+/** `wakeRetries` as routines.json may hold it: a small whole count, or nothing. */
+export const loadWakeRetries = (value: unknown): number | undefined =>
+ Number.isSafeInteger(value) && (value as number) > 0 && (value as number) <= WAKE_RETRY_AFTER_MS.length ? value as number : undefined;
diff --git a/server/routines.ts b/server/routines.ts
index 8754cb50d5..a15942ca38 100644
--- a/server/routines.ts
+++ b/server/routines.ts
@@ -32,7 +32,7 @@ import { busyWait, markStop, RunClock, runOverLimit, SlowStops, withBoundedStops
import { noStartAlert, noStartSpacing, turnBackOn } from "./routine-no-start.ts"; import { afterRunSpacing, failureSpacingAlert, runSpacing } from "./routine-failure-spacing.ts"; import { blockingRun, recordSkip, type RoutineSkips } from "./routine-skips.ts";
import { restartRetryAt, startupDecision } from "./routine-restarts.ts"; import { routineHealthOf, type RoutineHealth } from "./routine-health.ts"; import { Occurrences, ROUTINE_TURN_GONE } from "./routine-occurrences.ts"; import type { Occurrence } from "./routine-ledger.ts";
import { CATCH_UP_MS, planOccurrence, settleRestored, staggered } from "./routine-catch-up.ts"; import { evictRuns } from "./routine-run-history.ts"; import { RunWatch } from "./routine-run-watch.ts"; import { scheduleSection, type ScheduleSection } from "./routine-schedule-report.ts";
-import { EVENT_RETRY_WINDOW_MS, MAX_EVENT_RECEIPTS, type EventRunReceipt } from "./routine-event-receipts.ts";
+import { EVENT_RETRY_WINDOW_MS, MAX_EVENT_RECEIPTS, type EventRunReceipt } from "./routine-event-receipts.ts"; import { waitsToWakeAgain, wakeGiveUp, wakeRetry, wakeRetryEnded, type WakeRetryMark } from "./routine-wake-retry.ts";
import { attachmentPathsOf, cloneAttachments } from "./routine-attachments.ts";
import { loadInstalledPackage, matchingRequestReceipt, rememberRequest } from "./routine-load.ts";
import { applyHolds, holdCauses, type AppliedHolds } from "./routine-holds.ts";
@@ -97,7 +97,7 @@ export interface RoutinePackageStamp {
parts: Record<RoutinePart, PartPair>;
}
-export interface RoutineRun extends RoutineLineCodes, RoutineOwnerMark {
+export interface RoutineRun extends RoutineLineCodes, RoutineOwnerMark, WakeRetryMark {
id: string;
routineId: string;
routineName: string;
@@ -1026,7 +1026,7 @@ export class RoutineManager {
for (const threadId of this.slowStops.sweep()) interruptRunTurns(this.runs.filter((run) => run.threadId === threadId).slice(-1), this.options);
this.ledger.beat(); for (const run of this.watch.lost(this.runs, now)) this.settleFailure(run, ROUTINE_TURN_GONE, {});
for (const run of this.runs) {
- const over = runOverLimit(run, this.clock, now);
+ const over = runOverLimit(run, this.clock, now), ended = wakeRetryEnded(run, now, this.routines.find((routine) => routine.id === run.routineId)); if (ended !== null) { this.failRun(run, ended); continue; }
if (over) await this.stopRun(Object.assign(run, over.codes), over.text, "limit-reached");
}
const isDue = (routine: Routine) => !this.closing && routine.enabled && this.targetState(routine) !== "missing" && (!routine.checks
@@ -1106,7 +1106,7 @@ export class RoutineManager {
const mayDispatch = intervalAllowsOccurrence(definition.schedule, now) &&
(!requiresCurrentDayOccurrence || (latest !== null && isSameLocalDay(latest, now)));
if (!mayDispatch) {
- if (nextOccurrence(definition.schedule, now) === null) {
+ if (waitsToWakeAgain(run)) this.failRun(run, wakeGiveUp(run, definition)); else if (nextOccurrence(definition.schedule, now) === null) {
this.failRun(run, "The routine ended before this scheduled run could start", "missed");
}
continue;
@@ -1141,7 +1141,7 @@ export class RoutineManager {
if (state === "missing") { this.failRun(run, this.missingTargetMessage(run.target)); continue; }
const paused = run.target === "room-goal" ? null : this.options.pausedText?.(run.botId);
if (!this.ledger.ready(run)) continue; if (this.ledger.startedElsewhere(run)) { const line = codedLine("error", "routines.server.duplicate"); Object.assign(run, line.codes); void this.cancelRun(run.id, line.text); continue; }
- if (paused) { if (triggerSource !== "manual" && this.options.held?.(run.botId)) void this.cancelRun(run.id, paused); else this.failRun(run, paused); continue; } const startedBy = run.byPerson ? "manual" : triggerSource, capped = this.options.capText?.(run.botId, startedBy); if (capped) { if (startedBy === "manual") this.failRun(run, capped); else void this.cancelRun(run.id, capped); continue; } const gated = triggerSource === "manual" ? false : this.gate.hold(run); if (gated === true) { if (this.options.preparing && run.attention !== this.options.preparing) { run.attention = this.options.preparing; this.emitRun(run); } continue; } if (gated) { this.failRun(run, gated); continue; }
+ if (paused) { if (triggerSource !== "manual" && this.options.held?.(run.botId)) void this.cancelRun(run.id, paused); else this.failRun(run, paused); continue; } const startedBy = run.byPerson ? "manual" : triggerSource, capped = this.options.capText?.(run.botId, startedBy); if (capped) { if (startedBy === "manual") this.failRun(run, capped); else void this.cancelRun(run.id, capped); continue; } const gated = triggerSource === "manual" ? false : this.gate.hold(run); if (gated === true) { if (this.options.preparing && run.attention !== this.options.preparing) { run.attention = this.options.preparing; this.emitRun(run); } continue; } if (gated) { const again = wakeRetry(run, gated, definition, this.now()); if (again === true) { this.saveLater(); this.emitRun(run); } else this.failRun(run, again); continue; }
const startedAt = this.now();
const suffix = ` · ${new Date(startedAt).toLocaleString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })}`;
const title = `${run.routineName.slice(0, 80 - suffix.length).trimEnd()}${suffix}`;
diff --git a/shared/cloud-computer-recovery.ts b/shared/cloud-computer-recovery.ts
index b15fc04857..8cd2871bd1 100644
--- a/shared/cloud-computer-recovery.ts
+++ b/shared/cloud-computer-recovery.ts
@@ -106,10 +106,12 @@ export const CLOUD_COMPUTER_EXEC_ANSWER_LOST =
"The cloud computer started this command, but its answer was lost on the way back, so it may still be running or may have finished. It was not "
+ "started a second time. Do not run it again blindly: check first, for example with exec `pgrep -af '<part of the command>'` or by looking at the files it writes.";
-/** Why an unattended run did not start because of its cloud computer, and the note on one that finished unsure of it. */
+/** Why an unattended run did not start because of its cloud computer, and the note on one that finished unsure of it. A
+ * scheduled run that met `noWake` is tried again a few times first (server/routine-wake-retry.ts). */
export const RUN_COMPUTER_LINES = {
waking: "Waiting for its cloud computer to wake and answer",
noWake: "The cloud computer did not wake, so this run did not start. The next scheduled run tries again.",
+ wakeRefused: "The cloud computer did not wake because its provider refused to start it, so this run did not start. The next scheduled run tries again.",
noAnswer: "The cloud computer did not answer in time, so this run did not start. The next scheduled run tries again.",
afterRestart: "The cloud computer did not answer after a restart, so this run did not start. The next scheduled run tries again; Restart computer or Replace computer in the computer panel fixes it sooner.",
personBusy: "The cloud computer is not answering, and it was not restarted because someone is using it, so this run did not start. The next scheduled run tries again.",
diff --git a/src/locales/en.json b/src/locales/en.json
index e731bc0afc..b2332bf5fb 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -10157,6 +10157,9 @@
"routines.server.restored": "Not run again: this schedule was restored from a backup made before this run had its turn",
"routines.server.restoredMany": "Not run again: {count} scheduled runs from before this schedule was restored from a backup",
"routines.server.duplicate": "Not started: this scheduled run had already started once",
+ "routines.server.wakeRetry": "The cloud desktop did not wake, so this run has not started yet. It tries again at {resets}",
+ "routines.server.noWakeRetried": "The cloud desktop did not wake, even after more tries, so this run did not start. The next scheduled run tries again.",
+ "routines.server.noWakeRetriedLast": "The cloud desktop did not wake, even after more tries, so this run did not start.",
"routines.server.capSkippedOne": "Skipped: {why} ({amount}) is reached. Runs start again after {resets}",
"routines.server.capSkippedMany": "Skipped {count} runs: {why} ({amount}) is reached. Runs start again after {resets}",
"routines.server.part.capServerDay": "the daily usage cap for all bots",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 3ad230d5db..49f3030e93 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -10068,6 +10068,9 @@
"routines.server.restored": "Não rodou de novo: este agendamento foi restaurado de um backup feito antes de esta execução ter a vez dela",
"routines.server.restoredMany": "Não rodaram de novo: {count} execuções agendadas de antes de este agendamento ser restaurado de um backup",
"routines.server.duplicate": "Não iniciou: esta execução agendada já tinha iniciado uma vez",
+ "routines.server.wakeRetry": "O desktop na nuvem não acordou, então esta execução ainda não começou. Ela tenta de novo em {resets}",
+ "routines.server.noWakeRetried": "O desktop na nuvem não acordou, nem depois de novas tentativas, então esta execução não começou. A próxima execução agendada tenta de novo.",
+ "routines.server.noWakeRetriedLast": "O desktop na nuvem não acordou, nem depois de novas tentativas, então esta execução não começou.",
"routines.server.capSkippedOne": "Pulada: {why} ({amount}) foi atingido. As execuções voltam a começar depois de {resets}",
"routines.server.capSkippedMany": "{count} execuções puladas: {why} ({amount}) foi atingido. As execuções voltam a começar depois de {resets}",
"routines.server.part.capServerDay": "o limite diário de uso de todos os bots",