From 2c57cf195eb9dca6e7d6083575a4ba8bc749af9a Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:45:47 -0500 Subject: [PATCH] perf(search): precompute guidance word sets, skip regex worker on empty candidates, and index Go view lookups (#13610) * perf(search): precompute guidance word sets, skip regex worker on empty candidates, and index Go view lookups * test(go): cover filtered index paging across collections --- src/application/GuidanceAccess.ts | 99 ++++++++------- src/domain/analysisView/goBinaryView.test.ts | 74 +++++++++++ src/domain/analysisView/goBinaryView.ts | 122 ++++++++++++------- src/domain/analysisView/selectViewRows.ts | 30 ++++- src/process/RegexMatcher.ts | 11 ++ 5 files changed, 250 insertions(+), 86 deletions(-) diff --git a/src/application/GuidanceAccess.ts b/src/application/GuidanceAccess.ts index 4db24ff796..f13ea0b53c 100644 --- a/src/application/GuidanceAccess.ts +++ b/src/application/GuidanceAccess.ts @@ -43,6 +43,11 @@ interface GuidanceBundle { string, ReadonlyMap >; + readonly ownWordsBySection: ReadonlyMap>; + readonly headingWordsBySection: ReadonlyMap< + GuideSection, + ReadonlySet + >; } interface GuideFileStatStamp { @@ -212,10 +217,18 @@ const readBundle = async ( message: "Installed REA guidance exceeds the 4,096-section or 25,165,824 expanded UTF-16-code-unit index allowance; no partial index was used.", }; + const ownWordsBySection = new Map>(); + const headingWordsBySection = new Map>(); + for (const section of sections) { + ownWordsBySection.set(section, new Set(words(section.ownContent))); + headingWordsBySection.set(section, new Set(words(section.heading))); + } const bundle: GuidanceBundle = { digest, sections, sectionsByGuide: indexSectionsByGuide(sections), + ownWordsBySection, + headingWordsBySection, }; if (preReadStamps !== undefined) { const postReadStamps = await statPackagedGuides(); @@ -446,7 +459,7 @@ const searchGuidanceInScope = async ( const queryWords = words(parsed.data.query); const { coverage, ranked } = rankSections( - bundle.sections, + bundle, queryWords, queryWords.filter((word) => !GENERIC_QUERY_WORDS.has(word)), ); @@ -536,14 +549,16 @@ interface SectionRanking { * document order, so every subsection is complete before its parent reads it. */ const rankSections = ( - sections: readonly GuideSection[], + bundle: GuidanceBundle, queryWords: readonly string[], specificWords: readonly string[], ): SectionRanking => { if (specificWords.length === 0) return { coverage: [], ranked: [] }; const bySection = new Map(); - const coverage = sections.map((section) => { - const own = new Set(words(section.ownContent)); + const coverage = bundle.sections.map((section) => { + const own = + bundle.ownWordsBySection.get(section) ?? + new Set(words(section.ownContent)); const present = queryWords.filter((word) => own.has(word)); const fact = { section, @@ -556,7 +571,8 @@ const rankSections = ( }); const covers = (terms: ReadonlySet): boolean => specificWords.every((word) => terms.has(word)); - for (const fact of coverage.toReversed()) { + for (let index = coverage.length - 1; index >= 0; index -= 1) { + const fact = coverage[index]!; const parent = fact.section.parent === undefined ? undefined @@ -565,42 +581,43 @@ const rankSections = ( for (const word of fact.subtree) parent.subtree.add(word); if (covers(fact.subtree)) parent.childCovers = true; } - const ranked = coverage - .flatMap((fact, index): RankedSection[] => { - if (!covers(fact.subtree)) return []; - const own = new Set(fact.own); - const focused = covers(own); - // A subsection holding every term is already a match of its own. - if (!focused && fact.childCovers) return []; - const matched = focused - ? fact.own - : queryWords.filter((word) => fact.subtree.has(word)); - const headingWords = new Set(words(fact.section.heading)); - return [ - { - section: fact.section, - scope: focused ? "section" : "subsections", - matched, - score: - matched.length + - matched.filter((word) => headingWords.has(word)).length * 2, - own: fact.own, - scattered: specificWords.filter((word) => !own.has(word)), - index, - }, - ]; - }) - .sort( - (left, right) => - // Co-located terms rank before terms gathered across subsections. - Number(left.scope === "subsections") - - Number(right.scope === "subsections") || - right.score - left.score || - // Prefer a focused recipe over a long overview when term scores tie. - left.section.content.length - right.section.content.length || - compareText(left.section.guide, right.section.guide) || - left.section.ordinal - right.section.ordinal, - ); + const ranked: RankedSection[] = []; + for (let index = 0; index < coverage.length; index += 1) { + const fact = coverage[index]!; + if (!covers(fact.subtree)) continue; + const own = new Set(fact.own); + const focused = covers(own); + // A subsection holding every term is already a match of its own. + if (!focused && fact.childCovers) continue; + const matched = focused + ? fact.own + : queryWords.filter((word) => fact.subtree.has(word)); + const headingWords = + bundle.headingWordsBySection.get(fact.section) ?? + new Set(words(fact.section.heading)); + let headingHits = 0; + for (const word of matched) if (headingWords.has(word)) headingHits += 1; + ranked.push({ + section: fact.section, + scope: focused ? "section" : "subsections", + matched, + score: matched.length + headingHits * 2, + own: fact.own, + scattered: specificWords.filter((word) => !own.has(word)), + index, + }); + } + ranked.sort( + (left, right) => + // Co-located terms rank before terms gathered across subsections. + Number(left.scope === "subsections") - + Number(right.scope === "subsections") || + right.score - left.score || + // Prefer a focused recipe over a long overview when term scores tie. + left.section.content.length - right.section.content.length || + compareText(left.section.guide, right.section.guide) || + left.section.ordinal - right.section.ordinal, + ); return { coverage, ranked }; }; diff --git a/src/domain/analysisView/goBinaryView.test.ts b/src/domain/analysisView/goBinaryView.test.ts index 968946c3d8..0ac2775e2c 100644 --- a/src/domain/analysisView/goBinaryView.test.ts +++ b/src/domain/analysisView/goBinaryView.test.ts @@ -202,3 +202,77 @@ it.each(["dependencies", "settings"] as const)( }); }, ); + +const indexedNames = ["keep-0", "drop-1", "keep-2", "keep-3", "keep-4"]; +const indexedReport: GoBinary = { + ...report, + build_info: { + header_offset: 0, + encoding: "inline", + go_version: null, + go_version_bytes_base64: "", + module_text: null, + module_bytes_base64: "", + version_location: { offset: 32, bytes: 0 }, + module_location: { offset: 32, bytes: 0 }, + module: { + path: null, + main: null, + dependencies: indexedNames.map((path) => ({ + path, + version: "v1.0.0", + sum: null, + replacement: null, + })), + settings: indexedNames.map((key) => ({ key, value: "value" })), + unparsed_lines: [], + unparsed_line_bytes_base64: [], + complete: true, + }, + }, + string_literals: { + evidence_kind: "inferred", + items: indexedNames.map((value, index) => ({ + value, + location: { offset: 256 + index * 16, bytes: Buffer.byteLength(value) }, + first_header_offset: 64 + index * 16, + reference_count: 1, + })), + discovered_count: indexedNames.length, + aggregate_bytes: Buffer.byteLength(indexedNames.join("")), + max_items: indexedNames.length, + truncated: false, + }, +}; + +const selectedNames = indexedNames.filter((name) => name.startsWith("keep-")); +it.each([ + { collection: "dependencies", paths: selectedNames }, + { collection: "settings", keys: selectedNames }, + { collection: "string_literals", contains: "keep-" }, +] as const)("pages filtered $collection indices in source order", (filter) => { + const result = projectAnalysisView( + { ...parent(), normalizedResult: indexedReport }, + { + kind: "go", + indices: [3, 90, 0, 2, 1, 3], + offset: 1, + limit: 1, + ...filter, + }, + ); + if (!result.ok) throw result.error; + expect(result.value).toMatchObject({ + page: { + collection: filter.collection, + rows: [{ index: 2 }], + }, + coverage: { + status: "page", + examined: 1, + total: 3, + next_offset: 2, + exhausted: false, + }, + }); +}); diff --git a/src/domain/analysisView/goBinaryView.ts b/src/domain/analysisView/goBinaryView.ts index 03f808b291..e8312860c2 100644 --- a/src/domain/analysisView/goBinaryView.ts +++ b/src/domain/analysisView/goBinaryView.ts @@ -24,7 +24,7 @@ import { } from "./analysisViewCoverage.js"; import { analysisViewInputError } from "./analysisViewErrors.js"; import { createAnalysisViewResultReader } from "./analysisViewParent.js"; -import { selectViewRows } from "./selectViewRows.js"; +import { selectIndexedViewRows, selectViewRows } from "./selectViewRows.js"; const indexSchema = z.number().int().nonnegative(); const count = z.number().int().nonnegative(); @@ -301,25 +301,40 @@ export const projectGoBinaryView = ( ); const values = view.values === undefined ? undefined : new Set(view.values); const needle = view.contains; - const selected = selectViewRows( - stringLiterals.items, - view, - (row, index) => - (indices?.has(index) ?? true) && - (values?.has(row.value) ?? true) && - (needle === undefined || row.value.includes(needle)), - (row, index) => ({ - index, - ...((fields?.has("value") ?? true) && { value: row.value }), - ...((fields?.has("location") ?? true) && { location: row.location }), - ...((fields?.has("first_header_offset") ?? true) && { - first_header_offset: row.first_header_offset, - }), - ...((fields?.has("reference_count") ?? true) && { - reference_count: row.reference_count, - }), + const matchLiteral = ( + row: (typeof stringLiterals.items)[number], + ): boolean => + (values?.has(row.value) ?? true) && + (needle === undefined || row.value.includes(needle)); + const projectLiteral = ( + row: (typeof stringLiterals.items)[number], + index: number, + ) => ({ + index, + ...((fields?.has("value") ?? true) && { value: row.value }), + ...((fields?.has("location") ?? true) && { location: row.location }), + ...((fields?.has("first_header_offset") ?? true) && { + first_header_offset: row.first_header_offset, }), - ); + ...((fields?.has("reference_count") ?? true) && { + reference_count: row.reference_count, + }), + }); + const selected = + indices === undefined + ? selectViewRows( + stringLiterals.items, + view, + matchLiteral, + projectLiteral, + ) + : selectIndexedViewRows( + stringLiterals.items, + indices, + view, + matchLiteral, + projectLiteral, + ); return ok({ kind: "go" as const, view, @@ -342,21 +357,31 @@ export const projectGoBinaryView = ( }); if (view.collection === "dependencies") { const paths = view.paths === undefined ? undefined : new Set(view.paths); - const selected = selectViewRows( - info.module.dependencies, - view, - (row, index) => - (indices?.has(index) ?? true) && (paths?.has(row.path) ?? true), - (row, index) => ({ - index, - ...((fields?.has("path") ?? true) && { path: row.path }), - ...((fields?.has("version") ?? true) && { version: row.version }), - ...((fields?.has("sum") ?? true) && { sum: row.sum }), - ...((fields?.has("replacement") ?? true) && { - replacement: row.replacement, - }), + const matchDep = ( + row: (typeof info.module.dependencies)[number], + ): boolean => paths?.has(row.path) ?? true; + const projectDep = ( + row: (typeof info.module.dependencies)[number], + index: number, + ) => ({ + index, + ...((fields?.has("path") ?? true) && { path: row.path }), + ...((fields?.has("version") ?? true) && { version: row.version }), + ...((fields?.has("sum") ?? true) && { sum: row.sum }), + ...((fields?.has("replacement") ?? true) && { + replacement: row.replacement, }), - ); + }); + const selected = + indices === undefined + ? selectViewRows(info.module.dependencies, view, matchDep, projectDep) + : selectIndexedViewRows( + info.module.dependencies, + indices, + view, + matchDep, + projectDep, + ); return ok({ kind: "go" as const, view, @@ -370,17 +395,26 @@ export const projectGoBinaryView = ( }); } const keys = view.keys === undefined ? undefined : new Set(view.keys); - const selected = selectViewRows( - info.module.settings, - view, - (row, index) => - (indices?.has(index) ?? true) && (keys?.has(row.key) ?? true), - (row, index) => ({ - index, - ...((fields?.has("key") ?? true) && { key: row.key }), - ...((fields?.has("value") ?? true) && { value: row.value }), - }), - ); + const matchSetting = (row: (typeof info.module.settings)[number]): boolean => + keys?.has(row.key) ?? true; + const projectSetting = ( + row: (typeof info.module.settings)[number], + index: number, + ) => ({ + index, + ...((fields?.has("key") ?? true) && { key: row.key }), + ...((fields?.has("value") ?? true) && { value: row.value }), + }); + const selected = + indices === undefined + ? selectViewRows(info.module.settings, view, matchSetting, projectSetting) + : selectIndexedViewRows( + info.module.settings, + indices, + view, + matchSetting, + projectSetting, + ); return ok({ kind: "go" as const, view, diff --git a/src/domain/analysisView/selectViewRows.ts b/src/domain/analysisView/selectViewRows.ts index 53ec6f34a4..47ef5ff51a 100644 --- a/src/domain/analysisView/selectViewRows.ts +++ b/src/domain/analysisView/selectViewRows.ts @@ -7,7 +7,35 @@ export const selectViewRows = ( ): { rows: Row[]; total: number } => { const selected: Row[] = []; let total = 0; - for (const [index, row] of rows.entries()) { + for (let index = 0; index < rows.length; index += 1) { + const row = rows[index]!; + if (!matches(row, index)) continue; + if (total >= view.offset && selected.length < view.limit) + selected.push(project(row, index)); + total++; + } + return { rows: selected, total }; +}; + +/** Select only from an explicit set of candidate indices in ascending order. */ +export const selectIndexedViewRows = ( + rows: readonly Source[], + candidateIndices: ReadonlySet, + view: { readonly offset: number; readonly limit: number }, + matches: (row: Source, index: number) => boolean, + project: (row: Source, index: number) => Row, +): { rows: Row[]; total: number } => { + const ordered: number[] = []; + for (const index of candidateIndices) { + if (Number.isInteger(index) && index >= 0 && index < rows.length) + ordered.push(index); + } + ordered.sort((left, right) => left - right); + const selected: Row[] = []; + let total = 0; + for (let position = 0; position < ordered.length; position += 1) { + const index = ordered[position]!; + const row = rows[index]!; if (!matches(row, index)) continue; if (total >= view.offset && selected.length < view.limit) selected.push(project(row, index)); diff --git a/src/process/RegexMatcher.ts b/src/process/RegexMatcher.ts index 94bbfac96f..3fd7eba29d 100644 --- a/src/process/RegexMatcher.ts +++ b/src/process/RegexMatcher.ts @@ -6,6 +6,7 @@ import { readFileSync } from "node:fs"; import { Worker } from "node:worker_threads"; import { isRecord } from "../kernel/isRecord.js"; +import { errorMessage } from "../kernel/errorMessage.js"; import type { AnalysisError, @@ -747,6 +748,16 @@ export const matchRegexValues = async (input: { input.heapRequest, ); if (!admitted.ok) return admitted; + if (input.values.length === 0) { + try { + new RegExp(input.pattern, input.caseSensitive ? "u" : "iu"); + } catch (cause: unknown) { + return err( + invalidRegexPatternError(input.operation, errorMessage(cause)), + ); + } + return ok([]); + } const { deadline, heapRequest } = admitted.value; const transfer = packRegexValues(input.values); let worker: Worker;