Skip to content

Build your personal knowledge base with Trilium Notes

fix(sync): make a re-queued sector actually resend its entities

Elian Doranfe54f63208c1
diff --git a/packages/trilium-core/src/services/entity_changes.spec.ts b/packages/trilium-core/src/services/entity_changes.spec.ts
index e04d2d43fb..014d5ad2c0 100644
--- a/packages/trilium-core/src/services/entity_changes.spec.ts
+++ b/packages/trilium-core/src/services/entity_changes.spec.ts
@@ -213,6 +213,20 @@ describe("entity_changes service (real DB)", () => {
expect(before).not.toContain(id);
}
});
+
+ // A sector is re-queued precisely when the two sides disagree about its contents, which
+ // includes the case where the sync server has lost a change it once served. Keeping the
+ // server's instance ID on the re-queued row would leave that row unpushable (pushChanges
+ // skips it as "the server has this already") and the divergence unrepairable.
+ it("takes ownership of changes stamped with another instance, so they can be pushed again", () => {
+ const foreign = buildEntityChange({ entityId: "9foreignInstance", instanceId: "SOME_OTHER_INSTANCE" });
+ getContext().init(() => entityChangesService.putEntityChange(foreign));
+ expect(readRow("notes", foreign.entityId)?.instanceId).toBe("SOME_OTHER_INSTANCE");
+
+ getContext().init(() => entityChangesService.addEntityChangesForSector("notes", "9"));
+
+ expect(readRow("notes", foreign.entityId)?.instanceId).toBe(getInstanceId());
+ });
});
describe("fillAllEntityChanges", () => {
diff --git a/packages/trilium-core/src/services/entity_changes.ts b/packages/trilium-core/src/services/entity_changes.ts
index 49d1173341..5f4807ace7 100644
--- a/packages/trilium-core/src/services/entity_changes.ts
+++ b/packages/trilium-core/src/services/entity_changes.ts
@@ -24,6 +24,29 @@ function putEntityChangeWithForcedChange(origEntityChange: EntityChange) {
putEntityChange(ec);
}
+/**
+ * Re-queues an existing entity change so the next sync sends it to the rest of the cluster again.
+ *
+ * Beyond forcing a new change ID, this takes ownership of the row, and that is the point of it. A
+ * change carries the instance ID of wherever it came from, and both directions of the protocol use
+ * that to avoid echoing a change back to its origin: `pushChanges` skips changes stamped with the
+ * sync server's ID, and a server serving `/api/sync/changed` skips the ones stamped with the
+ * requesting client's. Either filter assumes the other side still holds what it once sent.
+ *
+ * A sector re-queue happens exactly when that assumption has already failed — the two sides disagree
+ * about the sector's contents, e.g. because the server purged a blob that briefly looked unreferenced
+ * while a push was still arriving, or because a peer was restored from an older backup. Keeping the
+ * original stamp would mean the only instance still holding the data refuses to send it, so the
+ * re-queue would produce a change nobody transmits and the sector could never converge. Stamping the
+ * local instance makes the row transmissible again; a receiver that turns out to have it already
+ * applies it as a no-op, since the hashes match.
+ */
+function requeueEntityChange(origEntityChange: EntityChange) {
+ const ec = { ...origEntityChange, changeId: null, instanceId: null };
+
+ putEntityChange(ec);
+}
+
function putEntityChange(origEntityChange: EntityChange) {
const ec = { ...origEntityChange };
@@ -114,7 +137,7 @@ function addEntityChangesForSector(entityName: string, sector: string) {
}
for (const ec of entityChanges) {
- putEntityChangeWithForcedChange(ec);
+ requeueEntityChange(ec);
}
});
@@ -134,7 +157,7 @@ function addEntityChangesForDependingEntity(sector: string, tableName: string, p
);
for (const ec of dependingEntityChanges) {
- putEntityChangeWithForcedChange(ec);
+ requeueEntityChange(ec);
}
return dependingEntityChanges.length;
diff --git a/packages/trilium-core/src/services/sync.spec.ts b/packages/trilium-core/src/services/sync.spec.ts
index f30ade3f7c..a59708bd04 100644
--- a/packages/trilium-core/src/services/sync.spec.ts
+++ b/packages/trilium-core/src/services/sync.spec.ts
@@ -1,4 +1,4 @@
-import type { EntityChange } from "@triliumnext/commons";
+import type { EntityChange, EntityChangeRecord } from "@triliumnext/commons";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import entityConstructor from "../becca/entity_constructor.js";
@@ -41,11 +41,18 @@ interface FakeConfig {
let config: FakeConfig = {};
let changedIdx = 0;
let checkIdx = 0;
-const requestLog: Array<{ method: string; url: string }> = [];
+const requestLog: Array<{ method: string; url: string; body?: ExecOpts["body"] }> = [];
+
+/** The entity IDs actually sent to the sync server, across every push of the run. */
+const pushedEntityIds = () => requestLog
+ .filter((r) => r.url.includes("/api/sync/update"))
+ // syncRequest always serializes the body itself, so a push body is a JSON string.
+ .flatMap((r) => (typeof r.body === "string" ? JSON.parse(r.body || "{}").entities ?? [] : []) as EntityChangeRecord[])
+ .map((record) => record.entityChange.entityId);
const fakeRequest: RequestProvider = fakeRequestProvider({
exec: (<T,>(opts: ExecOpts): Promise<T> => {
- requestLog.push({ method: opts.method, url: opts.url });
+ requestLog.push({ method: opts.method, url: opts.url, body: opts.body });
const url = opts.url;
const reply = (value: unknown) => Promise.resolve(value as T);
@@ -290,6 +297,35 @@ describe("sync service", () => {
expect(requestLog.some((r) => r.url.includes("/api/sync/queue-sector/notes/a"))).toBe(true);
});
+ // The situation the sector re-queue exists for: the sync server no longer has a change this
+ // instance holds. Since the change originally came from the server it carries the server's
+ // instance ID, which is exactly what pushChanges filters out, so before the re-queue took
+ // ownership of the row the one copy left in the cluster could never be sent back (#11073).
+ it("pushes a diverged change the sync server has lost even though it came from there", async () => {
+ const blobId = "9lostByServer";
+ cls.init(() => {
+ const sql = getSql();
+ sql.execute("INSERT INTO blobs (blobId, content, dateModified, utcDateModified) VALUES (?, 'lost content', ?, ?)",
+ [blobId, dateUtils.utcNowDateTime(), dateUtils.utcNowDateTime()]);
+ sql.execute(`
+ INSERT INTO entity_changes (entityName, entityId, hash, isErased, changeId, componentId, instanceId, isSynced, utcDateChanged)
+ VALUES ('blobs', ?, 'lostHash', 0, 'lostChangeId', 'NA', 'REMOTE_INSTANCE', 1, ?)`,
+ [blobId, dateUtils.utcNowDateTime()]);
+ // Everything is pushed as far as sync is concerned, so only the re-queue can resend it.
+ options.setOption("lastSyncedPush", String(syncService.getMaxEntityChangeId()));
+ });
+
+ vi.spyOn(consistencyChecks, "runEntityChangesChecks").mockImplementation(() => {});
+ vi.mocked(contentHashService.checkContentHashes).mockReturnValueOnce([{ entityName: "blobs", sector: "9" }]);
+ config.check = [
+ { maxEntityChangeId: 0, entityHashes: { blobs: { 9: "diverged" } } },
+ { maxEntityChangeId: 0, entityHashes: {} }
+ ];
+
+ await expect(runSync()).resolves.toEqual({ success: true });
+ expect(pushedEntityIds()).toContain(blobId);
+ });
+
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).