The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 05:30 UTC
feat(server): t3 doctor can delete the database from before 0.1.0 (#20948)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 17, 2026 at 10:24 UTC
13aa882c22d584de5388dfce3b3ca413387ba059
5 files changed
+223
-85
apps/server/src/cli/doctor.test.ts
+46
-41
@@ -7,46 +7,51 @@ import * as BootService from "../cloud/bootService.ts";
7
import { runDoctor } from "./doctor.ts";
8
import { DatabaseMaintenance } from "../persistence/DatabaseMaintenance.ts";
9
10
-it.effect("--fix reclaims space with the service paused, and --dry-run changes nothing", () =>
11
- Effect.gen(function* () {
12
- const calls: string[] = [];
13
- const doctor = (dryRun: boolean) =>
14
- runDoctor("/test/statev2.sqlite", { fix: true, dryRun, interactive: false }).pipe(
15
- Effect.provide(
16
- Layer.mergeAll(
17
- NodeServices.layer,
18
- Layer.mock(BootService.BootService)({
19
- withStopped: (operation) =>
20
- Effect.sync(() => calls.push("pause")).pipe(
21
- Effect.andThen(operation),
22
- Effect.ensuring(Effect.sync(() => calls.push("resume"))),
23
- ),
24
- }),
25
- Layer.succeed(DatabaseMaintenance, {
26
- // An unconverted database: reclaiming space is recommended.
27
- inspect: () =>
28
- Effect.succeed({
29
- databaseBytes: 2000,
30
- reclaimableBytes: 1000,
31
- incrementalVacuumEnabled: false,
32
- }),
33
- compact: () =>
34
- Effect.sync(() => {
35
- calls.push("compact");
36
- return {
37
- beforeBytes: 2000,
38
- afterBytes: 1000,
39
- deletedEventCount: 1,
40
- deletedReceiptCount: 0,
41
- };
42
- }),
43
- }),
10
+it.effect(
11
+ "--fix reclaims space with the service paused and keeps the V1 database, and --dry-run changes nothing",
12
+ () =>
13
+ Effect.gen(function* () {
14
+ const calls: string[] = [];
15
+ const doctor = (dryRun: boolean) =>
16
+ runDoctor("/test/statev2.sqlite", { fix: true, dryRun, interactive: false }).pipe(
17
+ Effect.provide(
18
+ Layer.mergeAll(
19
+ NodeServices.layer,
20
+ Layer.mock(BootService.BootService)({
21
+ withStopped: (operation) =>
22
+ Effect.sync(() => calls.push("pause")).pipe(
23
+ Effect.andThen(operation),
24
+ Effect.ensuring(Effect.sync(() => calls.push("resume"))),
25
+ ),
26
+ }),
27
+ Layer.succeed(DatabaseMaintenance, {
28
+ // An unconverted database: reclaiming space is recommended.
29
+ // A database from before 0.1.0 sits beside it; --fix must keep it.
30
+ inspect: () =>
31
+ Effect.succeed({
32
+ databaseBytes: 2000,
33
+ reclaimableBytes: 1000,
34
+ incrementalVacuumEnabled: false,
35
+ legacyDatabaseBytes: 4000,
36
+ }),
37
+ compact: () =>
38
+ Effect.sync(() => {
39
+ calls.push("compact");
40
+ return {
41
+ beforeBytes: 2000,
42
+ afterBytes: 1000,
43
+ deletedEventCount: 1,
44
+ deletedReceiptCount: 0,
45
+ };
46
+ }),
47
+ removeLegacyDatabase: () => Effect.sync(() => calls.push("remove legacy")),
48
+ }),
49
+ ),
50
),
45
- ),
46
- );
47
- yield* doctor(true);
48
- assert.deepEqual(calls, []);
49
- yield* doctor(false);
50
- assert.deepEqual(calls, ["pause", "compact", "resume"]);
51
- }),
51
+ );
52
+ yield* doctor(true);
53
+ assert.deepEqual(calls, []);
54
+ yield* doctor(false);
55
+ assert.deepEqual(calls, ["pause", "compact", "resume"]);
56
+ }),
57
);
apps/server/src/cli/doctor.ts
+57
-28
@@ -25,26 +25,47 @@ export const runDoctor = Effect.fn("runDoctor")(function* (
25
yield* Console.log(
26
`Database: ${formatBytes(status.databaseBytes)}, ${formatBytes(status.reclaimableBytes)} reclaimable.`,
27
);
28
- if (status.incrementalVacuumEnabled && status.reclaimableBytes === 0) {
29
- yield* Console.log("Nothing to repair.");
30
- return;
28
+ if (status.legacyDatabaseBytes !== null) {
29
+ yield* Console.log(
30
+ `Database from before 0.1.0: ${formatBytes(status.legacyDatabaseBytes)}, kept for rolling back.`,
31
+ );
32
}
32
- const recommended =
33
- !status.incrementalVacuumEnabled ||
34
- status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES;
33
const repairs = [
36
- {
37
- id: "database" as const,
38
- title: "Reclaim database space",
39
- description: status.incrementalVacuumEnabled
40
- ? "Returns unused space to disk."
41
- : "Returns unused space to disk and turns on automatic shrinking.",
42
- recommended,
43
- },
34
+ ...(status.incrementalVacuumEnabled && status.reclaimableBytes === 0
35
+ ? []
36
+ : [
37
+ {
38
+ id: "database" as const,
39
+ title: "Reclaim database space",
40
+ description: `${
41
+ status.incrementalVacuumEnabled
42
+ ? "Returns unused space to disk."
43
+ : "Returns unused space to disk and turns on automatic shrinking."
44
+ }\n Pauses the background service, if installed, while it runs and may need temporary disk space.`,
45
+ recommended:
46
+ !status.incrementalVacuumEnabled ||
47
+ status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES,
48
+ },
49
+ ]),
50
+ ...(status.legacyDatabaseBytes === null
51
+ ? []
52
+ : [
53
+ {
54
+ id: "legacy" as const,
55
+ title: "Delete the database from before 0.1.0",
56
+ description: `Frees ${formatBytes(status.legacyDatabaseBytes)}. Your threads and settings are already in the current database.\n Warning: after this, a T3 Code version before 0.1.0 starts with no threads or settings, so you can no longer roll back.`,
57
+ // Never chosen for you: deleting it gives up rolling back.
58
+ recommended: false,
59
+ },
60
+ ]),
61
];
62
+ if (repairs.length === 0) {
63
+ yield* Console.log("Nothing to repair.");
64
+ return;
65
+ }
66
for (const repair of repairs) {
67
yield* Console.log(
47
- `\n${repair.title}${repair.recommended ? " (recommended)" : ""}\n ${repair.description}\n Pauses the background service, if installed, while it runs and may need temporary disk space.`,
68
+ `\n${repair.title}${repair.recommended ? " (recommended)" : ""}\n ${repair.description}`,
69
);
70
}
71
if (options.dryRun) {
@@ -78,21 +99,29 @@ export const runDoctor = Effect.fn("runDoctor")(function* (
99
);
100
return;
101
}
81
- const service = yield* BootService.BootService;
82
- yield* Console.log("\nReclaiming database space. This can take several minutes...");
83
- // Report inside the pause: a repair that succeeded is worth knowing about
84
- // even when starting the service again fails afterwards.
85
- yield* service.withStopped(
86
- maintenance
87
- .compact(databasePath)
88
- .pipe(
89
- Effect.tap((result) =>
90
- Console.log(
91
- `Done: ${formatBytes(result.beforeBytes)} -> ${formatBytes(result.afterBytes)}, ${result.deletedEventCount} superseded events removed.`,
102
+ if (selected.includes("database")) {
103
+ const service = yield* BootService.BootService;
104
+ yield* Console.log("\nReclaiming database space. This can take several minutes...");
105
+ // Report inside the pause: a repair that succeeded is worth knowing about
106
+ // even when starting the service again fails afterwards.
107
+ yield* service.withStopped(
108
+ maintenance
109
+ .compact(databasePath)
110
+ .pipe(
111
+ Effect.tap((result) =>
112
+ Console.log(
113
+ `Done: ${formatBytes(result.beforeBytes)} -> ${formatBytes(result.afterBytes)}, ${result.deletedEventCount} superseded events removed.`,
114
+ ),
115
),
116
),
94
- ),
95
- );
117
+ );
118
+ }
119
+ if (selected.includes("legacy")) {
120
+ // Only versions before 0.1.0 open this file, so the service keeps running;
121
+ // the removal itself refuses while one of those still has it open.
122
+ yield* maintenance.removeLegacyDatabase(databasePath);
123
+ yield* Console.log("\nDeleted the database from before 0.1.0.");
124
+ }
125
});
126
127
export const doctorCommand = Command.make("doctor", {
apps/server/src/persistence/DatabaseMaintenance.test.ts
+39
@@ -31,6 +31,45 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))
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
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath })));
46
+ assert.isNull((yield* maintenance.inspect(dbPath)).legacyDatabaseBytes);
47
+
48
+ const openLegacy = NodeSqliteClient.layer({ filename: legacy });
49
+ yield* Effect.gen(function* () {
50
+ const sql = yield* SqlClient.SqlClient;
51
+ yield* sql`PRAGMA journal_mode = WAL`;
52
+ yield* sql`CREATE TABLE v1_data (value TEXT)`;
53
+ }).pipe(Effect.provide(openLegacy));
54
+ assert.isAbove((yield* maintenance.inspect(dbPath)).legacyDatabaseBytes ?? 0, 0);
55
+
56
+ // A version before 0.1.0 still running against it keeps it.
57
+ const refused = yield* Effect.gen(function* () {
58
+ const sql = yield* SqlClient.SqlClient;
59
+ yield* sql`SELECT value FROM v1_data`;
60
+ return yield* Effect.flip(maintenance.removeLegacyDatabase(dbPath));
61
+ }).pipe(Effect.provide(openLegacy));
62
+ assert.equal(refused._tag, "DatabaseInUseError");
63
+ assert.isTrue(yield* fs.exists(legacy));
64
+
65
+ yield* maintenance.removeLegacyDatabase(dbPath);
66
+ assert.isFalse(yield* fs.exists(legacy));
67
+ assert.isFalse(yield* fs.exists(`${legacy}-wal`));
68
+ assert.isTrue(yield* fs.exists(dbPath));
69
+ assert.isNull((yield* maintenance.inspect(dbPath)).legacyDatabaseBytes);
70
+ }).pipe(Effect.scoped),
71
+ );
72
+
73
it.effect("compacts an existing database offline only once its server has stopped", () =>
74
Effect.gen(function* () {
75
const fs = yield* FileSystem.FileSystem;
apps/server/src/persistence/DatabaseMaintenance.ts
+76
-16
@@ -3,6 +3,7 @@ import * as Context from "effect/Context";
3
import * as Effect from "effect/Effect";
4
import * as FileSystem from "effect/FileSystem";
5
import * as Layer from "effect/Layer";
6
+import * as Path from "effect/Path";
7
import * as Schema from "effect/Schema";
8
import * as SqlClient from "effect/sql/SqlClient";
9
import { isSqlError } from "effect/sql/SqlError";
@@ -25,7 +26,7 @@ export class DatabaseInUseError extends Schema.TaggedError<DatabaseInUseError>()
26
{ path: Schema.String, cause: Schema.Defect() },
27
) {
28
override get message() {
28
- return "Stop the T3 Code server and desktop app before compacting the database.";
29
+ return "Stop the T3 Code server and desktop app, including any version before 0.1.0, before repairing the database.";
30
}
31
}
32
@@ -56,6 +57,15 @@ export class DatabaseCompactError extends Schema.TaggedError<DatabaseCompactErro
57
}
58
}
59
60
+export class LegacyDatabaseRemoveError extends Schema.TaggedError<LegacyDatabaseRemoveError>()(
61
+ "LegacyDatabaseRemoveError",
62
+ { path: Schema.String, cause: Schema.Defect() },
63
+) {
64
+ override get message() {
65
+ return "Could not delete the database from before 0.1.0. Check that this user can write to the data directory.";
66
+ }
67
+}
68
+
69
/** Offline inspection and repair of a T3 state database, for `t3 doctor`. */
70
export class DatabaseMaintenance extends Context.Service<
71
DatabaseMaintenance,
@@ -65,6 +75,8 @@ export class DatabaseMaintenance extends Context.Service<
75
readonly databaseBytes: number;
76
readonly reclaimableBytes: number;
77
readonly incrementalVacuumEnabled: boolean;
78
+ /** Size of the database from before 0.1.0 still kept beside it, or null. */
79
+ readonly legacyDatabaseBytes: number | null;
80
},
81
DatabaseMissingError | DatabaseInspectError
82
>;
@@ -81,6 +93,13 @@ export class DatabaseMaintenance extends Context.Service<
93
| DatabaseProjectionsInvalidError
94
| DatabaseCompactError
95
>;
96
+ /**
97
+ * Deletes the database from before 0.1.0 kept beside this one. Versions
98
+ * before 0.1.0 read only that file; this one stays intact.
99
+ */
100
+ readonly removeLegacyDatabase: (
101
+ databasePath: string,
102
+ ) => Effect.Effect<void, DatabaseInUseError | LegacyDatabaseRemoveError>;
103
}
104
>()("t3/persistence/DatabaseMaintenance") {}
105
@@ -102,8 +121,31 @@ const readStorage = Effect.gen(function* () {
121
};
122
});
123
124
+/**
125
+ * Holds an exclusive lock on the connection's database. In WAL mode this is
126
+ * refused while any other connection has the file open, even an idle one,
127
+ * which is how a running server or desktop app is detected.
128
+ */
129
+const lockExclusively = (databasePath: string) =>
130
+ Effect.gen(function* () {
131
+ const sql = yield* SqlClient.SqlClient;
132
+ yield* sql`PRAGMA busy_timeout = 0`;
133
+ yield* sql`PRAGMA locking_mode = EXCLUSIVE`;
134
+ yield* sql`BEGIN EXCLUSIVE`.pipe(
135
+ Effect.mapError((cause) =>
136
+ isSqlError(cause) && cause.reason._tag === "LockTimeoutError"
137
+ ? new DatabaseInUseError({ path: databasePath, cause })
138
+ : cause,
139
+ ),
140
+ );
141
+ yield* sql`COMMIT`;
142
+ });
143
+
144
const make = Effect.gen(function* () {
145
const fs = yield* FileSystem.FileSystem;
146
+ const path = yield* Path.Path;
147
+ const legacyPath = (databasePath: string) =>
148
+ path.join(path.dirname(databasePath), "state.sqlite");
149
150
const locate = Effect.fn("DatabaseMaintenance.locate")(function* (databasePath: string) {
151
if (!(yield* fs.exists(databasePath))) {
@@ -114,9 +156,14 @@ const make = Effect.gen(function* () {
156
const inspect = Effect.fn("DatabaseMaintenance.inspect")(
157
function* (databasePath: string) {
158
yield* locate(databasePath);
117
- return yield* readStorage.pipe(
159
+ const storage = yield* readStorage.pipe(
160
Effect.provide(NodeSqliteClient.layer({ filename: databasePath, readonly: true })),
161
);
162
+ const legacy = legacyPath(databasePath);
163
+ const legacyDatabaseBytes = (yield* fs.exists(legacy))
164
+ ? Number((yield* fs.stat(legacy)).size)
165
+ : null;
166
+ return { ...storage, legacyDatabaseBytes };
167
},
168
(effect, databasePath) =>
169
effect.pipe(
@@ -132,19 +179,8 @@ const make = Effect.gen(function* () {
179
const beforeBytes = Number((yield* fs.stat(databasePath)).size);
180
const result = yield* Effect.gen(function* () {
181
const sql = yield* SqlClient.SqlClient;
135
- // Hold an exclusive lock through compaction and VACUUM. In WAL mode this
136
- // is refused while any other connection has the file open, even an idle
137
- // one, which is how a running server or desktop app is detected.
138
- yield* sql`PRAGMA busy_timeout = 0`;
139
- yield* sql`PRAGMA locking_mode = EXCLUSIVE`;
140
- yield* sql`BEGIN EXCLUSIVE`.pipe(
141
- Effect.mapError((cause) =>
142
- isSqlError(cause) && cause.reason._tag === "LockTimeoutError"
143
- ? new DatabaseInUseError({ path: databasePath, cause })
144
- : cause,
145
- ),
146
- );
147
- yield* sql`COMMIT`;
182
+ // Held through compaction and VACUUM.
183
+ yield* lockExclusively(databasePath);
184
const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
185
if (!(yield* maintenance.verify).valid) {
186
return yield* new DatabaseProjectionsInvalidError({ path: databasePath });
@@ -183,7 +219,31 @@ const make = Effect.gen(function* () {
219
),
220
);
221
186
- return DatabaseMaintenance.of({ inspect, compact });
222
+ const removeLegacyDatabase = Effect.fn("DatabaseMaintenance.removeLegacyDatabase")(
223
+ function* (databasePath: string) {
224
+ const legacy = legacyPath(databasePath);
225
+ if (!(yield* fs.exists(legacy))) return;
226
+ // A version before 0.1.0 may still be running against it. Keep the lock
227
+ // while deleting, and delete the database before its WAL so a failure
228
+ // never leaves it without committed transactions.
229
+ yield* Effect.gen(function* () {
230
+ yield* lockExclusively(legacy);
231
+ for (const suffix of ["", "-wal", "-shm"]) {
232
+ yield* fs.remove(legacy + suffix, { force: true });
233
+ }
234
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: legacy })));
235
+ },
236
+ (effect, databasePath) =>
237
+ effect.pipe(
238
+ Effect.mapError((cause) =>
239
+ cause._tag === "DatabaseInUseError"
240
+ ? cause
241
+ : new LegacyDatabaseRemoveError({ path: legacyPath(databasePath), cause }),
242
+ ),
243
+ ),
244
+ );
245
+
246
+ return DatabaseMaintenance.of({ inspect, compact, removeLegacyDatabase });
247
});
248
249
export const layer = Layer.effect(DatabaseMaintenance, make);
docs/user/background-service.md
+5
@@ -119,3 +119,8 @@ database through a temporary copy, so it needs free space of about the
119
database's size twice over: once in the system temporary directory (`TMPDIR`
120
or `/tmp` on Linux and macOS) and once next to the database for its
121
write-ahead log.
122
+
123
+If you upgraded from a version before 0.1.0, its database (`state.sqlite`) is
124
+still kept next to the current one so you can roll back. `t3 doctor` offers to
125
+delete it, but never selects that repair for you and `--fix` skips it: once it
126
+is gone, a version before 0.1.0 starts with no threads or settings.