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

DatabaseMaintenance.test.ts

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