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(core): two long-standing bugs in similar notes scoring
Elian Doran572de16ef6c5
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 9896f1cf04..e6f174600a 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -431,7 +431,7 @@ export interface SimilarNote {noteId: string;}-export type SimilarNoteResponse = (SimilarNote[] | undefined);+export type SimilarNoteResponse = SimilarNote[];export type SaveSearchNoteResponse = CloneResponse;diff --git a/packages/trilium-core/src/becca/similarity.spec.ts b/packages/trilium-core/src/becca/similarity.spec.tsindex 74ca70cb43..c17e3707d0 100644--- a/packages/trilium-core/src/becca/similarity.spec.ts+++ b/packages/trilium-core/src/becca/similarity.spec.ts@@ -208,6 +208,18 @@ describe("buildRewardMap", () => {expect(xMap.get("xcustom")).toBeUndefined();});+ it("stems english plurals ending in 'es' instead of discarding the word", () => {+ const note = buildNote({ title: "Foxes churches", content: "<p>b</p>" });+ const map = buildRewardMap(note);++ // "foxes" -> "fox", "churches" -> "church"; the stemmed forms carry the+ // reward and the original plural forms are absent.+ expect(typeof map.get("fox")).toStrictEqual("number");+ expect(typeof map.get("church")).toStrictEqual("number");+ expect(map.get("foxes")).toBeUndefined();+ expect(map.get("churches")).toBeUndefined();+ });+it("returns early for text notes whose content is not a string", () => {const note = buildNote({ title: "Binary backed", type: "text" });// Simulate WASM/binary content: getContent yields a non-string.@@ -252,8 +264,7 @@ describe("findSimilarNotes", () => {}const result = await similarity.findSimilarNotes(base.noteId);- const matches = result ?? [];- expect(matches.length).toBe(200);+ expect(result.length).toBe(200);});it("finds similar notes sharing distinctive title words", async () => {@@ -266,10 +277,8 @@ describe("findSimilarNotes", () => {buildRootNote({ title: `${word} alpha beta delta`, type: "text" });buildRootNote({ title: `${word} alpha beta epsilon`, type: "text" });- const result = await similarity.findSimilarNotes(base.noteId);+ const matches = await similarity.findSimilarNotes(base.noteId);- expect(Array.isArray(result)).toBe(true);- const matches = result ?? [];expect(matches.length).toBeGreaterThanOrEqual(2);// Each result has the expected shape and the base note is excluded.for (const r of matches) {@@ -371,8 +380,7 @@ describe("findSimilarNotes", () => {isInheritable: false});- const result = await similarity.findSimilarNotes(base.noteId);- const matches = result ?? [];+ const matches = await similarity.findSimilarNotes(base.noteId);expect(matches.some((r) => r.noteId === linked.noteId)).toBe(false);});@@ -385,20 +393,23 @@ describe("findSimilarNotes", () => {"#archived": ""});- const result = await similarity.findSimilarNotes(base.noteId);- const matches = result ?? [];+ const matches = await similarity.findSimilarNotes(base.noteId);expect(matches.length).toBeGreaterThanOrEqual(1);});- it("returns undefined when a high-scoring candidate has no resolvable note path", async () => {+ it("skips a high-scoring candidate with no resolvable note path instead of aborting", async () => {const word = "phantompathword";const base = buildRootNote({ title: `${word} sun moon star`, type: "text" });const orphan = buildRootNote({ title: `${word} sun moon star`, type: "text" });+ // Built after the orphan so the candidate loop reaches it only if the+ // orphan is skipped rather than aborting the whole search.+ const healthy = buildRootNote({ title: `${word} sun moon comet`, type: "text" });// Force the (hoisting) edge case where a scoring candidate yields no path.orphan.getBestNotePath = () => undefined as unknown as string[];- const result = await similarity.findSimilarNotes(base.noteId);- expect(result).toBeUndefined();+ const matches = await similarity.findSimilarNotes(base.noteId);+ expect(matches.some((r) => r.noteId === healthy.noteId)).toBe(true);+ expect(matches.some((r) => r.noteId === orphan.noteId)).toBe(false);});});diff --git a/packages/trilium-core/src/becca/similarity.ts b/packages/trilium-core/src/becca/similarity.tsindex 75a516b4ea..982968c050 100644--- a/packages/trilium-core/src/becca/similarity.ts+++ b/packages/trilium-core/src/becca/similarity.ts@@ -232,7 +232,7 @@ function splitToWords(text: string) {}// special case for english pluralselse if (words[idx].length > 2 && words[idx].endsWith("es")) {- words[idx] = words[idx].substr(0, words[idx] - 2);+ words[idx] = words[idx].substr(0, words[idx].length - 2);} else if (words[idx].length > 1 && words[idx].endsWith("s")) {words[idx] = words[idx].substr(0, words[idx] - 1);}@@ -250,7 +250,7 @@ function hasConnectingRelation(sourceNote: BNote, targetNote: BNote) {return sourceNote.getAttributes().find((attr) => attr.type === "relation" && ["includenotelink", "imagelink"].includes(attr.name) && attr.value === targetNote.noteId);}-async function findSimilarNotes(noteId: string): Promise<SimilarNote[] | undefined> {+async function findSimilarNotes(noteId: string): Promise<SimilarNote[]> {const results: SimilarNote[] = [];let i = 0;@@ -436,17 +436,14 @@ async function findSimilarNotes(noteId: string): Promise<SimilarNote[] | undefinif (score >= 1.5) {const notePath = candidateNote.getBestNotePath();- // this takes care of note hoisting- if (!notePath) {- // TODO: This return is suspicious, it should probably be continue- return;- }+ // a missing note path (e.g. due to note hoisting) skips only this candidate+ if (notePath) {+ if (beccaService.isNotePathArchived(notePath)) {+ score -= 0.5; // archived penalization+ }- if (beccaService.isNotePathArchived(notePath)) {- score -= 0.5; // archived penalization+ results.push({ score, notePath, noteId: candidateNote.noteId });}-- results.push({ score, notePath, noteId: candidateNote.noteId });}i++;