Skip to content

Commit e01004f

Browse files
t3dotggclaude
andcommitted
fix(scheduler): one-time runs survive save races, restarts and daylight saving edges
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 9a50907 commit e01004f

10 files changed

Lines changed: 161 additions & 28 deletions

File tree

‎apps/server/src/scheduledTasks/Schedule.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@ describe("scheduled task schedule calculation", () => {
2727
});
2828

2929
it("compares schedules structurally", () => {
30+
expect(
31+
isSameSchedule(
32+
{ type: "once", runAt: "2026-11-01T03:00:00-05:00" },
33+
{ type: "once", runAt: "2026-11-01T08:00:00.000Z" },
34+
),
35+
).toBe(true);
3036
expect(
3137
isSameSchedule({ type: "interval", everyMs: 60_000 }, { type: "interval", everyMs: 60_000 }),
3238
).toBe(true);

‎apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { ScheduledTaskUpsertInput } from "@t3tools/contracts";
44
import * as Effect from "effect/Effect";
55
import * as Layer from "effect/Layer";
66
import * as Schema from "effect/Schema";
7+
import * as SqlClient from "effect/sql/SqlClient";
78
import * as TestClock from "effect/testing/TestClock";
89
import { afterEach, vi } from "vite-plus/test";
910

@@ -179,3 +180,69 @@ it.effect("runs a one-time schedule once and rejects past times", () =>
179180
Effect.provide(SqlitePersistence.layerMemory),
180181
),
181182
);
183+
184+
const onceInput = {
185+
...input,
186+
commandId: "once-race",
187+
schedule: { type: "once", runAt: "2026-11-01T08:00:00Z" },
188+
};
189+
190+
it.effect("keeps a one-time run used up when a run completes during a title save", () =>
191+
Effect.gen(function* () {
192+
yield* TestClock.setTime(Date.parse("2026-11-01T07:00:00.000Z"));
193+
// The project check runs between the save's read and write, so it stands in for a
194+
// scheduled run that completes in that gap.
195+
const completeRunMidSave = Layer.unwrap(
196+
Effect.gen(function* () {
197+
const sql = yield* SqlClient.SqlClient;
198+
return Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
199+
namedProjectsRoot: "/projects",
200+
isScratchProject: () =>
201+
sql`UPDATE scheduled_tasks SET next_run_at = NULL`.pipe(Effect.as(false), Effect.orDie),
202+
});
203+
}),
204+
);
205+
const layer = ScheduledTaskService.layer.pipe(
206+
Layer.provide(Layer.merge(dependencies, completeRunMidSave)),
207+
);
208+
yield* Effect.gen(function* () {
209+
const service = yield* ScheduledTaskService.ScheduledTaskService;
210+
const worktree = { type: "worktree", baseRef: "main" };
211+
const created = yield* service.upsert(
212+
yield* decodeInput({ ...onceInput, workspaceStrategy: { type: "root" } }),
213+
);
214+
expect(created.task.nextRunAt).toBe("2026-11-01T08:00:00.000Z");
215+
const renamed = yield* service.upsert(
216+
yield* decodeInput({ ...onceInput, workspaceStrategy: worktree, title: "Renamed" }),
217+
);
218+
expect(renamed.task.nextRunAt).toBeNull();
219+
}).pipe(Effect.provide(layer));
220+
}).pipe(
221+
Effect.provideService(ServerActivation, Effect.never),
222+
Effect.provide(SqlitePersistence.layerMemory),
223+
),
224+
);
225+
226+
it.effect("keeps a one-time run after a restart interrupts an earlier manual run", () =>
227+
Effect.gen(function* () {
228+
yield* TestClock.setTime(Date.parse("2026-11-01T07:59:00.000Z"));
229+
const sql = yield* SqlClient.SqlClient;
230+
const created = yield* Effect.gen(function* () {
231+
const service = yield* ScheduledTaskService.ScheduledTaskService;
232+
return yield* service.upsert(yield* decodeInput(onceInput));
233+
}).pipe(Effect.provide(serviceLayer));
234+
yield* sql`UPDATE scheduled_tasks SET last_run_status = 'running', last_run_at = '2026-11-01T07:59:00.000Z'`;
235+
236+
yield* TestClock.setTime(Date.parse("2026-11-01T08:05:00.000Z"));
237+
yield* Effect.gen(function* () {
238+
const service = yield* ScheduledTaskService.ScheduledTaskService;
239+
const [task] = (yield* service.list()).tasks;
240+
expect(task?.id).toBe(created.task.id);
241+
expect(task?.lastRunStatus).toBe("failed");
242+
expect(task?.nextRunAt).toBe("2026-11-01T08:00:00.000Z");
243+
}).pipe(Effect.provide(serviceLayer));
244+
}).pipe(
245+
Effect.provideService(ServerActivation, Effect.never),
246+
Effect.provide(SqlitePersistence.layerMemory),
247+
),
248+
);

