GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(server): t3 doctor warns how long reclaiming takes and shows each step by juliusmarminge · Pull Request #29956 · pingdotgg/t3code

fix(server): t3 doctor warns how long reclaiming takes and shows each step #29956

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
juliusmarminge merged 8 commits into main from fix/issue-29941
Nov 11, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

fix(server): t3 doctor warns how long reclaiming takes and shows each step #29956

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
8 commits
Select commit Hold shift + click to select a range
c7a0811
test(server): reproduce silent long-running doctor database repair (#…
juliusmarminge Nov 3, 2026
c0f4d4a
fix(server): doctor warns how long reclaiming takes and shows each step
juliusmarminge Nov 3, 2026
0421f7d
fix(server): doctor's Done line reports the total repair time
juliusmarminge Nov 3, 2026
787a94d
fix(server): doctor measures repair progress on the monotonic clock
juliusmarminge Nov 3, 2026
29b4b3a
Merge remote-tracking branch 'origin/main' into fix/issue-29941
juliusmarminge Nov 10, 2026
994e70b
Merge remote-tracking branch 'origin/main' into fix/issue-29941
juliusmarminge Nov 11, 2026
b7c08ef
Merge remote-tracking branch 'origin/main' into fix/issue-29941
juliusmarminge Nov 11, 2026
d94de30
test(server): drop doctor assertion that only checks removed copy
juliusmarminge Nov 11, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

74 changes: 74 additions & 0 deletions 74 apps/server/src/cli/doctor.test.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as TestClock from "effect/testing/TestClock";

import * as BootService from "../cloud/bootService.ts";
import { runDoctor } from "./doctor.ts";
Expand Down Expand Up @@ -53,3 +55,75 @@ it.effect(
assert.deepEqual(calls, ["pause", "compact", "resume"]);
}),
);

it.effect("warns how long reclaiming can take and reports each step with its elapsed time", () =>
Effect.gen(function* () {
const output: string[] = [];
const steps = [
["prune-events", "65 seconds"],
["vacuum", "701 seconds"],
["rebuild-search", "1 second"],
["checkpoint", "1 second"],
] as const;
yield* runDoctor("/test/statev2.sqlite", { fix: true, dryRun: false, interactive: false }).pipe(
Effect.provide(
Layer.mergeAll(
NodeServices.layer,
Layer.mock(BootService.BootService)({
withStopped: (operation) =>
Effect.sync(() => output.push("<pause>")).pipe(
Effect.andThen(operation),
Effect.ensuring(Effect.sync(() => output.push("<resume>"))),
),
}),
Layer.succeed(DatabaseMaintenance, {
inspect: () =>
Effect.succeed({
databaseBytes: 12.8 * 1024 ** 3,
reclaimableBytes: 0,
incrementalVacuumEnabled: false,
legacyDatabaseBytes: null,
}),
compact: (_databasePath, onStep) =>
Effect.gen(function* () {
for (const [step, duration] of steps) {
if (onStep) yield* onStep(step);
yield* TestClock.adjust(duration);
}
return {
beforeBytes: 12.8 * 1024 ** 3,
afterBytes: 12.8 * 1024 ** 3,
deletedEventCount: 0,
deletedReceiptCount: 0,
};
}),
removeLegacyDatabase: () => Effect.void,
}),
),
),
Effect.provideService(Console.Console, {
...globalThis.console,
log: (...args: ReadonlyArray<unknown>) => {
output.push(...args.join(" ").split("\n"));
},
}),
);

const paused = output.indexOf("<pause>");
const resumed = output.indexOf("<resume>");
assert.isAbove(paused, -1, "the repair must run with the service paused");
const beforePause = output.slice(0, paused).join("\n");
const description = beforePause.slice(beforePause.indexOf("Reclaim database space"));
assert.include(description, "12.80 GiB", "the repair must state the database size up front");
assert.match(description, /hour/, "the repair must warn it can take over an hour");
const progress = output
.slice(paused + 1, resumed)
.filter((line) => line.trim() !== "" && !line.trim().startsWith("Done"))
.map((line) => /\[(\d+:\d{2})\]/.exec(line)?.[1] ?? `unprefixed: ${line}`);
assert.deepEqual(
progress,
["0:00", "1:05", "12:46", "12:47"],
"each compaction step must print one line with the elapsed time as it starts",
);
}),
);
34 changes: 29 additions & 5 deletions 34 apps/server/src/cli/doctor.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { DATABASE_COMPACTION_RECOMMENDED_BYTES } from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
Expand All @@ -16,6 +17,18 @@ const formatBytes = (bytes: number) =>
? `${(bytes / 1024 ** 2).toFixed(1)} MiB`
: `${Math.ceil(bytes / 1024)} KiB`;

