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