Skip to content

Commit c117b0c

Browse files
authored
perf(cli): share a running catalog gather between searches (#9460)
* perf(cli): share a running catalog gather between searches Searches that start while gatherCandidatesReused is still gathering now wait for that gather instead of starting their own. Locally, nine concurrent cold searches took 1.6 s instead of 13.8-18.8 s; a docs site's search sees this when several queries reach a server that is starting. * perf(cli): reuse gathers through reusedWhileUnchanged A search that joined a running gather skipped the stamp check, so after an edit to a file the gather had already read it could get the pre-edit catalog. Keep one reusedWhileUnchanged loader per folder and type instead: it shares a running load only while what it read is unchanged. The loader takes the stamp check its caller imports, so the adapter's tests can still hold that answer.
1 parent 41aa832 commit c117b0c

5 files changed

Lines changed: 78 additions & 26 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@astryxdesign/cli': patch
3+
---
4+
5+
[perf] `search()` shares a catalog gather that is still running: searches that start together in one long-running process, such as a docs site's search right after it starts, now gather once instead of once each
6+
@cixzhang

‎packages/cli/api/search/_adapter.mjs‎

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@
99
import {readFileSync} from 'node:fs';
1010
import * as path from 'node:path';
1111
import {requireCoreDir} from '../../foundation/fs/paths.mjs';
12-
import {recordReads, unchangedSince} from '../../foundation/fs/read-record.mjs';
12+
import {
13+
reusedWhileUnchanged,
14+
unchangedSince,
15+
} from '../../foundation/fs/read-record.mjs';
1316
import {isOutsideProject} from '../../foundation/env/project-scope.mjs';
1417
import {coreDirOrThrow} from '../error.mjs';
1518
import {CORELESS_DOMAINS} from './_query.mjs';
@@ -95,7 +98,7 @@ export async function gatherCandidates(options) {
9598

9699
/**
97100
* @typedef {Awaited<ReturnType<typeof gatherCandidates>>} Gathered
98-
* @type {Map<string, {reads: Map<string, string>, value: Promise<Gathered>}>}
101+
* @type {Map<string, (options?: {fresh?: boolean}) => Promise<Gathered>>}
99102
*/
100103
const gathered = new Map();
101104

@@ -104,30 +107,27 @@ const gathered = new Map();
104107
* folder, for the same `type`, ranks the candidates an earlier search
105108
* gathered when none of the files that gather read, and none of the folders
106109
* it listed or probed, changed since (each is checked by its change time and
107-
* size, so an edited doc in a linked package is seen on the next call). A
110+
* size, so an edited doc in a linked package is seen on the next call). That
111+
* holds for a gather that is still running too, so searches that start
112+
* together (a docs site's search right after it starts) share one gather. A
108113
* long-running caller (a docs site's search, an agent harness) then pays the
109114
* gather once. A one-shot `astryx search` gathers once, as before.
110115
* @param {{cwd?: string, type?: string}} options
111116
* @returns {Promise<Gathered>}
112117
*/
113-
export async function gatherCandidatesReused(options) {
118+
export function gatherCandidatesReused(options) {
114119
const cwd = path.resolve(options.cwd ?? process.cwd());
115-
const key = `${cwd}\0${options.type ?? ''}`;
116-
const hit = gathered.get(key);
117-
if (hit && unchangedSince(hit.reads)) return hit.value;
118-
/** @type {Map<string, string>} */
119-
const seen = new Map();
120-
const value = recordReads(seen, () => gatherCandidates({...options, cwd}));
121-
try {
122-
await value;
123-
} catch (error) {
124-
if (gathered.get(key)?.value === value) gathered.delete(key);
125-
throw error;
120+
const type = options.type;
121+
const key = `${cwd}\0${type ?? ''}`;
122+
let gather = gathered.get(key);
123+
if (!gather) {
124+
gather = reusedWhileUnchanged(
125+
() => gatherCandidates({cwd, type}),
126+
unchangedSince,
127+
);
128+
gathered.set(key, gather);
126129
}
127-
// Each path's state was taken as it was first read, so an edit made while
128-
// the gather ran shows as a change on the next call.
129-
gathered.set(key, {reads: seen, value});
130-
return value;
130+
return gather();
131131
}
132132

133133
/**

‎packages/cli/api/search/_adapter.test.mjs‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22

33
/**
44
* @file Tests for search's adapter: a long-running caller reuses the gathered
5-
* candidates while their inputs are unchanged (gatherCandidatesReused), and
6-
* gathers again when an input changes or for another folder or `type`.
5+
* candidates while their inputs are unchanged (gatherCandidatesReused), shares
6+
* a gather that is still running, and gathers again when an input changes or
7+
* for another folder or `type`.
78
*
89
* Whether inputs changed is read-record's answer (tested in
910
* read-record.test.mjs). Other tests running at the same time change shared
@@ -52,6 +53,22 @@ describe('gatherCandidatesReused', () => {
5253
SLOW,
5354
);
5455

56+
it(
57+
'shares one gather between searches that start while it runs',
58+
async () => {
59+
const cwd = scratchProject();
60+
const all = await Promise.all(
61+
Array.from({length: 9}, () =>
62+
gatherCandidatesReused({cwd, type: 'doc'}),
63+
),
64+
);
65+
// One gather: every search got the same candidates object.
66+
for (const each of all) expect(each).toBe(all[0]);
67+
expect(all[0].all.length).toBeGreaterThan(0);
68+
},
69+
SLOW,
70+
);
71+
5572
it(
5673
'gathers again when an input file changes',
5774
async () => {

‎packages/cli/foundation/fs/read-record.mjs‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -170,19 +170,23 @@ export function recordReads(seen, fn) {
170170
* read counts as read by the operation that asks for it.
171171
* @template T
172172
* @param {() => Promise<T>} load
173+
* @param {(recorded: Map<string, string>) => boolean} [isUnchanged] - Whether
174+
* recorded paths are unchanged; `unchangedSince` unless a caller passes the
175+
* one it imports (so a test of that caller can hold the answer).
173176
* @returns {(options?: {fresh?: boolean}) => Promise<T>}
174177
*/
175-
export function reusedWhileUnchanged(load) {
178+
export function reusedWhileUnchanged(load, isUnchanged = unchangedSince) {
176179
/** @type {{reads: Map<string, string>, value: Promise<T>} | undefined} */
177180
let last;
178181
return ({fresh = false} = {}) => {
179-
if (!fresh && last && unchangedSince(last.reads)) {
182+
if (!fresh && last && isUnchanged(last.reads)) {
180183
const {reads: recorded, value} = last;
181184
return value.then(result => {
182185
const runs = reads.getStore();
183-
if (runs) for (const [file, state] of recorded) {
184-
for (const seen of runs) if (!seen.has(file)) seen.set(file, state);
185-
}
186+
if (runs)
187+
for (const [file, state] of recorded) {
188+
for (const seen of runs) if (!seen.has(file)) seen.set(file, state);
189+
}
186190
return result;
187191
});
188192
}

‎packages/cli/foundation/fs/read-record.test.mjs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,31 @@ describe('reusedWhileUnchanged', () => {
151151
expect(unchangedSince(seen)).toBe(false);
152152
});
153153

154+
it('shares a load that is still running, unless what it read has changed since', async () => {
155+
const {file} = scratch();
156+
let loads = 0;
157+
/** @type {(() => void)[]} */
158+
const finish = [];
159+
const get = reusedWhileUnchanged(async () => {
160+
loads += 1;
161+
const text = fs.readFileSync(file, 'utf8');
162+
await new Promise(resolve => finish.push(() => resolve(undefined)));
163+
return text;
164+
});
165+
const running = get();
166+
const joined = get();
167+
expect(loads).toBe(1);
168+
// An edit to a file the running load already read: a later call loads
169+
// again instead of sharing the pre-edit value.
170+
fs.writeFileSync(file, 'two, longer');
171+
const afterEdit = get();
172+
expect(loads).toBe(2);
173+
for (const done of finish) done();
174+
expect(await running).toBe('one');
175+
expect(await joined).toBe('one');
176+
expect(await afterEdit).toBe('two, longer');
177+
});
178+
154179
it('tries a failed load again', async () => {
155180
let calls = 0;
156181
const get = reusedWhileUnchanged(async () => {

0 commit comments

Comments
 (0)