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): batch pulled chunks into byte-bounded transactions
Elian Doran1ec71a424b1c
diff --git a/packages/trilium-core/src/services/sync.ts b/packages/trilium-core/src/services/sync.tsindex e7ec335159..b5f9a3283f 100644--- a/packages/trilium-core/src/services/sync.ts+++ b/packages/trilium-core/src/services/sync.ts@@ -14,7 +14,7 @@ import { getSql } from "./sql/index.js";import syncMutexService from "./sync_mutex.js";import syncOptions from "./sync_options.js";import syncUpdateService from "./sync_update.js";-import { randomString, timeLimit } from "./utils/index.js";+import { isLinux, isMac, isWindows, randomString, timeLimit } from "./utils/index.js";import ws from "./ws.js";import getInstanceId from "./instance_id.js";import request, { CookieJar, ExecOpts } from "./request.js";@@ -163,58 +163,81 @@ async function doLogin(): Promise<SyncContext> {async function pullChanges(syncContext: SyncContext) {const log = getLog();+ const maxBatchBytes = getMaxPullBatchBytes();while (true) {- const lastSyncedPull = getLastSyncedPull();- const logMarkerId = randomString(10); // to easily pair sync events between client and server logs- const changesUri = `/api/sync/changed?instanceId=${getInstanceId()}&lastEntityChangeId=${lastSyncedPull}&logMarkerId=${logMarkerId}`;+ // Fetch phase: pull consecutive chunks (each needs its own HTTP round-trip) until we've+ // accumulated ~maxBatchBytes worth of content, then apply them all in a single transaction.+ // The commit itself carries a large fixed per-transaction overhead, so committing once per+ // pulled chunk dominates initial-sync time; batching amortizes it across many chunks. The+ // batch is bounded by bytes (not chunk count) to keep peak memory in check, since a single+ // chunk may already carry a large blob.+ const batch: ChangesResponse[] = [];+ let batchBytes = 0;+ let cursor = getLastSyncedPull();+ let noMoreChanges = false;+ const fetchStart = Date.now();++ do {+ const logMarkerId = randomString(10); // to easily pair sync events between client and server logs+ const changesUri = `/api/sync/changed?instanceId=${getInstanceId()}&lastEntityChangeId=${cursor}&logMarkerId=${logMarkerId}`;++ const resp = await syncRequest<ChangesResponse>(syncContext, "GET", changesUri);+ if (!resp) {+ throw new Error("Request failed.");+ }- const startDate = Date.now();+ outstandingPullCount = resp.outstandingPullCount;- const resp = await syncRequest<ChangesResponse>(syncContext, "GET", changesUri);- if (!resp) {- throw new Error("Request failed.");- }- const { entityChanges, lastEntityChangeId } = resp;+ const hasPendingChanges = resp.entityChanges.length > 0 || outstandingPullCount > 0;+ if (hasPendingChanges && optionService.getOptionOrNull("syncIncomplete") !== "true") {+ optionService.setOption("syncIncomplete", "true");- outstandingPullCount = resp.outstandingPullCount;+ getLog().info("Marking sync as incomplete — consistency checks will be deferred until sync converges.");+ }- const hasPendingChanges = entityChanges.length > 0 || outstandingPullCount > 0;- if (hasPendingChanges && optionService.getOptionOrNull("syncIncomplete") !== "true") {- optionService.setOption("syncIncomplete", "true");+ if (totalPullCount === null) {+ totalPullCount = resp.entityChanges.length + outstandingPullCount;+ }- getLog().info("Marking sync as incomplete — consistency checks will be deferred until sync converges.");- }+ if (resp.entityChanges.length === 0) {+ noMoreChanges = true;+ break;+ }++ batch.push(resp);+ cursor = resp.lastEntityChangeId;+ batchBytes += estimatePullResponseBytes(resp);+ } while (batchBytes < maxBatchBytes);- if (totalPullCount === null) {- totalPullCount = entityChanges.length + outstandingPullCount;+ if (batch.length === 0) {+ break; // nothing left to pull}- const pulledDate = Date.now();+ // Apply phase: all fetched chunks in a single transaction.+ const applyStart = Date.now();+ let batchChanges = 0;getSql().transactional(() => {- if (syncContext.instanceId) {- syncUpdateService.updateEntities(entityChanges, syncContext.instanceId);+ for (const resp of batch) {+ if (syncContext.instanceId) {+ syncUpdateService.updateEntities(resp.entityChanges, syncContext.instanceId);+ }++ batchChanges += resp.entityChanges.length;}- if (lastSyncedPull !== lastEntityChangeId) {- setLastSyncedPull(lastEntityChangeId);+ if (getLastSyncedPull() !== cursor) {+ setLastSyncedPull(cursor);}});- if (entityChanges.length === 0) {+ log.info(+ `Sync: pulled ${batch.length} chunk(s) (${batchChanges} changes, ~${Math.round(batchBytes / 1_048_576)} MB) in ${applyStart - fetchStart}ms and applied them in ${Date.now() - applyStart}ms, ${outstandingPullCount} outstanding pulls`+ );++ if (noMoreChanges) {break;- } else {- try {- // https://github.com/zadam/trilium/issues/4310- const sizeInKb = Math.round(JSON.stringify(resp).length / 1024);-- log.info(- `Sync ${logMarkerId}: Pulled ${entityChanges.length} changes in ${sizeInKb} KB, starting at entityChangeId=${lastSyncedPull} in ${pulledDate - startDate}ms and applied them in ${Date.now() - pulledDate}ms, ${outstandingPullCount} outstanding pulls`- );- } catch (e: any) {- log.error(`Error occurred ${e.message} ${e.stack}`);- }}}@@ -223,6 +246,39 @@ async function pullChanges(syncContext: SyncContext) {totalPullCount = null;}+/**+ * Maximum accumulated content size (in bytes) to buffer across pulled chunks before applying them+ * in a single transaction during {@link pullChanges}. Larger batches mean fewer commits (each of+ * which carries a large fixed overhead) at the cost of higher peak memory while the batch is held+ * in memory. The standalone/browser build runs SQLite (sql.js) fully in memory, so it uses a much+ * smaller budget than native desktop/server builds.+ */+function getMaxPullBatchBytes() {+ // Standalone/browser is the only platform reporting none of mac/windows/linux.+ const isBrowser = !isMac() && !isWindows() && !isLinux();++ return isBrowser ? 16 * 1024 * 1024 : 32 * 1024 * 1024;+}++/** Rough in-memory size of a pulled changes response, dominated by (base64-encoded) blob content. */+function estimatePullResponseBytes(resp: ChangesResponse) {+ let bytes = 0;++ for (const { entity } of resp.entityChanges) {+ const content = entity?.content;++ if (typeof content === "string") {+ bytes += content.length;+ } else if (content) {+ bytes += content.length; // Uint8Array+ }++ bytes += 128; // rough per-record metadata overhead+ }++ return bytes;+}+async function pushChanges(syncContext: SyncContext) {let lastSyncedPush: number | null | undefined = getLastSyncedPush();