Skip to content

Build your personal knowledge base with Trilium Notes

fix(core): stop consistency checks deleting relations to virtual notes

Elian Doran2b7f49a86e1a
diff --git a/packages/trilium-core/src/services/consistency_checks.spec.ts b/packages/trilium-core/src/services/consistency_checks.spec.ts
index 7fab767ec0..d6adfc847d 100644
--- a/packages/trilium-core/src/services/consistency_checks.spec.ts
+++ b/packages/trilium-core/src/services/consistency_checks.spec.ts
@@ -1,10 +1,14 @@
-import { describe, expect, it } from "vitest";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { getContext } from "./context.js";
import { getSql } from "./sql/index.js";
import consistency_checks from "./consistency_checks.js";
import syncOptions from "./sync_options.js";
import optionsService from "./options.js";
+import noteService from "./notes.js";
+import { registerVirtualNoteProvider, unregisterVirtualNoteProvider } from "./virtual_notes.js";
+import becca from "../becca/becca.js";
import becca_loader from "../becca/becca_loader.js";
+import BAttribute from "../becca/entities/battribute.js";
let testCounter = 0;
@@ -140,3 +144,71 @@ describe("Consistency checks during partial sync", () => {
});
});
});
+
+describe("Consistency checks and virtual notes", () => {
+ beforeAll(() => {
+ registerVirtualNoteProvider({
+ namespace: "_vcc",
+ parentNoteId: "_hidden",
+ getSubtree: () => [{ id: "_vccPage", title: "Virtual page", type: "text" }]
+ });
+ getContext().init(() => becca_loader.load());
+ });
+
+ afterAll(() => {
+ unregisterVirtualNoteProvider("_vcc");
+ getContext().init(() => becca_loader.load());
+ });
+
+ function createNote(title: string) {
+ return noteService.createNewNote({ parentNoteId: "root", title, content: "", type: "text" }).note.noteId;
+ }
+
+ /** Persisted relation to `targetNoteId`, as `scanForLinks` creates for a reference link. */
+ function linkTo(sourceNoteId: string, targetNoteId: string) {
+ return new BAttribute({
+ noteId: sourceNoteId,
+ type: "relation",
+ name: "internalLink",
+ value: targetNoteId
+ }).save().attributeId;
+ }
+
+ function isRelationAlive(attributeId: string) {
+ return !!getSql().getValue("SELECT attributeId FROM attributes WHERE attributeId = ? AND isDeleted = 0", [attributeId]);
+ }
+
+ it("keeps relations targeting virtual notes, while still deleting genuinely broken ones", async () => {
+ await getContext().init(async () => {
+ setOption("syncServerHost", "");
+ setOption("syncIncomplete", "false");
+
+ // A virtual note exists in becca but deliberately never in the `notes` table, so a
+ // relation pointing at one looks broken to every SQL-level existence check.
+ expect(becca.getNote("_vccPage")?.isVirtual).toBe(true);
+ expect(getSql().getValue("SELECT noteId FROM notes WHERE noteId = '_vccPage'")).toBeFalsy();
+
+ const sourceNoteId = createNote("note linking into the virtual subtree");
+ const virtualLinkId = linkTo(sourceNoteId, "_vccPage");
+
+ // A relation to a note that is simply gone — `BAttribute.validate()` refuses to create
+ // one, so it has to be planted the way sync does: straight into the table.
+ const brokenLinkId = "brokenLink___";
+ getSql().execute(
+ `INSERT INTO attributes (attributeId, noteId, type, name, value, position, utcDateModified, isDeleted, isInheritable)
+ VALUES (?, ?, 'relation', 'internalLink', 'MISSING_TARGET', 10, '2026-01-01 00:00:00Z', 0, 0)`,
+ [brokenLinkId, sourceNoteId]
+ );
+ becca_loader.reload("plant broken relation");
+
+ await consistency_checks.runOnDemandChecks(true);
+
+ expect(isRelationAlive(virtualLinkId)).toBe(true);
+ expect(isRelationAlive(brokenLinkId)).toBe(false);
+
+ // ...and the surviving relation keeps its becca backlink, so backlinks and link maps still resolve
+ expect(becca.getAttribute(virtualLinkId)).toBeTruthy();
+ expect(becca.getNoteOrThrow("_vccPage").targetRelations.some((rel) => rel.attributeId === virtualLinkId)).toBe(true);
+ });
+ });
+});
diff --git a/packages/trilium-core/src/services/consistency_checks.ts b/packages/trilium-core/src/services/consistency_checks.ts
index f60543ff71..7dbf017a2d 100644
--- a/packages/trilium-core/src/services/consistency_checks.ts
+++ b/packages/trilium-core/src/services/consistency_checks.ts
@@ -13,6 +13,7 @@ import optionsService from "./options.js";
import { getSql } from "./sql/index.js";
import sqlInit from "./sql_init.js";
import syncMutexService from "./sync_mutex.js";
+import { getVirtualNoteProvider } from "./virtual_notes.js";
import ws from "./ws.js";
import { default as eraseService } from "./erase.js";
import becca_loader from "../becca/becca_loader.js";
@@ -34,9 +35,13 @@ class ConsistencyChecks {
this.reloadNeeded = false;
}
- findAndFixIssues(query: string, fixerCb: (res: any) => void) {
+ /**
+ * @param isExempt - rows it accepts are not issues at all: they are dropped before the fixer
+ * runs, so they neither get "fixed" nor counted as unrecovered errors.
+ */
+ findAndFixIssues(query: string, fixerCb: (res: any) => void, isExempt?: (res: any) => boolean) {
const sql = getSql();
- const results = sql.getRows(query);
+ const results = sql.getRows(query).filter((res) => !isExempt?.(res));
for (const res of results) {
try {
@@ -250,7 +255,15 @@ class ConsistencyChecks {
} else {
logError(`Relation '${attributeId}' references missing note '${noteId}'`);
}
- }
+ },
+ // Virtual notes (the in-app help, …) live only in becca and are deliberately never
+ // written to the `notes` table, so a relation pointing at one — the `~internalLink` a
+ // reference link to a help page produces, say — looks broken to a check done in SQL.
+ // Such relations are legitimate, so their whole namespace is exempt. The test is the
+ // registered namespace rather than becca's contents: a provider may not have injected
+ // its subtree at check time, and deleting the user's relations over that would be
+ // irreversible and would propagate through sync.
+ ({ noteId }) => !!getVirtualNoteProvider(noteId)
);
this.findAndFixIssues(