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

DatabaseMaintenance.test.ts

191 lines9.5 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
5import * as Clock from "effect/Clock";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Path from "effect/Path";
11import * as SqlClient from "effect/sql/SqlClient";
12​
13import * as DatabaseMaintenance from "./DatabaseMaintenance.ts";
14import * as Sqlite from "./Sqlite.ts";
15​
16it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))(
17 "DatabaseMaintenance",
18 (it) => {
19 it.effect("reports an unreadable database as an inspection failure", () =>
20 Effect.gen(function* () {
21 const fs = yield* FileSystem.FileSystem;
22 const path = yield* Path.Path;
23 const maintenance = yield* DatabaseMaintenance.DatabaseMaintenance;
24 const dbPath = path.join(
25 yield* fs.makeTempDirectoryScoped({ prefix: "t3-inspect-" }),
26 "statev2.sqlite",
27 );
28 yield* fs.writeFileString(dbPath, "not a database");
29 const failure = yield* Effect.flip(maintenance.inspect(dbPath));
30 assert.equal(failure._tag, "DatabaseInspectError");
31 }).pipe(Effect.scoped),
32 );
33​
34 it.effect("reports and deletes only the database from before 0.1.0", () =>
35 Effect.gen(function* () {
36 const fs = yield* FileSystem.FileSystem;
37 const path = yield* Path.Path;
38 const maintenance = yield* DatabaseMaintenance.DatabaseMaintenance;
39 const userdata = yield* fs.makeTempDirectoryScoped({ prefix: "t3-legacy-" });
40 const dbPath = path.join(userdata, "statev2.sqlite");
41 const legacy = path.join(userdata, "state.sqlite");
42 yield* Effect.gen(function* () {
43 const sql = yield* SqlClient.SqlClient;
44 yield* sql`CREATE TABLE retained_data (value TEXT)`;
45 yield* sql`INSERT INTO retained_data VALUES ('keep')`;
46 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath })));
47 assert.isNull((yield* maintenance.inspect(dbPath)).legacyDatabaseBytes);
48​
49 const openLegacy = NodeSqliteClient.layer({ filename: legacy });
50 yield* Effect.gen(function* () {
51 const sql = yield* SqlClient.SqlClient;
52 yield* sql`PRAGMA journal_mode = WAL`;
53 yield* sql`CREATE TABLE v1_data (value TEXT)`;
54 yield* sql`INSERT INTO v1_data VALUES ('rollback')`;
55 }).pipe(Effect.provide(openLegacy));
56 assert.isAbove((yield* maintenance.inspect(dbPath)).legacyDatabaseBytes ?? 0, 0);
57​
58 const refused = yield* Effect.gen(function* () {
59 const sql = yield* SqlClient.SqlClient;
60 yield* sql`SELECT value FROM v1_data`;
61 const failure = yield* Effect.flip(maintenance.removeLegacyDatabase(dbPath));
62 assert.deepEqual(yield* sql`SELECT value FROM v1_data`, [{ value: "rollback" }]);
63 return failure;
64 }).pipe(Effect.provide(openLegacy));
65 assert.equal(refused._tag, "DatabaseInUseError");
66 assert.isTrue(yield* fs.exists(legacy));
67​
68 yield* Effect.flatMap(DatabaseMaintenance.DatabaseMaintenance, (service) =>
69 service.removeLegacyDatabase(dbPath),
70 ).pipe(
71 Effect.provide(Layer.fresh(DatabaseMaintenance.layer)),
72 Effect.provideService(HostProcess.Platform, "win32"),
73 Effect.provideService(FileSystem.FileSystem, {
74 ...fs,
75 remove: (target, options) =>
76 Effect.gen(function* () {
77 if (target === legacy) {
78 yield* Effect.gen(function* () {
79 const sql = yield* SqlClient.SqlClient;
80 yield* sql`PRAGMA busy_timeout = 0`;
81 yield* sql`BEGIN EXCLUSIVE`;
82 yield* sql`COMMIT`;
83 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: legacy })));
84 // Create sidecars after the probe closes so only Doctor can remove them.
85 yield* fs.writeFileString(`${legacy}-wal`, "leftover WAL");
86 yield* fs.writeFileString(`${legacy}-shm`, "leftover SHM");
87 }
88 yield* fs.remove(target, options);
89 }),
90 }),
91 );
92 assert.isFalse(yield* fs.exists(legacy));
93 assert.isFalse(yield* fs.exists(`${legacy}-wal`));
94 assert.isFalse(yield* fs.exists(`${legacy}-shm`));
95 assert.isTrue(yield* fs.exists(dbPath));
96 yield* Effect.gen(function* () {
97 const sql = yield* SqlClient.SqlClient;
98 assert.deepEqual(yield* sql`SELECT value FROM retained_data`, [{ value: "keep" }]);
99 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath, readonly: true })));
100 assert.isNull((yield* maintenance.inspect(dbPath)).legacyDatabaseBytes);
101 }).pipe(Effect.scoped),
102 );
103​
104 it.effect("compacts an existing database offline only once its server has stopped", () =>
105 Effect.gen(function* () {
106 const fs = yield* FileSystem.FileSystem;
107 const path = yield* Path.Path;
108 const maintenance = yield* DatabaseMaintenance.DatabaseMaintenance;
109 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-compact-" });
110 const dbPath = path.join(baseDir, "userdata", "statev2.sqlite");
111 // Opening the database migrates it.
112 yield* Effect.void.pipe(Effect.provide(Sqlite.layerFromPath(dbPath)));
113 yield* Effect.gen(function* () {
114 const sql = yield* SqlClient.SqlClient;
115 yield* sql`PRAGMA auto_vacuum = NONE`;
116 yield* sql`VACUUM`;
117 yield* sql`CREATE TABLE retained_data (value TEXT)`;
118 yield* sql`INSERT INTO retained_data VALUES ('keep')`;
119 yield* sql`CREATE TABLE discarded_data (value BLOB)`;
120 yield* sql`INSERT INTO discarded_data VALUES (zeroblob(4194304))`;
121 yield* sql`DROP TABLE discarded_data`;
122 yield* sql`
123 INSERT INTO orchestration_v2_projection_messages (
124 message_id, thread_id, run_id, node_id, role, streaming, created_at, updated_at, payload_json
125 )
126 VALUES (
127 'message-1', 'thread-1', NULL, NULL, 'user', 0,
128 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z', '{"text":"needle"}'
129 )
130 `;
131 // An index that drifted from its rows, as a renumbering VACUUM would leave it.
132 yield* sql`
133 INSERT INTO orchestration_v2_message_search (orchestration_v2_message_search)
134 VALUES ('delete-all')
135 `;
136 yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
137 yield* sql`INSERT INTO orchestration_v2_legacy_imports (
138 thread_id, source_updated_at, shell_imported_at, transcript_imported_at, imported_message_count
139 ) VALUES ('imported', '2026-10-17', '2026-10-17', '2026-10-17', 0)`;
140 yield* sql`WITH RECURSIVE history(n) AS (
141 SELECT 1 UNION ALL SELECT n + 1 FROM history WHERE n < 51
142 ) INSERT INTO orchestration_command_receipts (
143 command_id, aggregate_kind, aggregate_id, accepted_at, result_sequence, status, command_type
144 ) SELECT 'legacy-' || n, 'thread', 'imported', '2026-10-17', 0, 'accepted', 'legacy' FROM history`;
145 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath })));
146​
147 const sizeBefore = (yield* fs.stat(dbPath)).size;
148 const refused = yield* Effect.gen(function* () {
149 const sql = yield* SqlClient.SqlClient;
150 yield* sql`SELECT value FROM retained_data`;
151 return yield* maintenance.compact(dbPath).pipe(Effect.flip);
152 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath })));
153 assert.equal(refused._tag, "DatabaseInUseError");
154 assert.equal((yield* fs.stat(dbPath)).size, sizeBefore);
155​
156 const clock = yield* Clock.Clock;
157 const pauses: number[] = [];
158 let activeNanos = 0n;
159 const result = yield* maintenance.compact(dbPath).pipe(
160 Effect.provideService(Clock.Clock, {
161 ...clock,
162 // Exceed the background budget whenever the compactor checks elapsed time.
163 monotonicTimeNanos: Effect.sync(() => (activeNanos += 30_000_000n)),
164 sleep: (duration) =>
165 Effect.sync(() => {
166 pauses.push(Duration.toMillis(duration));
167 }),
168 }),
169 );
170 assert.deepEqual(pauses, [], "offline doctor must not throttle compaction");
171 assert.equal(result.deletedReceiptCount, 51);
172 assert.isBelow(result.afterBytes, result.beforeBytes - 3 * 1024 * 1024);
173 yield* Effect.gen(function* () {
174 const sql = yield* SqlClient.SqlClient;
175 assert.deepEqual(yield* sql`PRAGMA auto_vacuum`, [{ auto_vacuum: 2 }]);
176 assert.deepEqual(yield* sql`SELECT value FROM retained_data`, [{ value: "keep" }]);
177 assert.deepEqual(
178 yield* sql`
179 SELECT messages.message_id AS "messageId"
180 FROM orchestration_v2_message_search AS search
181 INNER JOIN orchestration_v2_projection_messages AS messages
182 ON messages.rowid = search.rowid
183 WHERE orchestration_v2_message_search MATCH '"needle"'
184 `,
185 [{ messageId: "message-1" }],
186 );
187 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath, readonly: true })));
188 }).pipe(Effect.scoped),
189 );
190 },
191);