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
feat(search): try to improve performance
perfectra1n585b6ccd3e3d
diff --git a/apps/server/spec/search_profiling.spec.ts b/apps/server/spec/search_profiling.spec.tsnew file mode 100644index 0000000000..9f5f848034--- /dev/null+++ b/apps/server/spec/search_profiling.spec.ts@@ -0,0 +1,284 @@+/**+ * Integration-level search profiling test.+ *+ * Uses the real SQLite database (spec/db/document.db loaded in-memory),+ * real sql module, real becca cache, and the full app stack.+ *+ * Seeds a large number of notes via direct SQL (much faster than ETAPI)+ * to create a realistic dataset for profiling.+ */+import { Application } from "express";+import { beforeAll, describe, expect, it } from "vitest";+import config from "../src/services/config.js";++let app: Application;++function timed<T>(fn: () => T): [T, number] {+ const start = performance.now();+ const result = fn();+ return [result, performance.now() - start];+}++function randomId(len = 12): string {+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";+ let id = "";+ for (let i = 0; i < len; i++) id += chars[Math.floor(Math.random() * chars.length)];+ return id;+}++function randomWord(len = 8): string {+ const chars = "abcdefghijklmnopqrstuvwxyz";+ let w = "";+ for (let i = 0; i < len; i++) w += chars[Math.floor(Math.random() * chars.length)];+ return w;+}++function generateContent(wordCount: number, keyword?: string): string {+ const paragraphs: string[] = [];+ let remaining = wordCount;+ let injected = false;+ while (remaining > 0) {+ const n = Math.min(remaining, 30 + Math.floor(Math.random() * 30));+ const words: string[] = [];+ for (let i = 0; i < n; i++) words.push(randomWord(3 + Math.floor(Math.random() * 10)));+ if (keyword && !injected && remaining < wordCount / 2) {+ words[Math.floor(words.length / 2)] = keyword;+ injected = true;+ }+ paragraphs.push(`<p>${words.join(" ")}</p>`);+ remaining -= n;+ }+ return paragraphs.join("\n");+}++describe("Search profiling (integration)", () => {+ beforeAll(async () => {+ config.General.noAuthentication = true;+ const buildApp = (await import("../src/app.js")).default;+ app = await buildApp();+ });++ it("seed and profile with realistic data", async () => {+ const sql = (await import("../src/services/sql.js")).default;+ const becca = (await import("../src/becca/becca.js")).default;+ const beccaLoader = (await import("../src/becca/becca_loader.js")).default;+ const cls = (await import("../src/services/cls.js")).default;+ const searchService = (await import("../src/services/search/services/search.js")).default;+ const SearchContext = (await import("../src/services/search/search_context.js")).default;++ await new Promise<void>((resolve) => {+ cls.init(() => {+ const initialNoteCount = Object.keys(becca.notes).length;+ console.log(`\n Initial becca notes: ${initialNoteCount}`);++ const configs = [+ { notes: 2000, words: 500, label: "2K notes × 500 words (~4KB)" },+ { notes: 2000, words: 2000, label: "2K notes × 2000 words (~15KB)" },+ { notes: 5000, words: 500, label: "5K notes × 500 words (~4KB)" },+ { notes: 5000, words: 2000, label: "5K notes × 2000 words (~15KB)" },+ { notes: 10000, words: 1000, label: "10K notes × 1000 words (~8KB)" },+ ];++ for (const cfg of configs) {+ // Reset DB: delete all seeded notes from prior iteration+ sql.execute(`DELETE FROM blobs WHERE blobId LIKE 'seed%'`);+ sql.execute(`DELETE FROM notes WHERE noteId LIKE 'seed%'`);+ sql.execute(`DELETE FROM branches WHERE branchId LIKE 'seed%'`);++ const TOTAL_NOTES = cfg.notes;+ const MATCH_FRACTION = 0.15;+ const CONTENT_WORDS = cfg.words;+ const matchCount = Math.floor(TOTAL_NOTES * MATCH_FRACTION);++ const now = new Date().toISOString().replace("T", " ").replace("Z", "+0000");++ console.log(`\n ──── ${cfg.label} ────`);+ console.log(` Seeding ${TOTAL_NOTES} notes (${matchCount} with keyword)...`);++ const [, seedMs] = timed(() => {+ sql.transactional(() => {+ for (let i = 0; i < TOTAL_NOTES; i++) {+ const isMatch = i < matchCount;+ const noteId = `seed${randomId(8)}`;+ const branchId = `seed${randomId(8)}`;+ const blobId = `seed${randomId(16)}`;+ const title = isMatch+ ? `Performance Doc ${i} ${randomWord(6)}`+ : `General Note ${i} ${randomWord(6)} ${randomWord(5)}`;+ const content = generateContent(+ CONTENT_WORDS,+ isMatch ? "performance" : undefined+ );++ sql.execute(+ `INSERT INTO blobs (blobId, content, dateModified, utcDateModified)+ VALUES (?, ?, ?, ?)`,+ [blobId, content, now, now]+ );++ sql.execute(+ `INSERT INTO notes (noteId, title, type, mime, blobId, isProtected, isDeleted,+ dateCreated, dateModified, utcDateCreated, utcDateModified)+ VALUES (?, ?, 'text', 'text/html', ?, 0, 0, ?, ?, ?, ?)`,+ [noteId, title, blobId, now, now, now, now]+ );++ sql.execute(+ `INSERT INTO branches (branchId, noteId, parentNoteId, notePosition, isDeleted, isExpanded,+ utcDateModified)+ VALUES (?, ?, 'root', ?, 0, 0, ?)`,+ [branchId, noteId, i * 10, now]+ );+ }+ });+ });+ console.log(` SQL seeding: ${seedMs.toFixed(0)}ms`);++ // Reload becca to pick up new notes+ const [, reloadMs] = timed(() => {+ beccaLoader.load();+ });+ console.log(` Becca reload: ${reloadMs.toFixed(0)}ms`);+ console.log(` Becca notes after seed: ${Object.keys(becca.notes).length}`);++ // Verify content is accessible+ const sampleNote = Object.values(becca.notes).find(n => n.title.startsWith("Performance Doc"));+ if (sampleNote) {+ const content = sampleNote.getContent();+ console.log(` Sample content length: ${typeof content === 'string' ? content.length : 0} chars`);+ }++ // ==========================================+ // PROFILING+ // ==========================================++ console.log(`\n --- PROFILING (${cfg.label}) ---\n`);++ // --- 1. Fast search (NoteFlatTextExp only) ---+ searchService.findResultsWithQuery("performance", new SearchContext({ fastSearch: true }));++ const fastTimes: number[] = [];+ let fastResultCount = 0;+ for (let i = 0; i < 5; i++) {+ const [r, ms] = timed(() =>+ searchService.findResultsWithQuery("performance",+ new SearchContext({ fastSearch: true })+ )+ );+ fastTimes.push(ms);+ fastResultCount = r.length;+ }+ const fastAvg = fastTimes.reduce((a, b) => a + b, 0) / fastTimes.length;+ console.log(` Fast search (flat text only): avg ${fastAvg.toFixed(1)}ms (${fastResultCount} results)`);++ // --- 2. Full search (flat text + content fulltext via SQL) ---+ const fullTimes: number[] = [];+ let fullResultCount = 0;+ for (let i = 0; i < 3; i++) {+ const [r, ms] = timed(() =>+ searchService.findResultsWithQuery("performance",+ new SearchContext({ fastSearch: false })+ )+ );+ fullTimes.push(ms);+ fullResultCount = r.length;+ }+ const fullAvg = fullTimes.reduce((a, b) => a + b, 0) / fullTimes.length;+ console.log(` Full search (flat + SQL content): avg ${fullAvg.toFixed(1)}ms (${fullResultCount} results)`);++ // --- 3. Content snippet extraction ---+ const fastResults = searchService.findResultsWithQuery("performance",+ new SearchContext({ fastSearch: true }));+ const trimmed = fastResults.slice(0, 200);+ const tokens = ["performance"];++ const snippetTimes: number[] = [];+ for (let i = 0; i < 3; i++) {+ const [, ms] = timed(() => {+ for (const r of trimmed) {+ r.contentSnippet = searchService.extractContentSnippet(r.noteId, tokens);+ }+ });+ snippetTimes.push(ms);+ }+ const snippetAvg = snippetTimes.reduce((a, b) => a + b, 0) / snippetTimes.length;+ console.log(` Content snippet (${trimmed.length} results): avg ${snippetAvg.toFixed(1)}ms (${(snippetAvg / trimmed.length).toFixed(3)}ms/note)`);++ // --- 4. Raw getContent() cost ---+ const contentTimes: number[] = [];+ const textNotes = trimmed+ .map(r => becca.notes[r.noteId])+ .filter(n => n && ["text", "code"].includes(n.type));++ for (let i = 0; i < 5; i++) {+ const [, ms] = timed(() => {+ for (const n of textNotes) n.getContent();+ });+ contentTimes.push(ms);+ }+ const contentAvg = contentTimes.reduce((a, b) => a + b, 0) / contentTimes.length;+ console.log(` getContent() × ${textNotes.length} notes: avg ${contentAvg.toFixed(1)}ms (${(contentAvg / textNotes.length).toFixed(3)}ms/note)`);++ // --- 5. striptags + normalize cost (isolated) ---+ const striptags = require("striptags");+ const normalizeString = require("normalize-strings");+ const contents = textNotes.map(n => n.getContent() as string).filter(Boolean);++ const [, stripMs] = timed(() => {+ for (const c of contents) {+ striptags(c);+ }+ });+ console.log(` striptags × ${contents.length} notes: ${stripMs.toFixed(1)}ms (${(stripMs / contents.length).toFixed(3)}ms/note)`);++ const stripped = contents.map(c => striptags(c));+ const [, normMs] = timed(() => {+ for (const s of stripped) {+ normalizeString(s.toLowerCase());+ }+ });+ console.log(` normalizeString × ${stripped.length} notes: ${normMs.toFixed(1)}ms (${(normMs / stripped.length).toFixed(3)}ms/note)`);++ // --- 6. Full autocomplete ---+ const autoTimes: number[] = [];+ let autoResultCount = 0;+ for (let i = 0; i < 3; i++) {+ const [r, ms] = timed(() =>+ searchService.searchNotesForAutocomplete("performance", true)+ );+ autoTimes.push(ms);+ autoResultCount = r.length;+ }+ const autoAvg = autoTimes.reduce((a, b) => a + b, 0) / autoTimes.length;+ console.log(`\n FULL AUTOCOMPLETE: avg ${autoAvg.toFixed(1)}ms (${autoResultCount} results)`);++ // --- 7. SQL content scan cost ---+ const [scanCount, scanMs] = timed(() => {+ let count = 0;+ for (const row of sql.iterateRows<{ content: Buffer | string }>(`+ SELECT noteId, type, mime, content, isProtected+ FROM notes JOIN blobs USING (blobId)+ WHERE type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')+ AND isDeleted = 0+ AND LENGTH(content) < 2097152`)) {+ count++;+ }+ return count;+ });+ console.log(` SQL content scan (${scanCount} rows): ${scanMs.toFixed(1)}ms`);++ // --- Summary ---+ console.log(`\n === SUMMARY (${cfg.label}, ${Object.keys(becca.notes).length} total notes) ===`);+ console.log(` Fast search: ${fastAvg.toFixed(1)}ms`);+ console.log(` Full search: ${fullAvg.toFixed(1)}ms`);+ console.log(` Content snippets: ${snippetAvg.toFixed(1)}ms (${(snippetAvg / trimmed.length).toFixed(3)}ms/note)`);+ console.log(` normalizeString: ${normMs.toFixed(1)}ms (${(normMs / stripped.length).toFixed(3)}ms/note)`);+ console.log(` Full autocomplete: ${autoAvg.toFixed(1)}ms`);+ console.log(` SQL scan: ${scanMs.toFixed(1)}ms (${scanCount} rows)`);+ }++ resolve();+ });+ });+ }, 600_000);+});diff --git a/apps/server/src/services/search/services/search.ts b/apps/server/src/services/search/services/search.tsindex 5ca4bda4a1..4701964f5b 100644--- a/apps/server/src/services/search/services/search.ts+++ b/apps/server/src/services/search/services/search.ts@@ -1,6 +1,5 @@"use strict";-import normalizeString from "normalize-strings";import lex from "./lex.js";import handleParens from "./handle_parens.js";import parse from "./parse.js";@@ -8,7 +7,7 @@ import SearchResult from "../search_result.js";import SearchContext from "../search_context.js";import becca from "../../../becca/becca.js";import beccaService from "../../../becca/becca_service.js";-import { normalize, escapeHtml, escapeRegExp } from "../../utils.js";+import { normalize, removeDiacritic, escapeHtml, escapeRegExp } from "../../utils.js";import log from "../../log.js";import hoistedNoteService from "../../hoisted_note.js";import type BNote from "../../../becca/entities/bnote.js";@@ -482,12 +481,12 @@ function extractContentSnippet(noteId: string, searchTokens: string[], maxLength}// Try to find a snippet around the first matching token- const normalizedContent = normalizeString(content.toLowerCase());+ const normalizedContent = normalize(content);let snippetStart = 0;let matchFound = false;for (const token of searchTokens) {- const normalizedToken = normalizeString(token.toLowerCase());+ const normalizedToken = normalize(token);const matchIndex = normalizedContent.indexOf(normalizedToken);if (matchIndex !== -1) {@@ -505,8 +504,8 @@ function extractContentSnippet(noteId: string, searchTokens: string[], maxLengthconst lines = snippet.split('\n');if (lines.length > 4) {// Find which lines contain the search tokens to ensure they're included- const normalizedLines = lines.map(line => normalizeString(line.toLowerCase()));- const normalizedTokens = searchTokens.map(token => normalizeString(token.toLowerCase()));+ const normalizedLines = lines.map(line => normalize(line));+ const normalizedTokens = searchTokens.map(token => normalize(token));// Find the first line that contains a search tokenlet firstMatchLine = -1;@@ -582,7 +581,7 @@ function extractAttributeSnippet(noteId: string, searchTokens: string[], maxLeng// Check if any search token matches the attribute name or valueconst hasMatch = searchTokens.some(token => {- const normalizedToken = normalizeString(token.toLowerCase());+ const normalizedToken = normalize(token);return attrName.includes(normalizedToken) || attrValue.includes(normalizedToken);});@@ -734,7 +733,7 @@ function highlightSearchResults(searchResults: SearchResult[], highlightedTokens// Highlight in note path titleif (result.highlightedNotePathTitle) {const titleRegex = new RegExp(escapeRegExp(token), "gi");- while ((match = titleRegex.exec(normalizeString(result.highlightedNotePathTitle))) !== null) {+ while ((match = titleRegex.exec(removeDiacritic(result.highlightedNotePathTitle))) !== null) {result.highlightedNotePathTitle = wrapText(result.highlightedNotePathTitle, match.index, token.length, "{", "}");// 2 characters are added, so we need to adjust the indextitleRegex.lastIndex += 2;@@ -744,7 +743,7 @@ function highlightSearchResults(searchResults: SearchResult[], highlightedTokens// Highlight in content snippetif (result.highlightedContentSnippet) {const contentRegex = new RegExp(escapeRegExp(token), "gi");- while ((match = contentRegex.exec(normalizeString(result.highlightedContentSnippet))) !== null) {+ while ((match = contentRegex.exec(removeDiacritic(result.highlightedContentSnippet))) !== null) {result.highlightedContentSnippet = wrapText(result.highlightedContentSnippet, match.index, token.length, "{", "}");// 2 characters are added, so we need to adjust the indexcontentRegex.lastIndex += 2;@@ -754,7 +753,7 @@ function highlightSearchResults(searchResults: SearchResult[], highlightedTokens// Highlight in attribute snippetif (result.highlightedAttributeSnippet) {const attributeRegex = new RegExp(escapeRegExp(token), "gi");- while ((match = attributeRegex.exec(normalizeString(result.highlightedAttributeSnippet))) !== null) {+ while ((match = attributeRegex.exec(removeDiacritic(result.highlightedAttributeSnippet))) !== null) {result.highlightedAttributeSnippet = wrapText(result.highlightedAttributeSnippet, match.index, token.length, "{", "}");// 2 characters are added, so we need to adjust the indexattributeRegex.lastIndex += 2;diff --git a/apps/server/src/services/search/services/search_profiling.spec.ts b/apps/server/src/services/search/services/search_profiling.spec.tsnew file mode 100644index 0000000000..96a414b257--- /dev/null+++ b/apps/server/src/services/search/services/search_profiling.spec.ts@@ -0,0 +1,526 @@+/**+ * Search performance profiling tests.+ *+ * These tests measure where time is spent in the search pipeline.+ * We monkeypatch note.getContent() to return synthetic HTML content+ * since unit tests don't have a real SQLite database.+ *+ * KNOWN GAPS vs production:+ * - note.getContent() is instant (monkeypatched) vs ~2ms SQL fetch+ * - NoteContentFulltextExp.execute() is skipped (no sql.iterateRows)+ * because fastSearch=true uses only NoteFlatTextExp+ * - These tests focus on the in-memory/CPU-bound parts of the pipeline+ */+import { describe, it, expect, beforeEach, afterEach } from "vitest";+import searchService from "./search.js";+import BNote from "../../../becca/entities/bnote.js";+import BBranch from "../../../becca/entities/bbranch.js";+import SearchContext from "../search_context.js";+import becca from "../../../becca/becca.js";+import beccaService from "../../../becca/becca_service.js";+import { NoteBuilder, note, id } from "../../../test/becca_mocking.js";+import SearchResult from "../search_result.js";+import { normalizeSearchText } from "../utils/text_utils.js";++// ── helpers ──────────────────────────────────────────────────────────++function randomWord(len = 6): string {+ const chars = "abcdefghijklmnopqrstuvwxyz";+ let word = "";+ for (let i = 0; i < len; i++) {+ word += chars[Math.floor(Math.random() * chars.length)];+ }+ return word;+}++function generateHtmlContent(wordCount: number, includeTarget = false): string {+ const paragraphs: string[] = [];+ let wordsRemaining = wordCount;++ while (wordsRemaining > 0) {+ const paraWords = Math.min(wordsRemaining, 20 + Math.floor(Math.random() * 40));+ const words: string[] = [];+ for (let i = 0; i < paraWords; i++) {+ words.push(randomWord(3 + Math.floor(Math.random() * 10)));+ }+ if (includeTarget && paragraphs.length === 2) {+ words[Math.floor(words.length / 2)] = "target";+ }+ paragraphs.push(`<p>${words.join(" ")}</p>`);+ wordsRemaining -= paraWords;+ }++ return `<html><body>${paragraphs.join("\n")}</body></html>`;+}++function timed<T>(fn: () => T): [T, number] {+ const start = performance.now();+ const result = fn();+ return [result, performance.now() - start];+}++interface TimingEntry { label: string; ms: number; }++function reportTimings(title: string, timings: TimingEntry[]) {+ const total = timings.reduce((s, t) => s + t.ms, 0);+ console.log(`\n=== ${title} (total: ${total.toFixed(1)}ms) ===`);+ for (const { label, ms } of timings) {+ const pct = total > 0 ? ((ms / total) * 100).toFixed(0) : "0";+ const bar = "#".repeat(Math.max(1, Math.round(ms / total * 40)));+ console.log(` ${label.padEnd(55)} ${ms.toFixed(1).padStart(8)}ms ${pct.padStart(3)}% ${bar}`);+ }+}++// ── dataset builder ──────────────────────────────────────────────────++const syntheticContent: Record<string, string> = {};++function buildDataset(noteCount: number, opts: {+ matchFraction?: number;+ labelsPerNote?: number;+ depth?: number;+ contentWordCount?: number;+} = {}) {+ const {+ matchFraction = 0.1,+ labelsPerNote = 3,+ depth = 3,+ contentWordCount = 200,+ } = opts;++ becca.reset();+ for (const key of Object.keys(syntheticContent)) {+ delete syntheticContent[key];+ }++ const rootNote = new NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));+ new BBranch({+ branchId: "none_root",+ noteId: "root",+ parentNoteId: "none",+ notePosition: 10+ });++ const containers: NoteBuilder[] = [];+ let parent = rootNote;+ for (let d = 0; d < depth; d++) {+ const container = note(`Container_${d}_${randomWord(4)}`);+ parent.child(container);+ containers.push(container);+ parent = container;+ }++ const matchCount = Math.floor(noteCount * matchFraction);++ for (let i = 0; i < noteCount; i++) {+ const isMatch = i < matchCount;+ const title = isMatch+ ? `${randomWord(5)} target ${randomWord(5)} Document ${i}`+ : `${randomWord(5)} ${randomWord(6)} ${randomWord(4)} Note ${i}`;++ const n = note(title);++ for (let l = 0; l < labelsPerNote; l++) {+ const labelName = isMatch && l === 0 ? "category" : `label_${randomWord(4)}`;+ const labelValue = isMatch && l === 0 ? "important target" : randomWord(8);+ n.label(labelName, labelValue);+ }++ syntheticContent[n.note.noteId] = generateHtmlContent(contentWordCount, isMatch);++ const containerIndex = i % containers.length;+ containers[containerIndex].child(n);+ }++ // Monkeypatch getContent()+ for (const noteObj of Object.values(becca.notes)) {+ const noteId = noteObj.noteId;+ if (syntheticContent[noteId]) {+ (noteObj as any).getContent = () => syntheticContent[noteId];+ } else {+ (noteObj as any).getContent = () => "";+ }+ }++ return { rootNote, matchCount };+}++// ── profiling tests ──────────────────────────────────────────────────++describe("Search Profiling", () => {++ afterEach(() => {+ becca.reset();+ });++ /**+ * Break down the autocomplete pipeline into every individual stage,+ * including previously unmeasured operations like getBestNotePath,+ * SearchResult construction, and getNoteTitleForPath.+ */+ describe("Granular autocomplete pipeline", () => {++ for (const noteCount of [500, 2000, 5000, 10000]) {+ it(`granular breakdown with ${noteCount} notes`, () => {+ const timings: TimingEntry[] = [];++ const [, buildMs] = timed(() => buildDataset(noteCount, {+ matchFraction: 0.2,+ contentWordCount: 300,+ depth: 5+ }));+ timings.push({ label: `Dataset build (${noteCount} notes)`, ms: buildMs });++ // === NoteFlatTextExp: getCandidateNotes ===+ // This calls getFlatText() + normalizeSearchText() for EVERY note+ const allNotes = Object.values(becca.notes);+ for (const n of allNotes) n.invalidateThisCache();++ const [, candidateMs] = timed(() => {+ const token = normalizeSearchText("target");+ let count = 0;+ for (const n of allNotes) {+ const flatText = normalizeSearchText(n.getFlatText());+ if (flatText.includes(token)) count++;+ }+ return count;+ });+ timings.push({ label: `getCandidateNotes simulation (cold caches)`, ms: candidateMs });++ // Warm cache version+ const [candidateCount, candidateWarmMs] = timed(() => {+ const token = normalizeSearchText("target");+ let count = 0;+ for (const n of allNotes) {+ const flatText = normalizeSearchText(n.getFlatText());+ if (flatText.includes(token)) count++;+ }+ return count;+ });+ timings.push({ label: `getCandidateNotes simulation (warm caches)`, ms: candidateWarmMs });++ // === getBestNotePath for each candidate ===+ const candidates = allNotes.filter(n => {+ const flatText = normalizeSearchText(n.getFlatText());+ return flatText.includes("target");+ });++ const [, pathMs] = timed(() => {+ for (const n of candidates) {+ n.getBestNotePath();+ }+ });+ timings.push({ label: `getBestNotePath (${candidates.length} notes)`, ms: pathMs });++ // === SearchResult construction (includes getNoteTitleForPath) ===+ const paths = candidates.map(n => n.getBestNotePath()).filter(Boolean);++ const [searchResults, srMs] = timed(() => {+ return paths.map(p => new SearchResult(p));+ });+ timings.push({ label: `SearchResult construction (${paths.length} results)`, ms: srMs });++ // === computeScore ===+ const [, scoreMs] = timed(() => {+ for (const r of searchResults) {+ r.computeScore("target", ["target"], true);+ }+ });+ timings.push({ label: `computeScore with fuzzy (${searchResults.length} results)`, ms: scoreMs });++ const [, scoreNoFuzzyMs] = timed(() => {+ for (const r of searchResults) {+ r.computeScore("target", ["target"], false);+ }+ });+ timings.push({ label: `computeScore no-fuzzy`, ms: scoreNoFuzzyMs });++ // === Sorting ===+ const [, sortMs] = timed(() => {+ searchResults.sort((a, b) => {+ if (a.score !== b.score) return b.score - a.score;+ if (a.notePathArray.length === b.notePathArray.length) {+ return a.notePathTitle < b.notePathTitle ? -1 : 1;+ }+ return a.notePathArray.length - b.notePathArray.length;+ });+ });+ timings.push({ label: `Sort results`, ms: sortMs });++ // === Trim + content snippet extraction ===+ const trimmed = searchResults.slice(0, 200);++ const [, snippetMs] = timed(() => {+ for (const r of trimmed) {+ r.contentSnippet = searchService.extractContentSnippet(+ r.noteId, ["target"]+ );+ }+ });+ timings.push({ label: `Content snippet extraction (${trimmed.length} results)`, ms: snippetMs });++ const [, attrMs] = timed(() => {+ for (const r of trimmed) {+ r.attributeSnippet = searchService.extractAttributeSnippet(+ r.noteId, ["target"]+ );+ }+ });+ timings.push({ label: `Attribute snippet extraction`, ms: attrMs });++ // === Highlighting ===+ const [, hlMs] = timed(() => {+ searchService.highlightSearchResults(trimmed, ["target"]);+ });+ timings.push({ label: `Highlighting`, ms: hlMs });++ // === Final mapping (getNoteTitleAndIcon) ===+ const [, mapMs] = timed(() => {+ for (const r of trimmed) {+ beccaService.getNoteTitleAndIcon(r.noteId);+ }+ });+ timings.push({ label: `getNoteTitleAndIcon (${trimmed.length} results)`, ms: mapMs });++ // === Full autocomplete for comparison ===+ const [autoResults, autoMs] = timed(() => {+ return searchService.searchNotesForAutocomplete("target", true);+ });+ timings.push({ label: `Full autocomplete call (end-to-end)`, ms: autoMs });++ reportTimings(`Granular Autocomplete — ${noteCount} notes`, timings);+ expect(autoResults.length).toBeGreaterThan(0);+ });+ }+ });++ /**+ * Test the specific cost of normalizeSearchText which is called+ * pervasively throughout the pipeline.+ */+ describe("normalizeSearchText cost", () => {++ it("profile normalizeSearchText at scale", () => {+ buildDataset(5000, { matchFraction: 0.2, contentWordCount: 100 });++ // Generate various text lengths to profile+ const shortTexts = Array.from({ length: 5000 }, () => randomWord(10));+ const mediumTexts = Array.from({ length: 5000 }, () =>+ Array.from({ length: 20 }, () => randomWord(6)).join(" ")+ );+ const longTexts = Object.values(becca.notes).map(n => n.getFlatText());++ console.log("\n=== normalizeSearchText cost ===");++ const [, shortMs] = timed(() => {+ for (const t of shortTexts) normalizeSearchText(t);+ });+ console.log(` 5000 short texts (10 chars): ${shortMs.toFixed(1)}ms (${(shortMs/5000*1000).toFixed(1)}µs/call)`);++ const [, medMs] = timed(() => {+ for (const t of mediumTexts) normalizeSearchText(t);+ });+ console.log(` 5000 medium texts (120 chars): ${medMs.toFixed(1)}ms (${(medMs/5000*1000).toFixed(1)}µs/call)`);++ const [, longMs] = timed(() => {+ for (const t of longTexts) normalizeSearchText(t);+ });+ console.log(` ${longTexts.length} flat texts (varying): ${longMs.toFixed(1)}ms (${(longMs/longTexts.length*1000).toFixed(1)}µs/call)`);+ });+ });++ /**+ * Test the searchPathTowardsRoot recursive walk which runs+ * for every candidate note in NoteFlatTextExp.+ */+ describe("searchPathTowardsRoot cost", () => {++ it("profile recursive walk with varying hierarchy depth", () => {+ console.log("\n=== Search path walk vs hierarchy depth ===");++ for (const depth of [3, 5, 8, 12]) {+ buildDataset(2000, {+ matchFraction: 0.15,+ depth,+ contentWordCount: 50+ });++ const [results, ms] = timed(() => {+ const ctx = new SearchContext({ fastSearch: true });+ return searchService.findResultsWithQuery("target", ctx);+ });+ console.log(` depth=${depth}: ${ms.toFixed(1)}ms (${results.length} results)`);+ }+ });+ });++ /**+ * Content snippet extraction scaling — the operation that calls+ * note.getContent() for each result.+ */+ describe("Content snippet extraction", () => {++ it("profile snippet extraction with varying content sizes", () => {+ console.log("\n=== Content snippet extraction vs content size ===");++ for (const wordCount of [50, 200, 500, 1000, 2000, 5000]) {+ buildDataset(500, {+ matchFraction: 0.5,+ contentWordCount: wordCount+ });++ const ctx = new SearchContext({ fastSearch: true });+ const results = searchService.findResultsWithQuery("target", ctx);+ const trimmed = results.slice(0, 200);++ const [, ms] = timed(() => {+ for (const r of trimmed) {+ r.contentSnippet = searchService.extractContentSnippet(+ r.noteId, ["target"]+ );+ }+ });++ const avgContentLen = Object.values(syntheticContent)+ .slice(0, 100)+ .reduce((s, c) => s + c.length, 0) / 100;++ console.log(` ${String(wordCount).padStart(5)} words/note (avg ${Math.round(avgContentLen)} chars) × ${trimmed.length} results: ${ms.toFixed(1)}ms (${(ms / trimmed.length).toFixed(3)}ms/note)`);+ }+ });++ it("profile snippet extraction with varying result counts", () => {+ console.log("\n=== Content snippet extraction vs result count ===");++ buildDataset(2000, {+ matchFraction: 0.5,+ contentWordCount: 500+ });++ const ctx = new SearchContext({ fastSearch: true });+ const allResults = searchService.findResultsWithQuery("target", ctx);++ for (const count of [5, 10, 20, 50, 100, 200]) {+ const subset = allResults.slice(0, count);++ const [, ms] = timed(() => {+ for (const r of subset) {+ r.contentSnippet = searchService.extractContentSnippet(+ r.noteId, ["target"]+ );+ }+ });++ console.log(` ${String(count).padStart(3)} results: ${ms.toFixed(1)}ms (${(ms / count).toFixed(3)}ms/note)`);+ }+ });+ });++ /**+ * Two-phase exact/fuzzy search cost.+ */+ describe("Two-phase search cost", () => {++ for (const noteCount of [1000, 5000, 10000]) {+ it(`exact vs progressive with ${noteCount} notes`, () => {+ const timings: TimingEntry[] = [];++ buildDataset(noteCount, { matchFraction: 0.005, contentWordCount: 50 });++ const [exactR, exactMs] = timed(() => {+ const ctx = new SearchContext({ fastSearch: true });+ ctx.enableFuzzyMatching = false;+ return searchService.findResultsWithQuery("target", ctx);+ });+ timings.push({ label: `Exact-only (${exactR.length} results)`, ms: exactMs });++ const [progR, progMs] = timed(() => {+ const ctx = new SearchContext({ fastSearch: true });+ return searchService.findResultsWithQuery("target", ctx);+ });+ timings.push({ label: `Progressive exact→fuzzy (${progR.length} results)`, ms: progMs });++ const overhead = progMs - exactMs;+ timings.push({ label: `Fuzzy phase overhead`, ms: Math.max(0, overhead) });++ reportTimings(`Two-phase — ${noteCount} notes`, timings);+ });+ }+ });++ /**+ * End-to-end scaling to give the full picture.+ */+ describe("End-to-end scaling", () => {++ it("autocomplete at different scales", () => {+ console.log("\n=== End-to-end autocomplete scaling ===");+ console.log(" (fastSearch=true, monkeypatched getContent, no real SQL)");++ for (const noteCount of [100, 500, 1000, 2000, 5000, 10000, 20000]) {+ buildDataset(noteCount, {+ matchFraction: 0.2,+ contentWordCount: 300,+ depth: 4+ });++ // Warm up+ searchService.searchNotesForAutocomplete("target", true);++ const times: number[] = [];+ for (let i = 0; i < 3; i++) {+ const [, ms] = timed(() => searchService.searchNotesForAutocomplete("target", true));+ times.push(ms);+ }++ const avg = times.reduce((a, b) => a + b, 0) / times.length;+ const min = Math.min(...times);++ console.log(+ ` ${String(noteCount).padStart(6)} notes: avg ${avg.toFixed(1)}ms ` ++ `min ${min.toFixed(1)}ms`+ );+ }+ });++ it("compare fast vs non-fast search", () => {+ console.log("\n=== Fast vs non-fast search (no real SQL for content) ===");++ for (const noteCount of [500, 2000, 5000]) {+ buildDataset(noteCount, {+ matchFraction: 0.2,+ contentWordCount: 200,+ depth: 4+ });++ const [, fastMs] = timed(() => {+ const ctx = new SearchContext({ fastSearch: true });+ return searchService.findResultsWithQuery("target", ctx);+ });++ // Non-fast search tries NoteContentFulltextExp which uses sql.iterateRows+ // This will likely fail/return empty since there's no real DB, but we+ // can still measure the overhead of attempting it+ let nonFastMs: number;+ let nonFastCount: number;+ try {+ const [results, ms] = timed(() => {+ const ctx = new SearchContext({ fastSearch: false });+ return searchService.findResultsWithQuery("target", ctx);+ });+ nonFastMs = ms;+ nonFastCount = results.length;+ } catch {+ nonFastMs = -1;+ nonFastCount = -1;+ }++ console.log(+ ` ${String(noteCount).padStart(5)} notes: fast=${fastMs.toFixed(1)}ms ` ++ `non-fast=${nonFastMs >= 0 ? nonFastMs.toFixed(1) + 'ms' : 'FAILED (no real DB)'} ` ++ `(non-fast results: ${nonFastCount})`+ );+ }+ });+ });+});