Public: anyone can read this; the crew can change it.

/search answers under 50 ms over 2,000 issues and 200 repositories #3382

Parked opened this
Closed without merging

scout/forge:scout/3360-search-answers-under-50-ms-over-2-000-is → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +263 −21
README.md +4
@@ -1845,3 +1845,7 @@ same rule. A guard installed by hand without the prefix answers `refused`
18451845 until it is re-created with `forge: ` in front of its message.
18461846
18471847 `reach` is a boards source for an admin only (anyone else gets 403, an agent too): `visitors` per day, `lcp_p75` and `inp_p75` per route per day, `server_p50` and `server_p95` per route per day (the beacon's time to first byte, the only per-route server timing the forge keeps), and `accounts_active_1d`, `accounts_active_7d` and `accounts_total` as of now. Filter by `metric`, group by `route` or a time bucket. Percentiles are nearest-rank within one route and day, so a `max` or `avg` over several days is a summary of daily percentiles, not a percentile of the period. Account activity comes from a session's last-seen time, so it is a count as of now, not a history. No dependency was added.
1848
1849 ## Search
1850
1851 `/search` answers in milliseconds for tells, changes, apps and repositories (indexed rows). Code is `git grep`, which spawns a process per repository, so the web page gives it a 20 ms budget (`CODE_BUDGET_MS`): it renders everything else, keeps the code hits from the repositories that finished in time (a prefix in repository order), and says so in a status line when the rest was cut off. Because of that, **two identical requests can differ** — the first search for a word may show fewer code lines than the next. The greps that were running when the page answered finish in the background and fill a cache keyed by repository, commit and query (a push changes the commit, so it cannot go stale); at most 8 greps run at once across all requests, and queued ones of an answer already sent never start. The JSON API (`/api/v1/search`) and the SSH terminal's search are unchanged and wait for the full code results.
src/actions/search.ts +5 −1
@@ -57,6 +57,8 @@ export interface SearchInput {
5757 * @default true
5858 */
5959 withCode?: boolean;
60 /** Give the code search this long, then answer with what it has (`codePartial`). @default none */
61 codeBudgetMs?: number;
6062 }
6163
6264 /**
@@ -125,13 +127,15 @@ export async function search(
125127 visible,
126128 q,
127129 Math.min(limit * 5, MAX_CODE_HITS),
130 input.codeBudgetMs,
128131 )
129 : { hits: [], truncated: false };
132 : { hits: [], truncated: false, partial: false };
130133
131134 return {
132135 repos,
133136 issues,
134137 code: code.hits,
138 ...(code.partial ? { codePartial: true } : {}),
135139 truncated: {
136140 repos: repos.length >= limit,
137141 issues: localIssueCount >= limit,
src/core/search.ts +115 −20
@@ -12,7 +12,8 @@
1212 *
1313 * **No index of its own.** Repos and issues are already indexed rows; code
1414 * is answered by `git grep` against the object store, which is the only copy
15 * of the truth. Nothing here caches, so nothing here can go stale — and
15 * of the truth. The only memory is a grep answer keyed by commit sha, which
16 * cannot go stale — and
1617 * there is no derived table to rebuild when git and the index disagree.
1718 *
1819 * **Visibility is the same visibility.** Local rows come through the same
@@ -22,6 +23,7 @@
2223 */
2324
2425 import type { Database } from "bun:sqlite";
26 import { readFileSync } from "node:fs";
2527 import { runGitCapture } from "../git/env.ts";
2628 import { isSafeRef } from "../git/guard.ts";
2729 import { repoDir } from "../git/repos.ts";
@@ -110,6 +112,8 @@ export interface SearchResults {
110112 readonly repos: readonly RepoHit[];
111113 readonly issues: readonly IssueHit[];
112114 readonly code: readonly CodeHit[];
115 /** True when the code search ran out of its time budget and stopped early. */
116 readonly codePartial?: boolean;
113117 /** Which lists hit their ceiling — a client can say "and more". */
114118 readonly truncated: {
115119 readonly repos: boolean;
@@ -323,6 +327,42 @@ export function searchLocalIssues(
323327
324328 // ---- code ----
325329
330 /**
331 * The commit a branch points at, read from the ref files rather than asked
332 * of git: no process, microseconds. Undefined when the ref is not a plain
333 * branch git has written as a loose or packed ref — the caller then asks git.
334 */
335 export function branchSha(dir: string, ref: string): string | undefined {
336 if (!isSafeRef(ref)) return undefined;
337 const sha = /^[0-9a-f]{40,64}$/;
338 try {
339 const loose = readFileSync(`${dir}/refs/heads/${ref}`, "utf8").trim();
340 if (sha.test(loose)) return loose;
341 } catch {
342 // not loose; maybe packed
343 }
344 try {
345 for (const line of readFileSync(`${dir}/packed-refs`, "utf8").split("\n")) {
346 const [id, name] = line.split(" ");
347 if (name === `refs/heads/${ref}` && id !== undefined && sha.test(id)) return id;
348 }
349 } catch {
350 // no packed refs
351 }
352 return undefined;
353 }
354
355 /** Grep answers by (repo, commit, query). A commit never changes, so an entry
356 * cannot go stale: a push moves the branch to a new sha and a new key. */
357 const GREP_CACHE_MAX = 1_000;
358 type Found = readonly { path: string; line: number; text: string }[];
359 const grepCache = new Map<string, Found>();
360
361 /** Forget every cached grep answer (tests; nothing else needs it). */
362 export function resetGrepCache(): void {
363 grepCache.clear();
364 }
365
326366 /**
327367 * `git grep` one repo at one ref.
328368 *
@@ -342,6 +382,11 @@ export async function grepRepo(
342382 const pattern = cleanQuery(query);
343383 if (pattern === "" || !isSafeRef(ref)) return [];
344384
385 const sha = branchSha(dir, ref);
386 const key = sha === undefined ? "" : `${dir}\0${sha}\0${maxCount}\0${pattern.toLowerCase()}`;
387 const cached = key === "" ? undefined : grepCache.get(key);
388 if (cached !== undefined) return cached.map((h) => ({ ...h }));
389
345390 const run = await runGitCapture(
346391 [
347392 "grep",
@@ -382,44 +427,94 @@ export async function grepRepo(
382427 });
383428 if (hits.length >= maxCount) break;
384429 }
430 if (key !== "") {
431 if (grepCache.size >= GREP_CACHE_MAX) grepCache.delete(grepCache.keys().next().value!);
432 grepCache.set(key, hits.map((h) => ({ ...h })));
433 }
385434 return hits;
386435 }
387436
437 /** Greps allowed to run at once, across every request. Background work left
438 * behind by an answer that gave up waiting queues here instead of piling up. */
439 export const MAX_GREPS_RUNNING = 8;
440 let grepsRunning = 0;
441 let grepsPeak = 0;
442 const grepQueue: (() => void)[] = [];
443
444 /** How many greps are running now and the most that ever were (tests). */
445 export function grepLoad(): { running: number; peak: number } {
446 return { running: grepsRunning, peak: grepsPeak };
447 }
448
449 async function inSlot<T>(abandoned: () => boolean, work: () => Promise<T>): Promise<T | undefined> {
450 if (grepsRunning >= MAX_GREPS_RUNNING) await new Promise<void>((go) => grepQueue.push(go));
451 else grepsRunning++;
452 // A slot handed on by `release` is already counted for us.
453 try {
454 if (abandoned()) return undefined;
455 grepsPeak = Math.max(grepsPeak, grepsRunning);
456 return await work();
457 } finally {
458 const next = grepQueue.shift();
459 if (next === undefined) grepsRunning--;
460 else next();
461 }
462 }
463
388464 /**
389 * Grep across a bounded set of repos. Repos are searched a few at a time so
390 * fifty small greps do not become fifty simultaneous processes, and the walk
391 * stops the moment the cap is reached — a common word in a monorepo costs
392 * one repo's work, not fifty.
465 * Grep across a bounded set of repos. At most `MAX_GREPS_RUNNING` run at
466 * once, forge-wide, and the walk stops the moment the cap is reached or
467 * the caller has what it needs — queued greps of a finished answer never
468 * start.
469 *
470 * With a `budgetMs` each repo is raced against the deadline in repo order and
471 * the answer is the prefix that finished in time, `partial` when something
472 * did not. Greps already running finish in the background and fill the cache.
393473 */
394474 export async function grepRepos(
395475 reposRoot: string,
396476 repos: readonly Repo[],
397477 query: string,
398478 limit = MAX_CODE_HITS,
399 ): Promise<{ hits: CodeHit[]; truncated: boolean }> {
479 budgetMs?: number,
480 ): Promise<{ hits: CodeHit[]; truncated: boolean; partial: boolean }> {
400481 const hits: CodeHit[] = [];
401482 const considered = repos.slice(0, MAX_SEARCH_REPOS);
402 const batch = 4;
403 for (let i = 0; i < considered.length; i += batch) {
404 const slice = considered.slice(i, i + batch);
405 const found = await Promise.all(
406 slice.map((repo) =>
483 let over = false;
484 const jobs = considered.map((repo) =>
485 inSlot(
486 () => over,
487 () =>
407488 grepRepo(
408489 repoDir(reposRoot, repo.ownerName, repo.name),
409490 repo.defaultBranch,
410491 query,
411492 ),
412 ),
413 );
414 for (const [j, repo] of slice.entries()) {
415 for (const hit of found[j] ?? []) {
416 if (hits.length >= limit) return { hits, truncated: true };
417 hits.push({
418 repo: { owner: repo.ownerName, name: repo.name },
419 ...hit,
493 ),
494 );
495 const late = Symbol("late");
496 let stop = (): void => {};
497 const deadline =
498 budgetMs === undefined
499 ? undefined
500 : new Promise<typeof late>((done) => {
501 const timer = setTimeout(() => done(late), Math.max(budgetMs, 0));
502 stop = () => clearTimeout(timer);
420503 });
504 try {
505 for (const [i, repo] of considered.entries()) {
506 const job = jobs[i]!;
507 const found = deadline === undefined ? await job : await Promise.race([job, deadline]);
508 if (found === late) return { hits, truncated: true, partial: true };
509 for (const hit of found ?? []) {
510 if (hits.length >= limit) return { hits, truncated: true, partial: false };
511 hits.push({ repo: { owner: repo.ownerName, name: repo.name }, ...hit });
421512 }
422513 }
514 return { hits, truncated: repos.length > MAX_SEARCH_REPOS, partial: false };
515 } finally {
516 over = true;
517 stop();
518 for (const job of jobs) job.catch(() => {});
423519 }
424 return { hits, truncated: repos.length > MAX_SEARCH_REPOS };
425520 }
src/web/pages/search.ts +12
@@ -52,6 +52,9 @@ import {
5252
5353 // ---- search ----
5454
55 /** How long the page waits on `git grep` before it answers with the rest. */
56 export const CODE_BUDGET_MS = 20;
57
5558 /** What was asked — everything a link back needs. */
5659 interface Asked {
5760 readonly query: string;
@@ -320,6 +323,7 @@ async function find(
320323 kind: a.kind,
321324 live: a.live,
322325 withCode,
326 codeBudgetMs: CODE_BUDGET_MS,
323327 });
324328 return held !== undefined && !held.allowed
325329 ? { found, busy: held.retryAfter }
@@ -467,6 +471,14 @@ export async function searchPage(ctx: Ctx): Promise<Response> {
467471 ${String(busy)} s.
468472 </p>`,
469473 )}
474 ${when(
475 found.codePartial === true,
476 () =>
477 html`<p class="muted small" role="status" data-code-partial>
478 Code search is still warming up: these are the lines found so far.
479 Reload in a moment for the rest.
480 </p>`,
481 )}
470482 ${WORDS
471483 .filter(
472484 ([kind]) => kind !== "all" && (a.kind === "all" || a.kind === kind),
test/search-scale.test.ts added +127
@@ -0,0 +1,127 @@
1 /** /search answers under 50 ms over 2,000 issues and 200 repositories (#3360). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { cpSync } from "node:fs";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp } from "../src/app.ts";
8 import { createToken } from "../src/core/tokens.ts";
9 import { createUser } from "../src/core/users.ts";
10 import { listReposVisibleTo } from "../src/core/repos.ts";
11 import { grepLoad, grepRepo, grepRepos, MAX_GREPS_RUNNING, resetGrepCache } from "../src/core/search.ts";
12 import { initBareRepo, repoDir } from "../src/git/repos.ts";
13 import { serve } from "../src/http/server.ts";
14
15 let dir = "";
16 let app: ReturnType<typeof createApp>;
17 let servers: Awaited<ReturnType<typeof serve>>;
18 let bearer = "";
19
20 beforeAll(async () => {
21 dir = await mkdtemp(join(tmpdir(), "forge-search-scale-"));
22 app = createApp({ dataDir: dir, port: 0 });
23 servers = await serve(app);
24 const made = await createUser(app.db, {
25 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
26 password: "a-good-passphrase", adminIfFirst: true,
27 });
28 if (!made.ok) throw new Error(made.error);
29 bearer = createToken(app.db, made.value.id, "t", "admin").token;
30 const owner = made.value.id;
31 // One real repository with a commit mentioning the word, copied 200 times.
32 const proto = join(dir, "proto");
33 await initBareRepo(proto);
34 const git = (...args: string[]) =>
35 Bun.spawnSync(["git", ...args], { cwd: proto, env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" } });
36 const hashed = Bun.spawnSync(["git", "hash-object", "-w", "--stdin"], { cwd: proto, stdin: new TextEncoder().encode("timing is everything\n") });
37 const blobId = hashed.stdout.toString().trim();
38 const tree = Bun.spawnSync(["git", "mktree"], { cwd: proto, stdin: new TextEncoder().encode(`100644 blob ${blobId}\tnotes.txt\n`) }).stdout.toString().trim();
39 const commit = git("commit-tree", tree, "-m", "seed").stdout.toString().trim();
40 git("update-ref", "refs/heads/main", commit);
41 for (let r = 0; r < 200; r++) cpSync(proto, repoDir(app.reposRoot, "alice", `service-${r}`), { recursive: true });
42 app.db.transaction(() => {
43 for (let r = 0; r < 200; r++) {
44 const repo = `r${String(r).padStart(4, "0")}`;
45 app.db.query(
46 "INSERT INTO repo (id, owner_id, name, visibility, description, issue_seq) VALUES (?1, ?2, ?3, 'public', ?4, 10)",
47 ).run(repo, owner, `service-${r}`, `timing service number ${r}`);
48 for (let n = 1; n <= 10; n++) {
49 app.db.query(
50 "INSERT INTO issue (id, repo_id, number, title, author_id, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
51 ).run(`${repo}-${n}`, repo, n, `Timing of step ${n} in ${r}`, owner,
52 `2026-01-01T00:${String(r % 60).padStart(2, "0")}:${String(n).padStart(2, "0")}.000Z`);
53 }
54 }
55 })();
56 });
57
58 afterAll(async () => {
59 servers.stop();
60 app.close();
61 await rm(dir, { recursive: true, force: true });
62 });
63
64 // Every request is a first one: the grep cache is emptied, so the word is new.
65 for (const kind of ["issues", "repos", "all"]) test(`a first search for a common word over 200 repositories and 2,000 issues answers under 50 ms (${kind})`, async () => {
66 resetGrepCache();
67 const res = await fetch(servers.url + `/search?q=timing&kind=${kind}`, { headers: { authorization: `Bearer ${bearer}` } });
68 expect(res.status).toBe(200);
69 await res.text();
70 const timing = res.headers.get("server-timing") ?? "";
71 const dur = (n: string) => Number(new RegExp(`${n};dur=([\\d.]+)`).exec(timing)?.[1]);
72 const own = ["session", "search", "apps", "render"].reduce((s, n) => s + dur(n), 0);
73 expect(own).toBeLessThan(50);
74 });
75
76 test("a code search out of time says so, keeps the issues, and a repeat fills in", async () => {
77 resetGrepCache();
78 const repos = listReposVisibleTo(app.db, undefined, { limit: 50 });
79 const cut = await grepRepos(app.reposRoot, repos, "timing", 100, 0);
80 expect(cut.partial).toBe(true);
81 // Each ask finishes some greps in the background; asking again is whole in the end.
82 let whole = await grepRepos(app.reposRoot, repos, "timing", 100, 50);
83 for (let i = 0; i < 100 && whole.partial; i++) whole = await grepRepos(app.reposRoot, repos, "timing", 100, 50);
84 expect(whole.partial).toBe(false);
85 expect(whole.hits.length).toBe(50);
86 });
87
88 test("a first page keeps the hits that finished in time, in repo order, and says the rest is partial", async () => {
89 resetGrepCache();
90 const repos = listReposVisibleTo(app.db, undefined, { limit: 50 });
91 // One repository already answered (its commit is cached); the rest are cold.
92 await grepRepo(repoDir(app.reposRoot, repos[0]!.ownerName, repos[0]!.name), repos[0]!.defaultBranch, "timing");
93 const early = await grepRepos(app.reposRoot, repos, "timing", 100, 0);
94 expect(early.hits.length).toBeGreaterThanOrEqual(1);
95 expect(early.hits[0]!.repo.name).toBe(repos[0]!.name);
96 expect(early.partial).toBe(true);
97 const res = await fetch(servers.url + "/search?q=timing&kind=code", { headers: { authorization: `Bearer ${bearer}` } });
98 const body = await res.text();
99 expect(body).toContain("notes.txt");
100 expect(body).toContain('role="status" data-code-partial');
101 });
102
103 test("greps running at once never exceed the cap, however many answers gave up waiting", async () => {
104 resetGrepCache();
105 const repos = listReposVisibleTo(app.db, undefined, { limit: 50 });
106 for (const q of ["alpha", "beta", "gamma", "delta"]) await grepRepos(app.reposRoot, repos, q, 100, 0);
107 expect(grepLoad().peak).toBeLessThanOrEqual(MAX_GREPS_RUNNING);
108 for (let i = 0; i < 200 && grepLoad().running > 0; i++) await Bun.sleep(10);
109 expect(grepLoad().running).toBe(0);
110 });
111
112 test("a cached code answer never outlives its commit, and equals the cold one", async () => {
113 const dirOf = repoDir(app.reposRoot, "alice", "service-0");
114 resetGrepCache();
115 const cold = await grepRepo(dirOf, "main", "timing");
116 expect(cold.length).toBe(1);
117 expect(await grepRepo(dirOf, "main", "TIMING")).toEqual(cold);
118 (await grepRepo(dirOf, "main", "timing"))[0]!.text = "mutated";
119 expect(await grepRepo(dirOf, "main", "timing")).toEqual(cold);
120 const env = { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" };
121 const run = (stdin: string, ...args: string[]) =>
122 Bun.spawnSync(["git", ...args], { cwd: dirOf, env, stdin: new TextEncoder().encode(stdin) }).stdout.toString().trim();
123 const blob = run("no match here\n", "hash-object", "-w", "--stdin");
124 const tree = run(`100644 blob ${blob}\tnotes.txt\n`, "mktree");
125 run("", "update-ref", "refs/heads/main", run("", "commit-tree", tree, "-m", "again"));
126 expect(await grepRepo(dirOf, "main", "timing")).toEqual([]);
127 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs