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, 09:15 UTC
feat(server): t3 doctor reclaims database space (#19436)
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Julius Marminge committed
Oct 15, 2026 at 17:03 UTC
2b6611ca01316c07ea707cb5e159286818230615
11 files changed
+627
-9
apps/server/src/binCli.ts
+2
@@ -1,3 +1,4 @@
1
+import { doctorCommand } from "./cli/doctor.ts";
2
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
3
import * as NodeServices from "@effect/platform-node/NodeServices";
4
import * as Effect from "effect/Effect";
@@ -85,6 +86,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
86
servicePreflightCommand,
87
themeCommand,
88
traceCommand,
89
+ doctorCommand,
90
triageCommand,
91
cloudEnabled ? connectCommand : connectUnavailableCommand,
92
]),
apps/server/src/cli/doctor.test.ts
new
+52
@@ -0,0 +1,52 @@
1
+import * as NodeServices from "@effect/platform-node/NodeServices";
2
+import { assert, it } from "@effect/vitest";
3
+import * as Effect from "effect/Effect";
4
+import * as Layer from "effect/Layer";
5
+
6
+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
+ }),
44
+ ),
45
+ ),
46
+ );
47
+ yield* doctor(true);
48
+ assert.deepEqual(calls, []);
49
+ yield* doctor(false);
50
+ assert.deepEqual(calls, ["pause", "compact", "resume"]);
51
+ }),
52
+);
apps/server/src/cli/doctor.ts
new
+121
@@ -0,0 +1,121 @@
1
+import { DATABASE_COMPACTION_RECOMMENDED_BYTES } from "@t3tools/contracts";
2
+import * as Console from "effect/Console";
3
+import * as Effect from "effect/Effect";
4
+import * as Layer from "effect/Layer";
5
+import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
6
+
7
+import * as BootService from "../cloud/bootService.ts";
8
+import * as DatabaseMaintenance from "../persistence/DatabaseMaintenance.ts";
9
+import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
10
+import * as CliService from "./service.ts";
11
+
12
+const formatBytes = (bytes: number) =>
13
+ bytes >= 1024 ** 3
14
+ ? `${(bytes / 1024 ** 3).toFixed(2)} GiB`
15
+ : bytes >= 1024 ** 2
16
+ ? `${(bytes / 1024 ** 2).toFixed(1)} MiB`
17
+ : `${Math.ceil(bytes / 1024)} KiB`;
18
+
19
+export const runDoctor = Effect.fn("runDoctor")(function* (
20
+ databasePath: string,
21
+ options: { readonly fix: boolean; readonly dryRun: boolean; readonly interactive?: boolean },
22
+) {
23
+ const maintenance = yield* DatabaseMaintenance.DatabaseMaintenance;
24
+ const status = yield* maintenance.inspect(databasePath);
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;
31
+ }
32
+ const recommended =
33
+ !status.incrementalVacuumEnabled ||
34
+ status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES;
35
+ 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
+ },
44
+ ];
45
+ for (const repair of repairs) {
46
+ 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.`,
48
+ );
49
+ }
50
+ if (options.dryRun) {
51
+ yield* Console.log("\nDry run: nothing changed.");
52
+ return;
53
+ }
54
+ const interactive = options.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
55
+ if (!options.fix && !interactive) {
56
+ yield* Console.log(
57
+ "\nRun in a terminal to choose repairs, or pass --fix for the recommended ones.",
58
+ );
59
+ return;
60
+ }
61
+ const selected = options.fix
62
+ ? repairs.filter((repair) => repair.recommended).map((repair) => repair.id)
63
+ : yield* Prompt.run(
64
+ Prompt.MultiSelect({
65
+ message: "Choose repairs to run",
66
+ choices: repairs.map((repair) => ({
67
+ title: repair.title + (repair.recommended ? " (recommended)" : ""),
68
+ value: repair.id,
69
+ selected: repair.recommended,
70
+ })),
71
+ }),
72
+ ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed([]) }));
73
+ if (selected.length === 0) {
74
+ yield* Console.log(
75
+ options.fix
76
+ ? "No recommended repairs; nothing changed."
77
+ : "No repairs selected; nothing changed.",
78
+ );
79
+ return;
80
+ }
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.`,
92
+ ),
93
+ ),
94
+ ),
95
+ );
96
+});
97
+
98
+export const doctorCommand = Command.make("doctor", {
99
+ ...projectLocationFlags,
100
+ fix: Flag.Boolean("fix").pipe(
101
+ Flag.withDescription("Apply the recommended repairs without prompting."),
102
+ Flag.withDefault(false),
103
+ ),
104
+ dryRun: Flag.Boolean("dry-run").pipe(
105
+ Flag.withDescription("Show the repairs without changing anything, even with --fix."),
106
+ Flag.withDefault(false),
107
+ ),
108
+}).pipe(
109
+ Command.withDescription(
110
+ "Inspect this T3 Code data directory and repair it. Pauses and restarts the background service as needed.",
111
+ ),
112
+ Command.withHandler((flags) =>
113
+ Effect.gen(function* () {
114
+ const logLevel = yield* GlobalFlag.LogLevel;
115
+ const config = yield* resolveCliAuthConfig(flags, logLevel);
116
+ yield* runDoctor(config.dbPath, { fix: flags.fix, dryRun: flags.dryRun }).pipe(
117
+ Effect.provide(Layer.merge(DatabaseMaintenance.layer, CliService.layer(config))),
118
+ );
119
+ }),
120
+ ),
121
+);
apps/server/src/cli/service.test.ts
+1
@@ -102,6 +102,7 @@ function makeTestService(serviceStatus: BootService.BootServiceStatus) {
102
const restarts: Array<true> = [];
103
const service = BootService.BootService.of({
104
status: Effect.succeed(serviceStatus),
105
+ withStopped: (operation) => operation,
106
restart: Effect.sync(() => {
107
restarts.push(true);
108
return serviceStatus.installed;
apps/server/src/cloud/bootService.test.ts
+74
-1
@@ -168,6 +168,8 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
168
control.linger = "yes";
169
if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true;
170
if (!failed && command === "systemctl --user restart t3code.service") control.active = true;
171
+ // A stop that fails (a timeout, say) has still stopped the service.
172
+ if (command === "systemctl --user stop t3code.service") control.active = false;
173
if (
174
control.stateAfterStop !== undefined &&
175
(command === "systemctl --user stop t3code.service" ||
@@ -190,7 +192,11 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
192
: "",
193
stderr: "",
194
code: ChildProcessSpawner.ExitCode(
193
- failed || (input.args[1] === "is-active" && !control.active) ? 1 : 0,
195
+ failed ||
196
+ (input.args[1] === "is-active" && !control.active) ||
197
+ (input.args[1] === "is-enabled" && !control.enabled)
198
+ ? 1
199
+ : 0,
200
),
201
timedOut: false,
202
stdoutTruncated: false,
@@ -560,6 +566,73 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
566
}),
567
);
568
569
+ it.effect("pauses only this home's running service for maintenance, even when it fails", () =>
570
+ Effect.gen(function* () {
571
+ const { service, commands, control, makeService } = yield* makeHarness();
572
+ yield* service.install();
573
+ const failure = yield* service
574
+ .withStopped(
575
+ Effect.suspend(() => Effect.fail(control.active ? "running" : "repair failed")),
576
+ )
577
+ .pipe(Effect.flip);
578
+ expect(failure).toBe("repair failed");
579
+ expect(control.active).toBe(true);
580
+
581
+ // A failed stop skips the operation but still starts the service again.
582
+ control.failCommand = "systemctl --user stop t3code.service";
583
+ let ran = false;
584
+ const stopFailure = yield* service
585
+ .withStopped(
586
+ Effect.sync(() => {
587
+ ran = true;
588
+ }),
589
+ )
590
+ .pipe(Effect.flip);
591
+ expect(stopFailure).toMatchObject({
592
+ _tag: "BootServiceCommandError",
593
+ step: "stopping the installed service",
594
+ });
595
+ expect(ran).toBe(false);
596
+ expect(control.active).toBe(true);
597
+ control.failCommand = undefined;
598
+
599
+ // An enabled unit that is not active (crash-looping in auto-restart, say)
600
+ // is still stopped for the repair and started again afterwards.
601
+ control.active = false;
602
+ commands.length = 0;
603
+ yield* service.withStopped(Effect.sync(() => commands.push("repair")));
604
+ expect(commands).toEqual([
605
+ "systemctl --user is-enabled t3code.service",
606
+ "systemctl --user is-active t3code.service",
607
+ "systemctl --user stop t3code.service",
608
+ "repair",
609
+ "systemctl --user restart t3code.service",
610
+ ]);
611
+ expect(control.active).toBe(true);
612
+ // A running unit the user disabled is started again but stays disabled.
613
+ control.enabled = false;
614
+ yield* service.withStopped(Effect.void);
615
+ expect(control).toMatchObject({ active: true, enabled: false });
616
+ // A unit that was neither enabled nor active stays stopped.
617
+ control.active = false;
618
+ control.enabled = false;
619
+ commands.length = 0;
620
+ yield* service.withStopped(Effect.sync(() => commands.push("repair")));
621
+ expect(commands).toContain("systemctl --user stop t3code.service");
622
+ expect(commands).not.toContain("systemctl --user restart t3code.service");
623
+ expect(control.active).toBe(false);
624
+ control.enabled = true;
625
+ control.active = true;
626
+
627
+ const fs = yield* FileSystem.FileSystem;
628
+ const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-doctor-other-" });
629
+ const other = yield* makeService(undefined, "1.2.3", otherHome);
630
+ commands.length = 0;
631
+ expect(yield* other.withStopped(Effect.sync(() => control.active))).toBe(true);
632
+ expect(commands).toEqual([]);
633
+ }),
634
+ );
635
+
636
it.effect("restart stops and starts an installed service, and is a no-op otherwise", () =>
637
Effect.gen(function* () {
638
const { service, commands } = yield* makeHarness();
apps/server/src/cloud/bootService.ts
+67
-1
@@ -4,6 +4,7 @@ import * as Context from "effect/Context";
4
import * as DateTime from "effect/DateTime";
5
import * as Duration from "effect/Duration";
6
import * as Effect from "effect/Effect";
7
+import * as Exit from "effect/Exit";
8
import * as FileSystem from "effect/FileSystem";
9
import * as Layer from "effect/Layer";
10
import * as Option from "effect/Option";
@@ -547,6 +548,16 @@ export class BootService extends Context.Service<
548
* restarted.
549
*/
550
readonly restart: Effect.Effect<boolean, BootServiceError>;
551
+ /**
552
+ * Run `operation` while this home's installed service is stopped, then
553
+ * start it again when it was enabled (systemd) or loaded (launchd)
554
+ * beforehand. A service that belongs to another home is left alone. The
555
+ * service is started again even when stopping it failed; the operation's
556
+ * own failure is reported ahead of a failure to restart.
557
+ */
558
+ readonly withStopped: <A, E, R>(
559
+ operation: Effect.Effect<A, E, R>,
560
+ ) => Effect.Effect<A, E | BootServiceError, R>;
561
readonly uninstall: Effect.Effect<boolean, BootServiceError>;
562
readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
563
}
@@ -931,6 +942,61 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
942
Effect.withSpan("cloud.boot_service.restart"),
943
);
944
945
+ const withStopped = <A, E, R>(
946
+ operation: Effect.Effect<A, E, R>,
947
+ ): Effect.Effect<A, E | BootServiceError, R> =>
948
+ Effect.gen(function* () {
949
+ if (detectedManager === undefined) return yield* operation;
950
+ const manager = detectedManager;
951
+ const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
952
+ if (Option.isNone(unit)) return yield* operation;
953
+ const installedBaseDir = bootServiceBaseDirOf(unit.value);
954
+ if (
955
+ installedBaseDir === undefined ||
956
+ path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
957
+ ) {
958
+ return yield* operation;
959
+ }
960
+ // `is-active` fails while a crash-looping unit sits in `activating
961
+ // (auto-restart)`, and a throttled launchd job is loaded without a pid;
962
+ // both would start the server mid-repair. So the unit is always
963
+ // stopped, and started again when it was active, enabled or loaded
964
+ // before; a disabled unit caught crash-looping stays stopped.
965
+ const restore =
966
+ manager.kind === "systemd"
967
+ ? yield* Effect.map(
968
+ Effect.all(
969
+ [
970
+ probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
971
+ probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
972
+ ],
973
+ { concurrency: "unbounded" },
974
+ ),
975
+ ([enabled, active]) => succeeded(active) || succeeded(enabled),
976
+ )
977
+ : succeeded(
978
+ yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]),
979
+ );
980
+ return yield* Effect.acquireUseRelease(
981
+ // Every stop step is required when the service is to be restored: a
982
+ // step that was fine to skip during uninstall would leave the server
983
+ // holding the database. A stop that fails (a timeout, say) may still
984
+ // have stopped the service, so the restore below runs either way.
985
+ // Nothing to restore means nothing is expected to be loaded, and the
986
+ // stop is best-effort (launchd's bootout fails on an unloaded job).
987
+ runSteps(manager.stop.map((step) => ({ ...step, optional: !restore }))).pipe(Effect.exit),
988
+ (stopped): Effect.Effect<A, E | BootServiceError, R> =>
989
+ Exit.isSuccess(stopped) ? operation : Effect.failCause(stopped.cause),
990
+ (_, exit) => {
991
+ if (!restore) return Effect.void;
992
+ // Start only: `activate` would also enable a unit the user disabled.
993
+ // When the operation itself failed, its error is the one worth reporting.
994
+ const start = runSteps(manager.restart);
995
+ return Exit.isFailure(exit) ? Effect.ignore(start) : start;
996
+ },
997
+ );
998
+ }).pipe(Effect.withSpan("cloud.boot_service.with_stopped"));
999
+
1000
const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
1001
const manager = yield* requireManager;
1002
if (
@@ -994,7 +1060,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1060
Effect.withSpan("cloud.boot_service.status"),
1061
);
1062
997
- return BootService.of({ install, restart, uninstall, status });
1063
+ return BootService.of({ install, restart, withStopped, uninstall, status });
1064
});
1065
1066
export const layer = (input: {
apps/server/src/persistence/DatabaseMaintenance.test.ts
new
+86
@@ -0,0 +1,86 @@
1
+import * as NodeServices from "@effect/platform-node/NodeServices";
2
+import { assert, it } from "@effect/vitest";
3
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
4
+import * as Effect from "effect/Effect";
5
+import * as FileSystem from "effect/FileSystem";
6
+import * as Layer from "effect/Layer";
7
+import * as Path from "effect/Path";
8
+import * as SqlClient from "effect/sql/SqlClient";
9
+
10
+import * as DatabaseMaintenance from "./DatabaseMaintenance.ts";
11
+import * as Sqlite from "./Sqlite.ts";
12
+import * as EventStore from "../orchestration-v2/EventStore.ts";
13
+import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
14
+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
15
+
16
+it.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("compacts an existing database offline only once its server has stopped", () =>
35
+ Effect.gen(function* () {
36
+ const fs = yield* FileSystem.FileSystem;
37
+ const path = yield* Path.Path;
38
+ const maintenance = yield* DatabaseMaintenance.DatabaseMaintenance;
39
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-compact-" });
40
+ const dbPath = path.join(baseDir, "userdata", "statev2.sqlite");
41
+ // A migrated database created before incremental auto_vacuum, with free pages.
42
+ yield* Effect.flatMap(
43
+ ProjectionMaintenance.ProjectionMaintenanceV2,
44
+ (projections) => projections.rebuild,
45
+ ).pipe(
46
+ Effect.provide(
47
+ ProjectionMaintenance.layer.pipe(
48
+ Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
49
+ Layer.provideMerge(Sqlite.layerFromPath(dbPath)),
50
+ ),
51
+ ),
52
+ );
53
+ yield* Effect.gen(function* () {
54
+ const sql = yield* SqlClient.SqlClient;
55
+ yield* sql`PRAGMA auto_vacuum = NONE`;
56
+ yield* sql`VACUUM`;
57
+ yield* sql`CREATE TABLE retained_data (value TEXT)`;
58
+ yield* sql`INSERT INTO retained_data VALUES ('keep')`;
59
+ yield* sql`CREATE TABLE discarded_data (value BLOB)`;
60
+ yield* sql`INSERT INTO discarded_data VALUES (zeroblob(4194304))`;
61
+ yield* sql`DROP TABLE discarded_data`;
62
+ yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
63
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath })));
64
+
65
+ // A server that merely has the database open, like an idle one, is enough to refuse.
66
+ const sizeBefore = (yield* fs.stat(dbPath)).size;
67
+ const refused = yield* Effect.gen(function* () {
68
+ const sql = yield* SqlClient.SqlClient;
69
+ yield* sql`SELECT value FROM retained_data`;
70
+ return yield* maintenance.compact(dbPath).pipe(Effect.flip);
71
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath })));
72
+ assert.equal(refused._tag, "DatabaseInUseError");
73
+ assert.equal((yield* fs.stat(dbPath)).size, sizeBefore);
74
+
75
+ const result = yield* maintenance.compact(dbPath);
76
+ // The 4 MiB of free pages are returned to the filesystem.
77
+ assert.isBelow(result.afterBytes, result.beforeBytes - 3 * 1024 * 1024);
78
+ yield* Effect.gen(function* () {
79
+ const sql = yield* SqlClient.SqlClient;
80
+ assert.deepEqual(yield* sql`PRAGMA auto_vacuum`, [{ auto_vacuum: 2 }]);
81
+ assert.deepEqual(yield* sql`SELECT value FROM retained_data`, [{ value: "keep" }]);
82
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath, readonly: true })));
83
+ }).pipe(Effect.scoped),
84
+ );
85
+ },
86
+);
apps/server/src/persistence/DatabaseMaintenance.ts
new
+189
@@ -0,0 +1,189 @@
1
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
2
+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 Schema from "effect/Schema";
7
+import * as SqlClient from "effect/sql/SqlClient";
8
+import { isSqlError } from "effect/sql/SqlError";
9
+
10
+import * as EventStore from "../orchestration-v2/EventStore.ts";
11
+import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
12
+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
13
+
14
+export class DatabaseMissingError extends Schema.TaggedError<DatabaseMissingError>()(
15
+ "DatabaseMissingError",
16
+ { path: Schema.String },
17
+) {
18
+ override get message() {
19
+ return "No existing T3 Code database was found in this data directory.";
20
+ }
21
+}
22
+
23
+export class DatabaseInUseError extends Schema.TaggedError<DatabaseInUseError>()(
24
+ "DatabaseInUseError",
25
+ { path: Schema.String, cause: Schema.Defect() },
26
+) {
27
+ override get message() {
28
+ return "Stop the T3 Code server and desktop app before compacting the database.";
29
+ }
30
+}
31
+
32
+export class DatabaseProjectionsInvalidError extends Schema.TaggedError<DatabaseProjectionsInvalidError>()(
33
+ "DatabaseProjectionsInvalidError",
34
+ { path: Schema.String },
35
+) {
36
+ override get message() {
37
+ return "Database projections need repair before compaction. Start T3 Code once so it rebuilds them, then run doctor again. If this CLI is older than the one that wrote the database, update T3 Code first.";
38
+ }
39
+}
40
+
41
+export class DatabaseInspectError extends Schema.TaggedError<DatabaseInspectError>()(
42
+ "DatabaseInspectError",
43
+ { path: Schema.String, cause: Schema.Defect() },
44
+) {
45
+ override get message() {
46
+ return "Could not read the database. Check that this user can open it.";
47
+ }
48
+}
49
+
50
+export class DatabaseCompactError extends Schema.TaggedError<DatabaseCompactError>()(
51
+ "DatabaseCompactError",
52
+ { path: Schema.String, cause: Schema.Defect() },
53
+) {
54
+ override get message() {
55
+ return "Database compaction failed. Check that no other process has the database open and enough disk space is available.";
56
+ }
57
+}
58
+
59
+/** Offline inspection and repair of a T3 state database, for `t3 doctor`. */
60
+export class DatabaseMaintenance extends Context.Service<
61
+ DatabaseMaintenance,
62
+ {
63
+ readonly inspect: (databasePath: string) => Effect.Effect<
64
+ {
65
+ readonly databaseBytes: number;
66
+ readonly reclaimableBytes: number;
67
+ readonly incrementalVacuumEnabled: boolean;
68
+ },
69
+ DatabaseMissingError | DatabaseInspectError
70
+ >;
71
+ /** Compacts history, then VACUUMs into incremental auto_vacuum. Refuses while a server has it open. */
72
+ readonly compact: (databasePath: string) => Effect.Effect<
73
+ {
74
+ readonly beforeBytes: number;
75
+ readonly afterBytes: number;
76
+ readonly deletedEventCount: number;
77
+ readonly deletedReceiptCount: number;
78
+ },
79
+ | DatabaseMissingError
80
+ | DatabaseInUseError
81
+ | DatabaseProjectionsInvalidError
82
+ | DatabaseCompactError
83
+ >;
84
+ }
85
+>()("t3/persistence/DatabaseMaintenance") {}
86
+
87
+const isDomainError = Schema.is(
88
+ Schema.Union([DatabaseMissingError, DatabaseInUseError, DatabaseProjectionsInvalidError]),
89
+);
90
+
91
+const readStorage = Effect.gen(function* () {
92
+ const sql = yield* SqlClient.SqlClient;
93
+ const pages = yield* sql<{ readonly page_count: number }>`PRAGMA page_count`;
94
+ const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
95
+ const size = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
96
+ const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
97
+ const pageSize = size[0]?.page_size ?? 0;
98
+ return {
99
+ databaseBytes: (pages[0]?.page_count ?? 0) * pageSize,
100
+ reclaimableBytes: (free[0]?.freelist_count ?? 0) * pageSize,
101
+ incrementalVacuumEnabled: mode[0]?.auto_vacuum === 2,
102
+ };
103
+});
104
+
105
+const make = Effect.gen(function* () {
106
+ const fs = yield* FileSystem.FileSystem;
107
+
108
+ const locate = Effect.fn("DatabaseMaintenance.locate")(function* (databasePath: string) {
109
+ if (!(yield* fs.exists(databasePath))) {
110
+ return yield* new DatabaseMissingError({ path: databasePath });
111
+ }
112
+ });
113
+
114
+ const inspect = Effect.fn("DatabaseMaintenance.inspect")(
115
+ function* (databasePath: string) {
116
+ yield* locate(databasePath);
117
+ return yield* readStorage.pipe(
118
+ Effect.provide(NodeSqliteClient.layer({ filename: databasePath, readonly: true })),
119
+ );
120
+ },
121
+ (effect, databasePath) =>
122
+ effect.pipe(
123
+ Effect.mapError((cause) =>
124
+ isDomainError(cause) ? cause : new DatabaseInspectError({ path: databasePath, cause }),
125
+ ),
126
+ ),
127
+ );
128
+
129
+ const compact = Effect.fn("DatabaseMaintenance.compact")(
130
+ function* (databasePath: string) {
131
+ yield* locate(databasePath);
132
+ const beforeBytes = Number((yield* fs.stat(databasePath)).size);
133
+ const result = yield* Effect.gen(function* () {
134
+ 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`;
148
+ const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
149
+ if (!(yield* maintenance.verify).valid) {
150
+ return yield* new DatabaseProjectionsInvalidError({ path: databasePath });
151
+ }
152
+ const summary = yield* maintenance.compactEventStore;
153
+ if (!(yield* maintenance.verify).valid) {
154
+ return yield* new DatabaseProjectionsInvalidError({ path: databasePath });
155
+ }
156
+ // VACUUM rebuilds the file, which is the only way to switch an existing
157
+ // database to incremental auto_vacuum; the server reclaims online after.
158
+ yield* sql`PRAGMA auto_vacuum = INCREMENTAL`;
159
+ yield* sql`VACUUM`;
160
+ yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
161
+ return summary;
162
+ }).pipe(
163
+ Effect.provide(
164
+ ProjectionMaintenance.layer.pipe(
165
+ Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
166
+ Layer.provideMerge(NodeSqliteClient.layer({ filename: databasePath })),
167
+ ),
168
+ ),
169
+ );
170
+ const afterBytes = Number((yield* fs.stat(databasePath)).size);
171
+ return {
172
+ beforeBytes,
173
+ afterBytes,
174
+ deletedEventCount: result.deletedEventCount,
175
+ deletedReceiptCount: result.deletedReceiptCount,
176
+ };
177
+ },
178
+ (effect, databasePath) =>
179
+ effect.pipe(
180
+ Effect.mapError((cause) =>
181
+ isDomainError(cause) ? cause : new DatabaseCompactError({ path: databasePath, cause }),
182
+ ),
183
+ ),
184
+ );
185
+
186
+ return DatabaseMaintenance.of({ inspect, compact });
187
+});
188
+
189
+export const layer = Layer.effect(DatabaseMaintenance, make);
docs/user/background-service.md
+24
@@ -95,3 +95,27 @@ Downloads, it may need Full Disk Access for the `t3` executable listed in
95
96
For failures after signing in to T3 Connect, see
97
[connection troubleshooting](./remote-access.md#t3-connect-troubleshooting).
98
+
99
+## Reclaim database space
100
+
101
+T3 Code removes superseded internal history on its own while it runs; your
102
+conversations are kept. Databases created before this shrank automatically
103
+still hold the freed space on disk until a one-time offline repair returns it
104
+and turns on automatic shrinking. Settings > Storage (web and desktop) or
105
+Settings > Maintenance (mobile) suggests the repair when at least 1 GiB can be
106
+reclaimed.
107
+
108
+Run `t3 doctor` on the machine that hosts the environment. It reports the
109
+database size and the space it can reclaim, then asks which repairs to run;
110
+pass `--fix` to run the recommended ones without a prompt (for scripts), or
111
+`--dry-run` to only report. An installed background service for the same data
112
+directory is stopped for the repair and started again afterwards, also when
113
+the repair fails. Quit a server you started by hand, or the desktop app, first:
114
+the repair refuses to touch a database that is in use. Use `--base-dir` for a
115
+different data directory.
116
+
117
+The repair can take several minutes on a large database. It rebuilds the
118
+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.
docs/user/install.md
+8
-7
@@ -25,13 +25,14 @@ afterwards, that directory is not on your `PATH` yet; the installer prints the
25
line to add. Set `T3CODE_CHANNEL=nightly` to install the nightly train, or
26
`T3CODE_VERSION` to pin an exact version.
27
28
-| Task | Command |
29
-| ------------------------------------------------ | --------------------------------------------------------- |
30
-| Start the server and open the web app | `t3` |
31
-| Start the server without a browser | `t3 serve` |
32
-| Keep it running in the background (macOS, Linux) | `t3 service install` ([details](./background-service.md)) |
33
-| Move to the newest release | `t3 update` |
34
-| Remove it again | `t3 uninstall` |
28
+| Task | Command |
29
+| ------------------------------------------------ | ----------------------------------------------------------------------- |
30
+| Start the server and open the web app | `t3` |
31
+| Start the server without a browser | `t3 serve` |
32
+| Keep it running in the background (macOS, Linux) | `t3 service install` ([details](./background-service.md)) |
33
+| Move to the newest release | `t3 update` |
34
+| Reclaim database space | `t3 doctor` ([details](./background-service.md#reclaim-database-space)) |
35
+| Remove it again | `t3 uninstall` |
36
37
Run `t3 help` or `t3 --help` for the full reference. To start in a new working
38
directory, use an explicit path such as `t3 ./my-project`. A bare directory name
packages/contracts/src/settings.ts
+3
@@ -1074,6 +1074,9 @@ const NULLABLE_PROJECT_SETTINGS_OVERRIDES: ReadonlySet<ProjectScopedServerSettin
1074
"sidebarAutoSettleAfterDays",
1075
]);
1076
1077
+/** Reclaimable bytes from which the offline `t3 doctor` repair is worth suggesting. */
1078
+export const DATABASE_COMPACTION_RECOMMENDED_BYTES = 1024 ** 3;
1079
+
1080
export const StorageCleanupReportEntry = Schema.Struct({
1081
kind: Schema.Literals(["worktree", "browser-artifacts", "logs"]),
1082
outcome: Schema.Literals(["removed", "kept", "failed"]),