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): cache content hashes behind an entity_changes fingerprint
Elian Doranf035cd9eaee8
diff --git a/packages/trilium-core/src/services/content_hash.spec.ts b/packages/trilium-core/src/services/content_hash.spec.tsindex 84cb3a51b5..3ce512bf8d 100644--- a/packages/trilium-core/src/services/content_hash.spec.ts+++ b/packages/trilium-core/src/services/content_hash.spec.ts@@ -1,7 +1,8 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import { getContext } from "./context.js";import contentHash from "./content_hash.js";+import eraseService from "./erase.js";import { getSql } from "./sql/index.js";import { hash } from "./utils/index.js";@@ -148,4 +149,40 @@ describe("content_hash", () => {expect(mismatch?.sector).toBe("O");});});++ describe("fingerprint cache", () => {+ it("serves cached hashes (and skips the unused-blob sweep) while entity_changes is unchanged", () => {+ getContext().init(() => {+ const eraseSpy = vi.spyOn(eraseService, "eraseUnusedBlobs");++ const first = contentHash.getEntityHashes();+ const callsAfterFirst = eraseSpy.mock.calls.length;++ const second = contentHash.getEntityHashes();++ expect(second).toEqual(first);+ // cache hit: neither the full scan nor the unused-blob pre-sweep ran again+ expect(eraseSpy.mock.calls.length).toBe(callsAfterFirst);++ eraseSpy.mockRestore();+ });+ });++ it("recomputes after raw-SQL writes (fingerprint moves) and returns to the original hashes after cleanup", () => {+ getContext().init(() => {+ const before = contentHash.getEntityHashes();++ // raw INSERT bypassing entityChangesService — count/max(id) must still catch it+ insertEntityChange({ entityName: "spec_f", entityId: "Zcached1", hash: "CH1" });+ const after = contentHash.getEntityHashes();+ expect(after["spec_f"]?.["Z"]).toBe(hash("CH1" + 0));++ // raw DELETE — caught as well, and the hashes return to their original values+ getSql().execute("DELETE FROM entity_changes WHERE entityName = 'spec_f'");+ const restored = contentHash.getEntityHashes();+ expect(restored).not.toHaveProperty("spec_f");+ expect(restored).toEqual(before);+ });+ });+ });});diff --git a/packages/trilium-core/src/services/content_hash.ts b/packages/trilium-core/src/services/content_hash.tsindex 138d0f6763..e311f56ccc 100644--- a/packages/trilium-core/src/services/content_hash.ts+++ b/packages/trilium-core/src/services/content_hash.ts@@ -10,7 +10,34 @@ interface FailedCheck {sector: string[1];}+/**+ * Cached sector hashes together with the entity_changes fingerprint they were computed at.+ *+ * Every write to entity_changes moves the fingerprint: updates go through a REPLACE that assigns a+ * fresh autoincrement id (raising MAX(id)) and deletions lower COUNT(*), so `(count, maxId)`+ * changing is a reliable "something changed" signal regardless of which code path wrote. The check+ * runs at the end of every sync cycle of every connected client (every ~60 s), and in the common+ * idle case nothing has changed — the cache turns a full scan-and-hash of entity_changes (plus the+ * unused-blob sweep) into a single index-only query.+ */+let cached: { hashes: Record<string, SectorHash>; count: number; maxId: number } | null = null;++function getEntityChangesFingerprint() {+ return getSql().getRow<{ count: number; maxId: number }>(+ "SELECT COUNT(*) AS count, COALESCE(MAX(id), 0) AS maxId FROM entity_changes");+}+function getEntityHashes() {+ const fingerprint = getEntityChangesFingerprint();++ if (cached && cached.count === fingerprint.count && cached.maxId === fingerprint.maxId) {+ // Nothing changed since the last computation. The unused-blob sweep can be skipped too:+ // a blob can only become unused through a change that itself writes entity_changes.+ getLog().info("Content hashes served from cache (entity changes unchanged)");++ return cached.hashes;+ }+// blob erasure is not synced, we should check before each sync if there's some blob to eraseeraseService.eraseUnusedBlobs();@@ -55,6 +82,9 @@ function getEntityHashes() {getLog().info(`Content hash computation took ${elapsedTimeMs}ms`);+ // fingerprint re-read AFTER the computation: eraseUnusedBlobs above may have deleted rows+ cached = { hashes: hashMap, ...getEntityChangesFingerprint() };+return hashMap;}