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
fix(sync): partial sync causes recovered notes (closes #9247)
Elian Doranc5808204c472
diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex d430be9ca9..94c5db6841 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -60,6 +60,7 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActisyncServerTimeout: string;syncServerTimeoutTimeScale: number;syncProxy: string;+ syncIncomplete: boolean;mainFontFamily: FontFamily;treeFontFamily: FontFamily;detailFontFamily: FontFamily;diff --git a/packages/trilium-core/src/services/consistency_checks.spec.ts b/packages/trilium-core/src/services/consistency_checks.spec.tsnew file mode 100644index 0000000000..22b1c02116--- /dev/null+++ b/packages/trilium-core/src/services/consistency_checks.spec.ts@@ -0,0 +1,158 @@+import { 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 becca_loader from "../becca/becca_loader.js";++/**+ * Wraps a callback in CLS context and waits for it to complete.+ */+function withContext(fn: () => void | Promise<void>): Promise<void> {+ return new Promise<void>((resolve, reject) => {+ getContext().init(async () => {+ try {+ await fn();+ resolve();+ } catch (e) {+ reject(e);+ }+ });+ });+}++let testCounter = 0;++/**+ * Simulates a partially-synced database by creating a note whose parent+ * note does not exist. This is exactly what happens when a sync client+ * pulls a branch/note record but the parent note hasn't arrived yet.+ *+ * Each call uses unique IDs to avoid conflicts between tests sharing the+ * same in-memory database.+ */+function simulatePartialSync() {+ const sql = getSql();+ testCounter++;+ const missingParentNoteId = `MISSING_PAR_${testCounter}`;+ const testNoteId = `PARTIAL_NOTE${testCounter}`;+ const branchId = `orphan_br_${testCounter}`;++ sql.execute(`+ INSERT INTO notes (noteId, title, type, mime, isProtected, isDeleted, deleteId, blobId, dateCreated, dateModified, utcDateCreated, utcDateModified)+ VALUES (?, 'Test Note', 'text', 'text/html', 0, 0, NULL,+ (SELECT blobId FROM notes WHERE noteId = 'root'),+ '2026-01-01 00:00:00', '2026-01-01 00:00:00', '2026-01-01 00:00:00Z', '2026-01-01 00:00:00Z')+ `, [testNoteId]);++ sql.execute(`+ INSERT INTO branches (branchId, noteId, parentNoteId, notePosition, prefix, isExpanded, isDeleted, utcDateModified)+ VALUES (?, ?, ?, 999, NULL, 0, 0, '2026-01-01 00:00:00Z')+ `, [branchId, testNoteId, missingParentNoteId]);++ // Reload Becca so it sees the raw-SQL-inserted entities,+ // just like what happens after sync_update applies pulled changes.+ becca_loader.reload("simulate partial sync");++ return { missingParentNoteId, testNoteId, branchId };+}++function setOption(name: string, value: string) {+ (optionsService.setOption as any)(name, value);+}++describe("Consistency checks during partial sync", () => {++ it("should NOT fix broken references when sync is incomplete", async () => {+ await withContext(async () => {+ // Simulate sync being configured+ setOption("syncServerHost", "https://fake-sync-server");+ expect(syncOptions.isSyncSetup()).toBe(true);++ // Mark sync as incomplete+ setOption("syncIncomplete", "true");++ const { testNoteId, branchId } = simulatePartialSync();++ // Verify the orphaned branch exists before checks+ const sql = getSql();+ const branchBefore = sql.getValue(+ "SELECT branchId FROM branches WHERE branchId = ? AND isDeleted = 0",+ [branchId]+ );+ expect(branchBefore).toBe(branchId);++ // Run consistency checks — with syncIncomplete=true, these should be skipped+ await consistency_checks.runOnDemandChecks(true);++ // The orphaned branch should still exist (NOT deleted)+ const branchAfter = sql.getValue(+ "SELECT branchId FROM branches WHERE branchId = ? AND isDeleted = 0",+ [branchId]+ );+ expect(branchAfter).toBe(branchId);++ // No recovery branch should have been created+ const recoveryBranch = sql.getValue(+ "SELECT branchId FROM branches WHERE noteId = ? AND parentNoteId = 'root' AND prefix = 'recovered'",+ [testNoteId]+ );+ expect(recoveryBranch).toBeFalsy();+ });+ });++ it("should fix broken references when sync is complete", async () => {+ await withContext(async () => {+ // Simulate sync being configured and complete+ setOption("syncServerHost", "https://fake-sync-server");+ setOption("syncIncomplete", "false");++ const { testNoteId, branchId } = simulatePartialSync();++ await consistency_checks.runOnDemandChecks(true);++ // The orphaned branch should have been deleted+ const sql = getSql();+ const branchAfter = sql.getValue(+ "SELECT branchId FROM branches WHERE branchId = ? AND isDeleted = 0",+ [branchId]+ );+ expect(branchAfter).toBeFalsy();++ // A recovery branch should have been created under root+ const recoveryBranch = sql.getValue(+ "SELECT branchId FROM branches WHERE noteId = ? AND parentNoteId = 'root' AND prefix = 'recovered'",+ [testNoteId]+ );+ expect(recoveryBranch).toBeTruthy();+ });+ });++ it("should fix broken references when sync is not configured", async () => {+ await withContext(async () => {+ // Ensure sync is not configured+ setOption("syncServerHost", "");+ expect(syncOptions.isSyncSetup()).toBe(false);++ const { testNoteId, branchId } = simulatePartialSync();++ await consistency_checks.runOnDemandChecks(true);++ // The orphaned branch should have been deleted (no sync = local DB is authoritative)+ const sql = getSql();+ const branchAfter = sql.getValue(+ "SELECT branchId FROM branches WHERE branchId = ? AND isDeleted = 0",+ [branchId]+ );+ expect(branchAfter).toBeFalsy();++ // A recovery branch should have been created+ const recoveryBranch = sql.getValue(+ "SELECT branchId FROM branches WHERE noteId = ? AND parentNoteId = 'root' AND prefix = 'recovered'",+ [testNoteId]+ );+ expect(recoveryBranch).toBeTruthy();+ });+ });+});diff --git a/packages/trilium-core/src/services/consistency_checks.ts b/packages/trilium-core/src/services/consistency_checks.tsindex b69039c823..f60543ff71 100644--- a/packages/trilium-core/src/services/consistency_checks.ts+++ b/packages/trilium-core/src/services/consistency_checks.ts@@ -898,6 +898,22 @@ class ConsistencyChecks {}async runChecks() {+ // When sync is configured but hasn't fully completed yet (e.g. the app+ // was closed mid-sync and restarted), the local database may be missing+ // notes, branches, or blobs that simply haven't arrived yet. Running+ // consistency checks in this state would incorrectly treat the missing+ // data as corruption and "fix" it — deleting branches, re-parenting+ // notes to root, erasing attachments — then push those destructive+ // changes back to the sync server, propagating the damage.+ //+ // The `syncIncomplete` option is set to "true" when a sync pull begins+ // and cleared to "false" only after sync fully converges. While it is+ // set, we skip consistency checks entirely.+ if (optionsService.getOptionOrNull("syncIncomplete") === "true") {+ getLog().info("Skipping consistency checks because sync is incomplete");+ return;+ }+let elapsedTimeMs;await syncMutexService.doExclusively(() => {diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex 3e19a8d44e..c5b09aba5e 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -69,6 +69,7 @@ export async function initNotSyncedOptions(initialized: boolean, opts: NotSyncedoptionService.createOption("syncServerHost", opts.syncServerHost || "", false);optionService.createOption("syncServerTimeout", "120", false); // 120 seconds (2 minutes)optionService.createOption("syncProxy", opts.syncProxy || "", false);+ optionService.createOption("syncIncomplete", "false", false);}/**diff --git a/packages/trilium-core/src/services/sync.ts b/packages/trilium-core/src/services/sync.tsindex 69ecb89a77..e7ec335159 100644--- a/packages/trilium-core/src/services/sync.ts+++ b/packages/trilium-core/src/services/sync.ts@@ -74,6 +74,12 @@ async function sync() {ws.syncFinished();+ if (optionService.getOptionOrNull("syncIncomplete") === "true") {+ optionService.setOption("syncIncomplete", "false");++ getLog().info("Sync complete — consistency checks will run on next scheduled check.");+ }+return {success: true};@@ -173,6 +179,13 @@ async function pullChanges(syncContext: SyncContext) {outstandingPullCount = resp.outstandingPullCount;+ const hasPendingChanges = entityChanges.length > 0 || outstandingPullCount > 0;+ if (hasPendingChanges && optionService.getOptionOrNull("syncIncomplete") !== "true") {+ optionService.setOption("syncIncomplete", "true");++ getLog().info("Marking sync as incomplete — consistency checks will be deferred until sync converges.");+ }+if (totalPullCount === null) {totalPullCount = entityChanges.length + outstandingPullCount;}@@ -465,7 +478,7 @@ function startSyncTimer() {becca_loader.beccaLoaded.then(() => {setInterval(cls.wrap(sync), 60000);- // kickoff initial sync immediately, but should happen after initial consistency checks+ // kickoff initial sync immediatelysetTimeout(cls.wrap(sync), 5000);// called just so ws.setLastSyncedPush() is called