diff --git a/.github/workflows/docs-pr-preview.yml b/.github/workflows/docs-pr-preview.yml index 3186d8aa..3116d62d 100644 --- a/.github/workflows/docs-pr-preview.yml +++ b/.github/workflows/docs-pr-preview.yml @@ -201,6 +201,8 @@ jobs: DOCS_ROOT: ${{ github.workspace }}/content/docs # Fetched above, before the content checkout. DOCS_RELEASE_SCHEDULE_FILE: ${{ runner.temp }}/release-schedule.json + # Matches publish-version.yml, so previews exercise the same search as production. + DOCS_SEMANTIC_SEARCH: ${{ vars.DOCS_SEMANTIC_SEARCH }} run: pnpm turbo run build --filter=@coder/offlinedocs - name: Upload the static export diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index b23cd8e8..640735e0 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -111,8 +111,23 @@ On the public site each build pass indexes only its own version and the stitch k With `DOCS_SEMANTIC_SEARCH=1`, `apps/docs/scripts/semantic-index.mjs` runs after the stitch (and after `next build` in `apps/offlinedocs`) and embeds each section of that `api/search` file with the Model2Vec static model `minishlab/potion-base-8M` (MIT), vendored as an int8 table in `apps/docs/semantic-model/`, so no build downloads a model. It writes `api/search-semantic/meta.json` (vocabulary, pages, sections) and two content-hashed int8 tables under `_next/static/semantic-search/`, so they share the immutable caching and asset prefix of the other build assets. -With `search.hybrid`, `DocsProvider` swaps in a dialog whose client answers from the keyword index at once and fuses in vector results once the semantic index has loaded: vector #1 first, keyword #1 second, then weighted reciprocal rank over both lists. -Vector rank carries 0.75 of the weight, except when a keyword hit contains the whole query (ignoring case), where keyword rank carries 0.75 so the keyword hits for an exact term such as a CLI flag or error message come before the vector-only pages. +The build weights each token by `log(1 + pageCount / (1 + pagesContainingToken))`, counting occurrences once per page so long pages do not distort the frequencies. +This reduces the influence of corpus-wide terms such as "workspace" while retaining distinguishing terms such as "expires". +Both section vectors and browser query embeddings use the resulting weighted token table; the vendored model and table dimensions remain unchanged. +With `search.hybrid`, `DocsProvider` swaps in a dialog whose client answers from the keyword index at once and fuses in vector results once the semantic index has loaded. +Hybrid keyword retrieval requires all informative query words (`threshold: 0`), omitting common English function words while preserving flags and identifiers. +Until the semantic index has loaded (or after it fails), a query that matches no record that way falls back to matching any word, so natural-language questions still return results. +The original query still drives semantic embedding and exact-match promotion. +Weighted reciprocal rank combines matches by full section URL, so evidence for one anchor never boosts a different section on the same page. +Vector rank carries 0.75 of the weight, except when a keyword hit contains the whole query (ignoring case), where keyword rank carries 0.75. +Exact page titles lead, followed by titles containing every query word, exact headings, exact text snippets, and the best vector page. +Titles containing every query word form one tier ordered by fused score, so for a common word such as `workspace` every such title outranks section matches. +The best keyword page is also promoted for queries without a literal keyword match; these pins apply whatever the fused scores, and the fused section ranks order only the pages after them. +Exact comparison ignores case and Markdown emphasis or escapes; query words split only on whitespace and title words on punctuation other than hyphens and underscores, without stemming, so `STUN?`, `self host` and `workspaces` do not match "STUN and NAT", "Self-host" or "workspace"; partial text matches retain their normal fused rank. +Vector candidates include the 30 strongest sections and the best section from each of the 30 strongest pages, so multiple sections can match without long pages crowding out other pages. +Fusion groups sections under their parent pages, keeps the strongest keyword representative for each full URL, and avoids duplicate semantic headings. +The dialog initially shows two matches per page, with the remaining matches available through a keyboard-accessible expansion action ("Show 3 more matches in ") that keeps the dialog open, moves the active row to the first revealed match and announces it in a polite live region. +Changing the query collapses the groups again. Embedding a query is a WordPiece tokenization, a table lookup, and a mean, in plain JavaScript shared with the build (`@coder/docs-next/semantic-search`), so there is no model runtime, worker, or CSP change. The generated REST API reference (pages under `reference/api/`, not its index page) is indexed by what names an endpoint or schema: the page title and description, the H2 headings (`Get workspace metadata by ID`, `codersdk.Workspace`), any text directly under an H2, and each endpoint's `` `METHOD /path` `` line, moved up to its H2. diff --git a/apps/docs/scripts/semantic-index.mjs b/apps/docs/scripts/semantic-index.mjs index 97353102..0719cc16 100644 --- a/apps/docs/scripts/semantic-index.mjs +++ b/apps/docs/scripts/semantic-index.mjs @@ -5,6 +5,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { createEmbeddingModel, + createCorpusEmbeddingModel, embedSections, quantize, sectionsFromExport, @@ -40,7 +41,7 @@ export async function buildSemanticIndex(outDir) { .replace(/\n$/, "") .split("\n"); const tokens = new Int8Array(await readFile(path.join(modelDir, "tokens.i8"))); - const model = createEmbeddingModel(vocab, tokens, dims); + const model = createCorpusEmbeddingModel(sections, createEmbeddingModel(vocab, tokens, dims)); const vectors = quantize(embedSections(sections, model)); @@ -53,7 +54,7 @@ export async function buildSemanticIndex(outDir) { format: 1, model: name, dims, - tokens: await writeHashed(outDir, "tokens", tokens), + tokens: await writeHashed(outDir, "tokens", model.table), vectors: await writeHashed(outDir, "vectors", vectors), vocab, pages, diff --git a/apps/docs/scripts/semantic-index.test.mjs b/apps/docs/scripts/semantic-index.test.mjs new file mode 100644 index 00000000..daf699f0 --- /dev/null +++ b/apps/docs/scripts/semantic-index.test.mjs @@ -0,0 +1,69 @@ +import assert from "node:assert/strict"; +import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { + createCorpusEmbeddingModel, + createEmbeddingModel, + embedSections, + quantize, + sectionsFromExport, +} from "@coder/docs-next/semantic-search"; +import { createSearchAPI } from "fumadocs-core/search/server"; +import { buildSemanticIndex } from "./semantic-index.mjs"; + +test("the published token table and section vectors use the same corpus weights", async (t) => { + const out = await mkdtemp(path.join(os.tmpdir(), "weighted-search-")); + t.after(() => rm(out, { recursive: true, force: true })); + const api = createSearchAPI("advanced", { + indexes: [ + { + id: "/login", + url: "/login", + title: "Login", + structuredData: { + headings: [], + contents: [{ content: "Log in to your Coder deployment." }], + }, + }, + { + id: "/sessions", + url: "/sessions", + title: "Session tokens", + structuredData: { + headings: [{ id: "expiration", content: "Token expiration" }], + contents: [ + { + heading: "expiration", + content: "The login session expires after its configured lifetime.", + }, + ], + }, + }, + ], + }); + const raw = await (await api.staticGET()).text(); + await mkdir(path.join(out, "api")); + await writeFile(path.join(out, "api/search"), raw); + await buildSemanticIndex(out); + const metaDir = path.join(out, "api/search-semantic"); + const meta = JSON.parse(await readFile(path.join(metaDir, "meta.json"), "utf8")); + const tokens = new Int8Array(await readFile(path.resolve(metaDir, meta.tokens))); + const vectors = new Int8Array(await readFile(path.resolve(metaDir, meta.vectors))); + const vendor = new Int8Array( + await readFile(fileURLToPath(new URL("../semantic-model/tokens.i8", import.meta.url))), + ); + const { sections } = sectionsFromExport(JSON.parse(raw)); + const weighted = createCorpusEmbeddingModel( + sections, + createEmbeddingModel(meta.vocab, vendor, meta.dims), + ); + assert.notDeepEqual(tokens, vendor); + assert.deepEqual(tokens, weighted.table); + assert.deepEqual( + vectors, + quantize(embedSections(sections, createEmbeddingModel(meta.vocab, tokens, meta.dims))), + ); +}); diff --git a/packages/docs-next/src/hybrid-search.test.tsx b/packages/docs-next/src/hybrid-search.test.tsx index 9f92cdea..feb58bd8 100644 --- a/packages/docs-next/src/hybrid-search.test.tsx +++ b/packages/docs-next/src/hybrid-search.test.tsx @@ -1,14 +1,16 @@ import assert from "node:assert/strict"; import { afterEach, test } from "node:test"; -import type { SortedResult } from "fumadocs-core/search"; +import { setTimeout as delay } from "node:timers/promises"; import { FrameworkProvider } from "fumadocs-core/framework"; +import type { SortedResult } from "fumadocs-core/search"; +import { createSearchAPI } from "fumadocs-core/search/server"; +import { act, createElement, useState } from "react"; import { type MetaData, type VirtualFile, loader } from "fumadocs-core/source"; -import { act, createElement } from "react"; -import { createRoot } from "react-dom/client"; import { CORPUS_PARAGRAPHS, FORBIDDEN_ELEMENTS } from "../test/search-xss.js"; -import HybridSearchDialog, { hybridSearchClient, preloadSemanticIndex } from "./hybrid-search.js"; import { createDocsSearchRoute } from "./search.js"; import type { DocsPageData } from "./types.js"; +import { createRoot } from "react-dom/client"; +import HybridSearchDialog, { hybridSearchClient, preloadSemanticIndex } from "./hybrid-search.js"; const KEYWORD: SortedResult[] = [{ id: "/k", type: "page", url: "/k", content: "Keyword" }]; const keyword = { search: async () => KEYWORD }; @@ -61,6 +63,19 @@ test("search answers with keyword results while the semantic index is missing, a } }); +test("without the semantic index, a query whose words share no record matches any word", async () => { + serve({}); + const warn = console.warn; + console.warn = () => {}; + try { + const none = { search: async () => [] }; + const client = hybridSearchClient("/missing-any/api/search", undefined, none, keyword); + assert.deepEqual(await client.search("why does my build fail"), KEYWORD); + } finally { + console.warn = warn; + } +}); + test("search fuses the semantic index, resolving its tables relative to meta.json, once it has loaded", async () => { const requested = serve(FILES); const client = hybridSearchClient("/api/search", undefined, keyword); @@ -72,6 +87,202 @@ test("search fuses the semantic index, resolving its tables relative to meta.jso assert.deepEqual(requested.sort(), Object.keys(FILES).sort()); }); +test("keyword retrieval requires the informative query words and preserves literal CLI terms", async () => { + const api = "/precision/api/search"; + const keywordIndex = createSearchAPI("advanced", { + indexes: [ + { + id: "/browser", + url: "/browser", + title: "File Browser", + structuredData: { + headings: [], + contents: [ + { + heading: undefined, + content: "Upload and download workspace files from your browser.", + }, + ], + }, + }, + { + id: "/lifecycle", + url: "/lifecycle", + title: "Workspace lifecycle", + structuredData: { + headings: [], + contents: [{ heading: undefined, content: "Start and stop a workspace." }], + }, + }, + { + id: "/jetbrains", + url: "/jetbrains", + title: "JetBrains", + structuredData: { + headings: [], + contents: [ + { heading: undefined, content: "Connect JetBrains Gateway to your workspace." }, + ], + }, + }, + { + id: "/server", + url: "/server", + title: "Server", + structuredData: { + headings: [{ id: "flag", content: "--wildcard-access-url" }], + contents: [], + }, + }, + { id: "/flag", url: "/flag", title: "--in", structuredData: { headings: [], contents: [] } }, + ], + }); + serve({ + [api]: await (await keywordIndex.staticGET()).text(), + [`${api}-semantic/meta.json`]: JSON.stringify({ ...META, sections: [] }), + "/precision/_next/static/semantic-search/tokens.i8": new Uint8Array([0, 0, 100, 0]), + "/precision/_next/static/semantic-search/vectors.i8": new Uint8Array(), + }); + await preloadSemanticIndex(api); + const client = hybridSearchClient(api); + const pages = async (query: string) => + (await client.search(query)).filter((item) => item.type === "page").map((item) => item.url); + assert.deepEqual(await pages("workspace files"), ["/browser"]); + assert.deepEqual(await pages("connect with JetBrains"), ["/jetbrains"]); + assert.deepEqual(await pages("--wildcard-access-url"), ["/server"]); + assert.deepEqual(await pages("--in"), ["/flag"]); +}); + +test("the hybrid dialog renders and navigates to multiple matches on the same page", async (t) => { + const url = "/admin/networking/workspace-proxies"; + const headings = [ + { id: "deploy-the-proxy", content: "Deploy the proxy" }, + { id: "create-the-proxy", content: "Create the proxy" }, + { id: "select-a-proxy", content: "Select a proxy" }, + ]; + const api = "/sections/api/search"; + const keywordIndex = createSearchAPI("advanced", { + indexes: [ + { + id: url, + url, + title: "Workspace proxies", + tag: "coder", + structuredData: { headings, contents: [] }, + }, + ], + }); + const sections = [ + { page: 0, url: `${url}#requirements`, heading: "Requirements" }, + { page: 0, url: `${url}#run-on-kubernetes`, heading: "Run on Kubernetes" }, + ]; + serve({ + [api]: await (await keywordIndex.staticGET()).text(), + [`${api}-semantic/meta.json`]: JSON.stringify({ + ...META, + vocab: ["[UNK]", "proxy"], + pages: [{ url, title: "Workspace proxies" }], + sections, + }), + "/sections/_next/static/semantic-search/tokens.i8": new Uint8Array([0, 0, 100, 0]), + "/sections/_next/static/semantic-search/vectors.i8": new Uint8Array([127, 0, 120, 0]), + }); + await preloadSemanticIndex(api); + const pushed: string[] = []; + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + function Dialog() { + const [open, setOpen] = useState(true); + return ; + } + t.after(async () => { + await act(async () => root.unmount()); + container.remove(); + }); + await act(async () => { + root.render( + "/"} + useParams={() => ({})} + useRouter={() => ({ + push: (href) => { + pushed.push(href); + }, + refresh() {}, + })} + > + + , + ); + }); + const input = document.querySelector('[role="dialog"] input'); + assert.ok(input); + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, "proxy"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + await act(async () => { + await delay(150); + }); + let options = [ + ...document.querySelectorAll('[role="dialog"] [role="option"]'), + ]; + assert.equal(options.length, 4); + const more = options.find( + (item) => item.textContent === "Show 3 more matches in Workspace proxies", + ); + assert.ok(more); + await act(async () => { + more.dispatchEvent(new Event("pointermove", { bubbles: true })); + }); + await act(async () => { + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + }); + assert.equal(pushed.length, 0); + assert.ok(document.querySelector('[role="dialog"]'), "expanding must keep the dialog open"); + options = [...document.querySelectorAll('[role="dialog"] [role="option"]')]; + assert.equal(options.length, 6); + assert.equal(input.getAttribute("aria-activedescendant"), options[3]?.id); + assert.equal( + document.querySelector('[role="dialog"] output')?.textContent, + "Showing 3 more matches in Workspace proxies", + ); + for (const heading of [ + ...headings, + ...sections.map((section) => ({ id: section.url.split("#")[1], content: section.heading })), + ]) { + const option = options.find((item) => item.textContent === heading.content); + assert.ok(option, `missing section: ${heading.content}`); + assert.ok(option.id); + } + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call( + input, + "proxy ", + ); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + await act(async () => { + await delay(150); + }); + options = [...document.querySelectorAll('[role="dialog"] [role="option"]')]; + assert.equal(options.length, 4, "a new query must collapse expanded groups"); + const moreAgain = options.find((item) => item.textContent?.includes("Show 3 more matches")); + assert.ok(moreAgain); + await act(async () => moreAgain.click()); + options = [...document.querySelectorAll('[role="dialog"] [role="option"]')]; + const expanded = options.find((item) => item.textContent === "Run on Kubernetes"); + assert.ok(expanded); + await act(async () => expanded.click()); + assert.equal(pushed.at(-1), `${url}#run-on-kubernetes`); + assert.equal( + document.querySelector('[role="dialog"]'), + null, + "an expansion must not swallow a later close", + ); +}); + async function corpusIndex(): Promise { const files: VirtualFile<{ pageData: DocsPageData & { structuredData: unknown }; diff --git a/packages/docs-next/src/hybrid-search.tsx b/packages/docs-next/src/hybrid-search.tsx index 87c88909..f2ccf94b 100644 --- a/packages/docs-next/src/hybrid-search.tsx +++ b/packages/docs-next/src/hybrid-search.tsx @@ -1,5 +1,5 @@ "use client"; -import type { SearchClient } from "fumadocs-core/search/client"; +import type { SearchClient, SearchResultItem as ListItem } from "fumadocs-core/search/client"; import { experimental_useSearch } from "fumadocs-core/search/client"; import { staticClient } from "fumadocs-core/search/client/orama-static"; import { @@ -11,9 +11,11 @@ import { SearchDialogInput, SearchDialogList, SearchDialogOverlay, + type SearchItemType, + useSearch, } from "fumadocs-ui/components/dialog/search"; import type { SharedProps } from "fumadocs-ui/contexts/search"; -import { useCallback, useEffect, useMemo, useState } from "react"; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { SearchResultItem, renderSearchTable, useActiveProduct } from "./search-markdown.js"; import { type SemanticIndex, @@ -25,6 +27,38 @@ import { // Semantic search is an enhancement: a stalled download must not hold the dialog. const FETCH_TIMEOUT_MS = 30_000; +const QUERY_STOP_WORDS = new Set([ + "a", + "an", + "the", + "to", + "of", + "for", + "with", + "in", + "on", + "at", + "by", + "from", + "how", + "can", + "i", + "my", + "is", + "are", + "do", + "does", +]); + +function keywordSearchClient(from: string, tag?: string): SearchClient { + const client = staticClient({ from, tag, search: { threshold: 0 } }); + return { + search(query) { + const words = query.split(/\s+/).filter((word) => !QUERY_STOP_WORDS.has(word.toLowerCase())); + return client.search(words.join(" ").trim() || query); + }, + }; +} async function fetchOk(url: URL): Promise { const response = await fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) }); @@ -71,14 +105,16 @@ export function preloadSemanticIndex(from: string): Promise 0 ? results : anyWord.search(query); return fuseResults( query, results, @@ -93,14 +129,31 @@ function renderResult(props: Parameters[0] & { onClick: return ; } +/** Moves the active row to the first match an expansion revealed and announces it; runs after the list resets it. */ +function RevealedMatches({ revealed }: { revealed: { id: string; message: string } | null }) { + const { setActive } = useSearch(); + useLayoutEffect(() => { + if (revealed) setActive(revealed.id); + }, [revealed, setActive]); + return ( + + {revealed?.message} + + ); +} + /** fumadocs' default search dialog (minus tags and links) over `hybridSearchClient`. */ export default function HybridSearchDialog({ api = "/api/search", + onOpenChange, ...props }: SharedProps & { api?: string }) { const product = useActiveProduct(); const client = useMemo(() => hybridSearchClient(api, product), [api, product]); const [loaded, setLoaded] = useState(false); + const [expanded, setExpanded] = useState>(() => new Set()); + const [revealed, setRevealed] = useState<{ id: string; message: string } | null>(null); + const expanding = useRef(false); useEffect(() => { if (!props.open) return; let active = true; @@ -112,9 +165,51 @@ export default function HybridSearchDialog({ // Re-run the current query once the semantic index arrives. // oxlint-disable-next-line react-hooks/exhaustive-deps -- `loaded` re-runs the current query once the semantic index arrives. const run = useCallback((query: string) => client.search(query), [client, loaded]); - const search = experimental_useSearch(run); + const { onSearchChange, ...search } = experimental_useSearch(run); + const items = useMemo((): (SearchItemType | ListItem)[] | null => { + if (!search.data) return null; + const groups: ListItem[][] = []; + for (const item of search.data.items) { + if (item.type === "page") groups.push([item]); + else groups.at(-1)?.push(item); + } + return groups.flatMap((group): (SearchItemType | ListItem)[] => { + const head = group[0]; + if (!head || group.length <= 3 || expanded.has(head.id)) return group; + const remaining = group.length - 3; + const label = `${remaining} more ${remaining === 1 ? "match" : "matches"} in ${"content" in head ? head.content : ""}`; + return [ + ...group.slice(0, 3), + { + id: `expand:${head.id}`, + type: "action", + node: `Show ${label}`, + onSelect() { + // Fumadocs closes the dialog right after an action; skip only that close. + expanding.current = true; + queueMicrotask(() => { + expanding.current = false; + }); + setExpanded((previous) => new Set([...previous, head.id])); + setRevealed({ id: group[3]?.id ?? head.id, message: `Showing ${label}` }); + }, + }, + ]; + }); + }, [search.data, expanded]); return ( - + { + setExpanded(new Set()); + setRevealed(null); + onSearchChange(value); + }} + onOpenChange={(open) => { + if (!expanding.current) onOpenChange(open); + }} + > @@ -122,7 +217,8 @@ export default function HybridSearchDialog({ - + + ); diff --git a/packages/docs-next/src/semantic-search.test.ts b/packages/docs-next/src/semantic-search.test.ts index a8a2b413..2db395e1 100644 --- a/packages/docs-next/src/semantic-search.test.ts +++ b/packages/docs-next/src/semantic-search.test.ts @@ -4,6 +4,7 @@ import type { SortedResult } from "fumadocs-core/search"; import golden from "./semantic-search.golden.json" with { type: "json" }; import { createEmbeddingModel, + createCorpusEmbeddingModel, embed, embedSections, fuseResults, @@ -124,7 +125,7 @@ test("sectionsFromExport groups records per heading, leads with title and headin assert.throws(() => sectionsFromExport({ type: "simple" }), /advanced static search export/); }); -test("vectorSearch returns each page's best section, best pages first", () => { +test("vectorSearch ranks matching sections, including multiple sections from the same page", () => { const table = new Int8Array(VOCAB.length * 2); table.set([100, 0], 3 * 2); table.set([0, 100], 4 * 2); @@ -144,16 +145,18 @@ test("vectorSearch returns each page's best section, best pages first", () => { { page: 0, url: "/a" }, { page: 0, url: "/a#daemon", heading: "Daemon" }, { page: 1, url: "/b" }, + { page: 0, url: "/a#agent", heading: "Agent" }, ], }; - const vectors = Int8Array.from([127, 0, 10, 120, 90, 90]); + const vectors = Int8Array.from([127, 0, 10, 120, 90, 90, 100, 70]); assert.deepEqual( vectorSearch("daemon", { meta, model, vectors }).map((section) => section.url), - ["/a#daemon", "/b"], + ["/a#daemon", "/b", "/a#agent"], ); + assert.deepEqual(vectorSearch("unknown", { meta, model, vectors }), []); }); -test("fuseResults leads with the top vector page then the top keyword page, orders the rest by weighted reciprocal rank, links each page row to the page with its best section below, keeps two keyword hits per page, and appends keyword-only pages", () => { +test("fuseResults keeps the leading search sources and distinct keyword matches", () => { const keyword: SortedResult[] = [ { id: "/k", type: "page", url: "/k", content: "Keyword only" }, { id: "k1", type: "text", url: "/k#x", content: "match" }, @@ -184,14 +187,122 @@ test("fuseResults leads with the top vector page then the top keyword page, orde ["page", "/k", "Keyword only"], ["text", "/k#x", "match"], ["text", "/k#y", "match 2"], + ["text", "/k#z", "match 3"], + ["page", "/mid", "Vector second"], ["page", "/both", "Both"], ["heading", "/both#y", "Why"], - ["page", "/mid", "Vector second"], ["page", "/kw2", "Keyword second"], ], ); }); +test("vectorSearch can return all 30 strongest sections from one page", () => { + const model = createEmbeddingModel(["agent"], Int8Array.from([127]), 1); + const sections = Array.from({ length: 34 }, (_, i) => ({ + page: 0, + url: `/agents#section-${i}`, + heading: `Section ${i}`, + })); + const meta = { + format: 1 as const, + model: "test", + dims: 1, + tokens: "", + vectors: "", + vocab: ["agent"], + pages: [{ url: "/agents", title: "Agents" }], + sections, + }; + assert.deepEqual( + vectorSearch("agent", { meta, model, vectors: Int8Array.from(sections, (_, i) => i - 1) }), + sections.slice(4).reverse(), + ); +}); + +test("vectorSearch keeps page coverage when one long page has many strong section matches", () => { + const model = createEmbeddingModel(["agent"], Int8Array.from([127]), 1); + const pages = Array.from({ length: 31 }, (_, i) => ({ url: `/page-${i}`, title: `Page ${i}` })); + const sections = [ + ...Array.from({ length: 32 }, (_, i) => ({ page: 0, url: `/page-0#section-${i}` })), + ...pages.slice(1).map((page, i) => ({ page: i + 1, url: page.url })), + ]; + const meta = { + format: 1 as const, + model: "test", + dims: 1, + tokens: "", + vectors: "", + vocab: ["agent"], + pages, + sections, + }; + const result = vectorSearch("agent", { + meta, + model, + vectors: Int8Array.from(sections, (_, i) => 127 - i), + }); + assert.deepEqual(result.slice(0, 30), sections.slice(0, 30)); + assert.deepEqual( + [...new Set(result.map((section) => section.page))], + pages.slice(0, 30).map((_, i) => i), + ); + assert.equal(result.length, 59); +}); + +test("fuseResults groups all semantic sections and deduplicates only overlapping section URLs", () => { + const url = "/beta-docs/@v2.38.1/admin/networking/port-forwarding"; + const keyword: SortedResult[] = [ + { id: url, type: "page", url, content: "Port forwarding" }, + { id: "ssh", type: "heading", url: `${url}#ssh`, content: "SSH" }, + { + id: "protocol", + type: "heading", + url: `${url}#configure-port-protocol`, + content: "Configure port protocol", + }, + { + id: "sharing", + type: "heading", + url: `${url}#configure-maximum-port-sharing-level`, + content: "Configure maximum port sharing level", + }, + ]; + const pages = [ + { url, title: "Port forwarding" }, + { url: "/other", title: "Other" }, + ]; + const vector = [ + { + page: 0, + url: `${url}#the-coder-port-forward-command`, + heading: "The coder port-forward command", + }, + { page: 1, url: "/other#ssh", heading: "SSH" }, + { page: 0, url: `${url}#ssh`, heading: "SSH" }, + { page: 0, url: `${url}#dashboard`, heading: "Dashboard" }, + { page: 0, url: `${url}#dashboard`, heading: "Dashboard" }, + { page: 0, url }, + ]; + const result = fuseResults("port forwarding", keyword, vector, pages); + assert.deepEqual( + result.map((item) => item.url), + [ + url, + `${url}#ssh`, + `${url}#configure-port-protocol`, + `${url}#configure-maximum-port-sharing-level`, + `${url}#the-coder-port-forward-command`, + `${url}#dashboard`, + "/other", + "/other#ssh", + ], + ); + assert.deepEqual( + result.filter((item) => keyword.some((hit) => hit.id === item.id)), + keyword, + ); +}); + test("hasExactMatch finds the whole query in a keyword hit, ignoring case", () => { const keyword: SortedResult[] = [ { id: "/a", type: "page", url: "/a", content: "Networking" }, @@ -230,7 +341,186 @@ test("fuseResults ranks every keyword hit for an exact match above a full list o fuseResults(query, keyword, vector, pages) .filter((item) => item.type === "page") .map((item) => item.url); - assert.deepEqual(order("--wildcard-access-url").slice(0, 5), ["/v0", "/k1", "/k2", "/k3", "/v1"]); + assert.deepEqual(order("--wildcard-access-url").slice(0, 5), ["/k1", "/k2", "/k3", "/v0", "/v1"]); // No hit quotes the query, so the vectors keep the lead: keyword #2 and #3 follow the vector list. assert.deepEqual(order("wildcard access url").slice(0, 3), ["/v0", "/k1", "/v1"]); }); + +test("exact section matches precede a semantic page and its weaker sibling headings", () => { + const lifecycle = "/user-guides/workspace-lifecycle"; + const cli = "/reference/cli"; + const keyword: SortedResult[] = [ + { id: cli, type: "page", url: cli, content: "Command Line" }, + { id: "create", type: "text", url: `${cli}#subcommands`, content: "Create a workspace" }, + { + id: "delete", + type: "text", + url: `${cli}#subcommands`, + content: "Delete a workspace", + }, + ]; + const vector = [ + { page: 0, url: `${lifecycle}#delete-workspaces`, heading: "Delete workspaces" }, + { page: 0, url: `${lifecycle}#next-steps`, heading: "Next steps" }, + ]; + const result = fuseResults("delete a workspace", keyword, vector, [ + { url: lifecycle, title: "Workspace lifecycle" }, + ]); + assert.deepEqual(result.slice(0, 2), [keyword[0], keyword[2]]); + assert.equal(result.filter((item) => item.url === `${cli}#subcommands`).length, 1); + assert.deepEqual( + result.slice(3).map((item) => item.url), + vector.map((item) => item.url), + ); +}); + +test("section evidence is fused by anchor, without boosting a different section on that page", () => { + const keyword: SortedResult[] = [ + { id: "/a", type: "page", url: "/a", content: "A" }, + { id: "a1", type: "heading", url: "/a#keyword", content: "Keyword" }, + { id: "a2", type: "heading", url: "/a#both", content: "Both" }, + { id: "a3", type: "heading", url: "/a#last", content: "Last" }, + ]; + const vector = [ + { page: 0, url: "/a#semantic", heading: "Semantic" }, + { page: 0, url: "/a#both", heading: "Both" }, + ]; + const result = fuseResults("related concept", keyword, vector, [{ url: "/a", title: "A" }]); + assert.deepEqual( + result.map((item) => item.url), + ["/a", "/a#both", "/a#semantic", "/a#keyword", "/a#last"], + ); +}); + +test("an exact page title precedes a loosely related semantic page even when it has child matches", () => { + const keyword: SortedResult[] = [ + { id: "/nat", type: "page", url: "/nat", content: "STUN and NAT" }, + { id: "/stun", type: "page", url: "/stun", content: "STUN" }, + { id: "stun1", type: "heading", url: "/stun#overview", content: "Overview" }, + ]; + const result = fuseResults( + "STUN", + keyword, + [{ page: 0, url: "/networking" }], + [{ url: "/networking", title: "Networking" }], + ); + assert.equal(result[0]?.url, "/stun"); +}); + +test("page titles matching all query words precede exact headings without matching word fragments", () => { + const keyword: SortedResult[] = [ + { id: "/guide", type: "page", url: "/guide", content: "Guide" }, + { id: "heading", type: "heading", url: "/guide#stun", content: "STUN" }, + { id: "/stun", type: "page", url: "/stun", content: "STUN and NAT" }, + ]; + for (const query of ["STUN", "nat stun", "stu", "STUN missing", ""]) { + const result = fuseResults( + query, + keyword, + [{ page: 0, url: "/networking" }], + [{ url: "/networking", title: "Networking" }], + ); + assert.equal(result[0]?.url, ["STUN", "nat stun"].includes(query) ? "/stun" : "/networking"); + } +}); + +test("literal queries let agreement between sources outrank a keyword-only page", () => { + const keyword: SortedResult[] = [ + { id: "/support", type: "page", url: "/support", content: "Support bundle" }, + { + id: "files", + type: "text", + url: "/support#files", + content: "Workspace files can contain tokens.", + }, + { id: "/browser", type: "page", url: "/browser", content: "File Browser" }, + ]; + const result = fuseResults( + "workspace files", + keyword, + [ + { page: 0, url: "/vscode#extensions", heading: "Add extensions to custom images" }, + { page: 1, url: "/browser" }, + ], + [ + { url: "/vscode", title: "Visual Studio Code" }, + { url: "/browser", title: "File Browser" }, + ], + ); + assert.deepEqual( + result.filter((item) => item.type === "page").map((item) => item.url), + ["/vscode", "/browser", "/support"], + ); +}); + +test("an exact escaped CLI heading precedes an exact snippet and the leading semantic page", () => { + const keyword: SortedResult[] = [ + { id: "/guide", type: "page", url: "/guide", content: "Guide" }, + { + id: "guide1", + type: "text", + url: "/guide#flag", + content: "--wildcard-access-url", + }, + ]; + const result = fuseResults( + "--wildcard-access-url", + keyword, + [ + { page: 0, url: "/networking" }, + { page: 1, url: "/cli#flag", heading: "`\\--wildcard-access-url`" }, + ], + [ + { url: "/networking", title: "Networking" }, + { url: "/cli", title: "CLI" }, + ], + ); + assert.deepEqual( + result.filter((item) => item.type === "page").map((item) => item.url), + ["/cli", "/guide", "/networking"], + ); +}); + +test("corpus weights let a rare query term distinguish pages sharing a common topic", () => { + const vocab = ["login", "expires", "logout"]; + const model = createEmbeddingModel(vocab, Int8Array.from([100, 0, 0, 50, 30, 30]), 2); + const sections = [ + ...Array.from({ length: 10 }, (_, page) => ({ page, url: `/page-${page}`, text: "login" })), + { page: 9, url: "/page-9#expiration", heading: "Expiration", text: "expires" }, + ]; + const meta = { + format: 1 as const, + model: "test", + dims: 2, + tokens: "", + vectors: "", + vocab, + pages: sections.slice(0, 10).map((s) => ({ url: s.url, title: "Login" })), + sections, + }; + const weighted = createCorpusEmbeddingModel(sections, model); + const results = vectorSearch("login expires", { + meta, + model: weighted, + vectors: quantize(embedSections(sections, weighted)), + }); + assert.equal(results[0]?.url, "/page-9#expiration"); + assert.deepEqual([...model.table], [100, 0, 0, 50, 30, 30]); + assert.ok(embed("logout", weighted).some((value) => value !== 0)); +}); + +test("corpus weights count each token once per page regardless of repetitions or section count", () => { + const model = createEmbeddingModel(["login", "expires"], Int8Array.from([100, 0, 0, 50]), 2); + const sections = [ + { page: 0, url: "/a", text: "login expires" }, + { page: 1, url: "/b", text: "login" }, + ]; + assert.deepEqual( + createCorpusEmbeddingModel(sections, model).table, + createCorpusEmbeddingModel( + [...sections, { page: 0, url: "/a#extra", text: "login login expires expires" }], + model, + ).table, + ); + assert.deepEqual(createCorpusEmbeddingModel([], model), model); +}); diff --git a/packages/docs-next/src/semantic-search.ts b/packages/docs-next/src/semantic-search.ts index f7b26759..3f118645 100644 --- a/packages/docs-next/src/semantic-search.ts +++ b/packages/docs-next/src/semantic-search.ts @@ -6,10 +6,8 @@ import type { SortedResult } from "fumadocs-core/search"; /** Tokens per embedded section: the title and heading lead, so truncation drops only the tail. */ export const MAX_TOKENS = 256; -/** Pages the vector search returns, best first. */ -const VECTOR_CANDIDATES = 30; -/** Highlighted matches kept under each keyword page. */ -const KEYWORD_MATCHES = 2; +const VECTOR_SECTION_CANDIDATES = 30; +const VECTOR_PAGE_CANDIDATES = 30; /** Reciprocal rank fusion constant and the vector side's share. */ const RRF_K = 60; const VECTOR_WEIGHT = 0.75; @@ -55,6 +53,35 @@ export interface EmbeddingModel { dims: number; } +/** Downweight tokens found across many pages, using the same weighted table for sections and queries. */ +export function createCorpusEmbeddingModel( + sections: (SemanticSection & { text: string })[], + model: EmbeddingModel, +): EmbeddingModel { + const pages = new Map>(); + for (const section of sections) { + let tokens = pages.get(section.page); + if (!tokens) { + tokens = new Set(); + pages.set(section.page, tokens); + } + for (const token of tokenize(section.text, model.vocab)) tokens.add(token); + } + if (pages.size === 0) return model; + const frequencies = new Uint32Array(model.vocab.size); + for (const tokens of pages.values()) { + for (const token of tokens) frequencies[token] = (frequencies[token] ?? 0) + 1; + } + const weights = Float32Array.from(frequencies, (count) => Math.log(1 + pages.size / (1 + count))); + const table = quantize( + Float32Array.from( + model.table, + (value, i) => value * (weights[Math.floor(i / model.dims)] ?? 1), + ), + ); + return { ...model, table }; +} + export function createEmbeddingModel( vocab: string[], table: Int8Array, @@ -222,7 +249,7 @@ export interface SemanticIndex { vectors: Int8Array; } -/** The best-scoring section of each page, best pages first, from the given product's pages only when one is named. */ +/** The strongest sections plus each top page's best match, so long pages cannot crowd out other pages; only the given product's pages when one is named. */ export function vectorSearch( query: string, index: SemanticIndex, @@ -230,7 +257,7 @@ export function vectorSearch( ): SemanticSection[] { const { meta, model, vectors } = index; const q = embed(query, model); - const best = new Map(); + const candidates: { section: SemanticSection; score: number }[] = []; const inProduct = meta.pages.map( (page) => product === undefined || productForUrl(page.url).id === product, ); @@ -239,75 +266,125 @@ export function vectorSearch( let score = 0; for (let d = 0; d < model.dims; d++) score += (q[d] ?? 0) * (vectors[row * model.dims + d] ?? 0); - const previous = best.get(section.page); - if (score > 0 && (!previous || previous.score < score)) - best.set(section.page, { section, score }); + if (score > 0) candidates.push({ section, score }); }); - return [...best.values()] + const pages = new Set(); + return candidates .sort((a, b) => b.score - a.score) - .slice(0, VECTOR_CANDIDATES) + .filter(({ section }, rank) => { + const firstOnPage = !pages.has(section.page) && pages.size < VECTOR_PAGE_CANDIDATES; + if (firstOnPage) pages.add(section.page); + return firstOnPage || rank < VECTOR_SECTION_CANDIDATES; + }) .map(({ section }) => section); } const pageKey = (url: string) => url.split("#")[0] ?? url; -// Vector #1, then keyword #1 (an exact term the vectors miss), then weighted reciprocal rank over both. +function exactResultMatch(query: string, item: SortedResult): number { + const normalize = (text: string) => + text + .replace(/[`*]|\\(?=[\p{P}\p{S}])/gu, "") + .trim() + .toLowerCase(); + const needle = normalize(query); + const content = normalize(item.content); + if (!needle) return 0; + if (content === needle) return item.type === "page" ? 4 : item.type === "heading" ? 2 : 1; + const words = content.split(/[^\p{L}\p{N}_-]+/u); + return item.type === "page" && needle.split(/\s+/).every((word) => words.includes(word)) ? 3 : 0; +} + +interface RankedMatch { + item: SortedResult; + exact: number; + score: number; +} + +// Fuse section URLs; a page's best section sets its position, without promoting its siblings. export function fuseResults( query: string, keyword: SortedResult[], vector: SemanticSection[], pages: SemanticPage[], ): SortedResult[] { - const groups = new Map(); - let current: SortedResult[] | undefined; + if (vector.length === 0) return keyword; + const headers = new Map(); + const candidates = new Map(); + const vectorWeight = hasExactMatch(query, keyword) ? EXACT_VECTOR_WEIGHT : VECTOR_WEIGHT; for (const item of keyword) { - if (item.type === "page") { - current = [item]; - groups.set(pageKey(item.url), current); - } else if (current && current.length <= KEYWORD_MATCHES) { - current.push(item); + if (item.type === "page") headers.set(pageKey(item.url), item); + const exact = exactResultMatch(query, item); + const match = candidates.get(item.url); + if (!match) { + candidates.set(item.url, { + item, + exact, + score: (1 - vectorWeight) / (RRF_K + candidates.size + 1), + }); + } else if ( + exact > match.exact || + (exact === match.exact && item.type === "heading" && match.item.type === "text") + ) { + match.item = item; + match.exact = exact; } } - const semantic = new Map(); - for (const section of vector) { + const seen = new Set(); + vector.forEach((section, rank) => { const page = pages[section.page]; - if (!page) continue; + if (!page || seen.has(section.url)) return; + seen.add(section.url); const key = pageKey(page.url); - const [head, ...matches] = groups.get(key) ?? []; - const best: SortedResult[] = - section.heading && !matches.some((match) => match.url === section.url) - ? [ - { - id: `semantic:${section.url}`, - type: "heading", - url: section.url, - content: section.heading, - }, - ] - : []; - semantic.set(key, [ - head ?? { + let head = headers.get(key); + if (!head) { + head = { id: `semantic:${key}`, type: "page", url: page.url, content: page.title, breadcrumbs: page.breadcrumbs, - }, - ...best, - ...matches, - ]); + }; + headers.set(key, head); + } + let match = candidates.get(section.url); + if (!match) { + const item: SortedResult = section.heading + ? { + id: `semantic:${section.url}`, + type: "heading", + url: section.url, + content: section.heading, + } + : head; + match = { item, exact: exactResultMatch(query, item), score: 0 }; + candidates.set(section.url, match); + } + match.score += vectorWeight / (RRF_K + rank + 1); + }); + const ranked = [...candidates.values()].sort((a, b) => b.exact - a.exact || b.score - a.score); + const groups = new Map(); + for (const { item } of ranked) { + const key = pageKey(item.url); + const head = headers.get(key); + if (!head) continue; + let group = groups.get(key); + if (!group) { + group = [head]; + groups.set(key, group); + } + if (item.type !== "page") group.push(item); } - const scores = new Map(); - const score = (keys: Iterable, weight: number) => - [...keys].forEach((key, rank) => { - scores.set(key, (scores.get(key) ?? 0) + weight / (RRF_K + rank + 1)); - }); - const vectorWeight = hasExactMatch(query, keyword) ? EXACT_VECTOR_WEIGHT : VECTOR_WEIGHT; - score(semantic.keys(), vectorWeight); - score(groups.keys(), 1 - vectorWeight); - const [first] = semantic.keys(); - const [topKeyword] = groups.keys(); - const ranked = [...scores.keys()].sort((a, b) => (scores.get(b) ?? 0) - (scores.get(a) ?? 0)); - const order = new Set([first, topKeyword, ...ranked]); - return [...order].flatMap((key) => (key ? (semantic.get(key) ?? groups.get(key) ?? []) : [])); + const exactPages = ranked.filter((match) => match.exact).map(({ item }) => pageKey(item.url)); + const firstVector = vector + .map((section) => pages[section.page]) + .find((page) => page !== undefined); + const firstKeyword = keyword.find((item) => item.type === "page"); + const order = new Set([ + ...exactPages, + firstVector && pageKey(firstVector.url), + vectorWeight === VECTOR_WEIGHT && firstKeyword && pageKey(firstKeyword.url), + ...groups.keys(), + ]); + return [...order].flatMap((key) => (key ? (groups.get(key) ?? []) : [])); }