Skip to content

Build your personal knowledge base with Trilium Notes

core/space usage/revisions: calculate the amount according to extra parameters (snapshots to keep, keep named revisions)

Adorian Doran796dec94fed3
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index 5d4b28ac63..41b54a0b3e 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -377,10 +377,16 @@ export interface SpaceUsageNoteResponse extends SpaceUsageSizes {
/** Like {@link noteContentSize}, over the note's whole canonical subtree. */
subtreeContentSize: number;
/**
- * What erasing the whole subtree's history would actually reclaim: blobs held only by the
- * subtree's revisions, each counted once, and none that a live body or note attachment still
- * shares. Tiered like the database-wide figure, so the two are comparable — unlike the
- * per-entity {@link revisionsSize}, which counts a shared snapshot at every entity holding it.
+ * An estimate of what trimming the subtree's history would reclaim: blobs held only by the
+ * snapshots that would go, each counted once, and none that a live body, a note attachment or a
+ * surviving snapshot still shares. Tiered like the database-wide figure, so the two are
+ * comparable — unlike the per-entity {@link revisionsSize}, which counts a shared snapshot at
+ * every entity holding it.
+ *
+ * How far that trimming goes is the request's own {@link EraseExcessRevisionsOptions}: by
+ * default every snapshot goes, which is the whole history. The limit asked for stands for every
+ * note at once, so a note whose `#versioningLimit` keeps more than that frees less than this
+ * figure allows for — an estimate reading high, not a promise.
*/
subtreeRevisionsContentSize: number;
attachments: SpaceUsageAttachment[];
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 93fa83573d..4950874048 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 { getSql } from "../../services/sql/index";
import { CoreApiTester } from "../../test/api_tester";
import { createTextNote, type CreatedNote } from "../../test/api_fixtures";
@@ -23,8 +24,8 @@ async function getOverview(query: Record<string, string | number | boolean> = {}
return res.body;
}
-async function getNoteUsage(noteId: string) {
- const res = await api.get<SpaceUsageNoteResponse>(`/api/space-usage/note/${noteId}`);
+async function getNoteUsage(noteId: string, query: Record<string, string | number | boolean> = {}) {
+ const res = await api.get<SpaceUsageNoteResponse>(`/api/space-usage/note/${noteId}`, { query });
expect(res.status).toBe(200);
return res.body;
}
@@ -303,6 +304,117 @@ describe("Space usage API (core)", () => {
expect(unusedAttachments.size).toBe(before.unusedAttachments.size);
});
+ describe("the reclaimable-history estimate", () => {
+ /**
+ * A note whose snapshots hold the given contents, oldest first, with a final body none of
+ * them shares — so every snapshot holds a blob of its own that only it keeps alive. Their
+ * creation times are spaced a day apart: trimming takes the oldest first, and snapshots
+ * saved within the same millisecond would leave that order up to the database.
+ */
+ async function createNoteWithSnapshots(title: string, snapshots: { content: string, name?: string }[]) {
+ const { noteId } = await createTextNote(api, { title, content: snapshots[0].content });
+
+ for (const [ index, { content, name } ] of snapshots.entries()) {
+ if (index > 0) {
+ const update = await api.put(`/api/notes/${noteId}/data`, { body: { content } });
+ expect(update.status).toBe(204);
+ }
+
+ const saved = await api.post<{ revisionId: string }>(`/api/notes/${noteId}/revision`, {
+ body: { description: name }
+ });
+ expect(saved.status).toBe(200);
+
+ getSql().execute("UPDATE revisions SET utcDateCreated = ? WHERE revisionId = ?", [
+ `2026-03-${String(index + 1).padStart(2, "0")} 00:00:00.000Z`,
+ saved.body.revisionId
+ ]);
+ }
+
+ // Leaves the live body sharing nothing with the history, and confirms no extra snapshot
+ // slipped in along the way — the figures below are exact, not approximate.
+ const update = await api.put(`/api/notes/${noteId}/data`, { body: { content: `<p>${title} now</p>` } });
+ expect(update.status).toBe(204);
+ expect(getSql().getValue<number>(
+ "SELECT COUNT(*) FROM revisions WHERE noteId = ?", [ noteId ])).toBe(snapshots.length);
+
+ return noteId;
+ }
+
+ // Content is deduplicated database-wide, so every fixture below needs a filler of its own:
+ // sharing one would leave the notes holding a single blob that no one of them can free.
+ const bodyOf = (filler: string, length: number) => `<p>${filler.repeat(length)}</p>`;
+
+ it("counts only the snapshots the given limit would actually erase", async () => {
+ const [ OLDEST, MIDDLE, NEWEST ] =
+ [ bodyOf("la", 1100), bodyOf("lb", 1200), bodyOf("lc", 1300) ];
+ const noteId = await createNoteWithSnapshots("Estimate limited",
+ [ { content: OLDEST }, { content: MIDDLE }, { content: NEWEST } ]);
+ const sizeOf = async (query: Record<string, string | number>) =>
+ (await getNoteUsage(noteId, query)).subtreeRevisionsContentSize;
+
+ // No options: the whole history, exactly as before they existed.
+ expect((await getNoteUsage(noteId)).subtreeRevisionsContentSize)
+ .toBe(OLDEST.length + MIDDLE.length + NEWEST.length);
+ expect(await sizeOf({ snapshotsToKeep: 0 })).toBe(OLDEST.length + MIDDLE.length + NEWEST.length);
+
+ // Keeping the newest snapshots takes their weight out of the estimate, oldest first.
+ expect(await sizeOf({ snapshotsToKeep: 1 })).toBe(OLDEST.length + MIDDLE.length);
+ expect(await sizeOf({ snapshotsToKeep: 2 })).toBe(OLDEST.length);
+ expect(await sizeOf({ snapshotsToKeep: 3 })).toBe(0);
+ // More room than there are snapshots, and the limit that spares every one of them.
+ expect(await sizeOf({ snapshotsToKeep: 99 })).toBe(0);
+ expect(await sizeOf({ snapshotsToKeep: -1 })).toBe(0);
+ });
+
+ it("leaves named snapshots out of both the estimate and the count when they are spared", async () => {
+ const [ OLDEST, NAMED, NEWEST ] =
+ [ bodyOf("na", 1100), bodyOf("nb", 1200), bodyOf("nc", 1300) ];
+ const noteId = await createNoteWithSnapshots("Estimate named",
+ [ { content: OLDEST }, { content: NAMED, name: "release" }, { content: NEWEST } ]);
+ const sizeOf = async (query: Record<string, string | number | boolean>) =>
+ (await getNoteUsage(noteId, query)).subtreeRevisionsContentSize;
+
+ // Spared, the named snapshot's weight is never on offer...
+ expect(await sizeOf({ keepNamedSnapshots: true })).toBe(OLDEST.length + NEWEST.length);
+ // ...and it does not eat into the allowance either: keeping one still keeps the newest
+ // automatic snapshot, leaving only the oldest to go.
+ expect(await sizeOf({ snapshotsToKeep: 1, keepNamedSnapshots: true })).toBe(OLDEST.length);
+ // Not spared, it is weighed and counted like any other snapshot.
+ expect(await sizeOf({ snapshotsToKeep: 1 })).toBe(OLDEST.length + NAMED.length);
+ });
+
+ it("promises nothing back for content a surviving snapshot still holds", async () => {
+ const SHARED = bodyOf("sa", 1400);
+ // Both snapshots were taken of the same body, so they share the one blob.
+ const noteId = await createNoteWithSnapshots("Estimate shared",
+ [ { content: SHARED }, { content: SHARED } ]);
+
+ // Erasing both frees that blob once — never twice, for all that two rows point at it.
+ expect((await getNoteUsage(noteId)).subtreeRevisionsContentSize).toBe(SHARED.length);
+ // Erasing one frees nothing at all: the survivor still holds the very same content.
+ expect((await getNoteUsage(noteId, { snapshotsToKeep: 1 })).subtreeRevisionsContentSize).toBe(0);
+
+ // Nor does a snapshot of another note let go of it — content is deduplicated across the
+ // whole database, so erasing this note's entire history now frees nothing either.
+ await createNoteWithSnapshots("Estimate shared elsewhere", [ { content: SHARED } ]);
+ expect((await getNoteUsage(noteId)).subtreeRevisionsContentSize).toBe(0);
+ });
+
+ it("400s on an estimate it cannot make, rather than quoting the whole history instead", async () => {
+ for (const query of [
+ { snapshotsToKeep: -2 },
+ { snapshotsToKeep: 1.5 },
+ { snapshotsToKeep: "many" },
+ { snapshotsToKeep: "" },
+ { keepNamedSnapshots: "of course" }
+ ]) {
+ const res = await api.get(`/api/space-usage/note/${parent.noteId}`, { query });
+ expect(res.status).toBe(400);
+ }
+ });
+ });
+
it("defaults and clamps the overview limit", async () => {
// No limit → the server default applies and the request just works.
const defaulted = await getOverview();
diff --git a/packages/trilium-core/src/routes/api/space_usage.ts b/packages/trilium-core/src/routes/api/space_usage.ts
index c188845a63..8d638bc654 100644
--- a/packages/trilium-core/src/routes/api/space_usage.ts
+++ b/packages/trilium-core/src/routes/api/space_usage.ts
@@ -1,3 +1,4 @@
+import type { EraseExcessRevisionsOptions } from "@triliumnext/commons";
import type { Request } from "express";
import {
@@ -20,7 +21,45 @@ function getOverview(req: Request) {
}
function getNoteUsage(req: Request<{ noteId: string }>) {
- return getNoteUsageFromService(req.params.noteId);
+ const revisionOptions = parseRevisionOptions(req.query);
+
+ if (typeof revisionOptions === "string") {
+ return [ 400, revisionOptions ];
+ }
+
+ return getNoteUsageFromService(req.params.noteId, revisionOptions);
+}
+
+/**
+ * How far the trimming being estimated would go, off the query string, or the message to answer 400
+ * with. Omitted, the reported history is what erasing all of it would reclaim — so a value that
+ * cannot be read has to fail rather than fall back to that, which would quote a far larger figure
+ * than the caller asked about.
+ */
+function parseRevisionOptions(query: Request["query"]): EraseExcessRevisionsOptions | string {
+ const { snapshotsToKeep, keepNamedSnapshots } = query;
+ const options: EraseExcessRevisionsOptions = {
+ keepNamedSnapshots: keepNamedSnapshots === "true"
+ };
+
+ if (keepNamedSnapshots !== undefined && keepNamedSnapshots !== "true" && keepNamedSnapshots !== "false") {
+ return "keepNamedSnapshots must be 'true' or 'false'.";
+ }
+
+ if (snapshotsToKeep !== undefined) {
+ // `Number("")` is 0, which would quietly turn a blank parameter into the harshest limit.
+ const parsed = typeof snapshotsToKeep === "string" && snapshotsToKeep.trim() !== ""
+ ? Number(snapshotsToKeep)
+ : NaN;
+
+ if (!Number.isInteger(parsed) || parsed < -1) {
+ return "snapshotsToKeep must be an integer of -1 (keep every snapshot) or above.";
+ }
+
+ options.snapshotsToKeep = parsed;
+ }
+
+ return options;
}
export default {
diff --git a/packages/trilium-core/src/services/space_usage.ts b/packages/trilium-core/src/services/space_usage.ts
index ca4fea5072..b7915dbfb3 100644
--- a/packages/trilium-core/src/services/space_usage.ts
+++ b/packages/trilium-core/src/services/space_usage.ts
@@ -1,4 +1,5 @@
import {
+ EraseExcessRevisionsOptions,
SpaceUsageBucket,
SpaceUsageContent,
SpaceUsageDeletedNotes,
@@ -106,16 +107,19 @@ function buildOverview({ includeRevisions, limit }: { includeRevisions: boolean,
};
}
-export function getNoteUsage(noteId: string): SpaceUsageNoteResponse {
+export function getNoteUsage(
+ noteId: string,
+ revisionOptions: EraseExcessRevisionsOptions = {}
+): SpaceUsageNoteResponse {
// Resolved before the measuring pass, so a bad note ID costs nothing.
const note = becca.getNoteOrThrow(noteId);
log(`measuring note ${note.noteId} and its subtree...`);
- return timed(`note ${note.noteId}`, () => withBlobUsage(() => buildNoteUsage(note.noteId)));
+ return timed(`note ${note.noteId}`, () => withBlobUsage(() => buildNoteUsage(note.noteId, revisionOptions)));
}
-function buildNoteUsage(noteId: string): SpaceUsageNoteResponse {
+function buildNoteUsage(noteId: string, revisionOptions: EraseExcessRevisionsOptions): SpaceUsageNoteResponse {
const note = becca.getNoteOrThrow(noteId);
const sizes = timed("adding the sizes up per note", collectSizes);
const forest = timed("placing the notes in the tree", buildForestFromBecca);
@@ -163,7 +167,7 @@ function buildNoteUsage(noteId: string): SpaceUsageNoteResponse {
...sizesOf(noteId, sizes),
noteContentSize: collectContentSizeOf([ noteId ]),
subtreeContentSize: collectContentSizeOf(subtreeNoteIds),
- subtreeRevisionsContentSize: collectRevisionsSizeOf(subtreeNoteIds),
+ subtreeRevisionsContentSize: collectRevisionsSizeOf(subtreeNoteIds, revisionOptions),
attachments,
children,
// Deleted notes have no place in the tree, so they surface once, at its root. Unused
@@ -570,34 +574,94 @@ function collectContentSizeOf(noteIds: string[]): number {
}
/**
- * The revision tier of {@link collectContentSizeOf}: what erasing the given notes' history would
- * actually reclaim. Deduplicated, and subtracted against the *database-wide* live bodies and note
- * attachments exactly as {@link collectContent} does — a snapshot still sharing its blob with any
- * live note frees nothing, so it counts for zero here. That tiering is what makes a subtree's figure
- * comparable to the database-wide one, and what separates this from the per-entity `revisionsSize`,
- * which counts a shared snapshot again at every entity holding it.
+ * The revision tier of {@link collectContentSizeOf}: an estimate of what trimming the given notes'
+ * history would reclaim. Deduplicated, and subtracted against the *database-wide* live bodies and
+ * note attachments exactly as {@link collectContent} does — a snapshot still sharing its blob with
+ * any live note frees nothing, so it counts for zero here. That tiering is what makes a subtree's
+ * figure comparable to the database-wide one, and what separates this from the per-entity
+ * `revisionsSize`, which counts a shared snapshot again at every entity holding it.
+ *
+ * The options are the ones "Erase excess revision snapshots" itself takes, so the figure answers
+ * what *that* operation would free rather than a number the action never delivers. Their absence
+ * keeps every snapshot doomed — the same figure as before they existed, and the one to report when
+ * nothing narrower was asked for.
+ *
+ * An estimate rather than a promise, because the limit it answers for is one number across every
+ * note, while the operation left to itself follows each note's own `#versioningLimit`. A note
+ * labelled to keep more than the stated limit frees less than its share of this figure, so the
+ * estimate reads high — the direction an estimate of reclaimable space should err in anyway. Run
+ * the operation with the same options and the two agree exactly, the override outranking the label.
+ *
+ * @param revisionOptions how far the trimming being estimated would go; `snapshotsToKeep` defaults
+ * to 0, which dooms the lot.
*/
-function collectRevisionsSizeOf(noteIds: string[]): number {
+function collectRevisionsSizeOf(
+ noteIds: string[],
+ { snapshotsToKeep, keepNamedSnapshots }: EraseExcessRevisionsOptions
+): number {
+ const snapshotsKept = Number.isInteger(snapshotsToKeep) ? Number(snapshotsToKeep) : 0;
+
+ // Nothing is ever excess once every snapshot is kept, so there is no query to run.
+ if (snapshotsKept < 0) {
+ return 0;
+ }
+
const sql = getSql();
sql.fillParamList(noteIds);
+ // The snapshots the trimming would take: per note the oldest ones past the allowance, ranked
+ // newest-first, sparing the named ones from the ranking altogether when they are to be kept —
+ // the same reckoning `BNote.eraseExcessRevisionSnapshots` makes. The revisionId tie-break only
+ // settles snapshots saved within the same millisecond, which the ordering alone cannot.
+ const doomed = `
+ SELECT revisionId, blobId FROM (
+ SELECT revisions.revisionId, revisions.blobId,
+ ROW_NUMBER() OVER (
+ PARTITION BY revisions.noteId
+ ORDER BY revisions.utcDateCreated DESC, revisions.revisionId DESC
+ ) AS age
+ FROM revisions
+ JOIN param_list ON param_list.paramId = revisions.noteId
+ ${keepNamedSnapshots ? "WHERE revisions.description IS NULL OR revisions.description = ''" : ""}
+ )
+ WHERE age > ${snapshotsKept}`;
+
return sql.getValue<number | null>(`
+ WITH doomed AS (${doomed})
SELECT SUM(blob_usage.size)
FROM blob_usage
WHERE blob_usage.blobId IN (
- SELECT revisions.blobId FROM revisions
- JOIN param_list ON param_list.paramId = revisions.noteId
- WHERE revisions.blobId IS NOT NULL
+ SELECT blobId FROM doomed WHERE blobId IS NOT NULL
UNION SELECT attachments.blobId FROM attachments
- JOIN revisions ON revisions.revisionId = attachments.ownerId
- JOIN param_list ON param_list.paramId = revisions.noteId
+ JOIN doomed ON doomed.revisionId = attachments.ownerId
WHERE attachments.isDeleted = 0 AND attachments.blobId IS NOT NULL
)
-- The same subtraction the database-wide tiers make, read off the tag each blob already
-- carries: one still held by a live body or note attachment frees nothing.
- AND blob_usage.kind NOT IN (${BLOB_BODY}, ${BLOB_ATTACHMENT})`) ?? 0;
+ AND blob_usage.kind NOT IN (${BLOB_BODY}, ${BLOB_ATTACHMENT})
+ -- And neither does one a snapshot that survives the trimming still holds — the spared named
+ -- ones, the newest kept per note, and every snapshot of every note outside this subtree.
+ -- Unchanged content is snapshotted onto the same blob over and over, so without this the
+ -- estimate would promise the same bytes back once per doomed snapshot sharing them.
+ AND blob_usage.blobId NOT IN (${SURVIVING_REVISION_BLOBS})`) ?? 0;
}
+/**
+ * Live-note revision blobs that a trimming would leave behind: {@link LIVE_REVISION_BLOBS} minus
+ * the snapshots being erased. Only valid inside a query defining the `doomed` set.
+ */
+const SURVIVING_REVISION_BLOBS = `
+ SELECT revisions.blobId FROM revisions
+ JOIN notes ON notes.noteId = revisions.noteId
+ WHERE notes.isDeleted = 0 AND revisions.blobId IS NOT NULL
+ AND revisions.revisionId NOT IN (SELECT revisionId FROM doomed)
+ UNION
+ SELECT attachments.blobId FROM attachments
+ JOIN revisions ON revisions.revisionId = attachments.ownerId
+ JOIN notes ON notes.noteId = revisions.noteId
+ WHERE attachments.isDeleted = 0 AND notes.isDeleted = 0 AND attachments.blobId IS NOT NULL
+ AND revisions.revisionId NOT IN (SELECT revisionId FROM doomed)`;
+
/**
* What erasing would actually reclaim: blobs referenced by deleted entities and by no live one.
* Deduplicated by blobId — several deleted clones of the same content free that content once.