Skip to content

Build your personal knowledge base with Trilium Notes

core/space usage: add an support for retrieving saving estimates for vacuuming the DB

Adorian Doran054b8e444149
diff --git a/apps/server/src/routes/api/database.spec.ts b/apps/server/src/routes/api/database.spec.ts
index 53d145f903..086f99993a 100644
--- a/apps/server/src/routes/api/database.spec.ts
+++ b/apps/server/src/routes/api/database.spec.ts
@@ -32,8 +32,23 @@ describe("Database API", () => {
expect(result.results[0].integrity_check).toBe("ok");
});
- it("vacuums the database without throwing", () => {
- expect(() => databaseRoute.vacuumDatabase()).not.toThrow();
+ it("vacuums the database, reporting the file's size on either side of the rebuild", () => {
+ const { sizeBefore, sizeAfter } = databaseRoute.vacuumDatabase();
+
+ // Real byte counts, and a rebuild never leaves the file larger than it found it.
+ expect(sizeBefore).toBeGreaterThan(0);
+ expect(sizeAfter).toBeGreaterThan(0);
+ expect(sizeAfter).toBeLessThanOrEqual(sizeBefore);
+ });
+
+ it("estimates what a rebuild would return, which is nothing right after one", () => {
+ const before = databaseRoute.getCompactionEstimate();
+ expect(before.reclaimableBytes).toBeGreaterThanOrEqual(0);
+
+ // A vacuum leaves no free pages behind, so the estimate that follows one is zero — which is
+ // what ties this figure to the thing it claims to predict.
+ databaseRoute.vacuumDatabase();
+ expect(databaseRoute.getCompactionEstimate().reclaimableBytes).toBe(0);
});
it("kicks off on-demand consistency checks", () => {
diff --git a/apps/server/src/routes/api/database.ts b/apps/server/src/routes/api/database.ts
index 97968976b9..734c4874fa 100644
--- a/apps/server/src/routes/api/database.ts
+++ b/apps/server/src/routes/api/database.ts
@@ -1,4 +1,10 @@
-import { BackupDatabaseNowResponse, DatabaseCheckIntegrityResponse, ExistingAnonymizedDatabasesResponse } from "@triliumnext/commons";
+import {
+ BackupDatabaseNowResponse,
+ CompactionEstimateResponse,
+ DatabaseCheckIntegrityResponse,
+ ExistingAnonymizedDatabasesResponse,
+ VacuumDatabaseResponse
+} from "@triliumnext/commons";
import { becca_loader, consistency_checks as consistencyChecksService, getBackup, getLog, ValidationError } from "@triliumnext/core";
import type { Request, Response } from "express";
import fs, { readFileSync } from "fs";
@@ -20,9 +26,39 @@ async function backupDatabase() {
}
function vacuumDatabase() {
+ const sizeBefore = databaseBytes();
sql.execute("VACUUM");
+ const sizeAfter = databaseBytes();
- getLog().info("Database has been vacuumed.");
+ getLog().info(`Database has been vacuumed, from ${sizeBefore} to ${sizeAfter} bytes.`);
+
+ return { sizeBefore, sizeAfter } satisfies VacuumDatabaseResponse;
+}
+
+/**
+ * What a rebuild would hand back, read before running one. Erasing content does not shrink the file
+ * — the pages it frees stay allocated in it, on the freelist — so this is where that space shows up
+ * until a vacuum returns it.
+ */
+function getCompactionEstimate() {
+ return { reclaimableBytes: reclaimableBytes() } satisfies CompactionEstimateResponse;
+}
+
+/**
+ * The database's own view of its size: every page it has allocated, the free ones included. Read
+ * through pragma functions rather than the file itself, so there is no path to resolve and no race
+ * with the filesystem — and it is exactly the figure a vacuum moves.
+ *
+ * Covers the main database alone; in WAL mode the `-wal` sidecar is not part of it.
+ */
+function databaseBytes(): number {
+ return sql.getValue<number>("SELECT page_count * page_size FROM pragma_page_count(), pragma_page_size()");
+}
+
+/** Pages already free inside the file. A floor, not a promise: a rebuild also recovers the slack
+ * left inside pages that are still in use, which no count of whole pages can see. */
+function reclaimableBytes(): number {
+ return sql.getValue<number>("SELECT freelist_count * page_size FROM pragma_freelist_count(), pragma_page_size()");
}
function findAndFixConsistencyIssues() {
@@ -72,6 +108,7 @@ export default {
getExistingBackups,
backupDatabase,
vacuumDatabase,
+ getCompactionEstimate,
findAndFixConsistencyIssues,
rebuildIntegrationTestDatabase,
getExistingAnonymizedDatabases,
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index 94fd376788..2e2f5ed64b 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -166,6 +166,7 @@ function register(app: express.Application) {
// backup routes (backups, backup-database, backup/download) are in core
// VACUUM requires execution outside of transaction
asyncRoute(PST, "/api/database/vacuum-database", [auth.checkApiAuthOrElectron, csrfMiddleware], databaseRoute.vacuumDatabase, apiResultHandler);
+ apiRoute(GET, "/api/database/compaction-estimate", databaseRoute.getCompactionEstimate);
asyncRoute(PST, "/api/database/find-and-fix-consistency-issues", [auth.checkApiAuthOrElectron, csrfMiddleware], databaseRoute.findAndFixConsistencyIssues, apiResultHandler);
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index 43d62c6873..f984f09de4 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -107,6 +107,25 @@ export interface DatabaseCheckIntegrityResponse {
}[];
}
+/**
+ * What rebuilding the database file gave back, measured either side of the vacuum. Erasing content
+ * does not shrink the file — the pages it frees stay allocated on the freelist — so this difference
+ * is the only figure that says what the disk actually got back.
+ */
+export interface VacuumDatabaseResponse {
+ /** The database's size in bytes before the rebuild, free pages included. */
+ sizeBefore: number;
+ sizeAfter: number;
+}
+
+export interface CompactionEstimateResponse {
+ /**
+ * Bytes a rebuild would return, from the pages already free inside the file. A floor rather than
+ * a promise: a rebuild also recovers the slack left inside pages still in use.
+ */
+ reclaimableBytes: number;
+}
+
export interface DatabaseAnonymizeResponse {
success: boolean;
anonymizedFilePath: string;