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
fix(sync): stop retrying a content hash divergence forever
Elian Doranf7b613289e72
diff --git a/apps/client/src/services/ws.spec.ts b/apps/client/src/services/ws.spec.tsindex 4f59bba1cc..c8b9c94b70 100644--- a/apps/client/src/services/ws.spec.ts+++ b/apps/client/src/services/ws.spec.ts@@ -84,7 +84,7 @@ describe("dispatchMessage", () => {await ws.dispatchMessage({ type: "reload-frontend", reason: "x" } as WebSocketMessage);expect(utilsCtrl.reloadFrontendApp).toHaveBeenCalledWith(expect.stringContaining("reload"));- await ws.dispatchMessage({ type: "sync-hash-check-failed" } as any);+ await ws.dispatchMessage({ type: "sync-hash-check-failed", sectors: ["blobs/9"] } as any);await ws.dispatchMessage({ type: "consistency-checks-failed" } as any);expect(toast.showError).toHaveBeenCalledTimes(2);diff --git a/apps/client/src/services/ws.ts b/apps/client/src/services/ws.tsindex 2bec415a17..19e8a52fa7 100644--- a/apps/client/src/services/ws.ts+++ b/apps/client/src/services/ws.ts@@ -98,7 +98,9 @@ export async function dispatchMessage(message: WebSocketMessage) {} else if (messageType === "frontend-update") {await executeFrontendUpdate(msg.data.entityChanges);} else if (messageType === "sync-hash-check-failed") {- toastService.showError(t("ws.sync-check-failed"), 60000);+ // Not auto-dismissed after the usual few seconds: syncing stays broken until the user acts,+ // and the backend only reports it once (it would otherwise recur with every sync attempt).+ toastService.showError(t("ws.sync-hash-check-failed", { sectors: (msg.sectors ?? []).join(", ") }), 50 * 60000);} else if (messageType === "consistency-checks-failed") {toastService.showError(t("ws.consistency-checks-failed"), 50 * 60000);} else if (messageType === "api-log-messages") {diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex b931d18b6a..aff5120442 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2748,7 +2748,7 @@"backend_scripting_disabled_more_info": "More info"},"ws": {- "sync-check-failed": "Sync check failed!",+ "sync-hash-check-failed": "Sync stopped: this database and the sync server disagree on {{sectors}} and re-syncing did not resolve it. See the logs for details.","consistency-checks-failed": "Consistency checks failed! See logs for details.","encountered-error": "Encountered error \"{{message}}\", check out the console.","lost-websocket-connection-title": "Lost connection to the server",diff --git a/packages/commons/src/lib/ws_api.ts b/packages/commons/src/lib/ws_api.tsindex 1251436833..cfc62e87ca 100644--- a/packages/commons/src/lib/ws_api.ts+++ b/packages/commons/src/lib/ws_api.ts@@ -165,6 +165,16 @@ export type WebSocketMessage = AllTaskDefinitions | {} | {type: "sync-pull-in-progress" | "sync-push-in-progress" | "sync-finished" | "sync-failed";lastSyncedPush: number;+} | {+ /**+ * Syncing stopped because the content hashes of these sectors kept differing from the sync+ * server's even after re-syncing them: the two databases hold data sync cannot reconcile. Unlike+ * every other sync failure this one does not resolve itself by retrying, so it is surfaced to+ * the user instead of only being logged.+ */+ type: "sync-hash-check-failed";+ /** The diverged sectors, each as `entityName/sector` (e.g. `blobs/9`). */+ sectors: string[];} | {type: "consistency-checks-failed"} | {diff --git a/packages/trilium-core/src/services/content_hash.ts b/packages/trilium-core/src/services/content_hash.tsindex b4eb416b74..db6c91830f 100644--- a/packages/trilium-core/src/services/content_hash.ts+++ b/packages/trilium-core/src/services/content_hash.ts@@ -5,9 +5,10 @@ import { hash } from "./utils/index.js";type SectorHash = Record<string, string>;-interface FailedCheck {+export interface FailedCheck {entityName: string;- sector: string[1];+ /** Single character: the first character of the entity ID the sector groups by. */+ sector: string;}/**diff --git a/packages/trilium-core/src/services/sync.spec.ts b/packages/trilium-core/src/services/sync.spec.tsindex 61b87dac9c..f30ade3f7c 100644--- a/packages/trilium-core/src/services/sync.spec.ts+++ b/packages/trilium-core/src/services/sync.spec.ts@@ -13,10 +13,11 @@ import { type ExecOpts, initRequest, type RequestProvider } from "./request.js";import { getSql } from "./sql/index.js";import setupService from "./setup.js";import sqlInit from "./sql_init.js";-import syncService, { estimateEntityChangeRecordSize } from "./sync.js";+import syncService, { estimateEntityChangeRecordSize, MAX_SECTOR_RESYNC_ATTEMPTS, MAX_SYNC_ROUNDS } from "./sync.js";import syncOptions from "./sync_options.js";import syncUpdateService from "./sync_update.js";import dateUtils from "./utils/date.js";+import ws from "./ws.js";interface ChangesResponse {entityChanges: unknown[];@@ -289,6 +290,70 @@ describe("sync service", () => {expect(requestLog.some((r) => r.url.includes("/api/sync/queue-sector/notes/a"))).toBe(true);});+ describe("unresolvable content hash divergence", () => {+ // A sector that keeps diverging after being re-queued used to spin the sync loop forever,+ // re-pushing the same sector every round without ever converging (#11073).+ beforeEach(() => {+ vi.spyOn(consistencyChecks, "runEntityChangesChecks").mockImplementation(() => {});+ vi.spyOn(entityChangesService, "addEntityChangesForSector").mockImplementation(() => {});+ });++ it("gives up on a sector that stays diverged and reports it as a sync error", async () => {+ vi.mocked(contentHashService.checkContentHashes).mockReturnValue([{ entityName: "blobs", sector: "9" }]);+ const notifySpy = vi.spyOn(ws, "syncHashCheckFailed").mockImplementation(() => {});++ const result = await runSync();++ expect(result).toMatchObject({ success: false, errorCode: "CONTENT_HASH_MISMATCH" });+ expect(syncService.getLastSyncError()).toContain("blobs/9");+ // The sector is re-queued on every attempt but the last, which only reports it.+ expect(entityChangesService.addEntityChangesForSector).toHaveBeenCalledTimes(MAX_SECTOR_RESYNC_ATTEMPTS - 1);+ expect(notifySpy).toHaveBeenCalledWith(["blobs/9"]);+ });++ it("notifies about the same divergence once, until a sync converges again", async () => {+ vi.mocked(contentHashService.checkContentHashes).mockReturnValue([{ entityName: "notes", sector: "b" }]);+ const notifySpy = vi.spyOn(ws, "syncHashCheckFailed").mockImplementation(() => {});++ await expect(runSync()).resolves.toMatchObject({ success: false });+ // The sync timer re-runs every minute; the toast must not come back with it.+ await expect(runSync()).resolves.toMatchObject({ success: false });+ expect(notifySpy).toHaveBeenCalledTimes(1);++ vi.mocked(contentHashService.checkContentHashes).mockReturnValue([]);+ await expect(runSync()).resolves.toEqual({ success: true });++ // A divergence that comes back after a healthy sync is worth reporting again.+ vi.mocked(contentHashService.checkContentHashes).mockReturnValue([{ entityName: "notes", sector: "b" }]);+ await expect(runSync()).resolves.toMatchObject({ success: false });+ expect(notifySpy).toHaveBeenCalledTimes(2);+ });++ it("keeps repairing the sectors that can still be fixed", async () => {+ // 'notes/c' is unfixable, 'notes/d' converges on its second attempt: giving up on the+ // former must not cut the latter's repair short.+ vi.mocked(contentHashService.checkContentHashes)+ .mockReturnValueOnce([{ entityName: "notes", sector: "c" }, { entityName: "notes", sector: "d" }])+ .mockReturnValue([{ entityName: "notes", sector: "c" }]);+ vi.spyOn(ws, "syncHashCheckFailed").mockImplementation(() => {});++ await expect(runSync()).resolves.toMatchObject({ success: false, errorCode: "CONTENT_HASH_MISMATCH" });++ expect(entityChangesService.addEntityChangesForSector).toHaveBeenCalledWith("notes", "d");+ expect(syncService.getLastSyncError()).toContain("notes/c");+ expect(syncService.getLastSyncError()).not.toContain("notes/d");+ });++ it("stops a sync run that never converges instead of looping forever", async () => {+ // The server always reports more changes than we have pulled, so every round is told to+ // try again — the shape of an endless sync that isn't a hash divergence.+ config.check = [{ maxEntityChangeId: 999_999_999, entityHashes: {} }];++ await expect(runSync()).resolves.toMatchObject({ success: false, errorCode: "NOT_CONVERGING" });+ expect(requestLog.filter((r) => r.url.endsWith("/api/sync/check")).length).toBe(MAX_SYNC_ROUNDS);+ });+ });+it("skips the content check while local pushes are still outstanding", async () => {// Inject an outstanding synced change while answering the check request.config.onCheck = (callIndex) => {diff --git a/packages/trilium-core/src/services/sync.ts b/packages/trilium-core/src/services/sync.tsindex 7d1fd09e7f..00ed4140f4 100644--- a/packages/trilium-core/src/services/sync.ts+++ b/packages/trilium-core/src/services/sync.ts@@ -4,7 +4,7 @@ import becca from "../becca/becca.js";import appInfo from "./app_info.js";import * as cls from "./context.js";import consistency_checks from "./consistency_checks.js";-import contentHashService from "./content_hash.js";+import contentHashService, { type FailedCheck } from "./content_hash.js";import dateUtils from "./utils/date.js";import entityChangesService from "./entity_changes.js";import { getLog } from "./log.js";@@ -30,6 +30,37 @@ let outstandingPullCount = 0;let totalPullCount: number | null = null;let lastSyncError: string | null = null;+/**+ * How many times the same `(entityName, sector)` pair may fail the content-hash check within a+ * single sync run before the divergence is treated as unresolvable.+ *+ * A failed check re-queues the sector on both sides, and one further round is all it takes for that+ * to have its effect: everything either side holds for the sector is pushed and pulled again before+ * the hashes are compared. The third attempt is slack for a check that raced a concurrent edit (the+ * outstanding-push/pull guards close most, but not all, of that window). Past that, re-queuing the+ * same sector can only produce the same mismatch — the two databases hold something sync is unable+ * to reconcile (a blob erased on one side only, an entity the other side keeps rejecting as older,+ * …) — and retrying it forever is what turned this into an endlessly spinning sync.+ */+export const MAX_SECTOR_RESYNC_ATTEMPTS = 3;++/**+ * Hard cap on the number of login/push/pull/check rounds a single sync run may take. Every repeated+ * round is meant to be making progress — draining outstanding pulls or pushes, or re-queuing a+ * diverged sector — so reaching this many rounds means something is cycling without converging.+ * Bailing out reports it as a sync error rather than looping inside `sync()` forever; the sync+ * timer starts a fresh run a minute later regardless.+ */+export const MAX_SYNC_ROUNDS = 50;++/**+ * The diverged sectors of the most recent unresolvable-divergence notification, so the same toast+ * isn't raised for the rest of the session: sync retries every minute and a divergence sync cannot+ * fix keeps failing every time. Cleared once a sync converges, so a divergence that returns later+ * is reported again.+ */+let notifiedDivergedSectors: string | null = null;+interface CheckResponse {maxEntityChangeId: number;entityHashes: Record<string, Record<string, string>>;@@ -63,8 +94,21 @@ async function sync() {lastSyncError = null;let continueSync = false;+ let rounds = 0;+ // Attempts per `entityName:sector`, and the sectors that exhausted them. Both are+ // per-run: a fresh sync run gets to try the whole repair sequence again.+ const sectorAttempts = new Map<string, number>();+ const unresolvableChecks: FailedCheck[] = [];do {+ if (++rounds > MAX_SYNC_ROUNDS) {+ return reportSyncFailure(+ `Sync did not converge after ${MAX_SYNC_ROUNDS} rounds, giving up for now. `+ + `See the preceding log entries for what each round was still waiting on.`,+ "NOT_CONVERGING"+ );+ }+const syncContext = await login();await pushChanges(syncContext);@@ -75,9 +119,20 @@ async function sync() {await syncFinished(syncContext);- continueSync = await checkContentHash(syncContext);+ const check = await checkContentHash(syncContext, sectorAttempts);++ unresolvableChecks.push(...check.unresolvable);+ continueSync = check.continueSync;} while (continueSync);+ if (unresolvableChecks.length > 0) {+ // Deliberately before setDbAsInitialized()/syncFinished(): this run did not+ // converge, so it must not be reported (nor recorded) as a completed sync.+ return reportUnresolvableDivergence(unresolvableChecks);+ }++ notifiedDivergedSectors = null;+// A converged sync (everything pushed, everything pulled, content hashes verified)// is what makes an initial sync-from-server database usable. setup.triggerSync()// only marks it initialized when its own sync() call succeeds — an initial sync@@ -144,6 +199,47 @@ function redactUrlHosts(message: string) {return message.replace(/(https?:\/\/)[^/\s]+/gi, "$1[redacted]");}+/**+ * Ends a sync run that cannot make progress: records the reason the same way a thrown sync error+ * would (log + `lastSyncError` + a failed sync status), but without the proxy toggle, since nothing+ * here points at the connection.+ */+function reportSyncFailure(message: string, errorCode: string) {+ getLog().error(message);++ lastSyncError = message;++ ws.syncFailed();++ return { success: false, errorCode, message };+}++/**+ * Reports sectors whose content hash kept diverging after {@link MAX_SECTOR_RESYNC_ATTEMPTS}+ * re-syncs. This is a state a user has to act on (the databases hold irreconcilable data, typically+ * repaired by a consistency check or a full re-sync of the client), so on top of the recorded sync+ * error it raises a toast — once per set of sectors, see {@link notifiedDivergedSectors}.+ */+function reportUnresolvableDivergence(failedChecks: FailedCheck[]) {+ const sectors = failedChecks.map(({ entityName, sector }) => `${entityName}/${sector}`);+ const result = reportSyncFailure(+ `Content hash mismatch in ${sectors.join(", ")} could not be resolved by re-syncing the sector(s) `+ + `${MAX_SECTOR_RESYNC_ATTEMPTS} times. The local database and the sync server hold data that sync `+ + `cannot reconcile, so syncing stopped instead of retrying indefinitely.`,+ "CONTENT_HASH_MISMATCH"+ );++ const notificationKey = sectors.join(",");++ if (notifiedDivergedSectors !== notificationKey) {+ notifiedDivergedSectors = notificationKey;++ ws.syncHashCheckFailed(sectors);+ }++ return result;+}+/*** The failure message of the most recent sync attempt, or null when the last attempt* succeeded (or none ran yet). The sync result itself only reaches whoever *triggered*@@ -436,7 +532,16 @@ async function syncFinished(syncContext: SyncContext) {await syncRequest(syncContext, "POST", "/api/sync/finished");}-async function checkContentHash(syncContext: SyncContext) {+/**+ * Compares the local content hashes against the sync server's and re-queues the sectors that+ * differ, so the next round of the sync loop exchanges them again.+ *+ * `sectorAttempts` counts, across the rounds of one sync run, how often each sector has been found+ * diverged; a sector that used up {@link MAX_SECTOR_RESYNC_ATTEMPTS} is not re-queued again and is+ * returned in `unresolvable` instead (exactly once — its counter keeps rising while other sectors+ * are still being repaired). `continueSync` reports whether another round can achieve anything.+ */+async function checkContentHash(syncContext: SyncContext, sectorAttempts: Map<string, number>): Promise<{ continueSync: boolean; unresolvable: FailedCheck[] }> {const resp = await syncRequest<CheckResponse>(syncContext, "GET", "/api/sync/check");if (!resp) {throw new Error("Got no response.");@@ -448,7 +553,7 @@ async function checkContentHash(syncContext: SyncContext) {if (lastSyncedPullId < resp.maxEntityChangeId) {log.info(`There are some outstanding pulls (${lastSyncedPullId} vs. ${resp.maxEntityChangeId}), skipping content check.`);- return true;+ return { continueSync: true, unresolvable: [] };}const notPushedSyncs = getSql().getValue("SELECT EXISTS(SELECT 1 FROM entity_changes WHERE isSynced = 1 AND id > ?)", [getLastSyncedPush()]);@@ -456,25 +561,43 @@ async function checkContentHash(syncContext: SyncContext) {if (notPushedSyncs) {log.info(`There's ${notPushedSyncs} outstanding pushes, skipping content check.`);- return true;+ return { continueSync: true, unresolvable: [] };}- const failedChecks = contentHashService.checkContentHashes(resp.entityHashes);+ const retryable: FailedCheck[] = [];+ const unresolvable: FailedCheck[] = [];++ for (const failedCheck of contentHashService.checkContentHashes(resp.entityHashes)) {+ const key = `${failedCheck.entityName}:${failedCheck.sector}`;+ const attempts = (sectorAttempts.get(key) ?? 0) + 1;++ sectorAttempts.set(key, attempts);++ if (attempts < MAX_SECTOR_RESYNC_ATTEMPTS) {+ retryable.push(failedCheck);+ } else if (attempts === MAX_SECTOR_RESYNC_ATTEMPTS) {+ log.error(`Content hash check for ${failedCheck.entityName} sector ${failedCheck.sector} still fails after ${attempts} attempts, giving up on re-syncing it.`);++ unresolvable.push(failedCheck);+ }+ }- if (failedChecks.length > 0) {+ if (retryable.length > 0) {// before re-queuing sectors, make sure the entity changes are correctconsistency_checks.runEntityChangesChecks();await syncRequest(syncContext, "POST", `/api/sync/check-entity-changes`);}- for (const { entityName, sector } of failedChecks) {+ for (const { entityName, sector } of retryable) {entityChangesService.addEntityChangesForSector(entityName, sector);await syncRequest(syncContext, "POST", `/api/sync/queue-sector/${entityName}/${sector}`);}- return failedChecks.length > 0;+ // Sectors that are out of attempts are reported, not retried, so they must not keep the loop+ // running — only sectors that were actually re-queued can be fixed by another round.+ return { continueSync: retryable.length > 0, unresolvable };}const PAGE_SIZE = 1000000;diff --git a/packages/trilium-core/src/services/ws.spec.ts b/packages/trilium-core/src/services/ws.spec.tsindex 2af44a81d6..6f74fe8aaa 100644--- a/packages/trilium-core/src/services/ws.spec.ts+++ b/packages/trilium-core/src/services/ws.spec.ts@@ -158,6 +158,7 @@ describe("ws service (real DB)", () => {ws.syncPullInProgress();ws.syncFinished();ws.syncFailed();+ ws.syncHashCheckFailed(["blobs/9"]);ws.reloadFrontend("because");const types = sentAll.map((m) => m.type);@@ -166,10 +167,12 @@ describe("ws service (real DB)", () => {"sync-pull-in-progress","sync-finished","sync-failed",+ "sync-hash-check-failed","reload-frontend"]));const pull = sentAll.find((m) => m.type === "sync-pull-in-progress");expect(pull).toMatchObject({ lastSyncedPush: 42 });+ expect(sentAll.find((m) => m.type === "sync-hash-check-failed")).toMatchObject({ sectors: ["blobs/9"] });});it("sends a ping frontend-update when there are no pending entity changes", () => {diff --git a/packages/trilium-core/src/services/ws.ts b/packages/trilium-core/src/services/ws.tsindex 8e6352407f..ae54b2242f 100644--- a/packages/trilium-core/src/services/ws.ts+++ b/packages/trilium-core/src/services/ws.ts@@ -200,6 +200,16 @@ function syncFailed() {sendMessageToAllClients({ type: "sync-failed", lastSyncedPush });}+/**+ * Tells the user that syncing has stopped because the given sectors kept diverging from the sync+ * server's, which no amount of retrying will fix. The sync status icon only ever shows a generic+ * failure (indistinguishable from an unreachable server), so this state — which needs the user to+ * act — is raised as a notification of its own.+ */+function syncHashCheckFailed(sectors: string[]) {+ sendMessageToAllClients({ type: "sync-hash-check-failed", sectors });+}+function reloadFrontend(reason: string) {sendMessageToAllClients({ type: "reload-frontend", reason });}@@ -215,6 +225,7 @@ export default {syncPullInProgress,syncFinished,syncFailed,+ syncHashCheckFailed,sendTransactionEntityChangesToAllClients,setLastSyncedPush,reloadFrontend