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

initializeV2Database.test.ts

197 lines9.2 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5import * as NodeSqlite from "node:sqlite";
6​
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { assert, it } from "@effect/vitest";
9import { ThreadId } from "@t3tools/contracts";
10import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as SqlClient from "effect/unstable/sql/SqlClient";
14​
15import { deriveServerPaths, layer as configLayer, layerTest } from "../config.ts";
16import { ServerConfig } from "../config.ts";
17import { layerConfig } from "./Layers/Sqlite.ts";
18import { runMigrations } from "./Migrations.ts";
19import { initializeV2Database } from "./initializeV2Database.ts";
20import { layer as eventStoreLayer } from "../orchestration-v2/EventStore.ts";
21import {
22 ProjectionStoreV2,
23 layer as projectionStoreLayer,
24} from "../orchestration-v2/ProjectionStore.ts";
25import { layer as eventSinkLayer } from "../orchestration-v2/EventSink.ts";
26import {
27 LegacyV1ThreadImporter,
28 layer as importerLayer,
29} from "../orchestration-v2/LegacyV1ThreadImporter.ts";
30​
31it.effect(
32 "snapshots V1, imports transcripts lazily, and preserves both databases across switches",
33 () => {
34 const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v1-v2-"));
35 const sourcePath = NodePath.join(directory, "state.sqlite");
36 const destinationPath = NodePath.join(directory, "statev2.sqlite");
37 const threadId = ThreadId.make("legacy-thread");
38 const seed = Effect.gen(function* () {
39 const sql = yield* SqlClient.SqlClient;
40 yield* runMigrations({ toMigrationInclusive: 52 });
41 yield* sql`INSERT INTO projection_projects (project_id, title, workspace_root, scripts_json, created_at, updated_at)
42 VALUES ('project', 'Project', '/tmp/project', '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z')`;
43 yield* sql`INSERT INTO projection_threads (thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode, created_at, updated_at)
44 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')`;
45 for (let index = 0; index < 6; index++) {
46 yield* sql`INSERT INTO projection_thread_messages (message_id, thread_id, role, text, is_streaming, created_at, updated_at)
47 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`})`;
48 }
49 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: sourcePath })));
50​
51 return Effect.gen(function* () {
52 yield* seed;
53 const original = NodeFS.readFileSync(sourcePath);
54 const config = yield* ServerConfig;
55 const databaseLayer = layerConfig.pipe(
56 Layer.provide(configLayer({ ...config, dbPath: destinationPath })),
57 );
58 const stores = Layer.mergeAll(eventStoreLayer, projectionStoreLayer).pipe(
59 Layer.provideMerge(databaseLayer),
60 );
61 const sink = eventSinkLayer.pipe(Layer.provide(stores));
62 const importer = importerLayer.pipe(Layer.provideMerge(Layer.mergeAll(stores, sink)));
63 yield* Effect.gen(function* () {
64 const sql = yield* SqlClient.SqlClient;
65 const legacy = yield* LegacyV1ThreadImporter;
66 yield* legacy.reconcileShells;
67 const projections = yield* ProjectionStoreV2;
68 const shell = yield* projections.getThreadProjection(threadId);
69 assert.equal(shell.thread.id, threadId);
70 assert.deepEqual(
71 shell.messages.map((message) => message.text),
72 ["Text 4", "Text 5"],
73 );
74 const pending =
75 yield* sql`SELECT transcript_imported_at FROM orchestration_v2_legacy_imports`;
76 assert.equal(pending[0]?.transcript_imported_at, null);
77 yield* legacy.ensureTranscript(threadId);
78 const transcript = yield* projections.getThreadProjection(threadId);
79 assert.deepEqual(
80 transcript.messages.map((message) => message.text),
81 ["Text 0", "Text 1", "Text 2", "Text 3", "Text 4", "Text 5"],
82 );
83 const imported =
84 yield* sql`SELECT imported_message_count, transcript_imported_at FROM orchestration_v2_legacy_imports`;
85 assert.equal(imported[0]?.imported_message_count, 6);
86 assert.isNotNull(imported[0]?.transcript_imported_at);
87 yield* sql`CREATE TABLE v2_work (text TEXT)`;
88 yield* sql`INSERT INTO v2_work VALUES ('Keep V2 work')`;
89 }).pipe(Effect.provide(importer));
90 assert.deepEqual(NodeFS.readFileSync(sourcePath), original);
91 const v1 = new NodeSqlite.DatabaseSync(sourcePath);
92 try {
93 assert.equal(
94 v1.prepare("SELECT MAX(migration_id) AS id FROM effect_sql_migrations").get()?.id,
95 52,
96 );
97 assert.equal(
98 v1
99 .prepare(
100 "SELECT count(*) AS count FROM sqlite_master WHERE name = 'orchestration_v2_legacy_imports'",
101 )
102 .get()?.count,
103 0,
104 );
105 v1.exec("UPDATE projection_threads SET title = 'Continued in V1'");
106 } finally {
107 v1.close();
108 }
109 yield* Effect.gen(function* () {
110 const sql = yield* SqlClient.SqlClient;
111 assert.equal((yield* sql`SELECT text FROM v2_work`)[0]?.text, "Keep V2 work");
112 assert.equal((yield* sql`SELECT title FROM projection_threads`)[0]?.title, "V1 thread");
113 }).pipe(Effect.provide(databaseLayer));
114 }).pipe(
115 Effect.provide(layerTest(directory, directory).pipe(Layer.provideMerge(NodeServices.layer))),
116 Effect.ensuring(
117 Effect.sync(() => NodeFS.rmSync(directory, { recursive: true, force: true })),
118 ),
119 );
120 },
121);
122​
123it.effect("includes committed WAL data and does not publish a failed snapshot", () => {
124 const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-snapshot-"));
125 const sourcePath = NodePath.join(directory, "state.sqlite");
126 const destinationPath = NodePath.join(directory, "statev2.sqlite");
127 return Effect.gen(function* () {
128 NodeFS.writeFileSync(sourcePath, "invalid SQLite");
129 assert.isTrue((yield* Effect.result(initializeV2Database(destinationPath)))._tag === "Failure");
130 assert.isFalse(NodeFS.existsSync(destinationPath));
131 NodeFS.unlinkSync(sourcePath);
132 const source = new NodeSqlite.DatabaseSync(sourcePath);
133 try {
134 source.exec(
135 "PRAGMA journal_mode=WAL; CREATE TABLE messages(text TEXT); INSERT INTO messages VALUES ('committed'); BEGIN; INSERT INTO messages VALUES ('uncommitted');",
136 );
137 yield* initializeV2Database(destinationPath);
138 const copy = new NodeSqlite.DatabaseSync(destinationPath, { readOnly: true });
139 try {
140 assert.deepEqual(
141 copy
142 .prepare("SELECT text FROM messages")
143 .all()
144 .map((row) => row.text),
145 ["committed"],
146 );
147 } finally {
148 copy.close();
149 }
150 source.exec("ROLLBACK");
151 } finally {
152 source.close();
153 }
154 }).pipe(
155 Effect.provide(NodeServices.layer),
156 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(directory, { recursive: true, force: true }))),
157 );
158});
159​
160it.effect("uses statev2.sqlite for default and explicit development paths", () =>
161 Effect.gen(function* () {
162 for (const devUrl of [undefined, new URL("http://localhost:5173")]) {
163 for (const baseDirIsExplicit of [false, true]) {
164 const paths = yield* deriveServerPaths("/tmp/t3", devUrl, { baseDirIsExplicit });
165 assert.equal(NodePath.basename(paths.dbPath), "statev2.sqlite");
166 assert.equal(paths.settingsPath, NodePath.join(paths.stateDir, "settings.json"));
167 }
168 }
169 }).pipe(Effect.provide(NodeServices.layer)),
170);
171​
172it.effect("starts fresh without V1 and never imports over existing V2 state", () => {
173 const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-fresh-"));
174 const destinationPath = NodePath.join(directory, "userdata", "statev2.sqlite");
175 return Effect.gen(function* () {
176 const config = yield* ServerConfig;
177 const database = layerConfig.pipe(
178 Layer.provide(configLayer({ ...config, dbPath: destinationPath })),
179 );
180 yield* Effect.gen(function* () {
181 const sql = yield* SqlClient.SqlClient;
182 yield* sql`CREATE TABLE v2_work (text TEXT)`;
183 yield* sql`INSERT INTO v2_work VALUES ('fresh V2 work')`;
184 }).pipe(Effect.provide(database));
185 const sourcePath = NodePath.join(NodePath.dirname(destinationPath), "state.sqlite");
186 assert.isFalse(NodeFS.existsSync(sourcePath));
187 NodeFS.writeFileSync(sourcePath, "This source must never be opened once V2 exists");
188 yield* initializeV2Database(destinationPath);
189 yield* Effect.gen(function* () {
190 const sql = yield* SqlClient.SqlClient;
191 assert.equal((yield* sql`SELECT text FROM v2_work`)[0]?.text, "fresh V2 work");
192 }).pipe(Effect.provide(database));
193 }).pipe(
194 Effect.provide(layerTest(directory, directory).pipe(Layer.provideMerge(NodeServices.layer))),
195 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(directory, { recursive: true, force: true }))),
196 );
197});