Skip to content

Build your personal knowledge base with Trilium Notes

client/cleanup tool: use accurate measurements for the cleanup result

Adorian Doranb7f9d80bcd15
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx
index 76ea7253a2..6ab383bc82 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx
@@ -7,16 +7,22 @@ import { t } from "../../../../../services/i18n";
import { formatSize } from "../../../../../services/utils";
// Hoisted with the mocks that read them: a `vi.mock` factory runs before any plain module constant.
-const { REVISIONS_ALL, REVISIONS_TRIMMED, DELETED, UNUSED } = vi.hoisted(() => ({
+const { REVISIONS_ALL, REVISIONS_TRIMMED, DELETED, UNUSED, MEASURED_BEFORE, MEASURED_AFTER } = vi.hoisted(() => ({
REVISIONS_ALL: 900,
REVISIONS_TRIMMED: 300,
DELETED: 100,
- UNUSED: 20
+ UNUSED: 20,
+ // Deliberately unlike any estimate above, so a toast quoting a prediction cannot pass for one
+ // quoting the measurement.
+ MEASURED_BEFORE: 7777,
+ MEASURED_AFTER: 1111
}));
const mocks = vi.hoisted(() => ({
getInt: vi.fn<(name: string) => number | null>(() => -1),
storedOption: "{}",
+ /** Occupied bytes handed to the run's before/after weighings, in that order. */
+ weighed: [] as number[],
save: vi.fn(async () => {}),
get: vi.fn(),
post: vi.fn(async (_url: string, _body?: object) => {}),
@@ -44,6 +50,12 @@ vi.mock("../../../../../services/server", () => ({
return Promise.resolve(url === "keyboard-actions" ? [] : {});
}
+ // The overview is what the run weighs itself against, before and after.
+ if (url.startsWith("space-usage/overview")) {
+ const size = mocks.weighed.shift() ?? MEASURED_AFTER;
+ return Promise.resolve({ content: { size }, deletedNotes: { size: 0 } });
+ }
+
const keeping = /snapshotsToKeep=(\d+)/.exec(url)?.[1];
return Promise.resolve({
subtreeRevisionsContentSize: keeping === "0" ? REVISIONS_ALL : REVISIONS_TRIMMED,
@@ -134,6 +146,7 @@ async function click(button: HTMLButtonElement | undefined) {
beforeEach(() => {
mocks.storedOption = "{}";
+ mocks.weighed = [ MEASURED_BEFORE, MEASURED_AFTER ];
mocks.getInt.mockReturnValue(-1);
mocks.confirm.mockResolvedValue(true);
vi.clearAllMocks();
@@ -188,10 +201,14 @@ describe("showCleanupDialog", () => {
// The confirmation is the last chance to back out of something with no recovery.
expect(mocks.confirm).toHaveBeenCalledOnce();
- await expect(closed).resolves.toBe(UNUSED);
+ // Weighed, not predicted: the estimate on screen was the attachments' own figure, while what
+ // is reported is what the database actually gave back.
+ const measured = MEASURED_BEFORE - MEASURED_AFTER;
+ expect(measured).not.toBe(UNUSED);
+ await expect(closed).resolves.toBe(measured);
expect(mocks.post).toHaveBeenCalledWith("notes/erase-unused-attachments-now");
expect(mocks.showMessage).toHaveBeenCalledWith(
- t("space_usage.cleanup_done", { size: formatSize(UNUSED) }));
+ t("space_usage.cleanup_done", { size: formatSize(measured) }));
// Gone from the page: it is mounted for the run and unmounted with it.
expect(document.body.querySelector(".modal-stub")).toBeNull();
});
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx
index d4eb3ff876..d0e16597a2 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx
@@ -118,14 +118,17 @@ function CleanupDialog({ onFinished }: { onFinished: (reclaimed: number | null)
return;
}
+ // What the estimate promised, standing in only if the run fails before it can be weighed.
+ let reclaimed = work.reclaimed;
+
try {
- await runCleanup(work.options);
- toast.showMessage(t("space_usage.cleanup_done", { size: formatSize(work.reclaimed) }));
+ reclaimed = await runCleanup(work.options);
+ toast.showMessage(t("space_usage.cleanup_done", { size: formatSize(reclaimed) }));
} finally {
// Settled either way: a run that failed part-way still changed the database, so whatever
// was watching has to re-measure rather than keep the figures from before it. The
// failure itself is already reported by the request layer.
- onFinished(work.reclaimed);
+ onFinished(reclaimed);
}
}
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts
index 9c824ca544..2d4f51ede2 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts
@@ -3,11 +3,23 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
getInt: vi.fn<(name: string) => number | null>(() => -1),
- post: vi.fn(async (_url: string, _body?: object) => {})
+ post: vi.fn(async (_url: string, _body?: object) => {}),
+ /** Occupied bytes, read once before the erasures and once after; shifted per test. */
+ occupied: [ 5000, 3000 ],
+ get: vi.fn()
}));
vi.mock("../../../../../services/options", () => ({ default: { getInt: mocks.getInt } }));
-vi.mock("../../../../../services/server", () => ({ default: { post: mocks.post } }));
+vi.mock("../../../../../services/server", () => ({
+ default: {
+ post: mocks.post,
+ get: (url: string) => {
+ mocks.get(url);
+ const size = mocks.occupied.shift() ?? 0;
+ return Promise.resolve({ content: { size }, deletedNotes: { size: 0 } });
+ }
+ }
+}));
import {
type CleanupToolOptions,
@@ -35,7 +47,9 @@ const ALL_PICKED: CleanupToolOptions = {
beforeEach(() => {
mocks.getInt.mockReturnValue(-1);
+ mocks.occupied = [ 5000, 3000 ];
mocks.post.mockClear();
+ mocks.get.mockClear();
});
describe("readCleanupOptions", () => {
@@ -105,21 +119,41 @@ describe("runCleanup", () => {
await runCleanup(ALL_PICKED);
// Erasing revisions or attachments leaves the blobs they held; only the deleted-entity sweep
- // purges those, so it has to run after the two that create the orphans.
+ // purges those, so it has to run after the two that create the orphans. The outcome is
+ // recorded last of all, once there is a measured figure to record.
expect(mocks.post.mock.calls.map(([ url ]) => url)).toEqual([
"revisions/erase-all-excess-revisions",
"notes/erase-unused-attachments-now",
- "notes/erase-deleted-notes-now"
+ "notes/erase-deleted-notes-now",
+ "space-usage/cleanup-completed"
]);
expect(mocks.post.mock.calls[0][1]).toEqual({ snapshotsToKeep: 3, keepNamedSnapshots: true });
});
+ it("reports what the database actually gave back, not what was predicted", async () => {
+ mocks.occupied = [ 5000, 1200 ];
+
+ // Weighed on either side of the erasures — the whole point of the two extra readings.
+ await expect(runCleanup(ALL_PICKED)).resolves.toBe(3800);
+ expect(mocks.get.mock.calls.map(([ url ]) => url))
+ .toEqual([ "space-usage/overview?limit=1", "space-usage/overview?limit=1" ]);
+ expect(mocks.post).toHaveBeenCalledWith("space-usage/cleanup-completed", { reclaimedBytes: 3800 });
+ });
+
+ it("never reports a gain when the database grew under it", async () => {
+ // Another client saving a note mid-run must not read as the cleanup handing space back.
+ mocks.occupied = [ 3000, 4000 ];
+ await expect(runCleanup(ALL_PICKED)).resolves.toBe(0);
+ });
+
it("asks for nothing that was not picked", async () => {
await runCleanup({ ...ALL_PICKED, revisionSnapshots: false, deletedEntities: false });
- expect(mocks.post.mock.calls.map(([ url ]) => url)).toEqual([ "notes/erase-unused-attachments-now" ]);
+ expect(mocks.post.mock.calls.map(([ url ]) => url))
+ .toEqual([ "notes/erase-unused-attachments-now", "space-usage/cleanup-completed" ]);
mocks.post.mockClear();
+ mocks.occupied = [ 5000, 5000 ];
await runCleanup({ ...ALL_PICKED, deletedEntities: false, unusedAttachments: false, revisionSnapshots: false });
- expect(mocks.post).not.toHaveBeenCalled();
+ expect(mocks.post.mock.calls.map(([ url ]) => url)).toEqual([ "space-usage/cleanup-completed" ]);
});
});
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts
index cc32d4170a..0f88ebff3b 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts
@@ -1,4 +1,4 @@
-import type { SpaceUsageNoteResponse } from "@triliumnext/commons";
+import type { SpaceUsageNoteResponse, SpaceUsageOverviewResponse } from "@triliumnext/commons";
import optionService from "../../../../../services/options";
import server from "../../../../../services/server";
@@ -98,14 +98,24 @@ export function computeCleanupSizes(
}
/**
- * Erases what the settings ask for, one endpoint per item.
+ * Erases what the settings ask for, one endpoint per item, and reports what that actually freed.
*
- * Ordered rather than issued at once, and deliberately: erasing revisions or attachments deletes the
- * rows but leaves the blobs they held, which only the deleted-entity sweep purges. Running that last
- * is therefore what actually hands the space back — and when it is not picked, the blobs the other
- * two orphan wait for the hourly cleanup instead.
+ * The figure is measured rather than estimated: the database is weighed on either side of the run
+ * and the difference reported, so what the user is told matches what happened rather than what was
+ * predicted. That costs two full measurements on top of the erasures, which is the price of quoting
+ * a number that is true.
+ *
+ * The erasures are ordered rather than issued at once, and deliberately: erasing revisions or
+ * attachments deletes the rows but leaves the blobs they held, which only the deleted-entity sweep
+ * purges. Running that last is therefore what actually hands the space back — and when it is not
+ * picked, the blobs the other two orphan wait for the hourly cleanup instead.
+ *
+ * @returns bytes reclaimed, never negative: a note saved by another client mid-run must not read as
+ * the cleanup having given space back.
*/
-export async function runCleanup(options: CleanupToolOptions): Promise<void> {
+export async function runCleanup(options: CleanupToolOptions): Promise<number> {
+ const before = await measureOccupiedBytes();
+
if (options.revisionSnapshots) {
await server.post("revisions/erase-all-excess-revisions", {
snapshotsToKeep: options.snapshotsToKeep,
@@ -120,4 +130,26 @@ export async function runCleanup(options: CleanupToolOptions): Promise<void> {
if (options.deletedEntities) {
await server.post("notes/erase-deleted-notes-now");
}
+
+ const reclaimed = Math.max(before - await measureOccupiedBytes(), 0);
+
+ // Recorded on the server as well as shown here: this erased content past recovery, and the log
+ // is where that is answerable for afterwards.
+ await server.post("space-usage/cleanup-completed", { reclaimedBytes: reclaimed });
+
+ return reclaimed;
+}
+
+/**
+ * Every blob the space report accounts for: the live content plus what deleted entities still hold.
+ * Blobs referenced by nothing at all are outside both, which is what makes this the right thing to
+ * weigh — a snapshot erased but not yet purged has stopped being content and is on its way out, so
+ * the reading falls by its size exactly as the estimate said it would.
+ */
+async function measureOccupiedBytes(): Promise<number> {
+ // The smallest ranking the endpoint will do: the totals are whole-database figures either way,
+ // and the listing this would return is of no use here.
+ const overview = await server.get<SpaceUsageOverviewResponse>("space-usage/overview?limit=1");
+
+ return overview.content.size + overview.deletedNotes.size;
}
diff --git a/packages/trilium-core/src/routes/api/space_usage.spec.ts b/packages/trilium-core/src/routes/api/space_usage.spec.ts
index 4950874048..ab2d09ab7f 100644
--- a/packages/trilium-core/src/routes/api/space_usage.spec.ts
+++ b/packages/trilium-core/src/routes/api/space_usage.spec.ts
@@ -1,6 +1,7 @@
import { SpaceUsageNoteResponse, SpaceUsageOverviewResponse } from "@triliumnext/commons";
-import { beforeAll, describe, expect, it } from "vitest";
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { getLog } from "../../services/log";
import { getSql } from "../../services/sql/index";
import { CoreApiTester } from "../../test/api_tester";
import { createTextNote, type CreatedNote } from "../../test/api_fixtures";
@@ -431,6 +432,31 @@ describe("Space usage API (core)", () => {
expect(garbage.notes.length).toBeGreaterThan(0);
});
+ describe("recording a finished cleanup", () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it("logs what was reclaimed, in the log's own words", async () => {
+ const logged = vi.spyOn(getLog(), "info");
+
+ const res = await api.post("/api/space-usage/cleanup-completed", {
+ body: { reclaimedBytes: 2 * 1024 * 1024 }
+ });
+ expect([ 200, 204 ]).toContain(res.status);
+ expect(logged).toHaveBeenCalledWith("Clean Up Tool: reclaimed 2 MiB.");
+ });
+
+ it("400s on a figure it cannot have measured, writing nothing", async () => {
+ const logged = vi.spyOn(getLog(), "info");
+
+ for (const body of [ {}, { reclaimedBytes: -1 }, { reclaimedBytes: "lots" } ]) {
+ const res = await api.post("/api/space-usage/cleanup-completed", { body });
+ expect(res.status).toBe(400);
+ }
+
+ expect(logged).not.toHaveBeenCalled();
+ });
+ });
+
it("404s for a missing note", async () => {
const res = await api.get("/api/space-usage/note/spaceUsageMissing");
expect(res.status).toBe(404);
diff --git a/packages/trilium-core/src/routes/api/space_usage.ts b/packages/trilium-core/src/routes/api/space_usage.ts
index 8d638bc654..b40f2bccf7 100644
--- a/packages/trilium-core/src/routes/api/space_usage.ts
+++ b/packages/trilium-core/src/routes/api/space_usage.ts
@@ -1,6 +1,8 @@
import type { EraseExcessRevisionsOptions } from "@triliumnext/commons";
import type { Request } from "express";
+import { getLog } from "../../services/log.js";
+import { formatSize } from "../../services/utils/index.js";
import {
DEFAULT_OVERVIEW_LIMIT,
getNoteUsage as getNoteUsageFromService,
@@ -62,7 +64,26 @@ function parseRevisionOptions(query: Request["query"]): EraseExcessRevisionsOpti
return options;
}
+/**
+ * Records a finished cleanup-tool run in the server log. The figure is measured by the client, which
+ * weighs the database on either side of erasures it drives one endpoint at a time — so this is the
+ * only place the whole of it is known, and erasing content past recovery is worth a line in the log.
+ *
+ * Only the number crosses over; the line itself is written here, so nothing a caller sends can shape
+ * what the log says.
+ */
+function logCleanupCompleted(req: Request) {
+ const reclaimedBytes = Number(req.body?.reclaimedBytes);
+
+ if (!Number.isFinite(reclaimedBytes) || reclaimedBytes < 0) {
+ return [ 400, "reclaimedBytes must be a non-negative number." ];
+ }
+
+ getLog().info(`Clean Up Tool: reclaimed ${formatSize(reclaimedBytes)}.`);
+}
+
export default {
getOverview,
- getNoteUsage
+ getNoteUsage,
+ logCleanupCompleted
};
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index e339ecbb9b..3caa882e54 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -204,6 +204,7 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRout
apiRoute(GET, "/api/space-usage/overview", spaceUsageRoute.getOverview);
apiRoute(GET, "/api/space-usage/note/:noteId", spaceUsageRoute.getNoteUsage);
+ apiRoute(PST, "/api/space-usage/cleanup-completed", spaceUsageRoute.logCleanupCompleted);
apiRoute(GET, "/api/sql/schema", sqlRoute.getSchema);
apiRoute(PST, "/api/sql/execute/:noteId", sqlRoute.execute);