‎apps/server/src/scheduledTasks/ScheduledTaskService.ts‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,24 @@ function nextRunAt(
298298
}
299299
}
300300

301+
/**
302+
* Next run after an interrupted run. A one-time task counts from the run's start
303+
* (`lastRunAt`), so a manual run that began before its time does not use it up.
304+
*/
305+
function nextRunAfterRun(
306+
task: Pick<ScheduledTask, "enabled" | "schedule" | "lastRunAt">,
307+
now: DateTime.DateTime,
308+
): string | null {
309+
const startedAt =
310+
task.schedule.type === "once" && task.lastRunAt !== null
311+
? DateTime.make(task.lastRunAt)
312+
: Option.none();
313+
return nextRunAt(
314+
task,
315+
Option.getOrElse(startedAt, () => now),
316+
);
317+
}
318+
301319
/** An enabled one-time task with a past time would never run, so saving it is an error. */
302320
function requireFutureOnce(
303321
task: Pick<ScheduledTask, "enabled" | "schedule">,
@@ -553,6 +571,7 @@ export const layer = Layer.effect(
553571
const saveTask = (
554572
task: ScheduledTask,
555573
requireExisting: boolean,
574+
keepNextRun: boolean,
556575
webhook: {
557576
readonly token: string | null;
558577
readonly secret: string | null;
@@ -623,7 +642,11 @@ export const layer = Layer.effect(
623642
interaction_mode = excluded.interaction_mode,
624643
creation_source = excluded.creation_source,
625644
updated_at = excluded.updated_at,
626-
next_run_at = excluded.next_run_at,
645+
-- A run that completes while this save is in flight already moved next_run_at.
646+
next_run_at = CASE
647+
WHEN ${keepNextRun ? 1 : 0} = 1 THEN scheduled_tasks.next_run_at
648+
ELSE excluded.next_run_at
649+
END,
627650
-- Only rotate changes a live token, so a save racing a rotation
628651
-- cannot bring the old URL back.
629652
webhook_token = CASE
@@ -715,7 +738,7 @@ export const layer = Layer.effect(
715738
UPDATE scheduled_tasks
716739
SET last_run_status = 'failed',
717740
last_run_error = ${message},
718-
next_run_at = ${nextRunAt(source, now)},
741+
next_run_at = ${nextRunAfterRun(source, now)},
719742
updated_at = ${iso(now)},
720743
run_count = run_count + CASE WHEN EXISTS (
721744
SELECT 1 FROM scheduled_task_webhook_pending
@@ -1054,7 +1077,7 @@ export const layer = Layer.effect(
10541077
UPDATE scheduled_tasks
10551078
SET last_run_status = 'failed',
10561079
last_run_error = 'Run was interrupted by a server restart.',
1057-
next_run_at = ${nextRunAt(decoded.success, now)},
1080+
next_run_at = ${nextRunAfterRun(decoded.success, now)},
10581081
updated_at = ${iso(now)},
10591082
run_count = run_count + CASE WHEN EXISTS (
10601083
SELECT 1 FROM scheduled_task_webhook_pending
@@ -1239,7 +1262,7 @@ export const layer = Layer.effect(
12391262
lastRunError: existingTask?.lastRunError ?? null,
12401263
runCount: existingTask?.runCount ?? 0,
12411264
};
1242-
yield* saveTask(task, input.requireExisting === true, webhook);
1265+
yield* saveTask(task, input.requireExisting === true, scheduleUnchanged, webhook);
12431266
yield* notifyChanged;
12441267
return { task: (yield* findTask(id)) ?? task };
12451268
});

‎apps/web/src/components/settings/ScheduledTasksSettings.tsx‎

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1596,20 +1596,27 @@ function ScheduledTaskEditorForm({
15961596
mode === "interval" ||
15971597
mode === "webhook"
15981598
)
1599-
setDraft((current) => ({
1600-
...current,
1601-
scheduleMode: mode,
1602-
runAt:
1599+
setDraft((current) => {
1600+
const suggested =
16031601
mode === "once" && !current.runAt
1604-
? toDateTimeLocalValue(
1605-
new Date(Math.ceil(Date.now() / 3_600_000) * 3_600_000),
1606-
)
1607-
: current.runAt,
1608-
prompt:
1609-
mode === "webhook" && !current.prompt.trim()
1610-
? DEFAULT_WEBHOOK_PROMPT
1611-
: current.prompt,
1612-
}));
1602+
? new Date(Math.ceil(Date.now() / 3_600_000) * 3_600_000)
1603+
: null;
1604+
return {
1605+
...current,
1606+
scheduleMode: mode,
1607+
// Keep the instant too, so an hour that repeats when clocks go back stays exact.
1608+
...(suggested === null
1609+
? {}
1610+
: {
1611+
runAt: toDateTimeLocalValue(suggested),
1612+
savedRunAt: suggested.toISOString(),
1613+
}),
1614+
prompt:
1615+
mode === "webhook" && !current.prompt.trim()
1616+
? DEFAULT_WEBHOOK_PROMPT
1617+
: current.prompt,
1618+
};
1619+
});
16131620
}}
16141621
>
16151622
<Toggle value="fixed">At a time</Toggle>

‎apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
ScheduledTaskId,
88
type ScheduledTask,
99
} from "@t3tools/contracts";
10-
import { describe, expect, it } from "vite-plus/test";
10+
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
1111

1212
import type {
1313
SidebarProjectGroupMember,
@@ -171,6 +171,8 @@ describe("editing scheduled task branch settings", () => {
171171
});
172172

173173
describe("one-time scheduled tasks", () => {
174+
afterEach(() => vi.unstubAllEnvs());
175+
174176
it("round-trips the run time through the local date-time input", () => {
175177
const runAt = "2026-11-03T17:00:42.000Z";
176178
const draft = taskToDraft({ ...legacyTask, schedule: { type: "once", runAt } });
@@ -180,6 +182,25 @@ describe("one-time scheduled tasks", () => {
180182
expect(moved).toEqual({ type: "once", runAt: new Date("2026-11-04T09:30").toISOString() });
181183
expect(scheduleFromDraft({ ...draft, runAt: "" })).toBeNull();
182184
});
185+
186+
it("rejects a skipped daylight saving time and keeps a repeated hour exact", () => {
187+
vi.stubEnv("TZ", "America/Los_Angeles");
188+
const draft = taskToDraft({
189+
...legacyTask,
190+
schedule: { type: "once", runAt: "2027-03-14T18:00:00.000Z" },
191+
});
192+
expect(scheduleFromDraft({ ...draft, runAt: "2027-03-14T02:30" })).toBeNull();
193+
// 01:00 happens twice on 2026-11-01; the second one is 09:00 UTC.
194+
const repeated = {
195+
...draft,
196+
runAt: "2026-11-01T01:00",
197+
savedRunAt: "2026-11-01T09:00:00.000Z",
198+
};
199+
expect(scheduleFromDraft(repeated)).toEqual({
200+
type: "once",
201+
runAt: "2026-11-01T09:00:00.000Z",
202+
});
203+
});
183204
});
184205

185206
describe("webhook scheduled tasks", () => {

‎apps/web/src/components/settings/scheduledTasksSettings.logic.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -107,10 +107,17 @@ export function toDateTimeLocalValue(date: Date): string {
107107
}
108108

109109
export function scheduleDraftErrors(draft: DraftState) {
110-
if (draft.scheduleMode === "once")
111-
return Number.isNaN(new Date(draft.runAt).getTime())
112-
? [{ title: "Invalid run time", description: "Pick a date and time." }]
113-
: [];
110+
if (draft.scheduleMode === "once") {
111+
const runAt = new Date(draft.runAt);
112+
if (Number.isNaN(runAt.getTime()))
113+
return [{ title: "Invalid run time", description: "Pick a date and time." }];
114+
// A time skipped by a daylight saving change parses to a different clock time.
115+
if (toDateTimeLocalValue(runAt) !== draft.runAt)
116+
return [
117+
{ title: "Invalid run time", description: "That time does not exist in your time zone." },
118+
];
119+
return [];
120+
}
114121
if (draft.scheduleMode !== "webhook") return [];
115122
if (parseMaxDeliveryAge(draft.maxDeliveryAgeMinutes) === undefined)
116123
return [

0 commit comments

Comments
 (0)