Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

perf(map): reuse the last map when nothing changed

KageBinary5e02b87a3b18
diff --git a/ix-cli/src/cli/__tests__/map-result-cache.test.ts b/ix-cli/src/cli/__tests__/map-result-cache.test.ts
new file mode 100644
index 00000000..0aa5d0c8
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/map-result-cache.test.ts
@@ -0,0 +1,498 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createServer, type Server, type ServerResponse } from "node:http";
+import type { AddressInfo } from "node:net";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { execFileSync } from "node:child_process";
+import { Command } from "commander";
+
+import { registerMapCommand } from "../commands/map.js";
+import { ingestFiles } from "../commands/ingest.js";
+import {
+ clearIngestMtimeCache,
+ clearMapBaseline,
+ ingestMtimeCachePath,
+ mapResultCachePath,
+} from "../config.js";
+import {
+ backendIdentity,
+ loadCachedMap,
+ resolveMapCacheSlot,
+ revisionToken,
+ saveCachedMap,
+ type MapCacheSlot,
+} from "../map-result-cache.js";
+import { lockPathForTest } from "../single-flight.js";
+
+/**
+ * `ix map` reuses its last `/v1/map` response when a run ingested nothing and
+ * the backend's head revision has not moved. These drive the real command
+ * against a fake backend and count the map requests, because "no request" is
+ * the whole point and "the same output" is the whole constraint.
+ *
+ * Each way the graph can move is tested so that only ONE guard can catch it:
+ * `frozenRevision` stops commits from advancing the revision, which isolates
+ * the ingest's `graphUnchanged` from the revision check, and a revision bumped
+ * with no ingest isolates the revision check from `graphUnchanged`.
+ */
+
+/** A backend that answers the endpoints `ix map` touches, and records them. */
+class FakeBackend {
+ readonly requests: string[] = [];
+ /** Paths this fake does not implement. Asserted empty after every test. */
+ readonly unknownPaths: string[] = [];
+ rev = 0;
+ /** Commits land without advancing the revision, isolating the ingest-side guard. */
+ frozenRevision = false;
+ /** Answer `/v1/revisions/current` with a record rather than a bare number. */
+ revisionRecord = false;
+ release = "1.0.30";
+ systemId: string | null = null;
+ readonly hashes = new Map<string, { workspaceId: string | null; uri: string; hash: string }>();
+ private readonly patches = new Map<string, unknown[]>();
+ private server: Server | undefined;
+
+ mapRequests(): number {
+ return this.requests.filter(p => p === "/v1/map").length;
+ }
+
+ async start(): Promise<string> {
+ this.server = createServer((req, res) => {
+ const chunks: Buffer[] = [];
+ req.on("data", (c: Buffer) => chunks.push(c));
+ req.on("end", () => this.route(req.url ?? "/", Buffer.concat(chunks).toString("utf8"), res));
+ });
+ await new Promise<void>((resolve, reject) => {
+ this.server!.once("error", reject);
+ this.server!.listen(0, "127.0.0.1", resolve);
+ });
+ return `http://127.0.0.1:${(this.server!.address() as AddressInfo).port}`;
+ }
+
+ async stop(): Promise<void> {
+ if (!this.server) return;
+ const server = this.server;
+ server.closeAllConnections();
+ await new Promise<void>(resolve => server.close(() => resolve()));
+ }
+
+ private route(url: string, body: string, res: ServerResponse): void {
+ const path = new URL(url, "http://x").pathname;
+ this.requests.push(path);
+ const send = (code: number, payload: unknown): void => {
+ res.writeHead(code, { "Content-Type": "application/json" });
+ res.end(JSON.stringify(payload));
+ };
+
+ if (path === "/v1/patches/bulk" || path === "/v1/patch") {
+ type SentPatch = { patchId?: string; source?: { uri?: string; sourceHash?: string; workspaceId?: string }; intent?: string; ops?: unknown[] };
+ let patches: SentPatch[] = [];
+ try {
+ const parsed = JSON.parse(body) as { patches?: SentPatch[] };
+ patches = parsed.patches ?? [parsed as SentPatch];
+ } catch { /* a body we cannot read is still a request */ }
+ if (!this.frozenRevision) this.rev += patches.length || 1;
+ for (const { patchId, source, intent, ops } of patches) {
+ if (patchId) this.patches.set(patchId, ops ?? []);
+ if (!source?.uri) continue;
+ const key = `${source.workspaceId ?? ""}\0${source.uri}`;
+ if (intent?.startsWith("Deleted ")) this.hashes.delete(key);
+ else if (source.sourceHash) {
+ this.hashes.set(key, { workspaceId: source.workspaceId ?? null, uri: source.uri, hash: source.sourceHash });
+ }
+ }
+ return send(200, path === "/v1/patches/bulk"
+ ? { rev: this.rev, applied: patches.length, status: "Ok" }
+ : { rev: this.rev, status: "Ok" });
+ }
+ if (path === "/v1/health") return send(200, { status: "ok", schema_version: 3, release_version: this.release });
+ if (path === "/v1/revisions/current") {
+ return send(200, this.revisionRecord
+ ? { rev: this.rev, patchId: `p-${this.rev}`, timestamp: "2026-09-28T00:00:00Z", summary: {} }
+ : this.rev);
+ }
+ if (path === "/v1/source-hashes") {
+ let uris: string[] = [];
+ try { uris = (JSON.parse(body) as { uris?: string[] }).uris ?? []; } catch { /* none */ }
+ const wanted = new Set(uris);
+ return send(200, [...this.hashes.values()].filter(row => wanted.has(row.uri)));
+ }
+ // A deletion reconciles against the patch it replaces.
+ if (path.startsWith("/v1/patches/")) {
+ const ops = this.patches.get(decodeURIComponent(path.slice("/v1/patches/".length)));
+ return ops ? send(200, { data: { ops } }) : send(404, { error: "Patch not found" });
+ }
+ // ...and asks after each node that patch wrote. A node with no edges is
+ // simply deleted, which is all this fake needs.
+ if (path.startsWith("/v1/entity/")) return send(200, { node: { kind: "function" }, edges: [] });
+ if (path.startsWith("/v1/stitch/system/")) return send(200, { systemId: this.systemId });
+ if (path === "/v1/stitch") return send(200, { stitched: 0, systemId: null, edges: [] });
+ if (path === "/v1/map") {
+ // Derived from the graph, so a stale reuse would show in the output.
+ const files = this.hashes.size;
+ return send(200, {
+ file_count: files,
+ region_count: 2,
+ levels: 2,
+ map_rev: this.rev,
+ outcome: "full_local_completed",
+ regions: [
+ region("r-sys", "system", "Fixture", 2, files, null),
+ region("r-mod", "module", `Module of ${files}`, 1, files, "r-sys"),
+ ],
+ edges: [],
+ hierarchy: [],
+ });
+ }
+ this.unknownPaths.push(path);
+ return send(404, { error: `404: no such endpoint ${path}` });
+ }
+}
+
+function region(id: string, kind: string, label: string, level: number, files: number, parent: string | null) {
+ return {
+ id, label, label_kind: kind, level, file_count: files, child_region_count: parent ? 0 : 1,
+ parent_id: parent, cohesion: 0.5, external_coupling: 0.1, boundary_ratio: 1, confidence: 0.8,
+ crosscut_score: 0, dominant_signals: ["imports"], interface_node_count: 0,
+ };
+}
+
+describe("ix map reuses an unchanged map", () => {
+ vi.setConfig({ testTimeout: 60_000, hookTimeout: 30_000 });
+
+ let home = "";
+ let repo = "";
+ let backend: FakeBackend;
+ const saved: Record<string, string | undefined> = {};
+
+ function fixture(count: number): void {
+ mkdirSync(join(repo, "src"), { recursive: true });
+ for (let i = 0; i < count; i++) {
+ writeFileSync(join(repo, "src", `m${i}.ts`), `export function f${i}(): number { return ${i}; }\n`, "utf8");
+ }
+ execFileSync("git", ["init", "-q"], { cwd: repo, stdio: "ignore" });
+ execFileSync("git", ["add", "-A"], { cwd: repo, stdio: "ignore" });
+ }
+
+ /** Run `ix map <repo>` in-process; stdout, plus stderr for `--silent`. */
+ async function map(...args: string[]): Promise<{ stdout: string; stderr: string }> {
+ const stdout: string[] = [];
+ const stderr: string[] = [];
+ const log = vi.spyOn(console, "log").mockImplementation((...a: unknown[]) => { stdout.push(a.map(String).join(" ")); });
+ const error = vi.spyOn(console, "error").mockImplementation((...a: unknown[]) => { stderr.push(`${a.map(String).join(" ")}\n`); });
+ const write = vi.spyOn(process.stderr, "write").mockImplementation((chunk: unknown) => { stderr.push(String(chunk)); return true; });
+ try {
+ const program = new Command();
+ registerMapCommand(program);
+ await program.parseAsync(["node", "ix", "map", repo, ...args]);
+ } finally {
+ log.mockRestore();
+ error.mockRestore();
+ write.mockRestore();
+ // The lock is released on process exit, which an in-process run never
+ // reaches; without this the next run would coalesce against it.
+ rmSync(lockPathForTest(repo), { force: true });
+ }
+ expect(process.exitCode ?? 0, stderr.join("")).toBe(0);
+ return { stdout: stdout.join("\n"), stderr: stderr.join("") };
+ }
+
+ beforeEach(async () => {
+ backend = new FakeBackend();
+ home = realpathSync(mkdtempSync(join(tmpdir(), "ix-mapcache-home-")));
+ repo = realpathSync(mkdtempSync(join(tmpdir(), "ix-mapcache-repo-")));
+ const endpoint = await backend.start();
+ for (const k of [
+ "HOME", "USERPROFILE", "IX_HOME", "IX_ENDPOINT", "IX_LOCK_DIR", "IX_AUTO_MAP",
+ "IX_MAP_FULL_INGEST", "IX_MAP_DEADLINE_MS", "IX_STITCH_COOLDOWN_MS", "IX_STITCH_WAIT_MS",
+ ]) {
+ saved[k] = process.env[k];
+ delete process.env[k];
+ }
+ process.env.HOME = home;
+ process.env.USERPROFILE = home;
+ process.env.IX_HOME = join(home, ".ix");
+ process.env.IX_ENDPOINT = endpoint;
+ process.env.IX_LOCK_DIR = join(home, "locks");
+ fixture(4);
+ });
+
+ afterEach(async () => {
+ try {
+ expect(backend.unknownPaths, "endpoints the fake does not implement").toEqual([]);
+ } finally {
+ process.exitCode = undefined;
+ await backend.stop();
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ for (const dir of [home, repo]) if (dir) rmSync(dir, { recursive: true, force: true });
+ home = "";
+ repo = "";
+ }
+ });
+
+ it("makes no map request for an unchanged repo, and prints the same thing", async () => {
+ // The first map ingests everything, which the output reports; every run
+ // compared below ingests nothing.
+ await map("--format", "json");
+ for (const format of ["json", "llm", "text"]) {
+ // Something to ask about: a fresh map for this format's first run.
+ backend.rev += 1;
+ const fresh = await map("--format", format);
+ const before = backend.mapRequests();
+ const reused = await map("--format", format);
+ expect(backend.mapRequests(), `${format}: second run must not ask`).toBe(before);
+ expect(reused.stdout, `${format}: output`).toBe(fresh.stdout);
+ expect(reused.stdout.length).toBeGreaterThan(0);
+ }
+
+ backend.rev += 1;
+ const fresh = await map("--silent");
+ const before = backend.mapRequests();
+ const reused = await map("--silent");
+ expect(backend.mapRequests()).toBe(before);
+ const line = (s: string) => s.split("\n").find(l => l.startsWith("map: "))?.replace(/ · \d+ms/, "");
+ expect(line(reused.stderr)).toBe(line(fresh.stderr));
+ expect(line(fresh.stderr)).toBe("map: 4 files · 1s/0ss/1m regions");
+ });
+
+ it("asks again when a file changed", async () => {
+ await map("--format", "json");
+ writeFileSync(join(repo, "src", "m9.ts"), "export const nine = 9;\n", "utf8");
+ const before = backend.mapRequests();
+ const after = await map("--format", "json");
+ expect(backend.mapRequests()).toBe(before + 1);
+ expect(JSON.parse(after.stdout).file_count).toBe(5);
+ });
+
+ it("asks again when an ingest wrote to the graph, even if the revision did not move", async () => {
+ await map("--format", "json");
+ backend.frozenRevision = true;
+ writeFileSync(join(repo, "src", "m1.ts"), "export function f1(): number { return 100; }\n", "utf8");
+ const before = backend.mapRequests();
+ await map("--format", "json");
+ expect(backend.mapRequests()).toBe(before + 1);
+ });
+
+ it("asks again when a file was deleted, even if the revision did not move", async () => {
+ await map("--format", "json");
+ backend.frozenRevision = true;
+ unlinkSync(join(repo, "src", "m3.ts"));
+ const before = backend.mapRequests();
+ const after = await map("--format", "json");
+ expect(backend.mapRequests()).toBe(before + 1);
+ expect(JSON.parse(after.stdout).file_count).toBe(3);
+ });
+
+ it("asks again when another client moved the revision", async () => {
+ backend.revisionRecord = true;
+ await map("--format", "json");
+ backend.rev += 1; // a commit this run's ingest knows nothing about
+ const before = backend.mapRequests();
+ const after = await map("--format", "json");
+ expect(backend.mapRequests()).toBe(before + 1);
+ expect(JSON.parse(after.stdout).map_rev).toBe(backend.rev);
+ });
+
+ it("asks again after the workspace's data was deleted without a commit", async () => {
+ await map("--format", "json");
+ // A scoped reset: nodes and hashes gone, head revision untouched.
+ backend.hashes.clear();
+ backend.frozenRevision = true;
+ const before = backend.mapRequests();
+ await map("--format", "json");
+ expect(backend.mapRequests()).toBe(before + 1);
+ });
+
+ it("asks again after `ix reset` cleared the local baselines", async () => {
+ await map("--format", "json");
+ // A global reset truncates the revision counter; by the time this runs,
+ // other workspaces' commits may have counted it back to the very value the
+ // cached map was computed at. Only the local invalidation can tell.
+ backend.hashes.clear();
+ clearIngestMtimeCache(repo);
+ backend.frozenRevision = true;
+ const before = backend.mapRequests();
+ await map("--format", "json");
+ expect(backend.mapRequests()).toBe(before + 1);
+ });
+
+ it("asks again when the backend release changed", async () => {
+ await map("--format", "json");
+ backend.release = "1.0.31";
+ const before = backend.mapRequests();
+ await map("--format", "json");
+ expect(backend.mapRequests()).toBe(before + 1);
+ });
+
+ it("always asks under --full, and for a system-scoped map", async () => {
+ await map("--format", "json");
+ let before = backend.mapRequests();
+ await map("--format", "json", "--full");
+ await map("--format", "json", "--full");
+ expect(backend.mapRequests()).toBe(before + 2);
+
+ backend.systemId = "sys-1";
+ before = backend.mapRequests();
+ await map("--format", "json");
+ await map("--format", "json");
+ expect(backend.mapRequests()).toBe(before + 2);
+ expect(existsSync(mapResultCachePath(repo)), "a map that is not kept leaves nothing behind").toBe(false);
+ });
+});
+
+describe("ingestFiles invalidates the cached map", () => {
+ vi.setConfig({ testTimeout: 60_000, hookTimeout: 30_000 });
+
+ let home = "";
+ let repo = "";
+ let backend: FakeBackend;
+ const saved: Record<string, string | undefined> = {};
+ const slot: MapCacheSlot = { key: "k", revision: "r" };
+ const response = { file_count: 1, region_count: 0, levels: 0, map_rev: 1, outcome: "full_local_completed", regions: [] };
+
+ beforeEach(async () => {
+ backend = new FakeBackend();
+ home = realpathSync(mkdtempSync(join(tmpdir(), "ix-mapcache-home-")));
+ repo = realpathSync(mkdtempSync(join(tmpdir(), "ix-mapcache-repo-")));
+ const endpoint = await backend.start();
+ for (const k of ["HOME", "USERPROFILE", "IX_HOME", "IX_ENDPOINT", "IX_LOCK_DIR"]) {
+ saved[k] = process.env[k];
+ delete process.env[k];
+ }
+ process.env.HOME = home;
+ process.env.USERPROFILE = home;
+ process.env.IX_HOME = join(home, ".ix");
+ process.env.IX_ENDPOINT = endpoint;
+ process.env.IX_LOCK_DIR = join(home, "locks");
+ mkdirSync(join(repo, "src"), { recursive: true });
+ for (let i = 0; i < 3; i++) writeFileSync(join(repo, "src", `m${i}.ts`), `export const v${i} = ${i};\n`, "utf8");
+ });
+
+ afterEach(async () => {
+ await backend.stop();
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ for (const dir of [home, repo]) if (dir) rmSync(dir, { recursive: true, force: true });
+ });
+
+ const ingest = async () => {
+ const write = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
+ try {
+ return await ingestFiles(repo, { format: "json", suppressOutput: true, printSummary: false, mapMode: true });
+ } finally {
+ write.mockRestore();
+ }
+ };
+
+ it("reports an ingest that wrote nothing as unchanged, and one that wrote as changed", async () => {
+ expect((await ingest()).graphUnchanged).toBe(false);
+ expect((await ingest()).graphUnchanged).toBe(true);
+ });
+
+ it("drops it when the DB-reset guard fires", async () => {
+ await ingest();
+ saveCachedMap(repo, slot, response);
+ backend.hashes.clear();
+ const summary = await ingest();
+ expect(summary.graphUnchanged).toBe(false);
+ expect(existsSync(mapResultCachePath(repo))).toBe(false);
+ });
+
+ it("drops it when an extractor change forces a re-ingest", async () => {
+ await ingest();
+ saveCachedMap(repo, slot, response);
+ const baseline = JSON.parse(readFileSync(ingestMtimeCachePath(repo), "utf8"));
+ writeFileSync(ingestMtimeCachePath(repo), JSON.stringify({ ...baseline, extractor: "tree-sitter/0.1" }));
+ const summary = await ingest();
+ expect(summary.graphUnchanged).toBe(false);
+ expect(existsSync(mapResultCachePath(repo))).toBe(false);
+ });
+});
+
+describe("map result cache store", () => {
+ let home = "";
+ const saved = process.env.IX_HOME;
+ const slot: MapCacheSlot = { key: "k1", revision: "[5]" };
+ const response = {
+ file_count: 2, region_count: 1, levels: 1, map_rev: 5, outcome: "full_local_completed",
+ regions: [region("r", "module", "M", 1, 2, null)],
+ };
+
+ beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), "ix-mapcache-store-"));
+ process.env.IX_HOME = home;
+ });
+ afterEach(() => {
+ if (saved === undefined) delete process.env.IX_HOME;
+ else process.env.IX_HOME = saved;
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ it("returns what was stored only for the same root, key and revision", () => {
+ saveCachedMap("/r", slot, { ...response, hierarchy: [{ big: true }] } as typeof response);
+ expect(loadCachedMap("/r", slot)).toEqual(response);
+ expect(loadCachedMap("/r", { ...slot, revision: "[6]" })).toBeUndefined();
+ expect(loadCachedMap("/r", { ...slot, key: "k2" })).toBeUndefined();
+ expect(loadCachedMap("/other", slot)).toBeUndefined();
+ });
+
+ it("treats a malformed file as absent", () => {
+ writeFileSync(mapResultCachePath("/r"), "{not json");
+ expect(loadCachedMap("/r", slot)).toBeUndefined();
+ writeFileSync(mapResultCachePath("/r"), JSON.stringify({ root: "/r", key: "k1", revision: "[5]", result: { regions: "x" } }));
+ expect(loadCachedMap("/r", slot)).toBeUndefined();
+ });
+
+ it("is removed by clearMapBaseline and clearIngestMtimeCache", () => {
+ saveCachedMap("/r", slot, response);
+ clearMapBaseline("/r");
+ expect(existsSync(mapResultCachePath("/r"))).toBe(false);
+ saveCachedMap("/r", slot, response);
+ clearIngestMtimeCache("/r");
+ expect(existsSync(mapResultCachePath("/r"))).toBe(false);
+ });
+});
+
+describe("map cache slot", () => {
+ const client = (head: unknown) => ({ endpoint: "http://127.0.0.1:1", currentRevision: async () => head });
+ const identified = async () => ({ release_version: "1.0.30", schema_version: 3 });
+
+ it("reads a bare revision and a revision record, and nothing else", () => {
+ expect(revisionToken(7)).toBe("[7]");
+ expect(revisionToken({ rev: 7, patchId: "p", timestamp: "t", summary: { a: 1 } })).toBe('[7,"p","t"]');
+ expect(revisionToken({ rev: 7 })).toBe("[7,null,null]");
+ for (const bad of [null, "7", -1, 1.5, {}, { rev: "7" }]) expect(revisionToken(bad)).toBeUndefined();
+ });
+
+ it("names the backend by release and schema, or not at all", () => {
+ expect(backendIdentity({ release_version: "1.0.30", schema_version: 3 })).toBe('["1.0.30",3]');
+ expect(backendIdentity({ version: "1.0.28" })).toBe('["1.0.28",null]');
+ expect(backendIdentity({ status: "ok" })).toBeUndefined();
+ });
+
+ it("is only offered for a workspace-scoped, non-full map on a backend it can identify", async () => {
+ const ok = client(9);
+ const slot = await resolveMapCacheSlot(ok, { workspaceId: "ws" }, identified);
+ expect(slot?.revision).toBe("[9]");
+ expect(await resolveMapCacheSlot(ok, { workspaceId: "ws", full: true }, identified)).toBeUndefined();
+ expect(await resolveMapCacheSlot(ok, { systemId: "sys" }, identified)).toBeUndefined();
+ expect(await resolveMapCacheSlot(ok, {}, identified)).toBeUndefined();
+ expect(await resolveMapCacheSlot(ok, { workspaceId: "ws" }, async () => ({ status: "ok" }))).toBeUndefined();
+ expect(await resolveMapCacheSlot(client("nope"), { workspaceId: "ws" }, identified)).toBeUndefined();
+ const failing = { ...ok, currentRevision: async () => { throw new Error("404: not found"); } };
+ expect(await resolveMapCacheSlot(failing, { workspaceId: "ws" }, identified)).toBeUndefined();
+ const down = async () => { throw new Error("ECONNREFUSED"); };
+ expect(await resolveMapCacheSlot(ok, { workspaceId: "ws" }, down)).toBeUndefined();
+
+ const other = await resolveMapCacheSlot(ok, { workspaceId: "ws2" }, identified);
+ expect(other?.key).not.toBe(slot?.key);
+ });
+});
diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.ts
index 1f63ba92..e47d6be9 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -12,7 +12,7 @@ import { ParsePool } from './parse-pool.js';
import chalk from 'chalk';
import { IxClient } from '../../client/api.js';
import type { GraphPatchPayload } from '../../client/types.js';
-import { getEndpoint, resolveWorkspaceRoot, clearStitchScopeCache } from '../config.js';
+import { getEndpoint, resolveWorkspaceRoot, clearMapResultCache, clearStitchScopeCache } from '../config.js';
import {
clearRebuildProgress, extractorChanged, isRev, loadIngestBaseline, loadRebuildProgress,
saveIngestBaseline, saveRebuildProgress,
@@ -1053,6 +1053,17 @@ export interface IngestFilesSummary {
* substring-matching English, which `StitchRefusal`'s own doc forbids.
*/
stitchSkippedRule?: StitchRefusal;
+ /**
+ * True only when this run cannot have changed the graph: nothing was
+ * forced (by `--force`, a schema mismatch or an extractor change), the
+ * workspace was not migrated, the DB-reset guard did not fire, no patch or
+ * deletion was sent, no stitch was sent, and nothing failed.
+ *
+ * `ix map` reads it to decide whether it may reuse its last `/v1/map`
+ * response. It errs towards false: a run that only might have written
+ * something must not claim the graph is where it was.
+ */
+ graphUnchanged: boolean;
}
/**
@@ -1476,6 +1487,7 @@ export async function ingestFiles(
process.stderr.write(
`Migrated workspace to a stable path-based id; re-ingesting this workspace once.\n`,
);
+ clearMapResultCache(workspaceRoot);
}
const toWorkspaceRelative = (absPath: string): string => {
// Force workspace-local POSIX separators so IDs are stable across OS.
@@ -1735,6 +1747,13 @@ export async function ingestFiles(
let filesChanged = 0;
let patchesApplied = 0;
let idempotentPatches = 0;
+ // What `graphUnchanged` is computed from, beside the counters above. Each is
+ // a way this run can have written to the graph, or have found it not where
+ // the last run left it, without a patch being counted.
+ let dbResetDetected = false;
+ let extractorRebuild = false;
+ let deletionsFound = false;
+ let stitchSent = false;
let filesSkipped = 0;
/**
* Files skipped because we ASSUMED THEY WERE UNCHANGED. (Ix#568)
@@ -1970,6 +1989,8 @@ export async function ingestFiles(
// A resumed re-ingest is not forced: the files it already committed are
// skipped by mtime below, and every other file is forced one by one.
if (!resumedRebuild) opts.force = true;
+ extractorRebuild = true;
+ clearMapResultCache(projectRoot);
}
const previousMtimes = previousBaseline?.files ?? new Map<string, number>();
const {
@@ -2017,6 +2038,9 @@ export async function ingestFiles(
mtimeCache.clear();
// What an unfinished re-ingest committed is gone with the rest.
rebuildProgress?.clear();
+ // And so is the hierarchy a cached map response describes.
+ dbResetDetected = true;
+ clearMapResultCache(projectRoot);
if (debug) process.stderr.write(`\n DB reset detected — invalidating mtime cache\n`);
}
}
@@ -2062,6 +2086,7 @@ export async function ingestFiles(
: [...previousMtimes.keys()].filter(filePath =>
!currentMtimes.has(filePath) && !fs.existsSync(filePath)
);
+ if (deletedPaths.length > 0) deletionsFound = true;
// Phase: hash lookup — only needed when files changed or were deleted.
let knownHashes: Map<string, string>;
@@ -3531,6 +3556,7 @@ export async function ingestFiles(
const stitchStart = performance.now();
let res;
try {
+ stitchSent = true;
res = await client.stitch({ workspaceId, provides, consumes: stitchConsumes, exports: stitchExports, symbolConsumes });
} catch (err) {
// Settle before rethrowing, so the shared catch below still sees
@@ -3628,6 +3654,18 @@ export async function ingestFiles(
stitchErrors,
stitchSkipped,
stitchSkippedRule,
+ graphUnchanged:
+ opts.force !== true &&
+ !workspaceMigrated &&
+ !dbResetDetected &&
+ !extractorRebuild &&
+ filesChanged === 0 &&
+ patchesApplied === 0 &&
+ !deletionsFound &&
+ !stitchSent &&
+ parseErrors + crashedParses() === 0 &&
+ commitErrors === 0 &&
+ stitchErrors === 0,
};
// `everTripped()` alone, and it is not a weakening: `recordFailure` has one
// call site, in the per-file catch immediately after `commitErrors++`, so a
diff --git a/ix-cli/src/cli/commands/map.ts b/ix-cli/src/cli/commands/map.ts
index 33d98ca8..f5183d57 100644
--- a/ix-cli/src/cli/commands/map.ts
+++ b/ix-cli/src/cli/commands/map.ts
@@ -3,7 +3,7 @@
import { type Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
-import { clearMapBaseline, getEndpoint } from "../config.js";
+import { clearMapBaseline, clearMapResultCache, getEndpoint } from "../config.js";
import { roundFloat, printJson } from "../format.js";
import { llmLine, llmError, llmShortId } from "../llm.js";
import { bootstrap, resolveWorkspaceId } from "../bootstrap.js";
@@ -15,7 +15,9 @@ import { acquireMapLock } from "../single-flight.js";
import { canRenderProgress } from "../stderr.js";
import { loadIngestBaseline } from "../ingest-baseline.js";
import { saveMapBaseline } from "../map-baseline.js";
+import { loadCachedMap, resolveMapCacheSlot, saveCachedMap } from "../map-result-cache.js";
import { resolveMapRoot } from "../map-root.js";
+import { readBackendHealth } from "./upgrade.js";
// Hard wall-clock budget for a single `ix map`. Past this, the shared deadline
// signal aborts every in-flight request and the command exits, so a single
@@ -125,6 +127,13 @@ export interface MapResult {
persistence?: MapPersistence;
}
+/**
+ * The fields of a `/v1/map` response that `ix map` reads -- all a reused
+ * response stores (see `map-result-cache.ts`), so the output of a map served
+ * from it cannot depend on anything it left out.
+ */
+export type MapView = Pick<MapResult, "file_count" | "region_count" | "levels" | "map_rev" | "regions" | "outcome">;
+
/**
* The backend's MapOutcome labels that mean "a map was produced" (MapTypes.scala).
*
@@ -517,17 +526,6 @@ Examples:
const mapBarWidth = 25;
const mapStart = performance.now();
- // Same gate as the ingest bar: --silent and the machine formats were the
- // only ways to avoid this, and neither is available to something merely
- // capturing normal output.
- const mapInterval = (!machineFormat && !silent && canRenderProgress()) ? setInterval(() => {
- const elapsed = performance.now() - mapStart;
- const pct = 1 - Math.exp(-elapsed / 4000);
- const filled = Math.round(pct * mapBarWidth);
- const bar = chalk.cyan('█'.repeat(filled)) + chalk.dim('░'.repeat(mapBarWidth - filled));
- const pctStr = chalk.cyan(`${Math.min(Math.round(pct * 100), 99)}%`.padStart(4));
- process.stderr.write(`\r Computing map... ${bar} ${pctStr}`);
- }, 80) : null;
// Path-2 grouping (Ix#225 Half B): a co-ingest system is found by detectSystem
// above; a SEPARATELY-ingested repo that the stitcher joined into a system has
@@ -541,17 +539,41 @@ Examples:
if (looked.systemId) effectiveSystemId = looked.systemId;
}
}
+ const mapRequest = { full: opts.full, workspaceId: effectiveSystemId ? undefined : resolveWorkspaceId(cwd), systemId: effectiveSystemId };
- let result: MapResult;
- try {
- result = await client.map({ full: opts.full, workspaceId: effectiveSystemId ? undefined : resolveWorkspaceId(cwd), systemId: effectiveSystemId }) as MapResult;
- } catch (err: any) {
+ // Reuse the last response when this run's ingest wrote nothing and the
+ // backend's head revision has not moved since it was computed. Local
+ // only: a cloud ingest reports no summary, so it cannot vouch for that.
+ const cacheSlot = localIngest ? await resolveMapCacheSlot(client, mapRequest, () => readBackendHealth(client)) : undefined;
+ const cached = cacheSlot && localIngest?.graphUnchanged ? loadCachedMap(cwd, cacheSlot) : undefined;
+
+ let result: MapView;
+ if (cached) {
+ result = cached;
+ } else {
+ // Same gate as the ingest bar: --silent and the machine formats were the
+ // only ways to avoid this, and neither is available to something merely
+ // capturing normal output.
+ const mapInterval = (!machineFormat && !silent && canRenderProgress()) ? setInterval(() => {
+ const elapsed = performance.now() - mapStart;
+ const pct = 1 - Math.exp(-elapsed / 4000);
+ const filled = Math.round(pct * mapBarWidth);
+ const bar = chalk.cyan('█'.repeat(filled)) + chalk.dim('░'.repeat(mapBarWidth - filled));
+ const pctStr = chalk.cyan(`${Math.min(Math.round(pct * 100), 99)}%`.padStart(4));
+ process.stderr.write(`\r Computing map... ${bar} ${pctStr}`);
+ }, 80) : null;
+
+ try {
+ result = await client.map(mapRequest) as MapResult;
+ } catch (err: any) {
+ if (mapInterval) { clearInterval(mapInterval); process.stderr.write('\r' + ' '.repeat(60) + '\r'); }
+ clearMapResultCache(cwd);
+ emitError(formatFetchError(err));
+ process.exitCode = 1;
+ return;
+ }
if (mapInterval) { clearInterval(mapInterval); process.stderr.write('\r' + ' '.repeat(60) + '\r'); }
- emitError(formatFetchError(err));
- process.exitCode = 1;
- return;
}
- if (mapInterval) { clearInterval(mapInterval); process.stderr.write('\r' + ' '.repeat(60) + '\r'); }
const mapMs = Math.round(performance.now() - mapStart);
const emptyMapError = invalidateBaselineForIncompleteCompletedMap(result, localIngest, cwd);
@@ -560,7 +582,14 @@ Examples:
process.exitCode = 1;
return;
}
- persistCompletedMapBaseline(result, cwd);
+ // The cache holds the latest response the backend gave, or nothing: a
+ // response that is not kept removes the one before it, so a later hit
+ // can never be older than a miss in between.
+ if (persistCompletedMapBaseline(result, cwd) && cacheSlot) {
+ if (!cached) saveCachedMap(cwd, cacheSlot, result);
+ } else {
+ clearMapResultCache(cwd);
+ }
// stderr, so it reaches a human on the text path and never contaminates
// the JSON/llm payload on stdout. The exit code deliberately stays 0:
@@ -662,7 +691,7 @@ Examples:
/** Flat one-record-per-line region listing with explicit parent= for the llm format. */
export function renderMapLlm(
- result: MapResult,
+ result: MapView,
regions: MapRegion[],
ingest?: Pick<IngestFilesSummary, "parseErrors" | "commitErrors" | "stitchSkipped" | "stitchSkippedRule">,
): void {
@@ -705,7 +734,7 @@ export function renderMapLlm(
}
}
-export function renderMapText(result: MapResult, cwd: string, opts: MapTextRenderOptions): void {
+export function renderMapText(result: MapView, cwd: string, opts: MapTextRenderOptions): void {
const minConf = parseFloat(opts.minConfidence ?? "0");
const levelFilter = opts.level ? parseInt(opts.level, 10) : null;
const parsedMaxItems = parseInt(opts.maxItems ?? "10", 10);
diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.ts
index e7d84d67..88a18862 100644
--- a/ix-cli/src/cli/config.ts
+++ b/ix-cli/src/cli/config.ts
@@ -34,6 +34,16 @@ export function mapBaselinePath(projectRoot: string): string {
return join(ixHome(), `map_baseline_${key}.json`);
}
+/**
+ * Path to the last `/v1/map` response for one project root, which a map that
+ * ingested nothing reuses instead of asking again (see `map-result-cache.ts`).
+ * Cleared with the map baseline, since both describe the same hierarchy.
+ */
+export function mapResultCachePath(projectRoot: string): string {
+ const key = createHash("sha256").update(projectRoot).digest("hex").slice(0, 12);
+ return join(ixHome(), `map_result_${key}.json`);
+}
+
/**
* Path to the cached answer to "is this workspace stitched into a System?".
*
@@ -86,9 +96,19 @@ export function clearStitchScopeCache(workspaceId: string): void {
try { rmSync(stitchScopeCachePath(workspaceId), { force: true }); } catch { /* non-critical */ }
}
-/** Remove only the architecture-map completion marker. Best-effort. */
+/** Drop the cached `/v1/map` response, so the next map asks the backend. Best-effort. */
+export function clearMapResultCache(projectRoot: string): void {
+ try { rmSync(mapResultCachePath(projectRoot), { force: true }); } catch { /* non-critical */ }
+}
+
+/**
+ * Remove the architecture-map completion marker, and the cached map response
+ * with it: whatever made the marker wrong makes the cached hierarchy wrong too.
+ * Leaves the source ingest baseline alone. Best-effort.
+ */
export function clearMapBaseline(projectRoot: string): void {
try { rmSync(mapBaselinePath(projectRoot), { force: true }); } catch { /* non-critical */ }
+ clearMapResultCache(projectRoot);
}
/**
diff --git a/ix-cli/src/cli/map-result-cache.ts b/ix-cli/src/cli/map-result-cache.ts
new file mode 100644
index 00000000..c0b52dc1
--- /dev/null
+++ b/ix-cli/src/cli/map-result-cache.ts
@@ -0,0 +1,193 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import * as fs from "node:fs";
+import * as path from "node:path";
+import { fileURLToPath } from "node:url";
+import type { IxClient } from "../client/api.js";
+import { mapResultCachePath } from "./config.js";
+import { isRev } from "./ingest-baseline.js";
+
+/**
+ * The last `/v1/map` response for a project root, reused by an `ix map` that
+ * ingested nothing.
+ *
+ * `ix map` runs after every agent response (the plugins' Stop hooks), and on
+ * a large repo the map request is most of its cost: 4.2 s of 5.7 s on a
+ * 30k-file repo where nothing had changed. The backend memoises a scoped map
+ * per revision, but still answers slowly, so the only way to skip the cost is
+ * to not ask.
+ *
+ * The response is reused only when every input that decides it is unchanged:
+ *
+ * - the graph, by the backend's head revision. Every committed patch in any
+ * workspace advances it, so this is stricter than the map needs, never
+ * laxer: a commit elsewhere costs one extra request, not a stale map.
+ * - the request itself (workspace, `full`), the endpoint, the backend's
+ * release and schema, and this CLI's version.
+ *
+ * And, decided by the caller, only when this run's ingest wrote nothing
+ * (`IngestFilesSummary.graphUnchanged`). The revision alone would miss a
+ * workspace whose data was deleted without a commit, which the ingest's
+ * DB-reset guard catches.
+ *
+ * Only a workspace-scoped map is cached. A system-scoped one can change
+ * without a commit: the stitcher writes cross-repo edges and stamps system
+ * ids directly. So does the unscoped global map, which persists regions as a
+ * commit of its own. Both always ask the backend.
+ */
+
+/** Everything besides the graph that decides what `/v1/map` answers. */
+export interface MapCacheSlot {
+ /** Request body, endpoint, backend release/schema and CLI version, as one string. */
+ key: string;
+ /** The backend's head revision when the slot was resolved. */
+ revision: string;
+}
+
+/** The parts of a `/v1/map` response `ix map` renders. Nothing else is stored. */
+export interface CachedMapResponse {
+ file_count: number;
+ region_count: number;
+ levels: number;
+ map_rev: number;
+ outcome?: string;
+ regions: any[];
+}
+
+interface SerializedMapCache {
+ root: string;
+ key: string;
+ revision: string;
+ result: CachedMapResponse;
+}
+
+let cachedCliVersion: string | undefined;
+
+function cliVersion(): string {
+ if (cachedCliVersion !== undefined) return cachedCliVersion;
+ let version = "unknown";
+ try {
+ const here = path.dirname(fileURLToPath(import.meta.url));
+ const pkg = JSON.parse(fs.readFileSync(path.join(here, "../../package.json"), "utf-8"));
+ if (typeof pkg.version === "string") version = pkg.version;
+ } catch { /* "unknown": still a key, just a coarser one */ }
+ cachedCliVersion = version;
+ return version;
+}
+
+/**
+ * A stable string for the backend's head revision, or undefined when the body
+ * is not one.
+ *
+ * `/v1/revisions/current` answers with the head's revision record when the
+ * backend has one and with the bare number when it does not. The record's
+ * patch id and timestamp are kept beside the number, so a graph that was
+ * reset and has since counted back up to the same revision does not match.
+ */
+export function revisionToken(body: unknown): string | undefined {
+ if (isRev(body)) return JSON.stringify([body]);
+ if (body === null || typeof body !== "object") return undefined;
+ const record = body as { rev?: unknown; patchId?: unknown; timestamp?: unknown };
+ if (!isRev(record.rev)) return undefined;
+ const patchId = typeof record.patchId === "string" ? record.patchId : null;
+ const timestamp = typeof record.timestamp === "string" ? record.timestamp : null;
+ return JSON.stringify([record.rev, patchId, timestamp]);
+}
+
+/**
+ * The release and schema the backend reports, or undefined when it reports
+ * neither -- a backend that cannot say what it is cannot be told apart from
+ * the next one, so its maps are not cached.
+ */
+export function backendIdentity(health: unknown): string | undefined {
+ if (health === null || typeof health !== "object") return undefined;
+ const h = health as { release_version?: unknown; version?: unknown; schema_version?: unknown };
+ const release = typeof h.release_version === "string" ? h.release_version
+ : typeof h.version === "string" ? h.version
+ : undefined;
+ const schema = typeof h.schema_version === "number" ? h.schema_version : undefined;
+ if (release === undefined && schema === undefined) return undefined;
+ return JSON.stringify([release ?? null, schema ?? null]);
+}
+
+/**
+ * The slot this map reads and writes, or undefined when it must ask the
+ * backend and not keep the answer.
+ *
+ * Two cheap reads -- health and the head revision -- and any failure of
+ * either means "not cacheable", never an error: the map request that follows
+ * reports a backend problem better than this would. Health is read through
+ * the caller's reader, so it goes through the one place health bodies are
+ * read and recorded (`readBackendHealth`).
+ */
+export async function resolveMapCacheSlot(
+ client: Pick<IxClient, "endpoint" | "currentRevision">,
+ request: { full?: boolean; workspaceId?: string; systemId?: string },
+ readHealth: () => Promise<unknown>,
+): Promise<MapCacheSlot | undefined> {
+ if (request.full || request.systemId || !request.workspaceId) return undefined;
+ try {
+ const [health, head] = await Promise.all([readHealth(), client.currentRevision()]);
+ const backend = backendIdentity(health);
+ const revision = revisionToken(head);
+ if (backend === undefined || revision === undefined) return undefined;
+ const key = JSON.stringify({
+ request: { full: false, workspace_id: request.workspaceId },
+ endpoint: client.endpoint,
+ backend,
+ cli: cliVersion(),
+ });
+ return { key, revision };
+ } catch {
+ return undefined;
+ }
+}
+
+function isCachedMapResponse(value: unknown): value is CachedMapResponse {
+ if (value === null || typeof value !== "object") return false;
+ const r = value as Record<string, unknown>;
+ return typeof r.file_count === "number"
+ && typeof r.region_count === "number"
+ && typeof r.levels === "number"
+ && typeof r.map_rev === "number"
+ && (r.outcome === undefined || typeof r.outcome === "string")
+ && Array.isArray(r.regions);
+}
+
+/** The response stored for this slot, or undefined when there is none that matches. */
+export function loadCachedMap(projectRoot: string, slot: MapCacheSlot): CachedMapResponse | undefined {
+ try {
+ const data = JSON.parse(fs.readFileSync(mapResultCachePath(projectRoot), "utf-8")) as Partial<SerializedMapCache>;
+ if (data.root !== projectRoot || data.key !== slot.key || data.revision !== slot.revision) return undefined;
+ return isCachedMapResponse(data.result) ? data.result : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** Store a response for this slot. Best-effort: a cache that cannot be written is not an error. */
+export function saveCachedMap(projectRoot: string, slot: MapCacheSlot, result: CachedMapResponse): void {
+ const data: SerializedMapCache = {
+ root: projectRoot,
+ key: slot.key,
+ revision: slot.revision,
+ result: {
+ file_count: result.file_count,
+ region_count: result.region_count,
+ levels: result.levels,
+ map_rev: result.map_rev,
+ outcome: result.outcome,
+ regions: result.regions,
+ },
+ };
+ const target = mapResultCachePath(projectRoot);
+ const tmp = `${target}.${process.pid}.tmp`;
+ try {
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ // Via a temp file and rename, so a reader never sees half a file.
+ fs.writeFileSync(tmp, JSON.stringify(data));
+ fs.renameSync(tmp, target);
+ } catch {
+ try { fs.rmSync(tmp, { force: true }); } catch { /* non-critical */ }
+ }
+}