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

Scheduler.integration.test.ts

154 lines6.1 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import { assert, expect, it } from "@effect/vitest";
3import {
4 CommandId,
5 DEFAULT_SERVER_SETTINGS,
6 ProjectId,
7 ProviderInstanceId,
8 RunId,
9 ThreadId,
10 type OrchestrationV2ServerCommand,
11 type OrchestrationV2ThreadShell,
12} from "@t3tools/contracts";
13import * as DateTime from "effect/DateTime";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16import * as Queue from "effect/Queue";
17import * as Ref from "effect/Ref";
18import * as SqlClient from "effect/unstable/sql/SqlClient";
19import * as TestClock from "effect/testing/TestClock";
20​
21import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
22import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
23import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
24import * as UsageLimitRecoveryWorker from "../orchestration-v2/UsageLimitRecoveryWorker.ts";
25import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
26import * as ScheduledTasks from "../scheduledTasks/ScheduledTaskService.ts";
27import * as ServerSettings from "../serverSettings.ts";
28import * as Scheduler from "./Scheduler.ts";
29​
30it.effect.each(["on time", "after restart"])(
31 "runs Scheduled Tasks and a persisted limit retry through the same scheduler %s",
32 (scenario) =>
33 Effect.gen(function* () {
34 const now = yield* DateTime.now;
35 const resetAt = DateTime.formatIso(DateTime.add(now, { seconds: 60 }));
36 const thread: OrchestrationV2ThreadShell = {
37 id: ThreadId.make("thread:limited"),
38 projectId: ProjectId.make("project:test"),
39 title: "Limited",
40 providerInstanceId: ProviderInstanceId.make("codex"),
41 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
42 runtimeMode: "full-access",
43 interactionMode: "default",
44 createdBy: "user",
45 creationSource: "web",
46 branch: null,
47 worktreePath: null,
48 lineage: {
49 rootThreadId: ThreadId.make("thread:limited"),
50 parentThreadId: null,
51 relationshipToParent: null,
52 },
53 forkedFrom: null,
54 activeProviderThreadId: null,
55 latestRunId: RunId.make("run:limited"),
56 latestRunCompletedAt: now,
57 activeRunId: null,
58 status: "failed",
59 lastErrorClass: "usage_limit",
60 usageLimitResetAt: resetAt,
61 pendingRuntimeRequest: null,
62 latestVisibleMessage: null,
63 latestUserMessageAt: now,
64 hasActionableProposedPlan: false,
65 itemCount: 1,
66 visibleItemCount: 1,
67 createdAt: now,
68 updatedAt: now,
69 archivedAt: null,
70 settledOverride: null,
71 settledAt: null,
72 lastVisitedAt: null,
73 pinnedAt: null,
74 deletedAt: null,
75 limitRecovery: {
76 runId: RunId.make("run:limited"),
77 resetAt,
78 autoResume: true,
79 requestId: CommandId.make("recovery:choice"),
80 },
81 };
82 if (scenario === "after restart") {
83 yield* TestClock.adjust("65 seconds");
84 }
85 const current = yield* Ref.make(thread);
86 const commands = yield* Ref.make<ReadonlyArray<OrchestrationV2ServerCommand>>([]);
87 const receipts = yield* Queue.unbounded<"task" | "retry">();
88 const dependencies = Layer.mergeAll(
89 NodeCrypto.layer,
90 Layer.mock(ThreadLaunchService.ThreadLaunchService)({
91 launch: () =>
92 Queue.offer(receipts, "task").pipe(
93 Effect.andThen(Effect.die("fixture dispatch failure")),
94 ),
95 }),
96 Layer.mock(ThreadManagementService.ThreadManagementService)({
97 dispatch: (command) =>
98 Ref.update(commands, (all) => [...all, command]).pipe(
99 Effect.andThen(
100 Ref.update(current, (shell) => ({ ...shell, status: "running" as const })),
101 ),
102 Effect.andThen(Queue.offer(receipts, "retry")),
103 Effect.as({ sequence: 1, storedEvents: [] }),
104 ),
105 }),
106 Layer.mock(ProjectionStore.ProjectionStoreV2)({
107 getLimitRecoveryCandidates: () =>
108 Ref.get(current).pipe(
109 Effect.map((shell) => (shell.status === "failed" ? [shell] : [])),
110 ),
111 }),
112 Layer.mock(ServerSettings.ServerSettingsService)({
113 getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS),
114 }),
115 );
116 const workers = Layer.mergeAll(
117 ScheduledTasks.layer,
118 UsageLimitRecoveryWorker.workerLive,
119 ).pipe(Layer.provide(dependencies), Layer.provide(Scheduler.layer));
120 yield* Effect.gen(function* () {
121 const tasks = yield* ScheduledTasks.ScheduledTaskService;
122 const { task } = yield* tasks.upsert({
123 title: "Scheduled work",
124 prompt: "Run scheduled work",
125 enabled: true,
126 schedule: { type: "interval", everyMs: 60_000 },
127 projectId: thread.projectId,
128 workspaceStrategy: { type: "root" },
129 modelSelection: thread.modelSelection,
130 runtimeMode: thread.runtimeMode,
131 interactionMode: thread.interactionMode,
132 });
133 const sql = yield* SqlClient.SqlClient;
134 yield* sql`UPDATE scheduled_tasks SET next_run_at = ${resetAt} WHERE task_id = ${task.id}`;
135 if (scenario === "on time") {
136 yield* TestClock.adjust("55 seconds");
137 assert.deepEqual(yield* Ref.get(commands), []);
138 }
139 yield* TestClock.adjust("5 seconds");
140 assert.deepEqual([yield* Queue.take(receipts), yield* Queue.take(receipts)].sort(), [
141 "retry",
142 "task",
143 ]);
144 const delivered = yield* Ref.get(commands);
145 assert.equal(delivered.length, 1);
146 expect(delivered[0]).toMatchObject({
147 type: "message.dispatch",
148 usageLimitContinuationOfRunId: thread.latestRunId,
149 usageLimitRecoveryRequestId: thread.limitRecovery!.requestId,
150 text: "Continue where you left off.",
151 });
152 }).pipe(Effect.provide(workers));
153 }).pipe(Effect.provide(SqlitePersistenceMemory)),
154);