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

migrate-dev-db.test.ts

313 lines14.6 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Path from "effect/Path";
6import * as SqlClient from "effect/sql/SqlClient";
7​
8import { runMigrations } from "../src/persistence/Migrations.ts";
9import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
10import { runMigrateDevDb } from "./migrate-dev-db.ts";
11​
12const withDatabase = <A, E>(
13 databasePath: string,
14 effect: Effect.Effect<A, E, SqlClient.SqlClient>,
15) => effect.pipe(Effect.provide(NodeSqliteClient.layer({ filename: databasePath })));
16​
17const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(function* (
18 baseDir: string,
19) {
20 const fs = yield* FileSystem.FileSystem;
21 const path = yield* Path.Path;
22 const stateDir = path.join(baseDir, "userdata");
23 const databasePath = path.join(stateDir, "statev2.sqlite");
24 yield* fs.makeDirectory(stateDir, { recursive: true });
25 yield* withDatabase(
26 databasePath,
27 Effect.gen(function* () {
28 const sql = yield* SqlClient.SqlClient;
29 yield* runMigrations();
30​
31 yield* sql`INSERT INTO projection_projects
32 (project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at)
33 VALUES
34 ('project-kept', 'Kept', '/tmp/kept', '[]', '2026-08-01', '2026-08-01', NULL),
35 ('project-deleted', 'Deleted', '/tmp/deleted', '[]', '2026-08-01', '2026-08-02', '2026-08-02')`;
36​
37 const forkPayload =
38 '{"lineage":{"parentThreadId":"stopped-thread","relationshipToParent":"fork","rootThreadId":"stopped-thread"}}';
39 const subagentPayload =
40 '{"lineage":{"parentThreadId":"subagent-parent","relationshipToParent":"subagent","rootThreadId":"subagent-parent"},"forkedFrom":{"type":"node","nodeId":"node-1"}}';
41 const threads = [
42 ["stopped-thread", "project-kept", "completed", "{}", "2026-08-01"],
43 ["fork-thread", "project-kept", "completed", forkPayload, "2026-08-02"],
44 ["running-thread", "project-kept", "running", "{}", "2026-08-05"],
45 ["settled-thread", "project-kept", "completed", '{"settledAt":"2026-08-01"}', "2026-08-05"],
46 [
47 "archived-thread",
48 "project-kept",
49 "completed",
50 '{"archivedAt":"2026-08-01"}',
51 "2026-08-05",
52 ],
53 [
54 "limit-thread",
55 "project-kept",
56 "completed",
57 '{"limitRecovery":{"autoResume":true}}',
58 "2026-08-05",
59 ],
60 ["subagent-parent", "project-kept", "completed", "{}", "2026-08-05"],
61 ["subagent-child", "project-kept", "completed", subagentPayload, "2026-08-05"],
62 ["deleted-project-thread", "project-deleted", "completed", "{}", "2026-08-05"],
63 ] as const;
64 for (const [threadId, projectId, runStatus, payload, updatedAt] of threads) {
65 yield* sql`INSERT INTO orchestration_v2_projection_threads
66 (thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, created_at, updated_at, payload_json)
67 VALUES (${threadId}, ${projectId}, ${threadId}, 'codex', 'full-access', 'default', '2026-08-01', ${updatedAt}, ${payload})`;
68 yield* sql`INSERT INTO orchestration_v2_projection_runs
69 (run_id, thread_id, ordinal, provider, status, requested_at, payload_json)
70 VALUES (${`run-${threadId}`}, ${threadId}, 1, 'codex', ${runStatus}, '2026-08-01', '{}')`;
71 yield* sql`INSERT INTO orchestration_events
72 (event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json)
73 VALUES (${`event-${threadId}`}, 'thread', ${threadId}, 0, 'thread.created', '2026-08-01', 'user', '{}', '{}')`;
74 }
75 yield* sql`INSERT INTO orchestration_v2_projection_provider_sessions
76 (provider_session_id, thread_id, provider, status, updated_at, payload_json)
77 VALUES ('session-shared', 'running-thread', 'codex', 'stopped', '2026-08-01', '{}')`;
78 yield* sql`INSERT INTO orchestration_v2_projection_provider_session_bindings
79 (provider_session_id, thread_id)
80 VALUES ('session-shared', 'running-thread'), ('session-shared', 'stopped-thread')`;
81 yield* sql`INSERT INTO orchestration_v2_projection_context_transfers
82 (context_transfer_id, source_thread_id, target_thread_id, type, status, updated_at, payload_json)
83 VALUES ('transfer-1', 'archived-thread', 'stopped-thread', 'provider_handoff', 'completed', '2026-08-01', '{}')`;
84 yield* sql`INSERT INTO scheduled_tasks
85 (task_id, title, prompt, enabled, schedule_json, project_id, workspace_strategy_json,
86 model_selection_json, runtime_mode, interaction_mode, created_by, creation_source,
87 created_at, updated_at, last_run_status, run_count)
88 VALUES ('task-1', 'Nightly', 'Run it', 1, '{}', 'project-kept', '{}', '{}',
89 'full-access', 'default', 'user', 'user', '2026-08-01', '2026-08-01', 'never', 0)`;
90 yield* sql`INSERT INTO scheduled_task_webhook_replay_keys
91 (task_id, replay_key, delivery_id, expires_at)
92 VALUES ('task-1', 'replay-1', 'delivery-1', 1900000000000)`;
93 yield* sql`INSERT INTO scheduled_task_webhook_pending
94 (delivery_id, task_id, coalesce_key, due_at, task_json, request_json, delivery_ids_json)
95 VALUES ('delivery-1', 'task-1', 'key-1', 1900000000000, '{}', '{}', '[]')`;
96 yield* sql`INSERT INTO auth_sessions (session_id, subject, scopes, method, issued_at, expires_at)
97 VALUES ('session-1', 'user', '[]', 'pairing', '2026-08-01', '2027-08-01')`;
98 yield* sql`INSERT INTO peer_environment_links
99 (environment_id, secret_name, label, urls_json, access, linked_at, expires_at)
100 VALUES ('environment-box', 'peer-link-box', 'Box', '["https://box.example"]', 'auto',
101 '2026-08-01', '2027-08-01')`;
102 }),
103 );
104 return databasePath;
105});
106​
107it.layer(NodeServices.layer)("migrate-dev-db", (it) => {
108 it.effect("keeps stopped and settled thread families and clears pending work", () =>
109 Effect.gen(function* () {
110 const fs = yield* FileSystem.FileSystem;
111 const path = yield* Path.Path;
112 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-src-" });
113 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-dest-" });
114 const source = yield* createFixtureSource(sourceDir);
115​
116 const result = yield* runMigrateDevDb(
117 { baseDir: destDir, source, projects: 5, threadsPerProject: 2 },
118 { sharedHome: sourceDir },
119 );
120​
121 assert.equal(result.databasePath, path.join(destDir, "userdata", "statev2.sqlite"));
122 const kept = yield* withDatabase(
123 result.databasePath,
124 Effect.gen(function* () {
125 const sql = yield* SqlClient.SqlClient;
126 const threads = yield* sql<{ thread_id: string }>`
127 SELECT thread_id FROM orchestration_v2_projection_threads ORDER BY thread_id`;
128 const events = yield* sql<{ stream_id: string }>`
129 SELECT stream_id FROM orchestration_events ORDER BY stream_id`;
130 const sessions = yield* sql<{ provider_session_id: string }>`
131 SELECT provider_session_id FROM orchestration_v2_projection_provider_sessions`;
132 const [leftovers] = yield* sql<{
133 auth: number;
134 tasks: number;
135 webhooks: number;
136 transfers: number;
137 links: number;
138 }>`
139 SELECT
140 (SELECT COUNT(*) FROM auth_sessions) AS auth,
141 (SELECT COUNT(*) FROM scheduled_tasks) AS tasks,
142 (SELECT COUNT(*) FROM scheduled_task_webhook_replay_keys) +
143 (SELECT COUNT(*) FROM scheduled_task_webhook_pending) AS webhooks,
144 (SELECT COUNT(*) FROM orchestration_v2_projection_context_transfers) AS transfers,
145 (SELECT COUNT(*) FROM peer_environment_links) AS links`;
146 return { threads, events, sessions, leftovers };
147 }),
148 );
149 assert.deepStrictEqual(
150 kept.threads.map((row) => row.thread_id),
151 ["fork-thread", "settled-thread", "stopped-thread"],
152 );
153 assert.deepStrictEqual(
154 kept.events.map((row) => row.stream_id),
155 ["fork-thread", "settled-thread", "stopped-thread"],
156 );
157 assert.deepStrictEqual(
158 kept.sessions.map((row) => row.provider_session_id),
159 ["session-shared"],
160 );
161 assert.deepStrictEqual(kept.leftovers, {
162 auth: 0,
163 tasks: 0,
164 webhooks: 0,
165 transfers: 0,
166 links: 0,
167 });
168 }),
169 );
170​
171 it.effect("never copies an archived thread, and new events append after the source's", () =>
172 Effect.gen(function* () {
173 const fs = yield* FileSystem.FileSystem;
174 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slice-" });
175 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slice-dest-" });
176 const source = yield* createFixtureSource(sourceDir);
177 const [sourceSequence] = yield* withDatabase(
178 source,
179 Effect.gen(function* () {
180 const sql = yield* SqlClient.SqlClient;
181 return yield* sql<{ seq: number }>`
182 SELECT seq FROM sqlite_sequence WHERE name = 'orchestration_events'`;
183 }),
184 );
185​
186 const result = yield* runMigrateDevDb(
187 { baseDir: destDir, source, projects: 5, threadsPerProject: 100 },
188 { sharedHome: sourceDir },
189 );
190​
191 const copied = yield* withDatabase(
192 result.databasePath,
193 Effect.gen(function* () {
194 const sql = yield* SqlClient.SqlClient;
195 const [archivedRows] = yield* sql<{ count: number }>`
196 SELECT
197 (SELECT COUNT(*) FROM orchestration_v2_projection_runs WHERE thread_id = 'archived-thread')
198 + (SELECT COUNT(*) FROM orchestration_events WHERE stream_id = 'archived-thread')
199 AS count`;
200 const [sequence] = yield* sql<{ seq: number }>`
201 SELECT seq FROM sqlite_sequence WHERE name = 'orchestration_events'`;
202 return { archivedRows: archivedRows?.count, sequence: sequence?.seq };
203 }),
204 );
205 assert.equal(copied.archivedRows, 0);
206 assert.equal(copied.sequence, sourceSequence?.seq);
207 }),
208 );
209​
210 it.effect("skips a thread family larger than the per-project limit", () =>
211 Effect.gen(function* () {
212 const fs = yield* FileSystem.FileSystem;
213 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-family-" });
214 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-family-dest-" });
215 const source = yield* createFixtureSource(sourceDir);
216​
217 // stopped-thread and its fork are 2 threads; settled-thread is 1.
218 const result = yield* runMigrateDevDb(
219 { baseDir: destDir, source, projects: 5, threadsPerProject: 1 },
220 { sharedHome: sourceDir },
221 );
222 const threads = yield* withDatabase(
223 result.databasePath,
224 Effect.gen(function* () {
225 const sql = yield* SqlClient.SqlClient;
226 return yield* sql<{ thread_id: string }>`
227 SELECT thread_id FROM orchestration_v2_projection_threads`;
228 }),
229 );
230 assert.deepStrictEqual(
231 threads.map((row) => row.thread_id),
232 ["settled-thread"],
233 );
234 }),
235 );
236​
237 it.effect("upgrades a source from before the V2 thread tables", () =>
238 Effect.gen(function* () {
239 const fs = yield* FileSystem.FileSystem;
240 const path = yield* Path.Path;
241 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-v1-" });
242 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-v1-dest-" });
243 const stateDir = path.join(sourceDir, "userdata");
244 const source = path.join(stateDir, "statev2.sqlite");
245 yield* fs.makeDirectory(stateDir, { recursive: true });
246 yield* withDatabase(source, runMigrations({ toMigrationInclusive: 54 }));
247​
248 const result = yield* runMigrateDevDb(
249 { baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
250 { sharedHome: sourceDir },
251 );
252 assert.include(result.executedMigrations, "55_OrchestrationV2");
253 }),
254 );
255​
256 it.effect("refuses while a dev server holds the destination", () =>
257 Effect.gen(function* () {
258 const fs = yield* FileSystem.FileSystem;
259 const path = yield* Path.Path;
260 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-busy-" });
261 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-busy-dest-" });
262 const source = yield* createFixtureSource(sourceDir);
263 const stateDir = path.join(destDir, "userdata");
264 yield* fs.makeDirectory(stateDir, { recursive: true });
265 yield* fs.writeFileString(
266 path.join(stateDir, "server-runtime.json"),
267 `{"version":1,"pid":${process.pid}}`,
268 );
269​
270 const error = yield* runMigrateDevDb(
271 { baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
272 { sharedHome: sourceDir },
273 ).pipe(Effect.flip);
274 assert.equal(error._tag, "MigrateDevDbServerRunningError");
275 if (error._tag === "MigrateDevDbServerRunningError") {
276 assert.equal(error.pid, process.pid);
277 }
278 }),
279 );
280​
281 it.effect("refuses a source that resolves to a destination path", () =>
282 Effect.gen(function* () {
283 const fs = yield* FileSystem.FileSystem;
284 const path = yield* Path.Path;
285 const sharedDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-" });
286 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-dest-" });
287 const leftoverSnapshot = path.join(destDir, "userdata", "statev2.sqlite.migrate-dev-db-tmp");
288 yield* fs.makeDirectory(path.dirname(leftoverSnapshot), { recursive: true });
289 yield* fs.writeFileString(leftoverSnapshot, "not a real db");
290​
291 const error = yield* runMigrateDevDb(
292 { baseDir: destDir, source: leftoverSnapshot, projects: 5, threadsPerProject: 10 },
293 { sharedHome: sharedDir },
294 ).pipe(Effect.flip);
295 assert.equal(error._tag, "MigrateDevDbSourceIsDestinationError");
296 assert.equal(yield* fs.exists(leftoverSnapshot), true);
297 }),
298 );
299​
300 it.effect("refuses to rebuild the shared home", () =>
301 Effect.gen(function* () {
302 const fs = yield* FileSystem.FileSystem;
303 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-shared-" });
304 const source = yield* createFixtureSource(sourceDir);
305​
306 const error = yield* runMigrateDevDb(
307 { baseDir: sourceDir, source, projects: 5, threadsPerProject: 10 },
308 { sharedHome: sourceDir },
309 ).pipe(Effect.flip);
310 assert.equal(error._tag, "MigrateDevDbSharedHomeError");
311 }),
312 );
313});