const formatElapsed = (nanos: bigint) => {
const seconds = Number(nanos / 1_000_000_000n);
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
};

const COMPACT_STEP_LABELS: Record<DatabaseMaintenance.DatabaseCompactStep, string> = {
"prune-events": "Removing superseded events",
vacuum: "Rewriting the database file",
"rebuild-search": "Rebuilding the search index",
checkpoint: "Flushing the write-ahead log",
};

export const runDoctor = Effect.fn("runDoctor")(function* (
databasePath: string,
options: { readonly fix: boolean; readonly dryRun: boolean; readonly interactive?: boolean },
Expand All @@ -41,7 +54,7 @@ export const runDoctor = Effect.fn("runDoctor")(function* (
status.incrementalVacuumEnabled
? "Returns unused space to disk."
: "Returns unused space to disk and turns on automatic shrinking."
}\n Pauses the background service, if installed, while it runs and may need temporary disk space.`,
}\n Rewrites the whole ${formatBytes(status.databaseBytes)} database, which can take more than an hour on a large database or slow disk.\n Pauses the background service, if installed, while it runs and may need temporary disk space.`,
recommended:
!status.incrementalVacuumEnabled ||
status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES,
Expand Down Expand Up @@ -100,15 +113,26 @@ export const runDoctor = Effect.fn("runDoctor")(function* (
}
if (selected.includes("database")) {
const service = yield* BootService.BootService;
yield* Console.log("\nReclaiming database space. This can take several minutes...");
yield* Console.log("\nReclaiming database space. Each step is shown as it starts.");
const startedAt = yield* Clock.monotonicTimeNanos;
const reportStep = (step: DatabaseMaintenance.DatabaseCompactStep) =>
Clock.monotonicTimeNanos.pipe(
Effect.flatMap((now) =>
Console.log(` [${formatElapsed(now - startedAt)}] ${COMPACT_STEP_LABELS[step]}`),
),
);
// Report the repair before restarting, which can fail independently.
yield* service.withStopped(
maintenance
.compact(databasePath)
.compact(databasePath, reportStep)
.pipe(
Effect.tap((result) =>
Console.log(
`Done: ${formatBytes(result.beforeBytes)} -> ${formatBytes(result.afterBytes)}, ${result.deletedEventCount} superseded events removed.`,
Clock.monotonicTimeNanos.pipe(
Effect.flatMap((now) =>
Console.log(
`Done in ${formatElapsed(now - startedAt)}: ${formatBytes(result.beforeBytes)} -> ${formatBytes(result.afterBytes)}, ${result.deletedEventCount} superseded events removed.`,
),
),
),
),
),
Expand Down
26 changes: 15 additions & 11 deletions 26 apps/server/src/persistence/DatabaseMaintenance.test.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -227,18 +227,22 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))
const clock = yield* Clock.Clock;
const pauses: number[] = [];
let activeNanos = 0n;
const result = yield* maintenance.compact(dbPath).pipe(
Effect.provideService(Clock.Clock, {
...clock,
// Exceed the background budget whenever the compactor checks elapsed time.
monotonicTimeNanos: Effect.sync(() => (activeNanos += 30_000_000n)),
sleep: (duration) =>
Effect.sync(() => {
pauses.push(Duration.toMillis(duration));
}),
}),
);
const steps: string[] = [];
const result = yield* maintenance
.compact(dbPath, (step) => Effect.sync(() => steps.push(step)))
.pipe(
Effect.provideService(Clock.Clock, {
...clock,
// Exceed the background budget whenever the compactor checks elapsed time.
monotonicTimeNanos: Effect.sync(() => (activeNanos += 30_000_000n)),
sleep: (duration) =>
Effect.sync(() => {
pauses.push(Duration.toMillis(duration));
}),
}),
);
assert.deepEqual(pauses, [], "offline doctor must not throttle compaction");
assert.deepEqual(steps, ["prune-events", "vacuum", "rebuild-search", "checkpoint"]);
assert.equal(result.deletedReceiptCount, 51);
assert.isBelow(result.afterBytes, result.beforeBytes - 3 * 1024 * 1024);
yield* Effect.gen(function* () {
Expand Down
21 changes: 18 additions & 3 deletions 21 apps/server/src/persistence/DatabaseMaintenance.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ export class DiskSpaceCheckError extends Schema.TaggedError<DiskSpaceCheckError>
}
}

export type DatabaseCompactStep = "prune-events" | "vacuum" | "rebuild-search" | "checkpoint";

export class DatabaseMaintenance extends Context.Service<
DatabaseMaintenance,
{
Expand All @@ -84,8 +86,14 @@ export class DatabaseMaintenance extends Context.Service<
},
DatabaseMissingError | DatabaseInspectError
>;
/** Compacts history, then VACUUMs into incremental auto_vacuum. Refuses while a server has it open. */
readonly compact: (databasePath: string) => Effect.Effect<
/**
* Compacts history, then VACUUMs into incremental auto_vacuum. Refuses while a server has it open.
* Calls `onStep` as each step starts; VACUUM time grows with the whole database size.
*/
readonly compact: (
databasePath: string,
onStep?: (step: DatabaseCompactStep) => Effect.Effect<void>,
) => Effect.Effect<
{
readonly beforeBytes: number;
readonly afterBytes: number;
Expand Down Expand Up @@ -171,18 +179,25 @@ const make = Effect.gen(function* () {
);

const compact = Effect.fn("DatabaseMaintenance.compact")(
function* (databasePath: string) {
function* (
databasePath: string,
onStep: (step: DatabaseCompactStep) => Effect.Effect<void> = () => Effect.void,
) {
yield* locate(databasePath);
const beforeBytes = Number((yield* fs.stat(databasePath)).size);
const result = yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* lockExclusively(databasePath);
const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
yield* onStep("prune-events");
const summary = yield* maintenance.pruneEventStore();
yield* onStep("vacuum");
// VACUUM is required to enable incremental auto_vacuum on existing databases.
yield* sql`PRAGMA auto_vacuum = INCREMENTAL`;
yield* sql`VACUUM`;
yield* onStep("rebuild-search");
yield* rebuildMessageSearch(sql);
yield* onStep("checkpoint");
yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;
return summary;
}).pipe(
Expand Down
12 changes: 7 additions & 5 deletions 12 docs/user/background-service.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -184,11 +184,13 @@ 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 twice the
data still in use (the database size minus the reclaimable space): once in the
system temporary directory (on Linux and macOS, `TMPDIR`, or `/var/tmp` when it
is not set) and once next to the database for its write-ahead log.
The repair's time grows with the size of the whole database, not only the
space it reclaims, and can exceed an hour on a large database or a slow disk;
`t3 doctor` shows each step as it runs. It rebuilds the database through a
temporary copy, so it needs free space of about twice the data still in use
(the database size minus the reclaimable space): once in the system temporary
directory (on Linux and macOS, `TMPDIR`, or `/var/tmp` when it is not set) and
once next to the database for its write-ahead log.

If you upgraded from a version before 0.1.0, its database (`state.sqlite`) is
still kept next to the current one so you can roll back. `t3 doctor` offers to
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.