Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
core: purge BLOBs after erasing revisions and attachments
Adorian Dorand0663646f92b
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.tsindex 0f88ebff3b..546c9f4b00 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@@ -105,10 +105,9 @@ export function computeCleanupSizes(* 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.+ * The erasures run one after another rather than at once: each ends by purging the content it+ * orphaned, and there is nothing to be gained by having two of those scan the blobs at the same+ * time. Their order carries no weight beyond that — every one of them hands its own space back.** @returns bytes reclaimed, never negative: a note saved by another client mid-run must not read as* the cleanup having given space back.diff --git a/packages/trilium-core/src/routes/api/revisions.spec.ts b/packages/trilium-core/src/routes/api/revisions.spec.tsindex 7f50b647af..7aebbcd442 100644--- a/packages/trilium-core/src/routes/api/revisions.spec.ts+++ b/packages/trilium-core/src/routes/api/revisions.spec.ts@@ -34,6 +34,10 @@ async function createNoteWithRevision(return { noteId, revisionId: res.body.revisionId };}+function blobExists(blobId: string): boolean {+ return getSql().getRowOrNull("SELECT blobId FROM blobs WHERE blobId = ?", [ blobId ]) !== null;+}+function revisionExists(revisionId: string): boolean {const row = getSql().getRowOrNull<{ revisionId: string }>("SELECT revisionId FROM revisions WHERE revisionId = ?",@@ -362,6 +366,26 @@ describe("Revisions API (core)", () => {expect(revisionIdsOf(noteId).length).toBe(1);});+ it("purges the content the erased snapshots held, rather than leaving it for later", async () => {+ const { noteId } = await createTextNote(api, { title: "Excess orphan" });+ const content = `<p>${"excess-orphan-".repeat(80)}</p>`;++ // Snapshot content the live note no longer holds, so the blob is the snapshot's alone.+ expect((await api.put(`/api/notes/${noteId}/data`, { body: { content } })).status).toBe(204);+ const saved = await api.post<ForceSaveResponse>(`/api/notes/${noteId}/revision`, { body: {} });+ expect(saved.status).toBe(200);+ expect((await api.put(`/api/notes/${noteId}/data`, { body: { content: "<p>moved on</p>" } })).status).toBe(204);++ const blobId = getSql().getValue<string>(+ "SELECT blobId FROM revisions WHERE revisionId = ?", [ saved.body.revisionId ]);+ expect(blobExists(blobId)).toBe(true);++ await eraseExcess({ snapshotsToKeep: 0 });++ expect(revisionIdsOf(noteId)).toEqual([]);+ expect(blobExists(blobId)).toBe(false);+ });+it("keeps only the newest snapshots the override asks for", async () => {const { noteId, revisionIds } = await createNoteWithRevisions("Excess override",[ undefined, undefined, undefined, undefined ]);diff --git a/packages/trilium-core/src/routes/api/revisions.ts b/packages/trilium-core/src/routes/api/revisions.tsindex 1814f5c17e..dc488ef916 100644--- a/packages/trilium-core/src/routes/api/revisions.ts+++ b/packages/trilium-core/src/routes/api/revisions.ts@@ -141,6 +141,13 @@ function eraseAllExcessRevisions(req: Request) {erasedCount += becca.getNote(row.noteId)?.eraseExcessRevisionSnapshots(options) ?? 0;}+ if (erasedCount > 0) {+ // Dropping the snapshots leaves their content behind, held by nothing. Purged here rather+ // than in the entity method, which also runs after every saved revision — a blob scan per+ // note save would be far too expensive for what it collects.+ eraseService.eraseUnusedBlobs();+ }+return { erasedCount } satisfies EraseExcessRevisionsResponse;}diff --git a/packages/trilium-core/src/services/erase.spec.ts b/packages/trilium-core/src/services/erase.spec.tsindex 7f7003b916..0ffa19bc7f 100644--- a/packages/trilium-core/src/services/erase.spec.ts+++ b/packages/trilium-core/src/services/erase.spec.ts@@ -191,6 +191,29 @@ describe("erase service (real DB)", () => {expect(entityChangeFor("attachments", attachmentId)?.isErased).toBe(1);});+ it("purges the content the erased attachment held, rather than leaving it for later", () => {+ const note = createNote();+ const content = `erase-spec-orphan-${Math.random()}`;+ const attachment = getContext().init(() =>+ note.saveAttachment({ role: "file", mime: "text/plain", title: "orphan", content })+ );+ const blobId = attachment.blobId ?? "";+ expect(rowCount("blobs", "blobId", blobId)).toBe(1);++ getContext().init(() =>+ getSql().execute(+ "UPDATE attachments SET utcDateScheduledForErasureSince = ? WHERE attachmentId = ?",+ ["2000-01-01 00:00:00.000Z", attachment.attachmentId]+ )+ );++ getContext().init(() => eraseService.eraseUnusedAttachmentsNow());++ // Dropping the row alone would leave this held by nothing and still on disk until some+ // later sweep happened to collect it.+ expect(rowCount("blobs", "blobId", blobId)).toBe(0);+ });+it("does not erase an attachment that is not scheduled for erasure", () => {const note = createNote();const attachment = getContext().init(() =>diff --git a/packages/trilium-core/src/services/erase.ts b/packages/trilium-core/src/services/erase.tsindex 91e63cd6a9..98ee51d3df 100644--- a/packages/trilium-core/src/services/erase.ts+++ b/packages/trilium-core/src/services/erase.ts@@ -179,7 +179,15 @@ function eraseScheduledAttachments(eraseUnusedAttachmentsAfterSeconds: number |const cutOffDate = dateUtils.utcDateTimeStr(new Date(Date.now() - eraseUnusedAttachmentsAfterSeconds * 1000));const attachmentIdsToErase = getSql().getColumn<string>("SELECT attachmentId FROM attachments WHERE utcDateScheduledForErasureSince < ?", [cutOffDate]);+ if (attachmentIdsToErase.length === 0) {+ return;+ }+eraseAttachments(attachmentIdsToErase);+ // Dropping the rows leaves their content behind, held by nothing: without this the space is not+ // handed back until some later erasure of deleted entities happens to sweep it up. Reached only+ // when something actually went, so the hourly pass costs no blob scan on a quiet database.+ eraseUnusedBlobs();}function startScheduledCleanup() {