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/erase excess revision snapshots: allow overriding the count of snapshots to keep, add exclusion flag for named snapshots
Adorian Doran7f7466687dee
diff --git a/apps/server/internal.openapi.yaml b/apps/server/internal.openapi.yamlindex ffea752eaf..3f1d573aaa 100644--- a/apps/server/internal.openapi.yaml+++ b/apps/server/internal.openapi.yaml@@ -1855,9 +1855,37 @@ paths:tags: [Revisions]summary: Cleanup old revisionsoperationId: eraseExcessRevisions+ requestBody:+ required: false+ content:+ application/json:+ schema:+ type: object+ properties:+ snapshotsToKeep:+ type: integer+ minimum: -1+ description: >+ Snapshots to keep per note, overriding the #versioningLimit label and the+ revisionSnapshotNumberLimit option. -1 keeps every snapshot, 0 keeps none.+ Omitted, the configured limits apply.+ keepNamedSnapshots:+ type: boolean+ description: >+ Spare named snapshots (those with a description) from erasure and leave them out+ of the count, so the limit governs the automatic snapshots alone.responses:- '204':+ '200':description: Excess revisions erased+ content:+ application/json:+ schema:+ type: object+ properties:+ erasedCount:+ type: integer+ '400':+ description: Invalid options/api/edited-notes/{date}:get:diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 32e60a1ef8..5d4b28ac63 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -59,6 +59,29 @@ export interface RevisionPojo {contentLength?: number;}+/**+ * How far "Erase excess revision snapshots" should go. Both fields are optional: left out, the+ * operation behaves exactly as the automatic trimming that runs after every saved revision.+ */+export interface EraseExcessRevisionsOptions {+ /**+ * How many snapshots to keep per note, overriding both the `#versioningLimit` label and the+ * `revisionSnapshotNumberLimit` option for this run. Negative keeps every snapshot (nothing is+ * excess), zero keeps none; omitted falls back to the configured limits.+ */+ snapshotsToKeep?: number;+ /**+ * Spares named snapshots — those the user gave a description — from erasure, and leaves them+ * out of the count as well, so the limit governs the automatic snapshots alone.+ */+ keepNamedSnapshots?: boolean;+}++export interface EraseExcessRevisionsResponse {+ /** Snapshots actually erased, across every note the operation visited. */+ erasedCount: number;+}+export interface RecentChangeRow {noteId: string;current_isDeleted: boolean;diff --git a/packages/trilium-core/src/becca/entities/bnote.ts b/packages/trilium-core/src/becca/entities/bnote.tsindex d0c1b77065..4eb21af950 100644--- a/packages/trilium-core/src/becca/entities/bnote.ts+++ b/packages/trilium-core/src/becca/entities/bnote.ts@@ -1,4 +1,4 @@-import type { AttachmentRow, AttributeType, CloneResponse, NoteRow, NoteType, RevisionRow, RevisionSource } from "@triliumnext/commons";+import type { AttachmentRow, AttributeType, CloneResponse, EraseExcessRevisionsOptions, NoteRow, NoteType, RevisionRow, RevisionSource } from "@triliumnext/commons";import { dayjs, getNoteIcon } from "@triliumnext/commons";import cloningService from "../../services/cloning.js";@@ -1601,24 +1601,47 @@ class BNote extends AbstractBeccaEntity<BNote> {});}- // Limit the number of Snapshots to revisionSnapshotNumberLimit- // Delete older Snapshots that exceed the limit- eraseExcessRevisionSnapshots() {- // lable has a higher priority- let revisionSnapshotNumberLimit = parseInt(this.getLabelValue("versioningLimit") ?? "");- if (!Number.isInteger(revisionSnapshotNumberLimit)) {- revisionSnapshotNumberLimit = parseInt(optionService.getOption("revisionSnapshotNumberLimit"));+ /**+ * Erases the oldest revision snapshots beyond the number to keep, newest kept first.+ *+ * How many are kept is normally configured: the note's own `#versioningLimit` label if it+ * carries a valid one, else the `revisionSnapshotNumberLimit` option. A negative limit keeps+ * every snapshot — nothing is ever excess — while zero keeps none of them.+ *+ * @returns how many snapshots were erased.+ */+ eraseExcessRevisionSnapshots({ snapshotsToKeep, keepNamedSnapshots }: EraseExcessRevisionsOptions = {}): number {+ const limit = Number.isInteger(snapshotsToKeep) ? Number(snapshotsToKeep) : this.getConfiguredSnapshotLimit();++ if (limit < 0) {+ return 0;}- if (revisionSnapshotNumberLimit >= 0) {- const revisions = this.getRevisions();- if (revisions.length - revisionSnapshotNumberLimit > 0) {- const revisionIds = revisions- .slice(0, revisions.length - revisionSnapshotNumberLimit)- .map((revision) => revision.revisionId)- .filter((id): id is string => id !== undefined);- eraseService.eraseRevisions(revisionIds);- }++ // Named snapshots are the ones the user deliberately marked, so sparing them takes them out+ // of the reckoning entirely: they are neither erased nor counted, and the limit then+ // governs the automatic snapshots alone. Counting them would let a handful of named ones+ // push every automatic snapshot out.+ const candidates = keepNamedSnapshots+ ? this.getRevisions().filter((revision) => !revision.description)+ : this.getRevisions();++ const revisionIds = candidates+ .slice(0, Math.max(candidates.length - limit, 0))+ .map((revision) => revision.revisionId)+ .filter((id): id is string => id !== undefined);++ if (revisionIds.length > 0) {+ eraseService.eraseRevisions(revisionIds);}++ return revisionIds.length;+ }++ /** The configured count to keep: the note's own label takes priority over the option. */+ private getConfiguredSnapshotLimit(): number {+ const labelled = parseInt(this.getLabelValue("versioningLimit") ?? "");++ return Number.isInteger(labelled) ? labelled : parseInt(optionService.getOption("revisionSnapshotNumberLimit"));}/**diff --git a/packages/trilium-core/src/becca/entities/bnote_content.spec.ts b/packages/trilium-core/src/becca/entities/bnote_content.spec.tsindex 85c98c8fcf..9e3b600e8b 100644--- a/packages/trilium-core/src/becca/entities/bnote_content.spec.ts+++ b/packages/trilium-core/src/becca/entities/bnote_content.spec.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { dayjs } from "@triliumnext/commons";+import { dayjs, type EraseExcessRevisionsOptions } from "@triliumnext/commons";import becca from "../becca.js";import { getContext } from "../../services/context.js";@@ -505,6 +505,82 @@ describe("BNote content / misc getters", () => {});});+ describe("eraseExcessRevisionSnapshots options", () => {+ /**+ * One revision per description, their creation times then spaced a day apart: snapshots are+ * trimmed oldest first, and several saved within the same millisecond would otherwise leave+ * the order — and with it the outcome — up to the database.+ */+ function createRevisions(note: BNote, descriptions: (string | undefined)[]) {+ return descriptions.map((description, index) => {+ const revision = getContext().init(() => note.saveRevision({ description }));++ getSql().execute("UPDATE revisions SET utcDateCreated = ? WHERE revisionId = ?", [+ `2026-01-${String(index + 1).padStart(2, "0")} 00:00:00.000Z`,+ revision.revisionId+ ]);++ return revision.revisionId;+ });+ }++ const revisionIdsOf = (note: BNote) => note.getRevisions().map((revision) => revision.revisionId);+ const eraseExcess = (note: BNote, options: EraseExcessRevisionsOptions) =>+ getContext().init(() => note.eraseExcessRevisionSnapshots(options));++ it("keeps the newest snapshots the override asks for, whatever the configured limit says", () => {+ const note = createNote();+ // Both configured limits are wider than the override, which still has the last word.+ getContext().init(() => note.setLabel("versioningLimit", "10"));+ const [ , , newer, newest ] = createRevisions(note, [ undefined, undefined, undefined, undefined ]);++ expect(eraseExcess(note, { snapshotsToKeep: 2 })).toBe(2);+ expect(revisionIdsOf(note)).toEqual([ newer, newest ]);+ });++ it("keeps everything at a negative override and nothing at zero", () => {+ const note = createNote();+ const ids = createRevisions(note, [ undefined, undefined ]);++ expect(eraseExcess(note, { snapshotsToKeep: -1 })).toBe(0);+ expect(revisionIdsOf(note)).toEqual(ids);++ expect(eraseExcess(note, { snapshotsToKeep: 0 })).toBe(2);+ expect(revisionIdsOf(note)).toEqual([]);+ });++ it("still follows the configured limit when no override is given", () => {+ const note = createNote();+ const [ , , newest ] = createRevisions(note, [ undefined, undefined, undefined ]);+ // Labelled only now: saving a revision trims as it goes, so a limit set up front would+ // have left nothing for the sweep to find.+ getContext().init(() => note.setLabel("versioningLimit", "1"));++ expect(eraseExcess(note, {})).toBe(2);+ expect(revisionIdsOf(note)).toEqual([ newest ]);+ });++ it("spares named snapshots and leaves them out of the count", () => {+ const note = createNote();+ const [ , firstNamed, , secondNamed, newest ] = createRevisions(note,+ [ undefined, "release", undefined, "before the refactor", undefined ]);++ // Two of the three automatic snapshots go. The named ones are not erased, and did not+ // eat into the single automatic snapshot the limit allows either.+ expect(eraseExcess(note, { snapshotsToKeep: 1, keepNamedSnapshots: true })).toBe(2);+ expect(revisionIdsOf(note)).toEqual([ firstNamed, secondNamed, newest ]);+ });++ it("erases named snapshots like any other when they are not spared", () => {+ const note = createNote();+ const [ , , , , newest ] = createRevisions(note,+ [ undefined, "release", undefined, "before the refactor", undefined ]);++ expect(eraseExcess(note, { snapshotsToKeep: 1 })).toBe(4);+ expect(revisionIdsOf(note)).toEqual([ newest ]);+ });+ });+describe("saveAttachment matchBy (lines 1628-1655)", () => {it("matches an existing attachment by title", () => {const note = createNote();diff --git a/packages/trilium-core/src/routes/api/revisions.spec.ts b/packages/trilium-core/src/routes/api/revisions.spec.tsindex 7ad0c943f2..7f50b647af 100644--- a/packages/trilium-core/src/routes/api/revisions.spec.ts+++ b/packages/trilium-core/src/routes/api/revisions.spec.ts@@ -315,12 +315,96 @@ describe("Revisions API (core)", () => {});describe("excess revisions", () => {- it("erases excess revision snapshots across notes", async () => {+ /**+ * A note carrying one revision per description, their creation times spaced a day apart:+ * snapshots are trimmed oldest first, and several saved within the same millisecond would+ * leave that order — and with it the outcome — up to the database.+ */+ async function createNoteWithRevisions(title: string, descriptions: (string | undefined)[]) {+ const { noteId } = await createTextNote(api, { title });+ const revisionIds: string[] = [];++ for (const [ index, description ] of descriptions.entries()) {+ const res = await api.post<ForceSaveResponse>(`/api/notes/${noteId}/revision`, {+ body: { description }+ });+ expect(res.status).toBe(200);++ getSql().execute("UPDATE revisions SET utcDateCreated = ? WHERE revisionId = ?", [+ `2026-02-${String(index + 1).padStart(2, "0")} 00:00:00.000Z`,+ res.body.revisionId+ ]);+ revisionIds.push(res.body.revisionId);+ }++ return { noteId, revisionIds };+ }++ function revisionIdsOf(noteId: string) {+ return getSql().getColumn<string>(+ "SELECT revisionId FROM revisions WHERE noteId = ? ORDER BY utcDateCreated ASC", [ noteId ]);+ }++ async function eraseExcess(body?: Record<string, unknown>) {+ const res = await api.post<{ erasedCount: number }>(+ "/api/revisions/erase-all-excess-revisions", body ? { body } : undefined);+ expect(res.status).toBe(200);+ return res.body.erasedCount;+ }++ it("erases excess revision snapshots across notes, reporting how many went", async () => {const { noteId } = await createTextNote(api, { title: "Excess" });await api.post(`/api/notes/${noteId}/revision`, { body: {} });- const res = await api.post("/api/revisions/erase-all-excess-revisions");- expect(res.status).toBe(204);+ // No limit is configured in a fresh database, so nothing is excess and the sweep is a+ // no-op — the case the button guards against, answered rather than refused.+ expect(await eraseExcess()).toBe(0);+ expect(revisionIdsOf(noteId).length).toBe(1);+ });++ it("keeps only the newest snapshots the override asks for", async () => {+ const { noteId, revisionIds } = await createNoteWithRevisions("Excess override",+ [ undefined, undefined, undefined, undefined ]);++ // Other notes of the shared database are swept too, so the total can only be a floor;+ // what this note keeps is the exact statement.+ expect(await eraseExcess({ snapshotsToKeep: 1 })).toBeGreaterThanOrEqual(3);+ expect(revisionIdsOf(noteId)).toEqual([ revisionIds[3] ]);+ });++ it("spares named snapshots without counting them against the limit", async () => {+ const { noteId, revisionIds } = await createNoteWithRevisions("Excess named",+ [ undefined, "release", undefined, "before the refactor", undefined ]);++ await eraseExcess({ snapshotsToKeep: 1, keepNamedSnapshots: true });++ // Both named snapshots survive, and the one automatic snapshot the limit allows is the+ // newest of them — the named ones did not eat into that allowance.+ expect(revisionIdsOf(noteId)).toEqual([ revisionIds[1], revisionIds[3], revisionIds[4] ]);+ });++ it("erases nothing at all when the override keeps every snapshot", async () => {+ const { noteId, revisionIds } = await createNoteWithRevisions("Excess kept",+ [ undefined, undefined ]);++ expect(await eraseExcess({ snapshotsToKeep: -1 })).toBe(0);+ expect(revisionIdsOf(noteId)).toEqual(revisionIds);+ });++ it("400s on options it cannot honour, rather than erasing by some other rule", async () => {+ const { noteId, revisionIds } = await createNoteWithRevisions("Excess rejected", [ undefined ]);++ for (const body of [+ { snapshotsToKeep: -2 },+ { snapshotsToKeep: 1.5 },+ { snapshotsToKeep: "2" },+ { keepNamedSnapshots: "yes" }+ ]) {+ const res = await api.post("/api/revisions/erase-all-excess-revisions", { body });+ expect(res.status).toBe(400);+ }++ expect(revisionIdsOf(noteId)).toEqual(revisionIds);});});diff --git a/packages/trilium-core/src/routes/api/revisions.ts b/packages/trilium-core/src/routes/api/revisions.tsindex a79ada7246..1814f5c17e 100644--- a/packages/trilium-core/src/routes/api/revisions.ts+++ b/packages/trilium-core/src/routes/api/revisions.ts@@ -1,4 +1,10 @@-import { EditedNotesResponse, RevisionItem, RevisionPojo } from "@triliumnext/commons";+import {+ EditedNotesResponse,+ EraseExcessRevisionsOptions,+ EraseExcessRevisionsResponse,+ RevisionItem,+ RevisionPojo+} from "@triliumnext/commons";import type { Request, Response } from "express";import becca from "../../becca/becca.js";@@ -121,11 +127,40 @@ function updateRevisionDescription(req: Request<{ revisionId: string }>) {revision.save();}-function eraseAllExcessRevisions() {+function eraseAllExcessRevisions(req: Request) {+ const options = parseEraseExcessRevisionsOptions(req.body);++ if (typeof options === "string") {+ return [ 400, options ];+ }+const allNoteIds = getSql().getRows("SELECT noteId FROM notes WHERE SUBSTRING(noteId, 1, 1) != '_'") as { noteId: string }[];- allNoteIds.forEach((row) => {- becca.getNote(row.noteId)?.eraseExcessRevisionSnapshots();- });+ let erasedCount = 0;++ for (const row of allNoteIds) {+ erasedCount += becca.getNote(row.noteId)?.eraseExcessRevisionSnapshots(options) ?? 0;+ }++ return { erasedCount } satisfies EraseExcessRevisionsResponse;+}++/**+ * Reads the operation's options off the request body, or returns the message to answer 400 with.+ * Both are optional and an empty body is the configured behaviour, so only values that were sent+ * are checked — a wrong one must fail loudly rather than quietly erase by some other rule.+ */+function parseEraseExcessRevisionsOptions(body: unknown): EraseExcessRevisionsOptions | string {+ const { snapshotsToKeep, keepNamedSnapshots } = (body ?? {}) as EraseExcessRevisionsOptions;++ if (snapshotsToKeep !== undefined && (!Number.isInteger(snapshotsToKeep) || Number(snapshotsToKeep) < -1)) {+ return "snapshotsToKeep must be an integer of -1 (keep every snapshot) or above.";+ }++ if (keepNamedSnapshots !== undefined && typeof keepNamedSnapshots !== "boolean") {+ return "keepNamedSnapshots must be a boolean.";+ }++ return { snapshotsToKeep, keepNamedSnapshots };}function restoreRevision(req: Request<{ revisionId: string }>) {