Skip to content

Commit 15769fa

Browse files
fix(server): isolate V2 migrations from the V1 database
1 parent 53bd734 commit 15769fa

14 files changed

Lines changed: 270 additions & 16 deletions

‎apps/server/scripts/migrate-dev-db.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => {
7777
{ sharedHome: sourceDir },
7878
);
7979

80-
assert.equal(result.databasePath, path.join(destDir, "userdata", "state.sqlite"));
80+
assert.equal(result.databasePath, path.join(destDir, "userdata", "statev2.sqlite"));
8181
const kept = yield* withDatabase(
8282
result.databasePath,
8383
Effect.gen(function* () {
@@ -166,7 +166,7 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => {
166166
const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-dest-" });
167167
// A leftover snapshot from a prior failed run, passed as --source: it
168168
// must not be deleted before it is read.
169-
const leftoverSnapshot = path.join(destDir, "userdata", "state.sqlite.migrate-dev-db-tmp");
169+
const leftoverSnapshot = path.join(destDir, "userdata", "statev2.sqlite.migrate-dev-db-tmp");
170170
yield* fs.makeDirectory(path.dirname(leftoverSnapshot), { recursive: true });
171171
yield* fs.writeFileString(leftoverSnapshot, "not a real db");
172172

‎apps/server/scripts/migrate-dev-db.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
* ~/.t3 database, then run this checkout's migrations against it.
66
*
77
* `vp run migrate-dev-db` from a worktree:
8-
* 1. Nukes `<worktree>/.t3/userdata/state.sqlite`.
8+
* 1. Nukes `<worktree>/.t3/userdata/statev2.sqlite`.
99
* 2. Snapshots the real db (read-only VACUUM INTO) and prunes it to the
1010
* most recently updated projects and, per project, the most recent
1111
* threads that have fully stopped. Working, settled, and monitored
@@ -373,7 +373,7 @@ export const runMigrateDevDb = Effect.fn("runMigrateDevDb")(function* (
373373
return yield* new MigrateDevDbNotInWorktreeError();
374374
}
375375
const stateDir = path.join(baseDir, "userdata");
376-
const databasePath = path.join(stateDir, "state.sqlite");
376+
const databasePath = path.join(stateDir, "statev2.sqlite");
377377
const snapshotPath = `${databasePath}.migrate-dev-db-tmp`;
378378

379379
if (!(yield* fs.exists(sourcePath))) {

‎apps/server/scripts/t3-sqlite-state.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ const createFixtureDatabase = Effect.fn("createSqliteStateFixtureDatabase")(func
1616
const fs = yield* FileSystem.FileSystem;
1717
const path = yield* Path.Path;
1818
const stateDir = path.join(baseDir, "userdata");
19-
const databasePath = path.join(stateDir, "state.sqlite");
19+
const databasePath = path.join(stateDir, "statev2.sqlite");
2020
yield* fs.makeDirectory(stateDir, { recursive: true });
2121
yield* Effect.gen(function* () {
2222
const sql = yield* SqlClient.SqlClient;

‎apps/server/scripts/t3-sqlite-state.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ export const runSqliteState = Effect.fn("runSqliteState")(function* (
182182
const path = yield* Path.Path;
183183
const baseDir = path.resolve(input.baseDir);
184184
const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));
185-
const databasePath = path.join(baseDir, "userdata", "state.sqlite");
185+
const databasePath = path.join(baseDir, "userdata", "statev2.sqlite");
186186
const source = yield* resolveSqlSource(input.sql, input.file);
187187

188188
if (!(yield* fs.exists(databasePath))) {
@@ -252,7 +252,7 @@ const t3SqliteStateCommand = Command.make(
252252
Argument.withDescription("Run a read-only query or a backed-up fixture mutation."),
253253
),
254254
baseDir: Flag.String("base-dir").pipe(
255-
Flag.withDescription("Explicit T3 base directory containing userdata/state.sqlite."),
255+
Flag.withDescription("Explicit T3 base directory containing userdata/statev2.sqlite."),
256256
),
257257
sql: Flag.String("sql").pipe(
258258
Flag.optional,

‎apps/server/src/cli/config.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
305305
tailscaleServeEnabled: true,
306306
tailscaleServePort: 8443,
307307
});
308-
assert.equal(resolved.dbPath, join(baseDir, "userdata", "state.sqlite"));
308+
assert.equal(resolved.dbPath, join(baseDir, "userdata", "statev2.sqlite"));
309309
}),
310310
);
311311

‎apps/server/src/config.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ export const deriveServerPaths = Effect.fn(function* (
136136
baseDir,
137137
devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata",
138138
);
139-
const dbPath = join(stateDir, "state.sqlite");
139+
const dbPath = join(stateDir, "statev2.sqlite");
140140
const attachmentsDir = join(stateDir, "attachments");
141141
const logsDir = join(stateDir, "logs");
142142
const providerLogsDir = join(logsDir, "provider");

‎apps/server/src/persistence/Layers/Sqlite.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
66
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
77

88
import { runMigrations } from "../Migrations.ts";
9+
import { initializeV2Database } from "../initializeV2Database.ts";
910
import { ServerConfig } from "../../config.ts";
1011

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

‎docs/internals/legacy-orchestration-migration.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# Legacy orchestration migration
22

3-
Orchestration v2 imports v1 threads in place. It creates v2 thread shell events first and imports
3+
Orchestration v2 snapshots `state.sqlite` into `statev2.sqlite` before opening writable persistence
4+
on its first launch. Only the copy receives v2 migrations; the original remains available to v1.
5+
Subsequent launches reuse the copy without refreshing it from v1. It creates v2 thread shell events first and imports
46
the complete user and assistant transcript lazily when a client reads or continues the thread. The
57
v1 projection tables remain the import source and provide a read-only recovery source if an import
68
needs investigation.

0 commit comments

Comments
 (0)