Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ScheduledTaskService.test.ts

350 lines14.6 KB

1import * as Scheduler from "../scheduling/Scheduler.ts";
2import * as NodeUtil from "node:util";
3​
4import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
5import { assert, it } from "@effect/vitest";
6import { ScheduledTaskError } from "@t3tools/contracts";
7import * as DateTime from "effect/DateTime";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Logger from "effect/Logger";
11import * as SqlClient from "effect/unstable/sql/SqlClient";
12​
13import * as Deferred from "effect/Deferred";
14import * as Ref from "effect/Ref";
15import * as Schema from "effect/Schema";
16import * as TestClock from "effect/testing/TestClock";
17​
18import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
19import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
20import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
21import * as ScheduledTaskService from "./ScheduledTaskService.ts";
22​
23const isScheduledTaskError = Schema.is(ScheduledTaskError);
24​
25const insertRow = (
26 sql: SqlClient.SqlClient,
27 row: {
28 id: string | null;
29 next: string | null;
30 enabled: number;
31 status: string;
32 scheduleJson?: string;
33 prompt?: string;
34 },
35 now: string,
36) =>
37 sql`INSERT INTO scheduled_tasks ${sql.insert({
38 task_id: row.id,
39 title: "task",
40 prompt: row.prompt ?? "Run task",
41 enabled: row.enabled,
42 schedule_json: row.scheduleJson ?? '{"type":"interval","everyMs":60000}',
43 project_id: "project:test",
44 thread_id: null,
45 workspace_strategy_json: '{"type":"root"}',
46 model_selection_json: '{"instanceId":"codex","model":"gpt-5"}',
47 runtime_mode: "full-access",
48 interaction_mode: "default",
49 created_by: "user",
50 creation_source: "web",
51 created_at: now,
52 updated_at: now,
53 next_run_at: row.next,
54 last_run_at: null,
55 last_run_status: row.status,
56 last_run_error: null,
57 run_count: 0,
58 })}`;
59​
60it.effect("loads only due tasks and skips corrupt due rows without decoding settled tasks", () =>
61 Effect.gen(function* () {
62 const sql = yield* SqlClient.SqlClient;
63 const now = "2026-09-09T12:00:00.000Z";
64 const secret = "PROMPT-SECRET-DO-NOT-LOG";
65 const credential = "CREDENTIAL-SECRET-DO-NOT-LOG";
66 for (const row of [
67 { id: "due-now", next: now, enabled: 1, status: "never" },
68 // Ids that cannot decode as ScheduledTaskId — empty, whitespace-only,
69 // and NULL (SQLite's TEXT primary key admits it).
70 { id: "", next: now, enabled: 1, status: "never" },
71 { id: " ", next: now, enabled: 1, status: "never" },
72 { id: null, next: now, enabled: 1, status: "never" },
73 {
74 id: "due-earlier",
75 next: "2026-09-09T11:00:00.000Z",
76 enabled: 1,
77 status: "failed",
78 },
79 // An unparseable next_run_at sorts before every real timestamp, so it
80 // passes the due filter and would defect the poll if not skipped.
81 { id: "due-bad-date", next: "", enabled: 1, status: "never" },
82 {
83 id: "due-corrupt",
84 next: now,
85 enabled: 1,
86 status: "never",
87 scheduleJson: "broken",
88 },
89 {
90 id: "due-cred",
91 next: now,
92 enabled: 1,
93 status: "never",
94 scheduleJson: `{"type":"interval","everyMs":"${credential}"}`,
95 },
96 { id: "disabled", next: now, enabled: 0, status: "never", scheduleJson: "broken" },
97 {
98 id: "future",
99 next: "2026-09-09T12:00:00.001Z",
100 enabled: 1,
101 status: "never",
102 scheduleJson: "broken",
103 },
104 {
105 id: "unscheduled",
106 next: null,
107 enabled: 1,
108 status: "never",
109 scheduleJson: "broken",
110 },
111 { id: "running", next: now, enabled: 1, status: "running", scheduleJson: "broken" },
112 ]) {
113 yield* insertRow(sql, { ...row, prompt: secret }, now);
114 }
115 const warnings: unknown[] = [];
116 const tasks = yield* ScheduledTaskService.listDueTasks(DateTime.makeUnsafe(now)).pipe(
117 Effect.provide(
118 Logger.layer([
119 Logger.make(({ message }) => {
120 warnings.push(message);
121 }),
122 ]),
123 ),
124 );
125 assert.deepEqual(
126 tasks.map((task) => task.id),
127 ["due-earlier", "due-now"],
128 );
129 // Corrupt rows sort between the healthy due rows; each is skipped with a
130 // warning instead of stopping the poll.
131 assert.equal(warnings.length, 6);
132 const annotations = warnings.map(
133 (warning) => (warning as ReadonlyArray<unknown>)[1] as Record<string, unknown>,
134 );
135 assert.deepEqual(
136 annotations.map((annotation) => annotation.taskId),
137 ["due-bad-date", null, "", " ", "due-corrupt", "due-cred"],
138 );
139 // The typed diagnostic carries a taskId only when the stored id itself
140 // decodes; the corrupt-id rows are still skipped, not fatal.
141 const causes = annotations.map((annotation) => annotation.cause);
142 assert.deepEqual(
143 causes.map((cause) => (isScheduledTaskError(cause) ? cause.taskId : undefined)),
144 [undefined, undefined, undefined, undefined, "due-corrupt", "due-cred"],
145 );
146 for (const cause of causes) {
147 if (cause !== undefined) assert.isTrue(isScheduledTaskError(cause));
148 }
149 const rendered = NodeUtil.inspect(annotations, { depth: null });
150 assert.isFalse(rendered.includes(secret));
151 assert.isFalse(rendered.includes(credential));
152 const running = yield* sql<{
153 last_run_status: string;
154 }>`SELECT last_run_status FROM scheduled_tasks WHERE task_id = 'running'`;
155 assert.equal(running[0]?.last_run_status, "running");
156 }).pipe(Effect.provide(SqlitePersistenceMemory)),
157);
158​
159it.effect(
160 "releases interrupted runs on startup and still executes due tasks, skipping corrupt rows",
161 () =>
162 Effect.gen(function* () {
163 const sql = yield* SqlClient.SqlClient;
164 const now = "2026-09-09T12:00:00.000Z";
165 // An interval that decodes but overflows the representable DateTime
166 // range must not defect recovery or the poll.
167 const hugeInterval = '{"type":"interval","everyMs":9000000000000000}';
168 for (const row of [
169 { id: "stuck-valid", next: now, status: "running" },
170 { id: "stuck-corrupt", next: now, status: "running", scheduleJson: "broken" },
171 { id: "stuck-huge", next: now, status: "running", scheduleJson: hugeInterval },
172 { id: null, next: now, status: "running" },
173 // A due row with an unparseable next_run_at must not defect the poll
174 // before the healthy due tasks run.
175 { id: "due-bad-date", next: "", status: "never" },
176 { id: "due-healthy", next: now, status: "never" },
177 { id: "due-huge", next: now, status: "never", scheduleJson: hugeInterval },
178 { id: "due-second", next: now, status: "never" },
179 { id: "due-third", next: now, status: "never" },
180 ]) {
181 yield* insertRow(sql, { ...row, enabled: 1 }, now);
182 }
183​
184 // it.effect freezes the clock; pin it just past the seeded due time so
185 // the poll sees the rows as due.
186 yield* TestClock.setTime(Date.parse(now) + 1_000);
187 // Runs are dispatched serially, so the fourth dispatch can only happen
188 // after the first three runs' completions were recorded — a drain
189 // receipt for the poll fiber, never a sleep. The fourth launch is held
190 // open so its in-flight state is observed deterministically.
191 const dispatched = yield* Ref.make(0);
192 const lastDispatched = yield* Deferred.make<void>();
193 const releaseLast = yield* Deferred.make<void>();
194 yield* Effect.scoped(
195 Effect.gen(function* () {
196 yield* Layer.build(
197 Layer.provideMerge(
198 ScheduledTaskService.layer,
199 Layer.mergeAll(
200 Layer.mock(ThreadLaunchService.ThreadLaunchService)({
201 launch: () =>
202 Ref.updateAndGet(dispatched, (n) => n + 1).pipe(
203 Effect.andThen((n) =>
204 n === 4
205 ? Deferred.succeed(lastDispatched, undefined).pipe(
206 Effect.andThen(Deferred.await(releaseLast)),
207 )
208 : Effect.void,
209 ),
210 Effect.andThen(Effect.die(new Error("test launch failure"))),
211 ),
212 }),
213 Layer.mock(ThreadManagementService.ThreadManagementService)({}),
214 NodeCrypto.layer,
215 Scheduler.layer,
216 ),
217 ),
218 );
219 // The poll loop delays before its first pass, so the frozen test
220 // clock must advance once to trigger it.
221 yield* TestClock.adjust("6 seconds");
222 yield* Deferred.await(lastDispatched);
223 // The fourth dispatch implies the first three completions landed;
224 // markRunning commits before dispatch, so due-third is 'running'.
225 const inflight = yield* sql<{
226 last_run_status: string;
227 }>`SELECT last_run_status FROM scheduled_tasks WHERE task_id = 'due-third'`;
228 assert.equal(inflight[0]?.last_run_status, "running");
229 yield* Deferred.succeed(releaseLast, undefined);
230 }),
231 );
232​
233 const rows = yield* sql<{
234 task_id: string | null;
235 last_run_status: string;
236 last_run_error: string | null;
237 next_run_at: string | null;
238 run_count: number;
239 }>`SELECT task_id, last_run_status, last_run_error, next_run_at, run_count
240 FROM scheduled_tasks ORDER BY task_id`;
241 const byId = new Map(rows.map((row) => [row.task_id, row]));
242 assert.equal(rows.length, 9);
243 // The decodable stuck run is rescheduled for its next occurrence; the
244 // undecodable and unrepresentable rows are released without a next run.
245 // A NULL id must still match its own row — `= NULL` never does.
246 assert.equal(byId.get("stuck-valid")?.last_run_status, "failed");
247 assert.isNotNull(byId.get("stuck-valid")?.next_run_at);
248 assert.equal(byId.get("stuck-corrupt")?.last_run_status, "failed");
249 assert.equal(byId.get(null)?.last_run_status, "failed");
250 const stuckHuge = byId.get("stuck-huge");
251 assert.equal(stuckHuge?.last_run_status, "failed");
252 assert.isNull(stuckHuge?.next_run_at);
253 for (const id of ["stuck-valid", "stuck-corrupt", "stuck-huge", null]) {
254 const row = byId.get(id);
255 assert.equal(row?.last_run_error, "Run was interrupted by a server restart.");
256 assert.equal(row?.run_count, 1);
257 }
258 // The healthy due tasks were dispatched and recorded failed runs; the
259 // corrupt due row was skipped without running.
260 for (const id of ["due-healthy", "due-huge", "due-second"]) {
261 const row = byId.get(id);
262 assert.equal(row?.last_run_status, "failed");
263 assert.isTrue(row?.last_run_error?.includes("test launch failure") === true);
264 assert.equal(row?.run_count, 1);
265 }
266 assert.isNull(byId.get("due-huge")?.next_run_at);
267 assert.equal(byId.get("due-bad-date")?.last_run_status, "never");
268 assert.equal(byId.get("due-bad-date")?.run_count, 0);
269 }).pipe(Effect.provide(SqlitePersistenceMemory)),
270);
271​
272it.effect(
273 "treats a next_run_at corrupted before the dispatch re-read as not due instead of defecting the poll",
274 () =>
275 Effect.gen(function* () {
276 const sql = yield* SqlClient.SqlClient;
277 const now = "2026-09-09T12:00:00.000Z";
278 // Equal next_run_at means dispatch order follows task_id order.
279 for (const row of [
280 { id: "run-a", next: now, status: "never" },
281 { id: "run-b-victim", next: now, status: "never" },
282 { id: "run-c", next: now, status: "never" },
283 { id: "run-d", next: now, status: "never" },
284 ]) {
285 yield* insertRow(sql, { ...row, enabled: 1 }, now);
286 }
287 yield* TestClock.setTime(Date.parse(now) + 1_000);
288 const dispatched = yield* Ref.make(0);
289 const lastDispatched = yield* Deferred.make<void>();
290 const releaseLast = yield* Deferred.make<void>();
291 yield* Effect.scoped(
292 Effect.gen(function* () {
293 yield* Layer.build(
294 Layer.provideMerge(
295 ScheduledTaskService.layer,
296 Layer.mergeAll(
297 Layer.mock(ThreadLaunchService.ThreadLaunchService)({
298 launch: () =>
299 Ref.updateAndGet(dispatched, (n) => n + 1).pipe(
300 // A concurrent writer (the CLI shares the SQLite file)
301 // corrupts the next row between the poll read and its
302 // dispatch re-read. Serial dispatch makes the
303 // interleaving deterministic.
304 Effect.andThen((n) =>
305 n === 1
306 ? sql`UPDATE scheduled_tasks
307 SET next_run_at = ''
308 WHERE task_id = 'run-b-victim'`.pipe(Effect.asVoid, Effect.orDie)
309 : n === 3
310 ? Deferred.succeed(lastDispatched, undefined).pipe(
311 Effect.andThen(Deferred.await(releaseLast)),
312 )
313 : Effect.void,
314 ),
315 Effect.andThen(Effect.die(new Error("test launch failure"))),
316 ),
317 }),
318 Layer.mock(ThreadManagementService.ThreadManagementService)({}),
319 NodeCrypto.layer,
320 Scheduler.layer,
321 ),
322 ),
323 );
324 yield* TestClock.adjust("6 seconds");
325 // The third dispatch (run-d) can only happen after the victim's
326 // re-read was handled — a receipt that the poll fiber survived.
327 yield* Deferred.await(lastDispatched);
328 assert.equal(yield* Ref.get(dispatched), 3);
329 const rows = yield* sql<{
330 task_id: string;
331 last_run_status: string;
332 next_run_at: string | null;
333 run_count: number;
334 }>`SELECT task_id, last_run_status, next_run_at, run_count
335 FROM scheduled_tasks ORDER BY task_id`;
336 const byId = new Map(rows.map((row) => [row.task_id, row]));
337 const victim = byId.get("run-b-victim");
338 assert.equal(victim?.last_run_status, "never");
339 assert.equal(victim?.run_count, 0);
340 assert.equal(victim?.next_run_at, "");
341 for (const id of ["run-a", "run-c"]) {
342 const row = byId.get(id);
343 assert.equal(row?.last_run_status, "failed");
344 assert.equal(row?.run_count, 1);
345 }
346 yield* Deferred.succeed(releaseLast, undefined);
347 }),
348 );
349 }).pipe(Effect.provide(SqlitePersistenceMemory)),
350);