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
perf(sync): only reconstruct the grand pull total during initial sync
Elian Doran217030f201b6
diff --git a/packages/trilium-core/src/services/sync.spec.ts b/packages/trilium-core/src/services/sync.spec.tsindex 9565471726..527f84954a 100644--- a/packages/trilium-core/src/services/sync.spec.ts+++ b/packages/trilium-core/src/services/sync.spec.ts@@ -115,11 +115,14 @@ describe("sync service", () => {expect(urls.some((u) => u.includes("/api/sync/check"))).toBe(true);});- it("counts already-pulled local changes into the pull total so a resumed sync keeps the grand total", async () => {+ it("counts already-pulled local changes into the pull total so a resumed initial sync keeps the grand total", async () => {// On resume the remote only reports the *remaining* changes; the already-pulled ones live in// the local entity_changes table. The total must be their sum, otherwise the setup progress- // bar rescales the leftover work to 0-100% and appears to restart from zero.+ // bar rescales the leftover work to 0-100% and appears to restart from zero. This only applies+ // while the DB is not yet marked initialized (the initial sync hasn't converged).const countSynced = () => getSql().getValue<number>("SELECT COUNT(1) FROM entity_changes WHERE isSynced = 1") ?? 0;+ const prevInitialized = options.getOptionOrNull("initialized");+ cls.init(() => options.setOption("initialized", "false"));let alreadyPulled = 0;let capturedTotal: number | null = null;@@ -134,12 +137,42 @@ describe("sync service", () => {{ entityChanges: [], lastEntityChangeId: 9, outstandingPullCount: 0 }];- await runSync();+ try {+ await runSync();+ } finally {+ cls.init(() => options.setOption("initialized", prevInitialized ?? "true"));+ }// grand total = already-pulled (local) + this batch (1) + remaining reported by the remote (5)expect(capturedTotal).toBe(alreadyPulled + 1 + 5);});+ it("does not count historical changes into the pull total on an established (initialized) database", async () => {+ // Post-initialization the setup progress bar isn't shown, and counting every change ever+ // pulled would both scan the full entity_changes table and inflate the total. The session+ // total should be just this batch plus the remaining outstanding changes.+ const prevInitialized = options.getOptionOrNull("initialized");+ cls.init(() => options.setOption("initialized", "true"));++ let capturedTotal: number | null = null;+ config.onChanged = (callIndex) => {+ if (callIndex === 1) capturedTotal = syncService.getTotalPullCount();+ };+ config.changed = [+ { entityChanges: [pulledOptionChange()], lastEntityChangeId: 9, outstandingPullCount: 5 },+ { entityChanges: [], lastEntityChangeId: 9, outstandingPullCount: 0 }+ ];++ try {+ await runSync();+ } finally {+ cls.init(() => options.setOption("initialized", prevInitialized ?? "true"));+ }++ // 1 change in this batch + 5 remaining, with no historical inflation.+ expect(capturedTotal).toBe(1 + 5);+ });+it("persists an advanced cursor even when the server returns an empty change batch", async () => {// The server may skip past changes owned by this instance and return no entity changes but an// advanced lastEntityChangeId. The client must persist that advance, otherwise every subsequentdiff --git a/packages/trilium-core/src/services/sync.ts b/packages/trilium-core/src/services/sync.tsindex 1f36b3635d..388329f954 100644--- a/packages/trilium-core/src/services/sync.ts+++ b/packages/trilium-core/src/services/sync.ts@@ -11,6 +11,7 @@ import { getLog } from "./log.js";import optionService from "./options.js";import setupService from "./setup.js";import { getSql } from "./sql/index.js";+import sqlInit from "./sql_init.js";import syncMutexService from "./sync_mutex.js";import syncOptions from "./sync_options.js";import syncUpdateService from "./sync_update.js";@@ -204,10 +205,19 @@ async function pullChanges(syncContext: SyncContext) {if (totalPullCount === null) {// Keep the denominator as the *grand* total so the setup progress bar doesn't reset- // to 0% after a restart. Already-pulled changes persist in the local entity_changes- // table, so adding them to the remaining count reconstructs the original total —- // a resumed sync would otherwise only see the leftover work and rescale from zero.- const alreadyPulled = getSql().getValue<number>("SELECT COUNT(1) FROM entity_changes WHERE isSynced = 1") ?? 0;+ // to 0% after a restart mid initial-sync. Already-pulled changes persist in the local+ // entity_changes table, so adding them to the remaining count reconstructs the+ // original total — a resumed sync would otherwise only see the leftover work and+ // rescale from zero.+ //+ // This only matters while the initial sync is in progress; the DB isn't marked+ // initialized until the first sync converges (syncFinished). On an established+ // database this COUNT would otherwise scan the full entity_changes table on every+ // routine sync and inflate the total with every change ever pulled, so skip it there+ // and count only this session's work.+ const alreadyPulled = sqlInit.isDbInitialized()+ ? 0+ : getSql().getValue<number>("SELECT COUNT(1) FROM entity_changes WHERE isSynced = 1") ?? 0;totalPullCount = alreadyPulled + resp.entityChanges.length + outstandingPullCount;}