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

ScheduledTaskService.test.ts

323 lines12.7 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/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 * as SecretRequests from "../secrets/SecretRequests.ts";
21import * as SqlitePersistence from "../persistence/Sqlite.ts";
22import * as ScheduledTaskService from "./ScheduledTaskService.ts";
23​
24const isScheduledTaskError = Schema.is(ScheduledTaskError);
25​
26const insertRow = (
27 sql: SqlClient.SqlClient,
28 row: {
29 id: string | null;
30 next: string | null;
31 enabled: number;
32 status: string;
33 scheduleJson?: string;
34 prompt?: string;
35 },
36 now: string,
37) =>
38 sql`INSERT INTO scheduled_tasks ${sql.insert({
39 task_id: row.id,
40 title: "task",
41 prompt: row.prompt ?? "Run task",
42 enabled: row.enabled,
43 schedule_json: row.scheduleJson ?? '{"type":"interval","everyMs":60000}',
44 project_id: "project:test",
45 thread_id: null,
46 workspace_strategy_json: '{"type":"root"}',
47 model_selection_json: '{"instanceId":"codex","model":"gpt-5"}',
48 runtime_mode: "full-access",
49 interaction_mode: "default",
50 created_by: "user",
51 creation_source: "web",
52 created_at: now,
53 updated_at: now,
54 next_run_at: row.next,
55 last_run_at: null,
56 last_run_status: row.status,
57 last_run_error: null,
58 run_count: 0,
59 })}`;
60​
61it.effect("loads only due tasks and skips corrupt due rows without decoding settled tasks", () =>
62 Effect.gen(function* () {
63 const sql = yield* SqlClient.SqlClient;
64 const now = "2026-09-09T12:00:00.000Z";
65 const secret = "PROMPT-SECRET-DO-NOT-LOG";
66 const credential = "CREDENTIAL-SECRET-DO-NOT-LOG";
67 for (const row of [
68 { id: "due-now", next: now, enabled: 1, status: "never" },
69 { id: "", next: now, enabled: 1, status: "never" },
70 { id: " ", next: now, enabled: 1, status: "never" },
71 { id: null, next: now, enabled: 1, status: "never" },
72 {
73 id: "due-earlier",
74 next: "2026-09-09T11:00:00.000Z",
75 enabled: 1,
76 status: "failed",
77 },
78 { id: "due-bad-date", next: "", enabled: 1, status: "never" },
79 {
80 id: "due-corrupt",
81 next: now,
82 enabled: 1,
83 status: "never",
84 scheduleJson: "broken",
85 },
86 {
87 id: "due-cred",
88 next: now,
89 enabled: 1,
90 status: "never",
91 scheduleJson: `{"type":"interval","everyMs":"${credential}"}`,
92 },
93 { id: "disabled", next: now, enabled: 0, status: "never", scheduleJson: "broken" },
94 {
95 id: "future",
96 next: "2026-09-09T12:00:00.001Z",
97 enabled: 1,
98 status: "never",
99 scheduleJson: "broken",
100 },
101 {
102 id: "unscheduled",
103 next: null,
104 enabled: 1,
105 status: "never",
106 scheduleJson: "broken",
107 },
108 { id: "running", next: now, enabled: 1, status: "running", scheduleJson: "broken" },
109 ]) {
110 yield* insertRow(sql, { ...row, prompt: secret }, now);
111 }
112 const warnings: unknown[] = [];
113 const tasks = yield* ScheduledTaskService.listDueTasks(DateTime.makeUnsafe(now)).pipe(
114 Effect.provide(
115 Logger.layer([
116 Logger.make(({ message }) => {
117 warnings.push(message);
118 }),
119 ]),
120 ),
121 );
122 assert.deepEqual(
123 tasks.map((task) => task.id),
124 ["due-earlier", "due-now"],
125 );
126 assert.equal(warnings.length, 6);
127 const annotations = warnings.map(
128 (warning) => (warning as ReadonlyArray<unknown>)[1] as Record<string, unknown>,
129 );
130 assert.deepEqual(
131 annotations.map((annotation) => annotation.taskId),
132 ["due-bad-date", null, "", " ", "due-corrupt", "due-cred"],
133 );
134 const causes = annotations.map((annotation) => annotation.cause);
135 assert.deepEqual(
136 causes.map((cause) => (isScheduledTaskError(cause) ? cause.taskId : undefined)),
137 [undefined, undefined, undefined, undefined, "due-corrupt", "due-cred"],
138 );
139 for (const cause of causes) {
140 if (cause !== undefined) assert.isTrue(isScheduledTaskError(cause));
141 }
142 const rendered = NodeUtil.inspect(annotations, { depth: null });
143 assert.isFalse(rendered.includes(secret));
144 assert.isFalse(rendered.includes(credential));
145 const running = yield* sql<{
146 last_run_status: string;
147 }>`SELECT last_run_status FROM scheduled_tasks WHERE task_id = 'running'`;
148 assert.equal(running[0]?.last_run_status, "running");
149 }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
150);
151​
152it.effect(
153 "releases interrupted runs on startup and still executes due tasks, skipping corrupt rows",
154 () =>
155 Effect.gen(function* () {
156 const sql = yield* SqlClient.SqlClient;
157 const now = "2026-09-09T12:00:00.000Z";
158 const hugeInterval = '{"type":"interval","everyMs":9000000000000000}';
159 for (const row of [
160 { id: "stuck-valid", next: now, status: "running" },
161 { id: "stuck-corrupt", next: now, status: "running", scheduleJson: "broken" },
162 { id: "stuck-huge", next: now, status: "running", scheduleJson: hugeInterval },
163 { id: null, next: now, status: "running" },
164 { id: "due-bad-date", next: "", status: "never" },
165 { id: "due-healthy", next: now, status: "never" },
166 { id: "due-huge", next: now, status: "never", scheduleJson: hugeInterval },
167 { id: "due-second", next: now, status: "never" },
168 { id: "due-third", next: now, status: "never" },
169 ]) {
170 yield* insertRow(sql, { ...row, enabled: 1 }, now);
171 }
172​
173 // it.effect freezes the clock; pin it just past the seeded due time so
174 // the poll sees the rows as due.
175 yield* TestClock.setTime(Date.parse(now) + 1_000);
176 const dispatched = yield* Ref.make(0);
177 const lastDispatched = yield* Deferred.make<void>();
178 const releaseLast = yield* Deferred.make<void>();
179 yield* Effect.scoped(
180 Effect.gen(function* () {
181 yield* Layer.build(
182 Layer.provideMerge(
183 ScheduledTaskService.layer,
184 Layer.mergeAll(
185 Layer.mock(ThreadLaunchService.ThreadLaunchService)({
186 launch: () =>
187 Ref.updateAndGet(dispatched, (n) => n + 1).pipe(
188 Effect.andThen((n) =>
189 n === 4
190 ? Deferred.succeed(lastDispatched, undefined).pipe(
191 Effect.andThen(Deferred.await(releaseLast)),
192 )
193 : Effect.void,
194 ),
195 Effect.andThen(Effect.die(new Error("test launch failure"))),
196 ),
197 }),
198 Layer.mock(ThreadManagementService.ThreadManagementService)({}),
199 Layer.mock(SecretRequests.SecretRequests)({}),
200 NodeCrypto.layer,
201 Scheduler.layer,
202 ),
203 ),
204 );
205 // The poll loop delays before its first pass, so the frozen test
206 // clock must advance once to trigger it.
207 yield* TestClock.adjust("6 seconds");
208 yield* Deferred.await(lastDispatched);
209 const inflight = yield* sql<{
210 last_run_status: string;
211 }>`SELECT last_run_status FROM scheduled_tasks WHERE task_id = 'due-third'`;
212 assert.equal(inflight[0]?.last_run_status, "running");
213 yield* Deferred.succeed(releaseLast, undefined);
214 }),
215 );
216​
217 const rows = yield* sql<{
218 task_id: string | null;
219 last_run_status: string;
220 last_run_error: string | null;
221 next_run_at: string | null;
222 run_count: number;
223 }>`SELECT task_id, last_run_status, last_run_error, next_run_at, run_count
224 FROM scheduled_tasks ORDER BY task_id`;
225 const byId = new Map(rows.map((row) => [row.task_id, row]));
226 assert.equal(rows.length, 9);
227 assert.equal(byId.get("stuck-valid")?.last_run_status, "failed");
228 assert.isNotNull(byId.get("stuck-valid")?.next_run_at);
229 assert.equal(byId.get("stuck-corrupt")?.last_run_status, "failed");
230 assert.equal(byId.get(null)?.last_run_status, "failed");
231 const stuckHuge = byId.get("stuck-huge");
232 assert.equal(stuckHuge?.last_run_status, "failed");
233 assert.isNull(stuckHuge?.next_run_at);
234 for (const id of ["stuck-valid", "stuck-corrupt", "stuck-huge", null]) {
235 const row = byId.get(id);
236 assert.equal(row?.last_run_error, "Run was interrupted by a server restart.");
237 assert.equal(row?.run_count, 1);
238 }
239 for (const id of ["due-healthy", "due-huge", "due-second"]) {
240 const row = byId.get(id);
241 assert.equal(row?.last_run_status, "failed");
242 assert.isTrue(row?.last_run_error?.includes("test launch failure") === true);
243 assert.equal(row?.run_count, 1);
244 }
245 assert.isNull(byId.get("due-huge")?.next_run_at);
246 assert.equal(byId.get("due-bad-date")?.last_run_status, "never");
247 assert.equal(byId.get("due-bad-date")?.run_count, 0);
248 }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
249);
250​
251it.effect(
252 "treats a next_run_at corrupted before the dispatch re-read as not due instead of defecting the poll",
253 () =>
254 Effect.gen(function* () {
255 const sql = yield* SqlClient.SqlClient;
256 const now = "2026-09-09T12:00:00.000Z";
257 for (const row of [
258 { id: "run-a", next: now, status: "never" },
259 { id: "run-b-victim", next: now, status: "never" },
260 { id: "run-c", next: now, status: "never" },
261 { id: "run-d", next: now, status: "never" },
262 ]) {
263 yield* insertRow(sql, { ...row, enabled: 1 }, now);
264 }
265 yield* TestClock.setTime(Date.parse(now) + 1_000);
266 const dispatched = yield* Ref.make(0);
267 const lastDispatched = yield* Deferred.make<void>();
268 const releaseLast = yield* Deferred.make<void>();
269 yield* Effect.scoped(
270 Effect.gen(function* () {
271 yield* Layer.build(
272 Layer.provideMerge(
273 ScheduledTaskService.layer,
274 Layer.mergeAll(
275 Layer.mock(ThreadLaunchService.ThreadLaunchService)({
276 launch: () =>
277 Ref.updateAndGet(dispatched, (n) => n + 1).pipe(
278 Effect.andThen((n) =>
279 n === 1
280 ? sql`UPDATE scheduled_tasks
281 SET next_run_at = ''
282 WHERE task_id = 'run-b-victim'`.pipe(Effect.asVoid, Effect.orDie)
283 : n === 3
284 ? Deferred.succeed(lastDispatched, undefined).pipe(
285 Effect.andThen(Deferred.await(releaseLast)),
286 )
287 : Effect.void,
288 ),
289 Effect.andThen(Effect.die(new Error("test launch failure"))),
290 ),
291 }),
292 Layer.mock(ThreadManagementService.ThreadManagementService)({}),
293 Layer.mock(SecretRequests.SecretRequests)({}),
294 NodeCrypto.layer,
295 Scheduler.layer,
296 ),
297 ),
298 );
299 yield* TestClock.adjust("6 seconds");
300 yield* Deferred.await(lastDispatched);
301 assert.equal(yield* Ref.get(dispatched), 3);
302 const rows = yield* sql<{
303 task_id: string;
304 last_run_status: string;
305 next_run_at: string | null;
306 run_count: number;
307 }>`SELECT task_id, last_run_status, next_run_at, run_count
308 FROM scheduled_tasks ORDER BY task_id`;
309 const byId = new Map(rows.map((row) => [row.task_id, row]));
310 const victim = byId.get("run-b-victim");
311 assert.equal(victim?.last_run_status, "never");
312 assert.equal(victim?.run_count, 0);
313 assert.equal(victim?.next_run_at, "");
314 for (const id of ["run-a", "run-c"]) {
315 const row = byId.get(id);
316 assert.equal(row?.last_run_status, "failed");
317 assert.equal(row?.run_count, 1);
318 }
319 yield* Deferred.succeed(releaseLast, undefined);
320 }),
321 );
322 }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
323);