Skip to content

Build your personal knowledge base with Trilium Notes

perf(sync): pipeline the pull loop so downloads overlap SQL apply

Elian Doran95714000bef6
diff --git a/packages/trilium-core/src/services/sync.spec.ts b/packages/trilium-core/src/services/sync.spec.ts
index ff69e6dadb..337ad43e7a 100644
--- a/packages/trilium-core/src/services/sync.spec.ts
+++ b/packages/trilium-core/src/services/sync.spec.ts
@@ -14,6 +14,7 @@ import setupService from "./setup.js";
import sqlInit from "./sql_init.js";
import syncService, { estimateEntityChangeRecordSize } from "./sync.js";
import syncOptions from "./sync_options.js";
+import syncUpdateService from "./sync_update.js";
import dateUtils from "./utils/date.js";
interface ChangesResponse {
@@ -116,6 +117,32 @@ describe("sync service", () => {
expect(urls.some((u) => u.includes("/api/sync/check"))).toBe(true);
});
+ it("prefetches the next chunk before applying the current batch (download/apply pipelining)", async () => {
+ const events: string[] = [];
+ // The first chunk's estimated size (content length) exceeds the batch budget, so the
+ // batch closes after one chunk and the next chunk must be prefetched before the apply.
+ const bigChange = { entityChange: { entityName: "notes", entityId: "pf1" }, entity: { content: "x".repeat(33 * 1024 * 1024) } };
+ const smallChange = { entityChange: { entityName: "notes", entityId: "pf2" }, entity: { content: "y" } };
+ config.changed = [
+ { entityChanges: [bigChange], lastEntityChangeId: 1, outstandingPullCount: 1 },
+ { entityChanges: [smallChange], lastEntityChangeId: 2, outstandingPullCount: 0 },
+ { entityChanges: [], lastEntityChangeId: 2, outstandingPullCount: 0 }
+ ];
+ config.onChanged = (i) => events.push(`fetch:${i}`);
+ vi.spyOn(syncUpdateService, "updateEntities").mockImplementation(() => {
+ events.push("apply");
+ });
+
+ await expect(runSync()).resolves.toEqual({ success: true });
+
+ // The request for chunk 1 is fired before batch 0 (the big chunk) is applied, so the
+ // download overlaps the SQL work; both batches are still applied, in order.
+ expect(events.indexOf("fetch:1")).toBeGreaterThan(events.indexOf("fetch:0"));
+ expect(events.indexOf("apply")).toBeGreaterThan(events.indexOf("fetch:1"));
+ expect(events.filter((e) => e === "apply")).toHaveLength(2);
+ expect(events.indexOf("fetch:2")).toBeGreaterThan(events.indexOf("apply"));
+ });
+
it("marks the database as initialized once a sync converges", async () => {
// An initial sync-from-server interrupted by a crash resumes via sync/now or the sync
// timer — NOT via setup.triggerSync(), which is the only other place that sets the flag.
diff --git a/packages/trilium-core/src/services/sync.ts b/packages/trilium-core/src/services/sync.ts
index b3785eff90..6e92e4d1ab 100644
--- a/packages/trilium-core/src/services/sync.ts
+++ b/packages/trilium-core/src/services/sync.ts
@@ -175,6 +175,13 @@ async function pullChanges(syncContext: SyncContext) {
const maxBatchBytes = getMaxPullBatchBytes();
const maxBlobContentSize = getMaxBlobContentSize();
+ // Download/apply pipeline: the request for the next batch's first chunk is fired just before
+ // the current batch is applied, so the network transfer overlaps the (synchronous) SQL work —
+ // the two are roughly equal halves of initial-sync wall time, so overlapping them nearly
+ // halves it. Only the first chunk of a batch can be prefetched: every subsequent chunk's URL
+ // depends on the cursor returned by the response before it.
+ let prefetchedChunk: Promise<ChangesResponse> | null = null;
+
while (true) {
// 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.
@@ -189,14 +196,8 @@ async function pullChanges(syncContext: SyncContext) {
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}`
- + (maxBlobContentSize ? `&maxBlobContentSize=${maxBlobContentSize}` : "");
-
- const resp = await syncRequest<ChangesResponse>(syncContext, "GET", changesUri);
- if (!resp) {
- throw new Error("Request failed.");
- }
+ const resp = await (prefetchedChunk ?? fetchChangesChunk(syncContext, cursor, maxBlobContentSize));
+ prefetchedChunk = null;
outstandingPullCount = resp.outstandingPullCount;
@@ -247,6 +248,13 @@ async function pullChanges(syncContext: SyncContext) {
break;
}
+ if (!noMoreChanges) {
+ prefetchedChunk = fetchChangesChunk(syncContext, cursor, maxBlobContentSize);
+ // If the apply phase throws, the in-flight prefetch is abandoned — pre-attach a
+ // handler so a late network failure doesn't surface as an unhandled rejection.
+ prefetchedChunk.catch(() => {});
+ }
+
// Apply phase: all fetched chunks in a single transaction.
const applyStart = Date.now();
let batchChanges = 0;
@@ -258,6 +266,11 @@ async function pullChanges(syncContext: SyncContext) {
}
batchChanges += resp.entityChanges.length;
+
+ // Drop the applied chunk's rows (and their multi-MB content strings) right away
+ // instead of keeping the whole batch alive until the loop ends — on the WASM build
+ // the renderer is memory-capped and peak size is what kills it.
+ resp.entityChanges = [];
}
if (getLastSyncedPull() !== cursor) {
@@ -281,6 +294,19 @@ async function pullChanges(syncContext: SyncContext) {
totalPullCount = null;
}
+async function fetchChangesChunk(syncContext: SyncContext, cursor: number, maxBlobContentSize: number): Promise<ChangesResponse> {
+ 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}`
+ + (maxBlobContentSize ? `&maxBlobContentSize=${maxBlobContentSize}` : "");
+
+ const resp = await syncRequest<ChangesResponse>(syncContext, "GET", changesUri);
+ if (!resp) {
+ throw new Error("Request failed.");
+ }
+
+ return resp;
+}
+
/**
* 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