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

initializeV2Database.test.ts

216 lines10.5 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6import * as NodeSqlite from "node:sqlite";
7​
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import { assert, it } from "@effect/vitest";
10import { ThreadId } from "@t3tools/contracts";
11import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
12import * as Effect from "effect/Effect";
13import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
14import * as Layer from "effect/Layer";
15import * as Predicate from "effect/Predicate";
16import * as SqlClient from "effect/sql/SqlClient";
17​
18import * as ServerConfig from "../config.ts";
19import * as SqlitePersistence from "./Sqlite.ts";
20import { runMigrations } from "./Migrations.ts";
21import { initializeV2Database } from "./initializeV2Database.ts";
22import * as EventStore from "../orchestration-v2/EventStore.ts";
23import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
24import * as EventSink from "../orchestration-v2/EventSink.ts";
25import * as LegacyV1ThreadImporter from "../orchestration-v2/legacy/LegacyV1ThreadImporter.ts";
26​
27it.effect(
28 "snapshots V1, imports transcripts lazily, and preserves both databases across switches",
29 () => {
30 const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v1-v2-"));
31 const sourcePath = NodePath.join(directory, "state.sqlite");
32 const destinationPath = NodePath.join(directory, "statev2.sqlite");
33 const threadId = ThreadId.make("legacy-thread");
34 const seed = Effect.gen(function* () {
35 const sql = yield* SqlClient.SqlClient;
36 yield* runMigrations({ toMigrationInclusive: 52 });
37 yield* sql`INSERT INTO projection_projects (project_id, title, workspace_root, scripts_json, created_at, updated_at)
38 VALUES ('project', 'Project', '/tmp/project', '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z')`;
39 yield* sql`INSERT INTO projection_threads (thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode, created_at, updated_at)
40 VALUES (${threadId}, 'project', 'V1 thread', '{"instanceId":"codex","model":"gpt-5.4"}', 'full-access', 'default', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z')`;
41 for (let index = 0; index < 6; index++) {
42 yield* sql`INSERT INTO projection_thread_messages (message_id, thread_id, role, text, is_streaming, created_at, updated_at)
43 VALUES (${`message-${index}`}, ${threadId}, ${index % 2 ? "assistant" : "user"}, ${`Text ${index}`}, 0, ${`2026-01-0${index + 1}T00:00:00.000Z`}, ${`2026-01-0${index + 1}T00:00:00.000Z`})`;
44 }
45 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: sourcePath })));
46​
47 return Effect.gen(function* () {
48 yield* seed;
49 const original = NodeFS.readFileSync(sourcePath);
50 const config = yield* ServerConfig.ServerConfig;
51 const layerDatabase = SqlitePersistence.layerConfig.pipe(
52 Layer.provide(ServerConfig.layer({ ...config, dbPath: destinationPath })),
53 );
54 const layerStores = Layer.mergeAll(
55 EventStore.layer,
56 ProjectionStore.layer.pipe(Layer.provide(NodeCrypto.layerDigest)),
57 ).pipe(Layer.provideMerge(layerDatabase));
58 const layerSink = EventSink.layer.pipe(Layer.provide(layerStores));
59 const layerImporter = LegacyV1ThreadImporter.layer.pipe(
60 Layer.provideMerge(Layer.mergeAll(layerStores, layerSink)),
61 );
62 yield* Effect.gen(function* () {
63 const sql = yield* SqlClient.SqlClient;
64 const legacy = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
65 yield* legacy.reconcileShells;
66 const projections = yield* ProjectionStore.ProjectionStoreV2;
67 const shell = yield* projections.getThreadProjection(threadId);
68 assert.equal(shell.thread.id, threadId);
69 assert.deepEqual(
70 shell.messages.map((message) => message.text),
71 ["Text 4", "Text 5"],
72 );
73 const pending =
74 yield* sql`SELECT transcript_imported_at FROM orchestration_v2_legacy_imports`;
75 assert.equal(pending[0]?.transcript_imported_at, null);
76 yield* legacy.ensureTranscript(threadId);
77 const transcript = yield* projections.getThreadProjection(threadId);
78 assert.deepEqual(
79 transcript.messages.map((message) => message.text),
80 ["Text 0", "Text 1", "Text 2", "Text 3", "Text 4", "Text 5"],
81 );
82 const imported =
83 yield* sql`SELECT imported_message_count, transcript_imported_at FROM orchestration_v2_legacy_imports`;
84 assert.equal(imported[0]?.imported_message_count, 6);
85 assert.isNotNull(imported[0]?.transcript_imported_at);
86 yield* sql`CREATE TABLE v2_work (text TEXT)`;
87 yield* sql`INSERT INTO v2_work VALUES ('Keep V2 work')`;
88 }).pipe(Effect.provide(layerImporter));
89 assert.deepEqual(NodeFS.readFileSync(sourcePath), original);
90 const v1 = new NodeSqlite.DatabaseSync(sourcePath);
91 try {
92 assert.equal(
93 v1.prepare("SELECT MAX(migration_id) AS id FROM effect_sql_migrations").get()?.id,
94 52,
95 );
96 assert.equal(
97 v1
98 .prepare(
99 "SELECT count(*) AS count FROM sqlite_master WHERE name = 'orchestration_v2_legacy_imports'",
100 )
101 .get()?.count,
102 0,
103 );
104 v1.exec("UPDATE projection_threads SET title = 'Continued in V1'");
105 } finally {
106 v1.close();
107 }
108 yield* Effect.gen(function* () {
109 const sql = yield* SqlClient.SqlClient;
110 assert.equal((yield* sql`SELECT text FROM v2_work`)[0]?.text, "Keep V2 work");
111 assert.equal((yield* sql`SELECT title FROM projection_threads`)[0]?.title, "V1 thread");
112 }).pipe(Effect.provide(layerDatabase));
113 }).pipe(
114 Effect.provide(
115 ServerConfig.layerTest(directory, directory).pipe(Layer.provideMerge(NodeServices.layer)),
116 ),
117 Effect.ensuring(
118 Effect.sync(() => NodeFS.rmSync(directory, { recursive: true, force: true })),
119 ),
120 );
121 },
122);
123​
124it.effect("includes committed WAL data and does not publish a failed snapshot", () => {
125 const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-snapshot-"));
126 const sourcePath = NodePath.join(directory, "state.sqlite");
127 const destinationPath = NodePath.join(directory, "statev2.sqlite");
128 return Effect.gen(function* () {
129 NodeFS.writeFileSync(sourcePath, "invalid SQLite");
130 const failure = yield* Effect.flip(initializeV2Database(destinationPath));
131 assert.isFalse(Predicate.isTagged(failure.cause, "V2DatabaseImportError"));
132 assert.isFalse(NodeFS.existsSync(destinationPath));
133 NodeFS.unlinkSync(sourcePath);
134 const source = new NodeSqlite.DatabaseSync(sourcePath);
135 try {
136 source.exec(
137 "PRAGMA journal_mode=WAL; CREATE TABLE messages(text TEXT); INSERT INTO messages VALUES ('committed'); CREATE TABLE dropped(blob BLOB); INSERT INTO dropped VALUES (randomblob(65536)); DROP TABLE dropped; BEGIN; INSERT INTO messages VALUES ('uncommitted');",
138 );
139 yield* initializeV2Database(destinationPath);
140 const copy = new NodeSqlite.DatabaseSync(destinationPath, { readOnly: true });
141 try {
142 assert.deepEqual(
143 copy
144 .prepare("SELECT text FROM messages")
145 .all()
146 .map((row) => row.text),
147 ["committed"],
148 );
149 assert.deepEqual(copy.prepare("PRAGMA auto_vacuum").get(), { auto_vacuum: 2 });
150 assert.deepEqual(copy.prepare("PRAGMA freelist_count").get(), { freelist_count: 0 });
151 } finally {
152 copy.close();
153 }
154 source.exec("ROLLBACK");
155 } finally {
156 source.close();
157 }
158 }).pipe(
159 Effect.provide(NodeServices.layer),
160 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(directory, { recursive: true, force: true }))),
161 );
162});
163​
164it.effect("starts fresh without V1 and never imports over existing V2 state", () => {
165 const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-fresh-"));
166 const destinationPath = NodePath.join(directory, "userdata", "statev2.sqlite");
167 return Effect.gen(function* () {
168 const config = yield* ServerConfig.ServerConfig;
169 const layerDatabase = SqlitePersistence.layerConfig.pipe(
170 Layer.provide(ServerConfig.layer({ ...config, dbPath: destinationPath })),
171 );
172 yield* Effect.gen(function* () {
173 const sql = yield* SqlClient.SqlClient;
174 yield* sql`CREATE TABLE v2_work (text TEXT)`;
175 yield* sql`INSERT INTO v2_work VALUES ('fresh V2 work')`;
176 }).pipe(Effect.provide(layerDatabase));
177 const sourcePath = NodePath.join(NodePath.dirname(destinationPath), "state.sqlite");
178 assert.isFalse(NodeFS.existsSync(sourcePath));
179 NodeFS.writeFileSync(sourcePath, "This source must never be opened once V2 exists");
180 yield* initializeV2Database(destinationPath);
181 yield* Effect.gen(function* () {
182 const sql = yield* SqlClient.SqlClient;
183 assert.equal((yield* sql`SELECT text FROM v2_work`)[0]?.text, "fresh V2 work");
184 }).pipe(Effect.provide(layerDatabase));
185 }).pipe(
186 Effect.provide(
187 ServerConfig.layerTest(directory, directory).pipe(Layer.provideMerge(NodeServices.layer)),
188 ),
189 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(directory, { recursive: true, force: true }))),
190 );
191});
192​
193it.effect("removes copies left by a killed start, but not one that is still running", () => {
194 const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-abandoned-"));
195 const killed = NodeChildProcess.spawnSync(process.execPath, ["-e", ""]).pid;
196 const running = `.v2-import-${process.pid}-Kq81Zx`;
197 const unrelated = ".v2-import-not-a-copy";
198 return Effect.gen(function* () {
199 for (const name of [`.v2-import-${killed}-Wm3nPa`, ".v2-import-Q3xZ9a", running]) {
200 NodeFS.mkdirSync(NodePath.join(directory, name));
201 NodeFS.writeFileSync(NodePath.join(directory, name, "snapshot.sqlite"), "partial copy");
202 }
203 NodeFS.mkdirSync(NodePath.join(directory, unrelated));
204 const destinationPath = NodePath.join(directory, "statev2.sqlite");
205 NodeFS.writeFileSync(destinationPath, "existing V2 database");
206 yield* initializeV2Database(destinationPath);
207 assert.deepEqual(
208 NodeFS.readdirSync(directory).sort(),
209 [running, unrelated, "statev2.sqlite"].sort(),
210 );
211 assert.equal(NodeFS.readFileSync(destinationPath, "utf8"), "existing V2 database");
212 }).pipe(
213 Effect.provide(NodeServices.layer),
214 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(directory, { recursive: true, force: true }))),
215 );
216});