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): fill the pull response byte cap across row fetches
Elian Doran2cfe8c55ca91
diff --git a/packages/trilium-core/src/routes/api/sync.spec.ts b/packages/trilium-core/src/routes/api/sync.spec.tsindex 054aa2d6af..61a8e85815 100644--- a/packages/trilium-core/src/routes/api/sync.spec.ts+++ b/packages/trilium-core/src/routes/api/sync.spec.ts@@ -199,6 +199,41 @@ describe("Sync API (core)", () => {sql.execute("DELETE FROM options WHERE name = 'otst_opt'");});+ it("fills the response across multiple 1000-row fetches instead of stopping at the row limit", async () => {+ // 1100 metadata-only rows estimate to ~0.33 MB — far below the 8 MB byte cap — so a+ // single pull must now return all of them in one response (two LIMIT-1000 fetches)+ // rather than capping at 1000 rows per round-trip.+ const sql = getSql();+ const maxId = sql.getValue<number>("SELECT COALESCE(MAX(id), 0) FROM entity_changes");+ const COUNT = 1100;++ sql.transactional(() => {+ for (let i = 0; i < COUNT; i++) {+ sql.execute("INSERT INTO options (name, value, isSynced, utcDateModified) VALUES (?, 'v', 1, '2020-01-01T00:00:00.000Z')", [`rowcap_opt_${i}`]);+ sql.execute(+ `INSERT INTO entity_changes (id, entityName, entityId, hash, isErased, changeId, componentId, instanceId, isSynced, utcDateChanged)+ VALUES (?, 'options', ?, 'h', 0, ?, 'cmp', 'OTHER', 1, '2020-01-01T00:00:00.000Z')`,+ [maxId + 1 + i, `rowcap_opt_${i}`, `rowcap_chg_${i}`]+ );+ }+ });++ const res = await api.get<{ entityChanges: unknown[]; lastEntityChangeId: number; outstandingPullCount: number }>(+ "/api/sync/changed",+ { query: { instanceId: "CLIENTX", lastEntityChangeId: String(maxId) } }+ );++ expect(res.status).toBe(200);+ expect(res.body.entityChanges.length).toBe(COUNT); // > 1000: the row limit no longer binds+ expect(res.body.lastEntityChangeId).toBe(maxId + COUNT);+ expect(res.body.outstandingPullCount).toBe(0);++ sql.transactional(() => {+ sql.execute("DELETE FROM entity_changes WHERE id BETWEEN ? AND ?", [maxId + 1, maxId + COUNT]);+ sql.execute("DELETE FROM options WHERE name LIKE 'rowcap_opt_%'");+ });+ });+it("getEntityChangeRecords stops accumulating once the response byte cap is reached", () => {const sql = getSql();const maxId = sql.getValue<number>("SELECT COALESCE(MAX(id), 0) FROM entity_changes");diff --git a/packages/trilium-core/src/routes/api/sync.ts b/packages/trilium-core/src/routes/api/sync.tsindex ccae8c6ac9..6acaa38b82 100644--- a/packages/trilium-core/src/routes/api/sync.ts+++ b/packages/trilium-core/src/routes/api/sync.ts@@ -1,4 +1,4 @@-import { type EntityChange, SyncTestResponse } from "@triliumnext/commons";+import { type EntityChange, type EntityChangeRecord, SyncTestResponse } from "@triliumnext/commons";import type { Request } from "express";import { t } from "i18next";@@ -9,7 +9,7 @@ import { getLog } from "../../services/log.js";import optionService from "../../services/options.js";import { getSql } from "../../services/sql/index.js";import sqlInit from "../../services/sql_init.js";-import syncService from "../../services/sync.js";+import syncService, { estimateEntityChangeRecordSize, MAX_PULL_RESPONSE_BYTES } from "../../services/sync.js";import syncOptions from "../../services/sync_options.js";import syncUpdateService from "../../services/sync_update.js";import * as utils from "../../services/utils/index.js";@@ -117,7 +117,7 @@ function forceFullSync() {* description: Marker to identify this request in server log* responses:* '200':- * description: Sync changes, limited to approximately one megabyte.+ * description: Sync changes, limited to approximately eight megabytes.* content:* application/json:* schema:@@ -146,12 +146,23 @@ function getChanged(req: Request) {throw new ValidationError("Missing or invalid last entity change ID.");}- let lastEntityChangeId: number | null | undefined = parseInt(req.query.lastEntityChangeId);+ let lastEntityChangeId = parseInt(req.query.lastEntityChangeId);const clientInstanceId = req.query.instanceId;- let filteredEntityChanges: EntityChange[] = [];const sql = getSql();- do {+ const entityChangeRecords: EntityChangeRecord[] = [];+ let estimatedResponseBytes = 0;+ // Where the next row fetch starts. Advances over every fetched row, unlike+ // `lastEntityChangeId` (the cursor returned to the client), which only advances over rows the+ // client can safely skip: records included in the response and batches consisting entirely of+ // the client's own changes.+ let fetchCursor = lastEntityChangeId;++ // Accumulate rows across LIMIT-1000 fetches until the response byte estimate crosses the cap+ // (or the table is exhausted). Metadata-only records are ~300 bytes, so a single 1000-row fetch+ // fills only ~4% of the byte budget — without this loop the row limit binds long before the+ // byte cap on metadata-dense ranges, costing many extra round-trips.+ while (estimatedResponseBytes < MAX_PULL_RESPONSE_BYTES) {const entityChanges: EntityChange[] = sql.getRows<EntityChange>(`SELECT *@@ -160,25 +171,45 @@ function getChanged(req: Request) {AND id > ?ORDER BY idLIMIT 1000`,- [lastEntityChangeId]+ [fetchCursor]);if (entityChanges.length === 0) {break;}- filteredEntityChanges = entityChanges.filter((ec) => ec.instanceId !== clientInstanceId);+ // rows fetched from entity_changes always carry an id+ fetchCursor = entityChanges[entityChanges.length - 1].id ?? fetchCursor;- if (filteredEntityChanges.length === 0) {- lastEntityChangeId = entityChanges[entityChanges.length - 1].id;+ const foreignEntityChanges = entityChanges.filter((ec) => ec.instanceId !== clientInstanceId);++ if (foreignEntityChanges.length === 0) {+ // the whole batch is the client's own changes — skip the client's cursor past it+ lastEntityChangeId = fetchCursor;+ continue;}- } while (filteredEntityChanges.length === 0);- const entityChangeRecords = syncService.getEntityChangeRecords(filteredEntityChanges);+ const records = syncService.getEntityChangeRecords(foreignEntityChanges, MAX_PULL_RESPONSE_BYTES - estimatedResponseBytes);- if (entityChangeRecords.length > 0) {- lastEntityChangeId = entityChangeRecords[entityChangeRecords.length - 1].entityChange.id;+ for (const record of records) {+ estimatedResponseBytes += estimateEntityChangeRecordSize(record);+ }++ entityChangeRecords.push(...records);++ if (records.length > 0) {+ // rows fetched from entity_changes always carry an id+ lastEntityChangeId = records[records.length - 1].entityChange.id ?? lastEntityChangeId;+ }+ if (records.length < foreignEntityChanges.length) {+ // the byte budget was reached mid-batch (or trailing records were skipped) — anything+ // not included must be re-served next request, so stop without advancing further+ break;+ }+ }++ if (entityChangeRecords.length > 0) {getLog().info(`Returning ${entityChangeRecords.length} entity changes in ${Date.now() - startTime}ms`);}diff --git a/packages/trilium-core/src/services/sync.ts b/packages/trilium-core/src/services/sync.tsindex 6d7be8d923..1fb47a39fc 100644--- a/packages/trilium-core/src/services/sync.ts+++ b/packages/trilium-core/src/services/sync.ts@@ -468,7 +468,7 @@ function getEntityChangeRow(entityChange: EntityChange) {* receiver's peak memory. It is a soft cap: a response is at least one record, and the record that* crosses the threshold is still included.*/-const MAX_PULL_RESPONSE_BYTES = 8 * 1024 * 1024;+export const MAX_PULL_RESPONSE_BYTES = 8 * 1024 * 1024;function getEntityChangeRecords(entityChanges: EntityChange[], maxResponseBytes = MAX_PULL_RESPONSE_BYTES) {const records: EntityChangeRecord[] = [];