Skip to content
TypeScript

feat(server): t3 doctor reclaims database space (#19436)

Julius Marminge2b6611ca0131
diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts
index 0a90cca5650..a4a836cf582 100644
--- a/apps/server/src/binCli.ts
+++ b/apps/server/src/binCli.ts
@@ -1,3 +1,4 @@
+import { doctorCommand } from "./cli/doctor.ts";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
@@ -85,6 +86,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
servicePreflightCommand,
themeCommand,
traceCommand,
+ doctorCommand,
triageCommand,
cloudEnabled ? connectCommand : connectUnavailableCommand,
]),
diff --git a/apps/server/src/cli/doctor.test.ts b/apps/server/src/cli/doctor.test.ts
new file mode 100644
index 00000000000..4197b560881
--- /dev/null
+++ b/apps/server/src/cli/doctor.test.ts
@@ -0,0 +1,52 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { assert, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+
+import * as BootService from "../cloud/bootService.ts";
+import { runDoctor } from "./doctor.ts";
+import { DatabaseMaintenance } from "../persistence/DatabaseMaintenance.ts";
+
+it.effect("--fix reclaims space with the service paused, and --dry-run changes nothing", () =>
+ Effect.gen(function* () {
+ const calls: string[] = [];
+ const doctor = (dryRun: boolean) =>
+ runDoctor("/test/statev2.sqlite", { fix: true, dryRun, interactive: false }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ NodeServices.layer,
+ Layer.mock(BootService.BootService)({
+ withStopped: (operation) =>
+ Effect.sync(() => calls.push("pause")).pipe(
+ Effect.andThen(operation),
+ Effect.ensuring(Effect.sync(() => calls.push("resume"))),
+ ),
+ }),
+ Layer.succeed(DatabaseMaintenance, {
+ // An unconverted database: reclaiming space is recommended.
+ inspect: () =>
+ Effect.succeed({
+ databaseBytes: 2000,
+ reclaimableBytes: 1000,
+ incrementalVacuumEnabled: false,
+ }),
+ compact: () =>
+ Effect.sync(() => {
+ calls.push("compact");
+ return {
+ beforeBytes: 2000,
+ afterBytes: 1000,
+ deletedEventCount: 1,
+ deletedReceiptCount: 0,
+ };
+ }),
+ }),
+ ),
+ ),
+ );
+ yield* doctor(true);
+ assert.deepEqual(calls, []);
+ yield* doctor(false);
+ assert.deepEqual(calls, ["pause", "compact", "resume"]);
+ }),
+);
diff --git a/apps/server/src/cli/doctor.ts b/apps/server/src/cli/doctor.ts
new file mode 100644
index 00000000000..62f25277ea9
--- /dev/null
+++ b/apps/server/src/cli/doctor.ts
@@ -0,0 +1,121 @@
+import { DATABASE_COMPACTION_RECOMMENDED_BYTES } from "@t3tools/contracts";
+import * as Console from "effect/Console";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
+
+import * as BootService from "../cloud/bootService.ts";
+import * as DatabaseMaintenance from "../persistence/DatabaseMaintenance.ts";
+import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
+import * as CliService from "./service.ts";
+
+const formatBytes = (bytes: number) =>
+ bytes >= 1024 ** 3
+ ? `${(bytes / 1024 ** 3).toFixed(2)} GiB`
+ : bytes >= 1024 ** 2
+ ? `${(bytes / 1024 ** 2).toFixed(1)} MiB`
+ : `${Math.ceil(bytes / 1024)} KiB`;
+
+export const runDoctor = Effect.fn("runDoctor")(function* (
+ databasePath: string,
+ options: { readonly fix: boolean; readonly dryRun: boolean; readonly interactive?: boolean },
+) {
+ const maintenance = yield* DatabaseMaintenance.DatabaseMaintenance;
+ const status = yield* maintenance.inspect(databasePath);
+ yield* Console.log(
+ `Database: ${formatBytes(status.databaseBytes)}, ${formatBytes(status.reclaimableBytes)} reclaimable.`,
+ );
+ if (status.incrementalVacuumEnabled && status.reclaimableBytes === 0) {
+ yield* Console.log("Nothing to repair.");
+ return;
+ }
+ const recommended =
+ !status.incrementalVacuumEnabled ||
+ status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES;
+ const repairs = [
+ {
+ id: "database" as const,
+ title: "Reclaim database space",
+ description: status.incrementalVacuumEnabled
+ ? "Returns unused space to disk."
+ : "Returns unused space to disk and turns on automatic shrinking.",
+ recommended,
+ },
+ ];
+ for (const repair of repairs) {
+ yield* Console.log(
+ `\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.`,
+ );
+ }
+ if (options.dryRun) {
+ yield* Console.log("\nDry run: nothing changed.");
+ return;
+ }
+ const interactive = options.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
+ if (!options.fix && !interactive) {
+ yield* Console.log(
+ "\nRun in a terminal to choose repairs, or pass --fix for the recommended ones.",
+ );
+ return;
+ }
+ const selected = options.fix
+ ? repairs.filter((repair) => repair.recommended).map((repair) => repair.id)
+ : yield* Prompt.run(
+ Prompt.MultiSelect({
+ message: "Choose repairs to run",
+ choices: repairs.map((repair) => ({
+ title: repair.title + (repair.recommended ? " (recommended)" : ""),
+ value: repair.id,
+ selected: repair.recommended,
+ })),
+ }),
+ ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed([]) }));
+ if (selected.length === 0) {
+ yield* Console.log(
+ options.fix
+ ? "No recommended repairs; nothing changed."
+ : "No repairs selected; nothing changed.",
+ );
+ return;
+ }
+ const service = yield* BootService.BootService;
+ yield* Console.log("\nReclaiming database space. This can take several minutes...");
+ // Report inside the pause: a repair that succeeded is worth knowing about
+ // even when starting the service again fails afterwards.
+ yield* service.withStopped(
+ maintenance
+ .compact(databasePath)
+ .pipe(
+ Effect.tap((result) =>
+ Console.log(
+ `Done: ${formatBytes(result.beforeBytes)} -> ${formatBytes(result.afterBytes)}, ${result.deletedEventCount} superseded events removed.`,
+ ),
+ ),
+ ),
+ );
+});
+
+export const doctorCommand = Command.make("doctor", {
+ ...projectLocationFlags,
+ fix: Flag.Boolean("fix").pipe(
+ Flag.withDescription("Apply the recommended repairs without prompting."),
+ Flag.withDefault(false),
+ ),
+ dryRun: Flag.Boolean("dry-run").pipe(
+ Flag.withDescription("Show the repairs without changing anything, even with --fix."),
+ Flag.withDefault(false),
+ ),
+}).pipe(
+ Command.withDescription(
+ "Inspect this T3 Code data directory and repair it. Pauses and restarts the background service as needed.",
+ ),
+ Command.withHandler((flags) =>
+ Effect.gen(function* () {
+ const logLevel = yield* GlobalFlag.LogLevel;
+ const config = yield* resolveCliAuthConfig(flags, logLevel);
+ yield* runDoctor(config.dbPath, { fix: flags.fix, dryRun: flags.dryRun }).pipe(
+ Effect.provide(Layer.merge(DatabaseMaintenance.layer, CliService.layer(config))),
+ );
+ }),
+ ),
+);
diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.ts
index 077274fc215..1f1b70dce8a 100644
--- a/apps/server/src/cli/service.test.ts
+++ b/apps/server/src/cli/service.test.ts
@@ -102,6 +102,7 @@ function makeTestService(serviceStatus: BootService.BootServiceStatus) {
const restarts: Array<true> = [];
const service = BootService.BootService.of({
status: Effect.succeed(serviceStatus),
+ withStopped: (operation) => operation,
restart: Effect.sync(() => {
restarts.push(true);
return serviceStatus.installed;
diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts
index 65bf0818a97..7182e59ab72 100644
--- a/apps/server/src/cloud/bootService.test.ts
+++ b/apps/server/src/cloud/bootService.test.ts
@@ -168,6 +168,8 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
control.linger = "yes";
if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true;
if (!failed && command === "systemctl --user restart t3code.service") control.active = true;
+ // A stop that fails (a timeout, say) has still stopped the service.
+ if (command === "systemctl --user stop t3code.service") control.active = false;
if (
control.stateAfterStop !== undefined &&
(command === "systemctl --user stop t3code.service" ||
@@ -190,7 +192,11 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
: "",
stderr: "",
code: ChildProcessSpawner.ExitCode(
- failed || (input.args[1] === "is-active" && !control.active) ? 1 : 0,
+ failed ||
+ (input.args[1] === "is-active" && !control.active) ||
+ (input.args[1] === "is-enabled" && !control.enabled)
+ ? 1
+ : 0,
),
timedOut: false,
stdoutTruncated: false,
@@ -560,6 +566,73 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
}),
);
+ it.effect("pauses only this home's running service for maintenance, even when it fails", () =>
+ Effect.gen(function* () {
+ const { service, commands, control, makeService } = yield* makeHarness();
+ yield* service.install();
+ const failure = yield* service
+ .withStopped(
+ Effect.suspend(() => Effect.fail(control.active ? "running" : "repair failed")),
+ )
+ .pipe(Effect.flip);
+ expect(failure).toBe("repair failed");
+ expect(control.active).toBe(true);
+
+ // A failed stop skips the operation but still starts the service again.
+ control.failCommand = "systemctl --user stop t3code.service";
+ let ran = false;
+ const stopFailure = yield* service
+ .withStopped(
+ Effect.sync(() => {
+ ran = true;
+ }),
+ )
+ .pipe(Effect.flip);
+ expect(stopFailure).toMatchObject({
+ _tag: "BootServiceCommandError",
+ step: "stopping the installed service",
+ });
+ expect(ran).toBe(false);
+ expect(control.active).toBe(true);
+ control.failCommand = undefined;
+
+ // An enabled unit that is not active (crash-looping in auto-restart, say)
+ // is still stopped for the repair and started again afterwards.
+ control.active = false;
+ commands.length = 0;
+ yield* service.withStopped(Effect.sync(() => commands.push("repair")));
+ expect(commands).toEqual([
+ "systemctl --user is-enabled t3code.service",
+ "systemctl --user is-active t3code.service",
+ "systemctl --user stop t3code.service",
+ "repair",
+ "systemctl --user restart t3code.service",
+ ]);
+ expect(control.active).toBe(true);
+ // A running unit the user disabled is started again but stays disabled.
+ control.enabled = false;
+ yield* service.withStopped(Effect.void);
+ expect(control).toMatchObject({ active: true, enabled: false });
+ // A unit that was neither enabled nor active stays stopped.
+ control.active = false;
+ control.enabled = false;
+ commands.length = 0;
+ yield* service.withStopped(Effect.sync(() => commands.push("repair")));
+ expect(commands).toContain("systemctl --user stop t3code.service");
+ expect(commands).not.toContain("systemctl --user restart t3code.service");
+ expect(control.active).toBe(false);
+ control.enabled = true;
+ control.active = true;
+
+ const fs = yield* FileSystem.FileSystem;
+ const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-doctor-other-" });
+ const other = yield* makeService(undefined, "1.2.3", otherHome);
+ commands.length = 0;
+ expect(yield* other.withStopped(Effect.sync(() => control.active))).toBe(true);
+ expect(commands).toEqual([]);
+ }),
+ );
+
it.effect("restart stops and starts an installed service, and is a no-op otherwise", () =>
Effect.gen(function* () {
const { service, commands } = yield* makeHarness();
diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts
index 1d7d50b1318..27dbf3a0f32 100644
--- a/apps/server/src/cloud/bootService.ts
+++ b/apps/server/src/cloud/bootService.ts
@@ -4,6 +4,7 @@ import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
+import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -547,6 +548,16 @@ export class BootService extends Context.Service<
* restarted.
*/
readonly restart: Effect.Effect<boolean, BootServiceError>;
+ /**
+ * Run `operation` while this home's installed service is stopped, then
+ * start it again when it was enabled (systemd) or loaded (launchd)
+ * beforehand. A service that belongs to another home is left alone. The
+ * service is started again even when stopping it failed; the operation's
+ * own failure is reported ahead of a failure to restart.
+ */
+ readonly withStopped: <A, E, R>(
+ operation: Effect.Effect<A, E, R>,
+ ) => Effect.Effect<A, E | BootServiceError, R>;
readonly uninstall: Effect.Effect<boolean, BootServiceError>;
readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
}
@@ -931,6 +942,61 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
Effect.withSpan("cloud.boot_service.restart"),
);
+ const withStopped = <A, E, R>(
+ operation: Effect.Effect<A, E, R>,
+ ): Effect.Effect<A, E | BootServiceError, R> =>
+ Effect.gen(function* () {
+ if (detectedManager === undefined) return yield* operation;
+ const manager = detectedManager;
+ const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
+ if (Option.isNone(unit)) return yield* operation;
+ const installedBaseDir = bootServiceBaseDirOf(unit.value);
+ if (
+ installedBaseDir === undefined ||
+ path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
+ ) {
+ return yield* operation;
+ }
+ // `is-active` fails while a crash-looping unit sits in `activating
+ // (auto-restart)`, and a throttled launchd job is loaded without a pid;
+ // both would start the server mid-repair. So the unit is always
+ // stopped, and started again when it was active, enabled or loaded
+ // before; a disabled unit caught crash-looping stays stopped.
+ const restore =
+ manager.kind === "systemd"
+ ? yield* Effect.map(
+ Effect.all(
+ [
+ probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
+ probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
+ ],
+ { concurrency: "unbounded" },
+ ),
+ ([enabled, active]) => succeeded(active) || succeeded(enabled),
+ )
+ : succeeded(
+ yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]),
+ );
+ return yield* Effect.acquireUseRelease(
+ // Every stop step is required when the service is to be restored: a
+ // step that was fine to skip during uninstall would leave the server
+ // holding the database. A stop that fails (a timeout, say) may still
+ // have stopped the service, so the restore below runs either way.
+ // Nothing to restore means nothing is expected to be loaded, and the
+ // stop is best-effort (launchd's bootout fails on an unloaded job).
+ runSteps(manager.stop.map((step) => ({ ...step, optional: !restore }))).pipe(Effect.exit),
+ (stopped): Effect.Effect<A, E | BootServiceError, R> =>
+ Exit.isSuccess(stopped) ? operation : Effect.failCause(stopped.cause),
+ (_, exit) => {
+ if (!restore) return Effect.void;
+ // Start only: `activate` would also enable a unit the user disabled.
+ // When the operation itself failed, its error is the one worth reporting.
+ const start = runSteps(manager.restart);
+ return Exit.isFailure(exit) ? Effect.ignore(start) : start;
+ },
+ );
+ }).pipe(Effect.withSpan("cloud.boot_service.with_stopped"));
+
const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
const manager = yield* requireManager;
if (
@@ -994,7 +1060,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
Effect.withSpan("cloud.boot_service.status"),
);
- return BootService.of({ install, restart, uninstall, status });
+ return BootService.of({ install, restart, withStopped, uninstall, status });
});
export const layer = (input: {
diff --git a/apps/server/src/persistence/DatabaseMaintenance.test.ts b/apps/server/src/persistence/DatabaseMaintenance.test.ts
new file mode 100644
index 00000000000..0d597c5b10d
--- /dev/null
+++ b/apps/server/src/persistence/DatabaseMaintenance.test.ts
@@ -0,0 +1,86 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { assert, it } from "@effect/vitest";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
+import * as Path from "effect/Path";
+import * as SqlClient from "effect/sql/SqlClient";
+
+import * as DatabaseMaintenance from "./DatabaseMaintenance.ts";
+import * as Sqlite from "./Sqlite.ts";
+import * as EventStore from "../orchestration-v2/EventStore.ts";
+import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
+
+it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))(
+ "DatabaseMaintenance",
+ (it) => {
+ it.effect("reports an unreadable database as an inspection failure", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const maintenance = yield* DatabaseMaintenance.DatabaseMaintenance;
+ const dbPath = path.join(
+ yield* fs.makeTempDirectoryScoped({ prefix: "t3-inspect-" }),
+ "statev2.sqlite",
+ );
+ yield* fs.writeFileString(dbPath, "not a database");
+ const failure = yield* Effect.flip(maintenance.inspect(dbPath));
+ assert.equal(failure._tag, "DatabaseInspectError");
+ }).pipe(Effect.scoped),
+ );
+
+ it.effect("compacts an existing database offline only once its server has stopped", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const maintenance = yield* DatabaseMaintenance.DatabaseMaintenance;
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-compact-" });
+ const dbPath = path.join(baseDir, "userdata", "statev2.sqlite");
+ // A migrated database created before incremental auto_vacuum, with free pages.
+ yield* Effect.flatMap(
+ ProjectionMaintenance.ProjectionMaintenanceV2,
+ (projections) => projections.rebuild,
+ ).pipe(
+ Effect.provide(
+ ProjectionMaintenance.layer.pipe(
+ Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
+ Layer.provideMerge(Sqlite.layerFromPath(dbPath)),
+ ),
+ ),
+ );
+ yield* Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* sql`PRAGMA auto_vacuum = NONE`;
+ yield* sql`VACUUM`;
+ yield* sql`CREATE TABLE retained_data (value TEXT)`;
+ yield* sql`INSERT INTO retained_data VALUES ('keep')`;
+ yield* sql`CREATE TABLE discarded_data (value BLOB)`;
+ yield* sql`INSERT INTO discarded_data VALUES (zeroblob(4194304))`;
+ yield* sql`DROP TABLE discarded_data`;
+ yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath })));
+
+ // A server that merely has the database open, like an idle one, is enough to refuse.
+ const sizeBefore = (yield* fs.stat(dbPath)).size;
+ const refused = yield* Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* sql`SELECT value FROM retained_data`;
+ return yield* maintenance.compact(dbPath).pipe(Effect.flip);
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath })));
+ assert.equal(refused._tag, "DatabaseInUseError");
+ assert.equal((yield* fs.stat(dbPath)).size, sizeBefore);
+
+ const result = yield* maintenance.compact(dbPath);
+ // The 4 MiB of free pages are returned to the filesystem.
+ assert.isBelow(result.afterBytes, result.beforeBytes - 3 * 1024 * 1024);
+ yield* Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ assert.deepEqual(yield* sql`PRAGMA auto_vacuum`, [{ auto_vacuum: 2 }]);
+ assert.deepEqual(yield* sql`SELECT value FROM retained_data`, [{ value: "keep" }]);
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath, readonly: true })));
+ }).pipe(Effect.scoped),
+ );
+ },
+);
diff --git a/apps/server/src/persistence/DatabaseMaintenance.ts b/apps/server/src/persistence/DatabaseMaintenance.ts
new file mode 100644
index 00000000000..bd794a1e269
--- /dev/null
+++ b/apps/server/src/persistence/DatabaseMaintenance.ts
@@ -0,0 +1,189 @@
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
+import * as Schema from "effect/Schema";
+import * as SqlClient from "effect/sql/SqlClient";
+import { isSqlError } from "effect/sql/SqlError";
+
+import * as EventStore from "../orchestration-v2/EventStore.ts";
+import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
+
+export class DatabaseMissingError extends Schema.TaggedError<DatabaseMissingError>()(
+ "DatabaseMissingError",
+ { path: Schema.String },
+) {
+ override get message() {
+ return "No existing T3 Code database was found in this data directory.";
+ }
+}
+
+export class DatabaseInUseError extends Schema.TaggedError<DatabaseInUseError>()(
+ "DatabaseInUseError",
+ { path: Schema.String, cause: Schema.Defect() },
+) {
+ override get message() {
+ return "Stop the T3 Code server and desktop app before compacting the database.";
+ }
+}
+
+export class DatabaseProjectionsInvalidError extends Schema.TaggedError<DatabaseProjectionsInvalidError>()(
+ "DatabaseProjectionsInvalidError",
+ { path: Schema.String },
+) {
+ override get message() {
+ 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.";
+ }
+}
+
+export class DatabaseInspectError extends Schema.TaggedError<DatabaseInspectError>()(
+ "DatabaseInspectError",
+ { path: Schema.String, cause: Schema.Defect() },
+) {
+ override get message() {
+ return "Could not read the database. Check that this user can open it.";
+ }
+}
+
+export class DatabaseCompactError extends Schema.TaggedError<DatabaseCompactError>()(
+ "DatabaseCompactError",
+ { path: Schema.String, cause: Schema.Defect() },
+) {
+ override get message() {
+ return "Database compaction failed. Check that no other process has the database open and enough disk space is available.";
+ }
+}
+
+/** Offline inspection and repair of a T3 state database, for `t3 doctor`. */
+export class DatabaseMaintenance extends Context.Service<
+ DatabaseMaintenance,
+ {
+ readonly inspect: (databasePath: string) => Effect.Effect<
+ {
+ readonly databaseBytes: number;
+ readonly reclaimableBytes: number;
+ readonly incrementalVacuumEnabled: boolean;
+ },
+ DatabaseMissingError | DatabaseInspectError
+ >;
+ /** Compacts history, then VACUUMs into incremental auto_vacuum. Refuses while a server has it open. */
+ readonly compact: (databasePath: string) => Effect.Effect<
+ {
+ readonly beforeBytes: number;
+ readonly afterBytes: number;
+ readonly deletedEventCount: number;
+ readonly deletedReceiptCount: number;
+ },
+ | DatabaseMissingError
+ | DatabaseInUseError
+ | DatabaseProjectionsInvalidError
+ | DatabaseCompactError
+ >;
+ }
+>()("t3/persistence/DatabaseMaintenance") {}
+
+const isDomainError = Schema.is(
+ Schema.Union([DatabaseMissingError, DatabaseInUseError, DatabaseProjectionsInvalidError]),
+);
+
+const readStorage = Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ const pages = yield* sql<{ readonly page_count: number }>`PRAGMA page_count`;
+ const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
+ const size = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
+ const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
+ const pageSize = size[0]?.page_size ?? 0;
+ return {
+ databaseBytes: (pages[0]?.page_count ?? 0) * pageSize,
+ reclaimableBytes: (free[0]?.freelist_count ?? 0) * pageSize,
+ incrementalVacuumEnabled: mode[0]?.auto_vacuum === 2,
+ };
+});
+
+const make = Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+
+ const locate = Effect.fn("DatabaseMaintenance.locate")(function* (databasePath: string) {
+ if (!(yield* fs.exists(databasePath))) {
+ return yield* new DatabaseMissingError({ path: databasePath });
+ }
+ });
+
+ const inspect = Effect.fn("DatabaseMaintenance.inspect")(
+ function* (databasePath: string) {
+ yield* locate(databasePath);
+ return yield* readStorage.pipe(
+ Effect.provide(NodeSqliteClient.layer({ filename: databasePath, readonly: true })),
+ );
+ },
+ (effect, databasePath) =>
+ effect.pipe(
+ Effect.mapError((cause) =>
+ isDomainError(cause) ? cause : new DatabaseInspectError({ path: databasePath, cause }),
+ ),
+ ),
+ );
+
+ const compact = Effect.fn("DatabaseMaintenance.compact")(
+ function* (databasePath: string) {
+ yield* locate(databasePath);
+ const beforeBytes = Number((yield* fs.stat(databasePath)).size);
+ const result = yield* Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ // Hold an exclusive lock through compaction and VACUUM. In WAL mode this
+ // is refused while any other connection has the file open, even an idle
+ // one, which is how a running server or desktop app is detected.
+ yield* sql`PRAGMA busy_timeout = 0`;
+ yield* sql`PRAGMA locking_mode = EXCLUSIVE`;
+ yield* sql`BEGIN EXCLUSIVE`.pipe(
+ Effect.mapError((cause) =>
+ isSqlError(cause) && cause.reason._tag === "LockTimeoutError"
+ ? new DatabaseInUseError({ path: databasePath, cause })
+ : cause,
+ ),
+ );
+ yield* sql`COMMIT`;
+ const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
+ if (!(yield* maintenance.verify).valid) {
+ return yield* new DatabaseProjectionsInvalidError({ path: databasePath });
+ }
+ const summary = yield* maintenance.compactEventStore;
+ if (!(yield* maintenance.verify).valid) {
+ return yield* new DatabaseProjectionsInvalidError({ path: databasePath });
+ }
+ // VACUUM rebuilds the file, which is the only way to switch an existing
+ // database to incremental auto_vacuum; the server reclaims online after.
+ yield* sql`PRAGMA auto_vacuum = INCREMENTAL`;
+ yield* sql`VACUUM`;
+ yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
+ return summary;
+ }).pipe(
+ Effect.provide(
+ ProjectionMaintenance.layer.pipe(
+ Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
+ Layer.provideMerge(NodeSqliteClient.layer({ filename: databasePath })),
+ ),
+ ),
+ );
+ const afterBytes = Number((yield* fs.stat(databasePath)).size);
+ return {
+ beforeBytes,
+ afterBytes,
+ deletedEventCount: result.deletedEventCount,
+ deletedReceiptCount: result.deletedReceiptCount,
+ };
+ },
+ (effect, databasePath) =>
+ effect.pipe(
+ Effect.mapError((cause) =>
+ isDomainError(cause) ? cause : new DatabaseCompactError({ path: databasePath, cause }),
+ ),
+ ),
+ );
+
+ return DatabaseMaintenance.of({ inspect, compact });
+});
+
+export const layer = Layer.effect(DatabaseMaintenance, make);
diff --git a/docs/user/background-service.md b/docs/user/background-service.md
index 9964fba54f7..eb70af50bb0 100644
--- a/docs/user/background-service.md
+++ b/docs/user/background-service.md
@@ -95,3 +95,27 @@ Downloads, it may need Full Disk Access for the `t3` executable listed in
For failures after signing in to T3 Connect, see
[connection troubleshooting](./remote-access.md#t3-connect-troubleshooting).
+
+## Reclaim database space
+
+T3 Code removes superseded internal history on its own while it runs; your
+conversations are kept. Databases created before this shrank automatically
+still hold the freed space on disk until a one-time offline repair returns it
+and turns on automatic shrinking. Settings > Storage (web and desktop) or
+Settings > Maintenance (mobile) suggests the repair when at least 1 GiB can be
+reclaimed.
+
+Run `t3 doctor` on the machine that hosts the environment. It reports the
+database size and the space it can reclaim, then asks which repairs to run;
+pass `--fix` to run the recommended ones without a prompt (for scripts), or
+`--dry-run` to only report. An installed background service for the same data
+directory is stopped for the repair and started again afterwards, also when
+the repair fails. Quit a server you started by hand, or the desktop app, first:
+the repair refuses to touch a database that is in use. Use `--base-dir` for a
+different data directory.
+
+The repair can take several minutes on a large database. It rebuilds the
+database through a temporary copy, so it needs free space of about the
+database's size twice over: once in the system temporary directory (`TMPDIR`
+or `/tmp` on Linux and macOS) and once next to the database for its
+write-ahead log.
diff --git a/docs/user/install.md b/docs/user/install.md
index 1b15bf0a057..b883667949f 100644
--- a/docs/user/install.md
+++ b/docs/user/install.md
@@ -25,13 +25,14 @@ afterwards, that directory is not on your `PATH` yet; the installer prints the
line to add. Set `T3CODE_CHANNEL=nightly` to install the nightly train, or
`T3CODE_VERSION` to pin an exact version.
-| Task | Command |
-| ------------------------------------------------ | --------------------------------------------------------- |
-| Start the server and open the web app | `t3` |
-| Start the server without a browser | `t3 serve` |
-| Keep it running in the background (macOS, Linux) | `t3 service install` ([details](./background-service.md)) |
-| Move to the newest release | `t3 update` |
-| Remove it again | `t3 uninstall` |
+| Task | Command |
+| ------------------------------------------------ | ----------------------------------------------------------------------- |
+| Start the server and open the web app | `t3` |
+| Start the server without a browser | `t3 serve` |
+| Keep it running in the background (macOS, Linux) | `t3 service install` ([details](./background-service.md)) |
+| Move to the newest release | `t3 update` |
+| Reclaim database space | `t3 doctor` ([details](./background-service.md#reclaim-database-space)) |
+| Remove it again | `t3 uninstall` |
Run `t3 help` or `t3 --help` for the full reference. To start in a new working
directory, use an explicit path such as `t3 ./my-project`. A bare directory name
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 569fcf40cf8..ea5185b4028 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -1074,6 +1074,9 @@ const NULLABLE_PROJECT_SETTINGS_OVERRIDES: ReadonlySet<ProjectScopedServerSettin
"sidebarAutoSettleAfterDays",
]);
+/** Reclaimable bytes from which the offline `t3 doctor` repair is worth suggesting. */
+export const DATABASE_COMPACTION_RECOMMENDED_BYTES = 1024 ** 3;
+
export const StorageCleanupReportEntry = Schema.Struct({
kind: Schema.Literals(["worktree", "browser-artifacts", "logs"]),
outcome: Schema.Literals(["removed", "kept", "failed"]),