Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
perf(client): share repeated reads within one query command
KageBinary5245b5916a1d
diff --git a/ix-cli/scripts/fetch-log.mjs b/ix-cli/scripts/fetch-log.mjsnew file mode 100644index 00000000..dd950c83--- /dev/null+++ b/ix-cli/scripts/fetch-log.mjs@@ -0,0 +1,42 @@+// Copyright 2026 Ix Infrastructure Inc.++// Dev-only preload that logs every backend request a CLI run makes, for+// measuring request counts and time spent waiting on the backend:+//+// IX_FETCH_LOG=/tmp/run.jsonl node --import ./scripts/fetch-log.mjs dist/cli/main.js context Foo+//+// Appends one JSON line per request -- method, path, ms, response bytes, and+// the ms since process start it was sent at -- plus a `first` line when the+// first request goes out (time to first request = start-up cost) and an+// `exit` line. IX_FETCH_BODY=1 adds each request body, which is what telling+// a repeated request from a merely similar one needs.++import { appendFileSync } from "node:fs";+import { performance } from "node:perf_hooks";++const out = process.env.IX_FETCH_LOG;+const withBody = process.env.IX_FETCH_BODY === "1";+const log = (record) => { if (out) appendFileSync(out, `${JSON.stringify(record)}\n`); };+const original = globalThis.fetch;+let first = true;++globalThis.fetch = async function loggedFetch(input, init) {+ const url = new URL(typeof input === "string" ? input : input.url ?? String(input));+ const start = performance.now();+ if (first) { first = false; log({ ev: "first", t: +start.toFixed(1) }); }+ const response = await original(input, init);+ // Measured to the end of the body, off a clone so the caller still reads it.+ const bytes = (await response.clone().arrayBuffer()).byteLength;+ log({+ ev: "req",+ method: init?.method ?? "GET",+ path: url.pathname + url.search,+ start: +start.toFixed(1),+ ms: +(performance.now() - start).toFixed(1),+ bytes,+ ...(withBody && typeof init?.body === "string" ? { body: init.body } : {}),+ });+ return response;+};++process.on("exit", () => log({ ev: "exit", t: +performance.now().toFixed(1) }));diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.tsindex 8eac3d7b..c3d4b828 100644--- a/ix-cli/src/cli/commands/context.ts+++ b/ix-cli/src/cli/commands/context.ts@@ -12,6 +12,7 @@ import {} from "../context-bundle-schema.js";import { IxClient } from "../../client/api.js";+import { QUERY_CLIENT_OPTIONS } from "../../client/request-memo.js";import type {ConflictReport,DecisionReport,@@ -431,7 +432,7 @@ export function registerContextCommand(program: Command): void {return;}- const client = new IxClient(getEndpoint());+ const client = new IxClient(getEndpoint(), undefined, QUERY_CLIENT_OPTIONS);const resolved = await resolveFileOrReport(client, target, {kind: opts.kind,@@ -542,7 +543,7 @@ async function buildFreshBundle(budgets: BudgetSnapshot,format: string,): Promise<ContextBundle | undefined> {- const client = new IxClient(getEndpoint());+ const client = new IxClient(getEndpoint(), undefined, QUERY_CLIENT_OPTIONS);const resolved = await resolveFileOrReport(client, target, {kind: opts.kind,path: opts.path,@@ -1646,7 +1647,7 @@ async function buildIssueBundle(return undefined;}- const client = new IxClient(getEndpoint());+ const client = new IxClient(getEndpoint(), undefined, QUERY_CLIENT_OPTIONS);await ensureReadScope(client);const scope = activeReadScope();const plan = await planIssue(text, {diff --git a/ix-cli/src/cli/commands/explain.ts b/ix-cli/src/cli/commands/explain.tsindex 521eed96..c254db3a 100644--- a/ix-cli/src/cli/commands/explain.ts+++ b/ix-cli/src/cli/commands/explain.ts@@ -2,6 +2,7 @@import type { Command } from "commander";import { IxClient } from "../../client/api.js";+import { QUERY_CLIENT_OPTIONS } from "../../client/request-memo.js";import { getEndpoint } from "../config.js";import { formatExplain, relativePath, printJson, type ExplainResult, type EntityRef, type Diagnostic } from "../format.js";import { resolveFileOrReport, isRawId } from "../resolve.js";@@ -26,7 +27,7 @@ export function registerExplainCommand(program: Command): void {.option("--raw", "Show raw metadata dump (legacy format)").addHelpText("after", "\nExamples:\n ix explain IngestionService\n ix explain expand --path memory-layer\n ix explain verify_token --kind function --format json\n ix explain IxClient --raw").action(async (symbol: string, opts: { kind?: string; path?: string; pick?: number; format: string; raw?: boolean }) => {- const client = new IxClient(getEndpoint());+ const client = new IxClient(getEndpoint(), undefined, QUERY_CLIENT_OPTIONS);const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick };const target = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);if (!target) return;diff --git a/ix-cli/src/cli/commands/impact.ts b/ix-cli/src/cli/commands/impact.tsindex a4a23285..0f06497a 100644--- a/ix-cli/src/cli/commands/impact.ts+++ b/ix-cli/src/cli/commands/impact.ts@@ -4,6 +4,7 @@ import type { Command } from "commander";import chalk from "chalk";import { renderSection, renderKeyValue, renderNote, renderResolvedHeader, colorizeKind } from "../ui.js";import { IxClient } from "../../client/api.js";+import { QUERY_CLIENT_OPTIONS } from "../../client/request-memo.js";import { getEndpoint } from "../config.js";import { resolveFileOrReport, printResolved } from "../resolve.js";import { bucketByHierarchy, getSystemPath, formatSystemPath, hasMapData, type SystemPath } from "../hierarchy.js";@@ -33,7 +34,7 @@ export function registerImpactCommand(program: Command): void {symbol: string,opts: { kind?: string; path?: string; pick?: number; depth: string; limit: string; format: string }) => {- const client = new IxClient(getEndpoint());+ const client = new IxClient(getEndpoint(), undefined, QUERY_CLIENT_OPTIONS);const limit = parseInt(opts.limit, 10);const depth = Math.min(Math.max(parseInt(opts.depth, 10) || 1, 1), 3);diff --git a/ix-cli/src/cli/commands/overview.ts b/ix-cli/src/cli/commands/overview.tsindex eabb54db..8c683b33 100644--- a/ix-cli/src/cli/commands/overview.ts+++ b/ix-cli/src/cli/commands/overview.ts@@ -2,6 +2,7 @@import type { Command } from "commander";import { IxClient } from "../../client/api.js";+import { QUERY_CLIENT_OPTIONS } from "../../client/request-memo.js";import { getEndpoint } from "../config.js";import { resolveFileOrReport, printResolved } from "../resolve.js";import { getEffectiveSystemPath, getSystemPath, hasMapData } from "../hierarchy.js";@@ -56,7 +57,7 @@ Examples:ix overview scoreCandidate --pick 2`).action(async (symbol: string, opts: { kind?: string; path?: string; pick?: number; format: string }) => {- const client = new IxClient(getEndpoint());+ const client = new IxClient(getEndpoint(), undefined, QUERY_CLIENT_OPTIONS);const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick };const target = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);if (!target) return;diff --git a/ix-cli/src/client/__tests__/request-memo.test.ts b/ix-cli/src/client/__tests__/request-memo.test.tsnew file mode 100644index 00000000..8391e277--- /dev/null+++ b/ix-cli/src/client/__tests__/request-memo.test.ts@@ -0,0 +1,238 @@+// Copyright 2026 Ix Infrastructure Inc.++import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";+import type { AddressInfo } from "node:net";+import { afterEach, describe, expect, it } from "vitest";++import { IxClient } from "../api.js";+import { Limiter, mapLimit, QUERY_CLIENT_OPTIONS, RequestMemo } from "../request-memo.js";++const servers: Server[] = [];+type Seen = { method: string; path: string; body: string };++/** A backend that records every request and answers after `delayMs`. */+async function backend(+ reply: (request: Seen) => { status?: number; body: unknown },+ delayMs = 0,+) {+ const seen: Seen[] = [];+ let inFlight = 0;+ let peak = 0;+ const server = createServer((request: IncomingMessage, response: ServerResponse) => {+ let body = "";+ inFlight++;+ peak = Math.max(peak, inFlight);+ request.setEncoding("utf8");+ request.on("data", (chunk) => { body += chunk; });+ request.on("end", () => {+ const record = { method: request.method ?? "", path: request.url ?? "", body };+ seen.push(record);+ setTimeout(() => {+ const { status = 200, body: out } = reply(record);+ inFlight--;+ response.writeHead(status, { "content-type": "application/json" });+ response.end(typeof out === "string" ? out : JSON.stringify(out));+ }, delayMs);+ });+ });+ servers.push(server);+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ return {+ seen,+ peak: () => peak,+ endpoint: `http://127.0.0.1:${(server.address() as AddressInfo).port}`,+ };+}++afterEach(async () => {+ await Promise.all(servers.splice(0).map((server) => new Promise<void>((resolve) => {+ server.closeAllConnections();+ server.close(() => resolve());+ })));+});++const expandReply = (request: Seen) => {+ const { nodeId } = JSON.parse(request.body) as { nodeId: string };+ return { body: { nodes: [{ id: `${nodeId}-n` }, { id: `${nodeId}-m` }], edges: [] } };+};++describe("IxClient shareReads", () => {+ it("sends an identical read once, however many callers ask", async () => {+ const b = await backend(expandReply, 20);+ const client = new IxClient(b.endpoint, undefined, { shareReads: true });++ const [one, two, three] = await Promise.all([+ client.expand("a", { direction: "in", predicates: ["CALLS"] }),+ client.expand("a", { direction: "in", predicates: ["CALLS"] }),+ client.expand("a", { direction: "in", predicates: ["CALLS"] }),+ ]);+ // After the first has finished, too.+ const four = await client.expand("a", { direction: "in", predicates: ["CALLS"] });++ expect(b.seen).toHaveLength(1);+ expect(client.sharedReadHits).toBe(3);+ for (const r of [two, three, four]) expect(r).toEqual(one);+ });++ it("keys on the whole request: a different body or path is its own read", async () => {+ const b = await backend((request) => request.path.startsWith("/v1/entity/")+ ? { body: { node: { id: request.path }, claims: [], edges: [] } }+ : expandReply(request));+ const client = new IxClient(b.endpoint, undefined, { shareReads: true });++ await client.expand("a", { direction: "in", predicates: ["CALLS"] });+ await client.expand("a", { direction: "out", predicates: ["CALLS"] });+ await client.expand("a", { direction: "in", predicates: ["CALLS"], hops: 2 });+ await client.expand("b", { direction: "in", predicates: ["CALLS"] });+ await client.entity("a");+ await client.entity("a");++ expect(b.seen.map((s) => s.path)).toEqual([+ "/v1/expand", "/v1/expand", "/v1/expand", "/v1/expand", "/v1/entity/a",+ ]);+ });++ it("hands every caller its own copy, so one caller's edits never reach another", async () => {+ const b = await backend(expandReply);+ const client = new IxClient(b.endpoint, undefined, { shareReads: true });++ const first = await client.expand("a");+ first.nodes.sort((x: { id: string }, y: { id: string }) => (x.id < y.id ? 1 : -1)).push({ id: "added" });+ const second = await client.expand("a");++ expect(second.nodes).toEqual([{ id: "a-n" }, { id: "a-m" }]);+ expect(b.seen).toHaveLength(1);+ });++ it("never shares a write", async () => {+ const b = await backend(() => ({ body: [{ status: "Ok", rev: 1 }] }));+ const client = new IxClient(b.endpoint, undefined, { shareReads: true });++ await client.commitPatchBatch([]);+ await client.commitPatchBatch([]);++ expect(b.seen).toHaveLength(2);+ });++ it("does not keep a failure: the next identical read asks again", async () => {+ let fail = true;+ const b = await backend((request) => {+ if (fail) { fail = false; return { status: 503, body: "busy" }; }+ return expandReply(request);+ });+ const client = new IxClient(b.endpoint, undefined, { shareReads: true });++ await expect(client.expand("a")).rejects.toThrow("503: busy");+ await expect(client.expand("a")).resolves.toEqual({ nodes: [{ id: "a-n" }, { id: "a-m" }], edges: [] });+ expect(b.seen).toHaveLength(2);+ });++ it("is off by default: a plain client sends every request it is asked to", async () => {+ const b = await backend(expandReply);+ const client = new IxClient(b.endpoint);++ await Promise.all([client.expand("a"), client.expand("a")]);+ await client.expand("a");++ expect(b.seen).toHaveLength(3);+ });++ it("keeps the status in a non-JSON 2xx error, as the unshared path always did", async () => {+ const b = await backend(() => ({ body: "<html>proxy</html>" }));+ for (const options of [{}, QUERY_CLIENT_OPTIONS]) {+ const client = new IxClient(b.endpoint, undefined, options);+ await expect(client.expand("a")).rejects.toThrow("200: response body is not JSON: <html>proxy</html>");+ }+ });+});++describe("IxClient maxInFlight", () => {+ it("holds concurrent requests to the cap", async () => {+ const b = await backend(expandReply, 15);+ const client = new IxClient(b.endpoint, undefined, { maxInFlight: 3 });++ const ids = Array.from({ length: 12 }, (_, i) => `n${i}`);+ const results = await Promise.all(ids.map((id) => client.expand(id)));++ expect(b.seen).toHaveLength(12);+ expect(b.peak()).toBeLessThanOrEqual(3);+ expect(results.map((r) => r.nodes[0].id)).toEqual(ids.map((id) => `${id}-n`));+ });+});++describe("RequestMemo", () => {+ it("shares a pending load and counts the hits", async () => {+ const memo = new RequestMemo<number>();+ let loads = 0;+ const load = async () => { loads++; return 7; };++ const values = await Promise.all([memo.run("k", load), memo.run("k", load), memo.run("j", load)]);++ expect(values).toEqual([7, 7, 7]);+ expect(loads).toBe(2);+ expect(memo.hits).toBe(1);+ });++ it("evicts a rejected load", async () => {+ const memo = new RequestMemo<number>();+ await expect(memo.run("k", async () => { throw new Error("no"); })).rejects.toThrow("no");+ await expect(memo.run("k", async () => 1)).resolves.toBe(1);+ expect(memo.hits).toBe(0);+ });+});++describe("Limiter", () => {+ it("runs at most `max` at once and starts waiters in arrival order", async () => {+ const limiter = new Limiter(2);+ let active = 0;+ let peak = 0;+ const started: number[] = [];+ const task = (i: number) => limiter.run(async () => {+ started.push(i);+ active++;+ peak = Math.max(peak, active);+ await new Promise((resolve) => setTimeout(resolve, 5));+ active--;+ return i;+ });++ const out = await Promise.all([0, 1, 2, 3, 4, 5].map(task));++ expect(out).toEqual([0, 1, 2, 3, 4, 5]);+ expect(peak).toBe(2);+ expect(started).toEqual([0, 1, 2, 3, 4, 5]);+ });++ it("frees the slot when a task throws", async () => {+ const limiter = new Limiter(1);+ await expect(limiter.run(async () => { throw new Error("boom"); })).rejects.toThrow("boom");+ await expect(limiter.run(async () => "next")).resolves.toBe("next");+ });++ it("refuses a cap that is not a positive integer", () => {+ expect(() => new Limiter(0)).toThrow();+ expect(() => new Limiter(1.5)).toThrow();+ });+});++describe("mapLimit", () => {+ it("returns results in input order whatever order they finish in", async () => {+ const delays = [30, 5, 20, 0, 10];+ let active = 0;+ let peak = 0;+ const out = await mapLimit(delays, 2, async (ms, index) => {+ active++;+ peak = Math.max(peak, active);+ await new Promise((resolve) => setTimeout(resolve, ms));+ active--;+ return `${index}:${ms}`;+ });++ expect(out).toEqual(["0:30", "1:5", "2:20", "3:0", "4:10"]);+ expect(peak).toBe(2);+ });++ it("handles an empty list", async () => {+ await expect(mapLimit([], 4, async () => 1)).resolves.toEqual([]);+ });+});diff --git a/ix-cli/src/client/api.ts b/ix-cli/src/client/api.tsindex 11554823..fb85eb10 100644--- a/ix-cli/src/client/api.ts+++ b/ix-cli/src/client/api.ts@@ -1,6 +1,7 @@// Copyright 2026 Ix Infrastructure Inc.import { isPreConnectionFailure, RESET_RECONCILIATION_ERROR } from "./transport.js";+import { Limiter, RequestMemo } from "./request-memo.js";import type {IngestResult,StructuredContext,@@ -21,7 +22,38 @@ export interface ListSubsystemsOptions {memberFileCap?: number;}+/**+ * How a client created for ONE query command talks to the backend. Off by+ * default: every existing caller sends exactly the requests it did.+ */+export interface IxClientOptions {+ /**+ * Answer a repeated read (same method, path and body) from the first+ * response instead of asking again. See `request-memo.ts` for why this is+ * per-command only and never for a long-lived client.+ */+ shareReads?: boolean;+ /** At most this many requests in flight at once. */+ maxInFlight?: number;+}++/**+ * The reads `shareReads` may answer from an earlier response: lookups whose+ * answer cannot change because of anything the same command does.+ */+const SHARED_READ_PREFIXES = [+ "/v1/expand", "/v1/search", "/v1/context", "/v1/list",+ "/v1/entity/", "/v1/provenance/", "/v1/resolve-prefix/",+];++function isSharedRead(path: string): boolean {+ return SHARED_READ_PREFIXES.some((prefix) => path.startsWith(prefix));+}+export class IxClient {+ private readonly memo?: RequestMemo<SuccessBody>;+ private readonly limiter?: Limiter;+// An optional deadline signal shared across every request this client makes.// `ix map` sets it to a hard wall-clock budget so that, even when the backend// is unhealthy and individual requests would otherwise sit on their long@@ -32,7 +64,16 @@ export class IxClient {// than being handed a second string that is only equal by inspection.public readonly endpoint: string = "http://localhost:8090",private deadlineSignal?: AbortSignal,- ) {}+ options: IxClientOptions = {},+ ) {+ if (options.shareReads) this.memo = new RequestMemo();+ if (options.maxInFlight !== undefined) this.limiter = new Limiter(options.maxInFlight);+ }++ /** Reads answered from `shareReads` instead of the backend, for diagnostics and tests. */+ get sharedReadHits(): number {+ return this.memo?.hits ?? 0;+ }// Combine a per-request timeout with the optional shared deadline. Whichever// fires first aborts the fetch. AbortSignal.any propagates the first abort.@@ -650,32 +691,51 @@ export class IxClient {}private async post<T>(path: string, body: unknown): Promise<T> {- const resp = await fetch(`${this.endpoint}${path}`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- // These small reads/writes (source-hashes, stitch, list, ...) had no- // timeout, so a stalled connection could hang the process indefinitely.- // 2 min per request, also bounded by the shared deadline when set.- signal: this.signalFor(2 * 60 * 1000),- });- if (!resp.ok) {- const text = await resp.text();- throw new Error(`${resp.status}: ${text}`);- }- return parseOrThrowWithStatus<T>(resp);+ const payload = JSON.stringify(body);+ return this.read<T>("POST", path, payload, () =>+ fetch(`${this.endpoint}${path}`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: payload,+ // These small reads/writes (source-hashes, stitch, list, ...) had no+ // timeout, so a stalled connection could hang the process indefinitely.+ // 2 min per request, also bounded by the shared deadline when set.+ signal: this.signalFor(2 * 60 * 1000),+ }));}private async get<T>(path: string): Promise<T> {- const resp = await fetch(`${this.endpoint}${path}`, {- signal: this.signalFor(2 * 60 * 1000),- });- if (!resp.ok) {- const text = await resp.text();- throw new Error(`${resp.status}: ${text}`);- }- return parseOrThrowWithStatus<T>(resp);+ return this.read<T>("GET", path, "", () =>+ fetch(`${this.endpoint}${path}`, {+ signal: this.signalFor(2 * 60 * 1000),+ }));}++ /**+ * One request whose body is JSON: sent under the in-flight limit when there+ * is one, shared with an identical earlier request when `shareReads` is on+ * and the path is a read, and parsed per caller either way.+ */+ private async read<T>(method: string, path: string, payload: string, send: () => Promise<Response>): Promise<T> {+ const fetchBody = async (): Promise<SuccessBody> => {+ const run = async (): Promise<SuccessBody> => {+ const resp = await send();+ const text = await resp.text();+ if (!resp.ok) throw new Error(`${resp.status}: ${text}`);+ return { status: resp.status, text };+ };+ return this.limiter ? this.limiter.run(run) : run();+ };+ const body = this.memo && isSharedRead(path)+ ? await this.memo.run(`${method} ${path} ${payload}`, fetchBody)+ : await fetchBody();+ return parseOrThrowWithStatus<T>(body);+ }+}++interface SuccessBody {+ status: number;+ text: string;}/**@@ -690,12 +750,11 @@ export class IxClient {* inference into a fact the error carries, and it matches the `${status}: ...`* shape every other failure here already uses.*/-async function parseOrThrowWithStatus<T>(resp: Response): Promise<T> {- const text = await resp.text();+function parseOrThrowWithStatus<T>({ status, text }: SuccessBody): T {try {return JSON.parse(text) as T;} catch {const preview = text.length > 200 ? `${text.slice(0, 200)}…` : text;- throw new Error(`${resp.status}: response body is not JSON: ${preview}`);+ throw new Error(`${status}: response body is not JSON: ${preview}`);}}diff --git a/ix-cli/src/client/request-memo.ts b/ix-cli/src/client/request-memo.tsnew file mode 100644index 00000000..4fc1a176--- /dev/null+++ b/ix-cli/src/client/request-memo.ts@@ -0,0 +1,112 @@+// Copyright 2026 Ix Infrastructure Inc.++/**+ * Per-command request sharing for the read paths of `IxClient`.+ *+ * The query commands build their answer from many small reads, and several+ * collectors ask the same question independently: `ix context --from-issue`+ * walks each starting point's neighbourhood with the same helpers, so the+ * files they share are expanded once per starting point -- measured at 56 of+ * 225 requests on one issue against the Ix repository's own graph. Sharing a+ * read by its exact request (method, path, body) removes those without any+ * collector having to know about the others.+ *+ * Scope is one command invocation: `IxClient.shareReads()` is called on the+ * client an action handler creates, and that client is dropped when the+ * command returns. It is never enabled on a long-lived client (`ix watch`, the+ * MCP server), where a read after a write must see the write.+ *+ * What is cached is the response TEXT, not the parsed value: every caller+ * parses its own copy, so a caller that sorts or edits the arrays it was+ * handed cannot change what another caller sees. A miss costs nothing extra --+ * the first caller's parse is the one it always did.+ *+ * A failed read is not kept: every caller waiting on it sees the failure, and+ * the next identical request goes back to the backend, as it did before.+ */+export class RequestMemo<V> {+ private readonly entries = new Map<string, Promise<V>>();+ /** Requests answered from the memo rather than the backend. */+ hits = 0;++ run(key: string, load: () => Promise<V>): Promise<V> {+ const existing = this.entries.get(key);+ if (existing) {+ this.hits++;+ return existing;+ }+ const pending = load();+ this.entries.set(key, pending);+ pending.catch(() => {+ if (this.entries.get(key) === pending) this.entries.delete(key);+ });+ return pending;+ }+}++/**+ * At most `max` tasks in flight; the rest wait in arrival order.+ *+ * Lets the collectors run independent steps concurrently without each one+ * multiplying the load on a backend other workspaces share. Only leaf work+ * (one HTTP round trip) runs under it, so a task never waits for a slot while+ * holding one, and it cannot deadlock.+ */+export class Limiter {+ private active = 0;+ private readonly waiting: Array<() => void> = [];++ constructor(readonly max: number) {+ if (!Number.isInteger(max) || max < 1) throw new Error(`Limiter max must be a positive integer, got ${max}`);+ }++ async run<T>(task: () => Promise<T>): Promise<T> {+ if (this.active >= this.max) {+ await new Promise<void>((resolve) => this.waiting.push(resolve));+ } else {+ this.active++;+ }+ try {+ return await task();+ } finally {+ const next = this.waiting.shift();+ // Hand the slot straight to the next task rather than releasing it, so a+ // task arriving in between cannot overtake one that has been waiting.+ if (next) next();+ else this.active--;+ }+ }+}++/**+ * `fn` over `items` with at most `limit` calls in flight, results in input+ * order. The order of completion never reaches the result, so a caller that+ * renders it renders the same thing on every run.+ */+export async function mapLimit<T, R>(+ items: readonly T[],+ limit: number,+ fn: (item: T, index: number) => Promise<R>,+): Promise<R[]> {+ const out = new Array<R>(items.length);+ let next = 0;+ const worker = async () => {+ while (next < items.length) {+ const index = next++;+ out[index] = await fn(items[index], index);+ }+ };+ await Promise.all(Array.from({ length: Math.min(Math.max(1, limit), items.length) }, worker));+ return out;+}++/**+ * The options a one-shot query command creates its client with: repeated+ * reads shared, and at most this many requests in flight. The cap is what the+ * graph walkers already used (`trace`, `depends`, related files: 8) with room+ * for the independent steps of `collectFacts` to overlap.+ *+ * Kept here rather than in `api.ts` so a test that mocks the client module+ * still gets the value.+ */+export const QUERY_CLIENT_OPTIONS = { shareReads: true, maxInFlight: 12 } as const;