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(trace,depends): fetch the graph walk breadth-first, in parallel
KageBinary03a82c2a5dba
diff --git a/ix-cli/src/cli/__tests__/depends-semantics.test.ts b/ix-cli/src/cli/__tests__/depends-semantics.test.tsindex c8ef32f9..781c8ade 100644--- a/ix-cli/src/cli/__tests__/depends-semantics.test.ts+++ b/ix-cli/src/cli/__tests__/depends-semantics.test.ts@@ -11,6 +11,8 @@ import * as path from "node:path";const dependsTsPath = path.resolve(__dirname, "../commands/depends.ts");const dependsContent = fs.readFileSync(dependsTsPath, "utf-8");+// The walk itself is shared with `ix trace`.+const walkContent = fs.readFileSync(path.resolve(__dirname, "../tree-walk.ts"), "utf-8");// ── Direction semantics ─────────────────────────────────────────────@@ -42,9 +44,11 @@ describe("depends full-tree traversal", () => {});it("expands recursively via one-hop calls", () => {- // Uses hops: 1 for each level, then recurses+ // Uses hops: 1 for each level; the shared walk fetches breadth-first and+ // builds the tree by the depth-first recursion it always used.expect(dependsContent).toContain("hops: 1");- expect(dependsContent).toContain("await expand(n.id, depth + 1)");+ expect(dependsContent).toContain("walkTree<DependencyNode>");+ expect(walkContent).toContain("await expand(n.id, depth + 1)");});it("defaults to full traversal without --depth", () => {@@ -59,20 +63,20 @@ describe("depends full-tree traversal", () => {});it("has cycle detection", () => {- expect(dependsContent).toContain("visited.has(n.id)");+ expect(walkContent).toContain("visited.has(n.id)");expect(dependsContent).toContain("cycle: true");});it("has node cap safety limit", () => {expect(dependsContent).toContain("MAX_NODES");- expect(dependsContent).toContain("nodesVisited >= maxNodes");+ expect(walkContent).toContain("nodesVisited >= opts.maxNodes");});it("reports a cap cut and a depth stop as the different things they are", () => {// Only the node cap can know that nodes were lost; reaching the depth// bound means the walk stopped descending, which is not the same claim.- expect(dependsContent).toContain("truncated = true");- expect(dependsContent).toContain("depthLimited = true");+ expect(walkContent).toContain("truncated = true");+ expect(walkContent).toContain("depthLimited = true");expect(dependsContent).toContain("traversalHint");});});diff --git a/ix-cli/src/cli/__tests__/trace-walk.test.ts b/ix-cli/src/cli/__tests__/trace-walk.test.tsnew file mode 100644index 00000000..3f708210--- /dev/null+++ b/ix-cli/src/cli/__tests__/trace-walk.test.ts@@ -0,0 +1,206 @@+// Copyright 2026 Ix Infrastructure Inc.++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { Command } from "commander";++import { registerTraceCommand } from "../commands/trace.js";+import { compactTreeNode } from "../format.js";+import { isRawId } from "../resolve.js";+import { EXPAND_CONCURRENCY } from "../tree-walk.js";++/**+ * `ix trace --upstream/--downstream` and the both-directions mode, end to end+ * through the command, against the depth-first walk they used before the+ * shared breadth-first one (kept here verbatim as the oracle).+ */++const expand = vi.hoisted(() => vi.fn());+vi.mock("../../client/api.js", () => ({+ IxClient: class { async expand(...args: unknown[]) { return expand(...args); } },+}));+vi.mock("../resolve.js", async (importOriginal) => ({+ ...await importOriginal<typeof import("../resolve.js")>(),+ resolveFileOrReport: async (_client: unknown, name: string) => ({ id: name, name, kind: "function" }),+}));++const PREDICATES = ["CALLS", "IMPORTS", "REFERENCES", "EXTENDS", "IMPLEMENTS", "CONTAINS"];++/** `buildTraceTree` as it was before the breadth-first walk. */+async function oldBuildTraceTree(+ client: any, rootId: string,+ opts: { direction: "in" | "out"; predicates: string[]; maxDepth: number; maxNodes: number },+) {+ const { direction, predicates, maxDepth, maxNodes } = opts;+ const visited = new Set<string>([rootId]);+ let nodesVisited = 0;+ let truncated = false;+ let depthLimited = false;+ let maxDepthReached = 0;++ async function expandNode(nodeId: string, depth: number): Promise<any[]> {+ if (depth > maxDepth) { depthLimited = true; return []; }+ if (nodesVisited >= maxNodes) { truncated = true; return []; }+ maxDepthReached = Math.max(maxDepthReached, depth);+ const results = await Promise.all(+ predicates.map((p) => client.expand(nodeId, { direction, predicates: [p], hops: 1 })),+ );+ const children: any[] = [];+ const levelSeen = new Set<string>();+ for (const result of results) {+ for (const n of result.nodes) {+ if (nodesVisited >= maxNodes) { truncated = true; break; }+ if (levelSeen.has(n.id)) continue;+ const name = n.name || n.attrs?.name || "";+ const resolved = !!name && !isRawId(name);+ const isCycle = visited.has(n.id);+ nodesVisited++;+ levelSeen.add(n.id);+ visited.add(n.id);+ const child: any = {+ id: n.id,+ name: resolved ? name : n.id.slice(0, 8),+ kind: n.kind ?? "unknown",+ resolved,+ path: n.provenance?.sourceUri ?? n.provenance?.source_uri ?? undefined,+ children: [],+ ...(isCycle ? { cycle: true } : {}),+ };+ if (!isCycle && resolved) child.children = await expandNode(n.id, depth + 1);+ children.push(child);+ }+ }+ return children;+ }++ const tree = await expandNode(rootId, 1);+ return { tree, truncated, depthLimited, nodesVisited, maxDepthReached };+}++function mulberry32(seed: number): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/** Separate in- and out-adjacency per predicate, with cycles and shared nodes. */+function randomGraph(seed: number, size: number, maxFanout: number) {+ const rand = mulberry32(seed);+ const pick = (n: number) => Math.floor(rand() * n);+ const nodeFor = (i: number): any => {+ const roll = (i * 7919 + seed) % 20;+ const id = `n${i}`;+ if (roll === 0) return { id, name: "0123456789abcdef0123456789abcdef", kind: "function" };+ if (roll === 1) return { id, attrs: { name: `attr${i}` }, kind: "method" };+ if (roll < 8) return { id, name: `fn${i}`, kind: "function" };+ return { id, name: `fn${i}`, kind: "function", provenance: { source_uri: `src/f${i % 5}.ts` } };+ };+ const graph: Record<string, Record<string, Record<string, any[]>>> = { in: {}, out: {} };+ for (const direction of ["in", "out"]) {+ for (let i = 0; i < size; i++) {+ const lists: Record<string, any[]> = {};+ for (const p of PREDICATES) lists[p] = Array.from({ length: pick(maxFanout + 1) }, () => nodeFor(pick(size)));+ graph[direction][`n${i}`] = lists;+ }+ }+ return graph;+}++type Graph = ReturnType<typeof randomGraph>;++let inFlight = 0;+let maxInFlight = 0;++function serve(graph: Graph, delaySeed?: number) {+ const rand = delaySeed === undefined ? undefined : mulberry32(delaySeed);+ inFlight = 0;+ maxInFlight = 0;+ expand.mockReset().mockImplementation(async (id: string, opts: { direction: string; predicates: string[] }) => {+ inFlight++;+ maxInFlight = Math.max(maxInFlight, inFlight);+ try {+ if (rand) await new Promise((r) => setTimeout(r, Math.floor(rand() * 3)));+ return { nodes: graph[opts.direction]?.[id]?.[opts.predicates[0]] ?? [], edges: [] };+ } finally {+ inFlight--;+ }+ });+}++async function trace(args: string[]) {+ const program = new Command().name("ix").exitOverride();+ registerTraceCommand(program);+ const output: string[] = [];+ vi.spyOn(console, "log").mockImplementation((...parts) => { output.push(parts.join(" ")); });+ await program.parseAsync(["trace", "n0", ...args, "--format", "json"], { from: "user" });+ return JSON.parse(output.join("\n"));+}++/** What the command prints for one direction, computed from the oracle. */+async function expected(graph: Graph, direction: "in" | "out", maxDepth: number, maxNodes: number) {+ const client = { expand: async (id: string, o: { direction: string; predicates: string[] }) => ({ nodes: graph[o.direction]?.[id]?.[o.predicates[0]] ?? [] }) };+ const r = await oldBuildTraceTree(client, "n0", { direction, predicates: PREDICATES, maxDepth, maxNodes });+ return JSON.parse(JSON.stringify({+ tree: r.tree.map(compactTreeNode),+ summary: {+ nodes_visited: r.nodesVisited,+ max_depth: r.maxDepthReached,+ truncated: r.truncated ? true : undefined,+ depth_limited: r.depthLimited ? true : undefined,+ },+ }));+}++describe("ix trace directional output against the depth-first walk", () => {+ beforeEach(() => { inFlight = 0; maxInFlight = 0; });+ afterEach(() => vi.restoreAllMocks());++ it("is identical upstream, downstream and both ways when no cap cuts", async () => {+ for (let seed = 1; seed <= 12; seed++) {+ const graph = randomGraph(seed, 25, 2);+ for (const [depth, cap] of [[1000, 1000000], [3, 1000000], [2, 1000000]] as const) {+ const bounds = ["--depth", String(depth), "--cap", String(cap)];+ const up = await expected(graph, "in", depth, cap);+ const down = await expected(graph, "out", depth, cap);++ serve(graph, seed);+ const upOut = await trace(["--upstream", ...bounds]);+ expect({ tree: upOut.tree ?? [], summary: upOut.summary }, `seed ${seed} up`).toEqual({ tree: up.tree, summary: up.summary });++ serve(graph, seed + 100);+ const downOut = await trace(["--downstream", ...bounds]);+ expect({ tree: downOut.tree ?? [], summary: downOut.summary }, `seed ${seed} down`).toEqual({ tree: down.tree, summary: down.summary });++ serve(graph, seed + 200);+ const both = await trace(bounds);+ expect(both.upstream, `seed ${seed} both/up`).toEqual(up);+ expect(both.downstream, `seed ${seed} both/down`).toEqual(down);+ }+ }+ });++ it(`keeps both directions together under ${EXPAND_CONCURRENCY} requests in flight`, async () => {+ serve(randomGraph(4, 150, 4), 9);+ await trace(["--depth", "4", "--cap", "400"]);+ expect(maxInFlight).toBe(EXPAND_CONCURRENCY);+ });++ it("keeps the shallowest nodes when the cap cuts, and says so", async () => {+ const fn = (id: string) => ({ id, name: id, kind: "function" });+ // n0 -> a, b, c; a -> a1 -> a2+ const graph: Graph = {+ in: {},+ out: { n0: { CALLS: [fn("a"), fn("b"), fn("c")] }, a: { CALLS: [fn("a1")] }, a1: { CALLS: [fn("a2")] } },+ };+ serve(graph);+ const out = await trace(["--downstream", "--kind", "calls", "--depth", "5", "--cap", "3"]);+ expect(out.tree.map((n: { name: string; children?: unknown[] }) => [n.name, n.children?.length ?? 0]))+ .toEqual([["a", 0], ["b", 0], ["c", 0]]);+ expect(out.summary).toEqual({ nodes_visited: 3, max_depth: 1, truncated: true });+ expect(out.diagnostics.map((d: { code: string }) => d.code)).toEqual(["truncated"]);+ });+});diff --git a/ix-cli/src/cli/__tests__/tree-walk.test.ts b/ix-cli/src/cli/__tests__/tree-walk.test.tsnew file mode 100644index 00000000..6438c46e--- /dev/null+++ b/ix-cli/src/cli/__tests__/tree-walk.test.ts@@ -0,0 +1,481 @@+// Copyright 2026 Ix Infrastructure Inc.++import { describe, expect, it, vi } from "vitest";++import { buildDependencyTree, type DependencyNode } from "../commands/depends.js";+import { searchPath } from "../commands/trace.js";+import { isRawId } from "../resolve.js";+import { createLimiter, EXPAND_CONCURRENCY, walkTree } from "../tree-walk.js";++/**+ * The walks behind `ix depends` and `ix trace` fetch breadth-first now. The+ * contract is that nobody can tell from the output unless the node cap cut the+ * walk: the depth-first walks they replaced are kept below, verbatim, as the+ * oracle.+ */++// ── Oracles: the implementations this replaced ──────────────────────++const PREDICATE_META: Record<string, { relation: DependencyNode["relation"]; sourceEdge: DependencyNode["sourceEdge"] }> = {+ CALLS: { relation: "called_by", sourceEdge: "CALLS" },+ IMPORTS: { relation: "imported_by", sourceEdge: "IMPORTS" },+ REFERENCES: { relation: "referenced_by", sourceEdge: "REFERENCES" },+ EXTENDS: { relation: "extended_by", sourceEdge: "EXTENDS" },+ IMPLEMENTS: { relation: "implemented_by", sourceEdge: "IMPLEMENTS" },+};+const DEPENDS_PREDICATES = Object.keys(PREDICATE_META);++function nodePriority(n: any): number {+ const name = n.name || n.attrs?.name || "";+ if (!name || isRawId(name)) return 2;+ return (n.provenance?.source_uri ?? n.provenance?.sourceUri ?? n.attrs?.path) ? 0 : 1;+}++/** `buildDependencyTree` as it was before the breadth-first walk. */+async function oldBuildDependencyTree(client: any, rootId: string, opts: { maxDepth: number; maxNodes: number }) {+ const { maxDepth, maxNodes } = opts;+ const activePredicates = DEPENDS_PREDICATES;+ const visited = new Set<string>([rootId]);+ let nodesVisited = 0;+ let truncated = false;+ let depthLimited = false;+ let maxDepthReached = 0;++ async function expand(nodeId: string, depth: number): Promise<DependencyNode[]> {+ if (depth > maxDepth) { depthLimited = true; return []; }+ if (nodesVisited >= maxNodes) { truncated = true; return []; }+ maxDepthReached = Math.max(maxDepthReached, depth);+ const expandResults = await Promise.all(+ activePredicates.map((p) => client.expand(nodeId, { direction: "in", predicates: [p], hops: 1 })),+ );+ const children: DependencyNode[] = [];+ const levelSeen = new Set<string>();+ const processNodes = async (rawNodes: any[], relation: DependencyNode["relation"], sourceEdge: DependencyNode["sourceEdge"]) => {+ const nodes = [...rawNodes].sort((a, b) => nodePriority(a) - nodePriority(b));+ for (const n of nodes) {+ if (nodesVisited >= maxNodes) { truncated = true; break; }+ if (levelSeen.has(n.id)) continue;+ const name = n.name || n.attrs?.name || "";+ const resolved = !!name && !isRawId(name);+ const isCycle = visited.has(n.id);+ nodesVisited++;+ levelSeen.add(n.id);+ visited.add(n.id);+ const child: DependencyNode = {+ id: n.id,+ name: resolved ? name : n.id.slice(0, 8),+ kind: n.kind ?? "unknown",+ resolved,+ relation,+ sourceEdge,+ path: n.provenance?.source_uri ?? n.provenance?.sourceUri ?? n.attrs?.path ?? undefined,+ children: [],+ ...(isCycle ? { cycle: true } : {}),+ };+ if (!isCycle && resolved) {+ child.children = await expand(n.id, depth + 1);+ }+ children.push(child);+ }+ };+ for (let i = 0; i < activePredicates.length; i++) {+ const meta = PREDICATE_META[activePredicates[i]];+ await processNodes(expandResults[i].nodes, meta.relation, meta.sourceEdge);+ }+ return children;+ }++ const tree = await expand(rootId, 1);+ return { tree, truncated, depthLimited, nodesVisited, maxDepthReached };+}++/** `searchPath` as it was before its queue was prefetched. */+async function oldSearchPath(client: any, fromId: string, toId: string, predicates: string[], maxDepth: number, maxNodes: number) {+ if (maxNodes < 1) return { path: null, cut: true, cutReason: "node-cap" };+ if (fromId === toId) return { path: [{ id: fromId, name: "", kind: "" }], cut: false };+ const nodeMap = new Map<string, { name: string; kind: string }>();+ const queue: Array<{ id: string; path: string[] }> = [{ id: fromId, path: [fromId] }];+ const visited = new Set<string>([fromId]);+ let depthCut = false;+ while (queue.length > 0) {+ const { id, path } = queue.shift()!;+ if (path.length - 1 >= maxDepth) { depthCut = true; continue; }+ const [outResult, inResult] = await Promise.all([+ client.expand(id, { direction: "out", predicates, hops: 1 }),+ client.expand(id, { direction: "in", predicates, hops: 1 }),+ ]);+ for (const n of [...outResult.nodes, ...inResult.nodes]) {+ if (visited.has(n.id)) continue;+ if (visited.size >= maxNodes) return { path: null, cut: true, cutReason: "node-cap" };+ visited.add(n.id);+ const name = n.name || n.attrs?.name || n.id.slice(0, 8);+ if (!nodeMap.has(n.id)) nodeMap.set(n.id, { name, kind: n.kind ?? "unknown" });+ if (n.id === toId) {+ return {+ path: [...path, n.id].map((nodeId) => {+ if (nodeId === fromId) return { id: nodeId, name: "", kind: "" };+ const meta = nodeMap.get(nodeId) ?? { name: nodeId.slice(0, 8), kind: "unknown" };+ return { id: nodeId, ...meta };+ }),+ cut: false,+ };+ }+ queue.push({ id: n.id, path: [...path, n.id] });+ }+ }+ return { path: null, cut: depthCut, cutReason: depthCut ? "depth" : undefined };+}++// ── Graphs and clients ──────────────────────────────────────────────++function mulberry32(seed: number): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++type Adjacency = Record<string, Record<string, any[]>>;++/**+ * Branching, shared children, cycles back to the root and to ancestors,+ * self-loops, one node under two predicates, and the node shapes the walk+ * treats differently: unresolved (raw-id or empty name), name only in attrs,+ * with and without a path.+ */+function randomGraph(seed: number, size: number, predicates: string[], maxFanout = 3): Adjacency {+ const rand = mulberry32(seed);+ const pick = (n: number) => Math.floor(rand() * n);+ const nodeFor = (i: number): any => {+ const roll = (i * 7919 + seed) % 20;+ const id = `n${i}`;+ if (roll === 0) return { id, name: `${String(i).padStart(4, "0")}d41d8cd98f00b204e9800998ecf8427e`, kind: "function" };+ if (roll === 1) return { id, name: "", kind: "function" };+ if (roll === 2) return { id, attrs: { name: `attr${i}` }, kind: "method" };+ if (roll < 8) return { id, name: `fn${i}`, kind: "function" };+ return { id, name: `fn${i}`, kind: "function", provenance: { source_uri: `src/f${i % 5}.ts` } };+ };+ const adjacency: Adjacency = {};+ for (let i = 0; i < size; i++) {+ const lists: Record<string, any[]> = {};+ for (const p of predicates) {+ const k = pick(maxFanout + 1);+ lists[p] = Array.from({ length: k }, () => nodeFor(pick(size)));+ }+ adjacency[`n${i}`] = lists;+ }+ return adjacency;+}++/**+ * A client over an adjacency, with optional per-request delays (so responses+ * come back out of order) and in-flight accounting.+ */+function clientFor(adjacency: Adjacency, delaySeed?: number) {+ const rand = delaySeed === undefined ? undefined : mulberry32(delaySeed);+ const stats = { calls: 0, inFlight: 0, maxInFlight: 0, ids: [] as string[] };+ const client = {+ expand: vi.fn(async (id: string, opts: { predicates: string[] }) => {+ stats.calls++;+ stats.ids.push(id);+ stats.inFlight++;+ stats.maxInFlight = Math.max(stats.maxInFlight, stats.inFlight);+ try {+ if (rand) await new Promise((r) => setTimeout(r, Math.floor(rand() * 4)));+ return { nodes: adjacency[id]?.[opts.predicates[0]] ?? [], edges: [] };+ } finally {+ stats.inFlight--;+ }+ }),+ };+ return { client: client as never, stats };+}++/** Breadth-first listing of a tree: `depth:name` per node. */+function levelOrder(tree: Array<{ name: string; children: any[] }>): string[] {+ const out: string[] = [];+ let level = tree.map((n) => ({ n, d: 1 }));+ while (level.length > 0) {+ const next: typeof level = [];+ for (const { n, d } of level) {+ out.push(`${d}:${n.name}`);+ for (const c of n.children) next.push({ n: c, d: d + 1 });+ }+ level = next;+ }+ return out;+}++const UNBOUNDED = { maxDepth: Infinity, maxNodes: Infinity };++// ── Same output when no bound cuts ──────────────────────────────────++describe("the breadth-first walk reproduces the depth-first one", () => {+ it("on a hand-built graph with a shared child, a diamond and cycles", async () => {+ // root <- a, b; a <- c; c <- shared, and d under two predicates;+ // b <- shared, root (a cycle); shared <- a (a cycle back up). The old+ // walk expands `shared` under `c`, its first occurrence in pre-order, at+ // depth 3, and marks it a cycle under `b` at depth 2 — a level-order walk+ // would do it the other way round.+ const fn = (id: string) => ({ id, name: id, kind: "function", provenance: { source_uri: `src/${id}.ts` } });+ const adjacency: Adjacency = {+ root: { CALLS: [fn("a"), fn("b")] },+ a: { CALLS: [fn("c")] },+ c: { CALLS: [fn("shared"), fn("d")], REFERENCES: [fn("d")] },+ b: { CALLS: [fn("shared"), fn("root")] },+ shared: { REFERENCES: [fn("a")] },+ };+ for (const bounds of [UNBOUNDED, { maxDepth: 2, maxNodes: Infinity }, { maxDepth: 3, maxNodes: 100 }]) {+ const expected = await oldBuildDependencyTree(clientFor(adjacency).client, "root", bounds);+ const actual = await buildDependencyTree(clientFor(adjacency).client, "root", bounds);+ expect(actual).toEqual(expected);+ }+ const walk = await buildDependencyTree(clientFor(adjacency).client, "root", UNBOUNDED);+ const c = walk.tree[0].children[0];+ expect(c.children.map((n) => [n.name, n.relation, !!n.cycle])).toEqual([["shared", "called_by", false], ["d", "called_by", false]]);+ expect(c.children[0].children.map((n) => [n.name, !!n.cycle])).toEqual([["a", true]]);+ expect(walk.tree[1].children.map((n) => [n.name, !!n.cycle])).toEqual([["shared", true], ["root", true]]);+ });++ it("on random graphs, unbounded and depth-limited, for every counter and every node", async () => {+ for (let seed = 1; seed <= 60; seed++) {+ const adjacency = randomGraph(seed, 12 + (seed % 25), DEPENDS_PREDICATES);+ for (const maxDepth of [Infinity, 1, 2, 3, 5]) {+ const bounds = { maxDepth, maxNodes: Infinity };+ const expected = await oldBuildDependencyTree(clientFor(adjacency).client, "n0", bounds);+ const actual = await buildDependencyTree(clientFor(adjacency).client, "n0", bounds);+ expect(actual, `seed ${seed} depth ${maxDepth}`).toEqual(expected);+ }+ }+ });++ it("whenever the cap does not cut the breadth-first walk", async () => {+ let compared = 0;+ let exact = 0;+ for (let seed = 1; seed <= 40; seed++) {+ const adjacency = randomGraph(seed, 20, DEPENDS_PREDICATES, 1);+ for (const maxNodes of [0, 1, 5, 10, 20, 40, 80, 160]) {+ const bounds = { maxDepth: 3, maxNodes };+ const actual = await buildDependencyTree(clientFor(adjacency).client, "n0", bounds);+ if (actual.truncated) continue;+ compared++;+ const expected = await oldBuildDependencyTree(clientFor(adjacency).client, "n0", bounds);+ // The one deliberate difference: the old walk said `truncated` when+ // the cap was spent exactly on the last node, though nothing was left.+ if (expected.truncated) {+ exact++;+ expect(expected.nodesVisited).toBe(maxNodes);+ }+ expect(actual, `seed ${seed} cap ${maxNodes}`).toEqual({ ...expected, truncated: false });+ }+ }+ expect(compared).toBeGreaterThan(100);+ expect(exact).toBeGreaterThan(0);+ });++ it("the same tree however the responses are ordered in time", async () => {+ for (let seed = 1; seed <= 8; seed++) {+ const adjacency = randomGraph(seed, 30, DEPENDS_PREDICATES);+ for (const bounds of [UNBOUNDED, { maxDepth: 3, maxNodes: 25 }]) {+ const inOrder = await buildDependencyTree(clientFor(adjacency).client, "n0", bounds);+ for (const delaySeed of [11, 12, 13]) {+ const shuffled = await buildDependencyTree(clientFor(adjacency, delaySeed * seed).client, "n0", bounds);+ expect(shuffled, `seed ${seed} delays ${delaySeed}`).toEqual(inOrder);+ }+ }+ }+ });+});++// ── Cap semantics under level order ─────────────────────────────────++describe("when the node cap cuts the walk", () => {+ const fn = (id: string) => ({ id, name: id, kind: "function", provenance: { source_uri: `src/${id}.ts` } });+ // root <- a, b, c; a <- a1 <- a2 <- a3; b <- b1+ const adjacency: Adjacency = {+ root: { CALLS: [fn("a"), fn("b"), fn("c")] },+ a: { CALLS: [fn("a1")] },+ a1: { CALLS: [fn("a2")] },+ a2: { CALLS: [fn("a3")] },+ b: { CALLS: [fn("b1")] },+ };++ it("keeps the shallowest nodes, where depth-first kept the first branch", async () => {+ const bounds = { maxDepth: 10, maxNodes: 4 };+ const old = await oldBuildDependencyTree(clientFor(adjacency).client, "root", bounds);+ expect(levelOrder(old.tree)).toEqual(["1:a", "2:a1", "3:a2", "4:a3"]);++ const walk = await buildDependencyTree(clientFor(adjacency).client, "root", bounds);+ expect(levelOrder(walk.tree)).toEqual(["1:a", "1:b", "1:c", "2:a1"]);+ expect(walk).toMatchObject({ nodesVisited: 4, maxDepthReached: 2, truncated: true, depthLimited: false });+ });++ it("is a prefix of the next larger cap's walk, level by level", async () => {+ for (let seed = 1; seed <= 30; seed++) {+ const graph = randomGraph(seed, 40, DEPENDS_PREDICATES);+ let previous: string[] | undefined;+ for (let cap = 1; cap <= 60; cap++) {+ const walk = await buildDependencyTree(clientFor(graph).client, "n0", { maxDepth: 4, maxNodes: cap });+ if (!walk.truncated) break;+ expect(walk.nodesVisited).toBe(cap);+ const order = levelOrder(walk.tree);+ expect(order).toHaveLength(cap);+ if (previous) expect(order.slice(0, previous.length), `seed ${seed} cap ${cap}`).toEqual(previous);+ previous = order;+ }+ }+ });++ it("reports the depth bound only for kept nodes it stopped descending into", async () => {+ // cap 4 keeps a, b, c, a1 and drops b1; a1 sits at the depth limit of 2+ // and has a caller, so the walk stopped descending there as well.+ const both = await buildDependencyTree(clientFor(adjacency).client, "root", { maxDepth: 2, maxNodes: 4 });+ expect(levelOrder(both.tree)).toEqual(["1:a", "1:b", "1:c", "2:a1"]);+ expect(both).toMatchObject({ nodesVisited: 4, maxDepthReached: 2, truncated: true, depthLimited: true });++ // cap 3 is spent on the first level: nothing kept reached the depth limit.+ const capOnly = await buildDependencyTree(clientFor(adjacency).client, "root", { maxDepth: 2, maxNodes: 3 });+ expect(capOnly).toMatchObject({ nodesVisited: 3, maxDepthReached: 1, truncated: true, depthLimited: false });+ });++ it("does not claim a cut when the budget is spent exactly and nothing is left below", async () => {+ // Four nodes in all; a cap of four keeps all of them.+ const small: Adjacency = { root: { CALLS: [fn("a"), fn("b")] }, a: { CALLS: [fn("a1"), fn("a2")] } };+ const walk = await buildDependencyTree(clientFor(small).client, "root", { maxDepth: 10, maxNodes: 4 });+ expect(walk.nodesVisited).toBe(4);+ expect(walk.truncated).toBe(false);+ });++ it("stops requesting once the cap is reached", async () => {+ // Every node has two callers, forever.+ const fanout = () => ({+ expand: vi.fn(async (id: string, opts: { predicates: string[] }) => ({+ nodes: opts.predicates[0] === "CALLS" ? [fn(`${id}.a`), fn(`${id}.b`)] : [],+ })),+ });+ const bounds = { maxDepth: 50, maxNodes: 100 };+ const client = fanout();+ const walk = await buildDependencyTree(client as never, "root", bounds);+ expect(walk.truncated).toBe(true);+ const expanded = new Set(client.expand.mock.calls.map(([id]) => id));+ // Level order reads 1 + 2 + 4 + 8 + 16 nodes and 19 of the next 32+ // before the 100th kept node: 50. Past that is only what was already+ // requested when the cap was reached.+ expect(expanded.size).toBeGreaterThanOrEqual(50);+ expect(expanded.size).toBeLessThanOrEqual(50 + EXPAND_CONCURRENCY);++ // The depth-first walk spent the same budget on 73 expansions, most of+ // them one long branch.+ const old = fanout();+ await oldBuildDependencyTree(old, "root", bounds);+ expect(new Set(old.expand.mock.calls.map(([id]) => id)).size).toBe(73);+ });+});++// ── Bounded concurrency ─────────────────────────────────────────────++describe("in-flight requests", () => {+ it(`never exceed ${EXPAND_CONCURRENCY}, and the walk does use them`, async () => {+ const adjacency = randomGraph(7, 200, DEPENDS_PREDICATES, 6);+ const { client, stats } = clientFor(adjacency, 99);+ await buildDependencyTree(client, "n0", { maxDepth: 4, maxNodes: 500 });+ expect(stats.maxInFlight).toBeLessThanOrEqual(EXPAND_CONCURRENCY);+ expect(stats.maxInFlight).toBe(EXPAND_CONCURRENCY);+ });++ it("hold across walks that share a limiter", async () => {+ const adjacency = randomGraph(8, 200, ["CALLS"], 6);+ const { client, stats } = clientFor(adjacency, 5);+ const limiter = createLimiter(3);+ const walk = (rootId: string) => walkTree({+ rootId, maxDepth: 4, maxNodes: 200, predicates: ["CALLS"], limiter,+ expand: (id, p) => (client as any).expand(id, { predicates: [p] }),+ makeNode: (n, _p, { name }) => ({ id: n.id, name, children: [] as any[] }),+ });+ await Promise.all([walk("n0"), walk("n1"), walk("n2")]);+ expect(stats.maxInFlight).toBe(3);+ });++ it("the limiter runs tasks in the order they were queued", async () => {+ const limit = createLimiter(2);+ const started: number[] = [];+ await Promise.all([0, 1, 2, 3, 4, 5].map((i) => limit(async () => {+ started.push(i);+ await new Promise((r) => setTimeout(r, (6 - i) % 3));+ })));+ expect(started).toEqual([0, 1, 2, 3, 4, 5]);+ });+});++// ── Failures ────────────────────────────────────────────────────────++describe("a failed expand", () => {+ it("still rejects the walk, and a prefetch nobody reads does not crash the process", async () => {+ const unhandled = vi.fn();+ process.on("unhandledRejection", unhandled);+ try {+ const client = {+ expand: vi.fn(async (id: string) => {+ if (id === "bad") throw new Error("500: boom");+ return { nodes: id === "root" ? [{ id: "bad", name: "bad", kind: "function" }, { id: "ok", name: "ok", kind: "function" }] : [] };+ }),+ };+ await expect(buildDependencyTree(client as never, "root", UNBOUNDED)).rejects.toThrow("500: boom");+ await new Promise((r) => setTimeout(r, 10));+ expect(unhandled).not.toHaveBeenCalled();+ } finally {+ process.off("unhandledRejection", unhandled);+ }+ });+});++// ── Path mode ───────────────────────────────────────────────────────++describe("trace --to with a prefetched queue", () => {+ it("returns the route, cut and reason the one-at-a-time search did", async () => {+ let compared = 0;+ for (let seed = 1; seed <= 40; seed++) {+ const adjacency = randomGraph(seed, 40, ["out", "in"], 2);+ const directed = (a: Adjacency) => ({+ expand: async (id: string, opts: { direction: string }) => ({ nodes: a[id]?.[opts.direction] ?? [], edges: [] }),+ });+ const shuffled = (a: Adjacency, s: number) => {+ const rand = mulberry32(s);+ return {+ expand: async (id: string, opts: { direction: string }) => {+ await new Promise((r) => setTimeout(r, Math.floor(rand() * 3)));+ return { nodes: a[id]?.[opts.direction] ?? [], edges: [] };+ },+ };+ };+ for (const [to, maxDepth, maxNodes] of [["n7", 10, 100], ["n13", 3, 100], ["n21", 10, 8], ["n39", 2, 1000]] as const) {+ const expected = await oldSearchPath(directed(adjacency), "n0", to, ["X"], maxDepth, maxNodes);+ expect(await searchPath(directed(adjacency) as never, "n0", to, ["X"], maxDepth, maxNodes)).toEqual(expected);+ expect(await searchPath(shuffled(adjacency, seed) as never, "n0", to, ["X"], maxDepth, maxNodes)).toEqual(expected);+ compared++;+ }+ }+ expect(compared).toBe(160);+ });++ it(`keeps at most ${EXPAND_CONCURRENCY} requests in flight`, async () => {+ const adjacency = randomGraph(3, 300, ["out", "in"], 5);+ const { stats } = clientFor(adjacency);+ let inFlight = 0;+ const client = {+ expand: async (id: string, opts: { direction: string }) => {+ inFlight++;+ stats.maxInFlight = Math.max(stats.maxInFlight, inFlight);+ await new Promise((r) => setTimeout(r, 1));+ inFlight--;+ return { nodes: adjacency[id]?.[opts.direction] ?? [], edges: [] };+ },+ };+ await searchPath(client as never, "n0", "nowhere", ["X"], 4, 1000);+ expect(stats.maxInFlight).toBe(EXPAND_CONCURRENCY);+ });+});diff --git a/ix-cli/src/cli/commands/depends.ts b/ix-cli/src/cli/commands/depends.tsindex feaea8ef..dcfdcd24 100644--- a/ix-cli/src/cli/commands/depends.ts+++ b/ix-cli/src/cli/commands/depends.ts@@ -5,6 +5,7 @@ import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { resolveFileOrReport, printResolved, isRawId } from "../resolve.js";+import { walkTree, type TreeWalkResult } from "../tree-walk.js";import { compactTreeNode, relativePath, printJson } from "../format.js";import { llmLine, llmShortId } from "../llm.js";import { parsePickOption } from "../options.js";@@ -57,100 +58,40 @@ function nodePriority(n: any): number {// ── Tree building ───────────────────────────────────────────────────/**- * Build a full dependency tree by recursive one-hop expansion.+ * Build a full dependency tree by one-hop expansion (see tree-walk.ts for the+ * order requests go out in and the tree that comes back).* Stops at: frontier end, cycle, depth limit, or node cap.*/export async function buildDependencyTree(client: IxClient,rootId: string,opts?: { maxDepth?: number; maxNodes?: number; predicates?: string[] },-): Promise<{- tree: DependencyNode[];- truncated: boolean;- depthLimited: boolean;- nodesVisited: number;- maxDepthReached: number;-}> {- const maxDepth = opts?.maxDepth ?? DEFAULT_MAX_DEPTH;- const maxNodes = opts?.maxNodes ?? MAX_NODES;+): Promise<TreeWalkResult<DependencyNode>> {const activePredicates = (opts?.predicates ?? ALL_DEPENDENCY_PREDICATES).filter((p) => p in PREDICATE_META);- const visited = new Set<string>([rootId]);- let nodesVisited = 0;- let truncated = false;- let depthLimited = false;- let maxDepthReached = 0;-- async function expand(nodeId: string, depth: number): Promise<DependencyNode[]> {- // Stopping at the depth bound is not the same as cutting something off:- // there may have been nothing below. `truncated` stays a claim that nodes- // were definitely lost — which only the node cap can know — and- // `depthLimited` says the walk stopped descending. With an infinite- // default the distinction never mattered; with a default of 3 it is the- // difference between a true report and a lie on most leaf branches.- if (depth > maxDepth) { depthLimited = true; return []; }- if (nodesVisited >= maxNodes) { truncated = true; return []; }-- maxDepthReached = Math.max(maxDepthReached, depth);-- const expandResults = await Promise.all(- activePredicates.map((p) => client.expand(nodeId, { direction: "in", predicates: [p], hops: 1 })),- );-- const children: DependencyNode[] = [];- // Track IDs added at this level to suppress same-level duplicates from- // multiple edge types (e.g. a node that both EXTENDS and REFERENCES the- // root would otherwise appear twice, the second time as a spurious cycle).- const levelSeen = new Set<string>();-- const processNodes = async (rawNodes: any[], relation: "called_by" | "imported_by" | "referenced_by" | "extended_by" | "implemented_by", sourceEdge: "CALLS" | "IMPORTS" | "REFERENCES" | "EXTENDS" | "IMPLEMENTS") => {- // Rank before the cap, or the cap keeps whatever the graph returned- // first. A node whose name is a raw id is a dangling reference nothing- // can follow, and one with no path costs a `locate` before it can be- // read; neither should displace a node carrying both. Stable within a- // band, and the predicate order (CALLS before IMPLEMENTS) is untouched.- const nodes = [...rawNodes].sort((a, b) => nodePriority(a) - nodePriority(b));- for (const n of nodes) {- if (nodesVisited >= maxNodes) { truncated = true; break; }- // Skip if already emitted at this level via a different edge type.- if (levelSeen.has(n.id)) continue;- const name = n.name || n.attrs?.name || "";- const resolved = !!name && !isRawId(name);- const isCycle = visited.has(n.id);-- nodesVisited++;- levelSeen.add(n.id);- visited.add(n.id);-- const child: DependencyNode = {- id: n.id,- name: resolved ? name : n.id.slice(0, 8),- kind: n.kind ?? "unknown",- resolved,- relation,- sourceEdge,- path: n.provenance?.source_uri ?? n.provenance?.sourceUri ?? n.attrs?.path ?? undefined,- children: [],- ...(isCycle ? { cycle: true } : {}),- };-- if (!isCycle && resolved) {- child.children = await expand(n.id, depth + 1);- }-- children.push(child);- }- };-- for (let i = 0; i < activePredicates.length; i++) {- const meta = PREDICATE_META[activePredicates[i]];- await processNodes(expandResults[i].nodes, meta.relation, meta.sourceEdge);- }-- return children;- }-- const tree = await expand(rootId, 1);- return { tree, truncated, depthLimited, nodesVisited, maxDepthReached };+ return walkTree<DependencyNode>({+ rootId,+ maxDepth: opts?.maxDepth ?? DEFAULT_MAX_DEPTH,+ maxNodes: opts?.maxNodes ?? MAX_NODES,+ predicates: activePredicates,+ expand: (nodeId, p) => client.expand(nodeId, { direction: "in", predicates: [p], hops: 1 }),+ // Rank before the cap, or the cap keeps whatever the graph returned+ // first. A node whose name is a raw id is a dangling reference nothing+ // can follow, and one with no path costs a `locate` before it can be+ // read; neither should displace a node carrying both. Stable within a+ // band, and the predicate order (CALLS before IMPLEMENTS) is untouched.+ order: (nodes) => [...nodes].sort((a, b) => nodePriority(a) - nodePriority(b)),+ makeNode: (n, p, { name, resolved, cycle }) => ({+ id: n.id,+ name: resolved ? name : n.id.slice(0, 8),+ kind: n.kind ?? "unknown",+ resolved,+ relation: PREDICATE_META[p].relation,+ sourceEdge: PREDICATE_META[p].sourceEdge,+ path: n.provenance?.source_uri ?? n.provenance?.sourceUri ?? n.attrs?.path ?? undefined,+ children: [],+ ...(cycle ? { cycle: true } : {}),+ }),+ });}// ── Tree rendering ──────────────────────────────────────────────────diff --git a/ix-cli/src/cli/commands/trace.ts b/ix-cli/src/cli/commands/trace.tsindex e172a403..ea84188b 100644--- a/ix-cli/src/cli/commands/trace.ts+++ b/ix-cli/src/cli/commands/trace.ts@@ -4,7 +4,7 @@ import type { Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";-import { resolveFileOrEntityFull, resolveFileOrReport, isRawId, activeReadScope, ensureReadScope } from "../resolve.js";+import { resolveFileOrEntityFull, resolveFileOrReport, activeReadScope, ensureReadScope } from "../resolve.js";import type { ResolvedEntity } from "../resolve.js";import {renderSection,@@ -18,6 +18,7 @@ import { compactTreeNode, relativePath, printJson } from "../format.js";import { llmLine, llmShortId, type LlmValue } from "../llm.js";import { traversalHint } from "./depends.js";import { parsePickOption } from "../options.js";+import { createLimiter, EXPAND_CONCURRENCY, walkTree, type Limiter, type TreeWalkResult } from "../tree-walk.js";// ── Types ────────────────────────────────────────────────────────────@@ -172,72 +173,28 @@ async function buildTraceTree(predicates: string[];maxDepth: number;maxNodes: number;+ limiter?: Limiter;},-): Promise<{- tree: TraceNode[];- truncated: boolean;- depthLimited: boolean;- nodesVisited: number;- maxDepthReached: number;-}> {- const { direction, predicates, maxDepth, maxNodes } = opts;- const visited = new Set<string>([rootId]);- let nodesVisited = 0;- let truncated = false;- let depthLimited = false;- let maxDepthReached = 0;-- async function expand(nodeId: string, depth: number): Promise<TraceNode[]> {- // See depends.ts: stopping at the depth bound is not evidence that- // anything was cut off.- if (depth > maxDepth) { depthLimited = true; return []; }- if (nodesVisited >= maxNodes) { truncated = true; return []; }- maxDepthReached = Math.max(maxDepthReached, depth);-+): Promise<TreeWalkResult<TraceNode>> {+ const { direction, predicates, maxDepth, maxNodes, limiter } = opts;+ return walkTree<TraceNode>({+ rootId,+ maxDepth,+ maxNodes,// One call per predicate (matches depends.ts behaviour — order and dedup are stable)- const results = await Promise.all(- predicates.map((p) => client.expand(nodeId, { direction, predicates: [p], hops: 1 })),- );-- const children: TraceNode[] = [];- const levelSeen = new Set<string>();-- for (const result of results) {- for (const n of result.nodes) {- if (nodesVisited >= maxNodes) { truncated = true; break; }- if (levelSeen.has(n.id)) continue;-- const name = n.name || n.attrs?.name || "";- const resolved = !!name && !isRawId(name);- const isCycle = visited.has(n.id);-- nodesVisited++;- levelSeen.add(n.id);- visited.add(n.id);-- const child: TraceNode = {- id: n.id,- name: resolved ? name : n.id.slice(0, 8),- kind: n.kind ?? "unknown",- resolved,- path: n.provenance?.sourceUri ?? n.provenance?.source_uri ?? undefined,- children: [],- ...(isCycle ? { cycle: true } : {}),- };-- if (!isCycle && resolved) {- child.children = await expand(n.id, depth + 1);- }-- children.push(child);- }- }-- return children;- }-- const tree = await expand(rootId, 1);- return { tree, truncated, depthLimited, nodesVisited, maxDepthReached };+ predicates,+ expand: (nodeId, p) => client.expand(nodeId, { direction, predicates: [p], hops: 1 }),+ makeNode: (n, _p, { name, resolved, cycle }) => ({+ id: n.id,+ name: resolved ? name : n.id.slice(0, 8),+ kind: n.kind ?? "unknown",+ resolved,+ path: n.provenance?.sourceUri ?? n.provenance?.source_uri ?? undefined,+ children: [],+ ...(cycle ? { cycle: true } : {}),+ }),+ limiter,+ });}// ── Path search (BFS) ────────────────────────────────────────────────@@ -274,46 +231,68 @@ export async function searchPath(if (fromId === toId) return { path: [{ id: fromId, name: "", kind: "" }], cut: false };const nodeMap = new Map<string, { name: string; kind: string }>();- const queue: Array<{ id: string; path: string[] }> = [{ id: fromId, path: [fromId] }];+ // Breadth-first as before, and still read one entry at a time in queue+ // order, so the route returned — the shortest, first-queued on a tie — does+ // not change. What changes is that an entry's neighbours are requested as+ // soon as it is queued, a bounded number at a time, instead of when the+ // loop reaches it.+ const limit = createLimiter(EXPAND_CONCURRENCY);+ let done = false;+ const noNodes = { nodes: [] as any[], edges: [] as any[] };+ const neighbours = (id: string) => {+ const both = Promise.all([+ limit(() => (done ? Promise.resolve(noNodes) : client.expand(id, { direction: "out", predicates, hops: 1 }))),+ limit(() => (done ? Promise.resolve(noNodes) : client.expand(id, { direction: "in", predicates, hops: 1 }))),+ ]);+ both.catch(() => {}); // read later, or never once a route is found+ return both;+ };+ type Entry = { id: string; path: string[]; next?: ReturnType<typeof neighbours> };+ const enqueue = (id: string, path: string[]): Entry =>+ // An entry at the depth bound is never expanded, so nothing is fetched for it.+ ({ id, path, next: path.length - 1 >= maxDepth ? undefined : neighbours(id) });++ const queue: Entry[] = [enqueue(fromId, [fromId])];const visited = new Set<string>([fromId]);let depthCut = false;- while (queue.length > 0) {- const entry = queue.shift()!;- const { id, path } = entry;- if (path.length - 1 >= maxDepth) {- depthCut = true;- continue;- }+ try {+ for (let head = 0; head < queue.length; head++) {+ const { path, next } = queue[head];+ if (!next) {+ depthCut = true;+ continue;+ }- const [outResult, inResult] = await Promise.all([- client.expand(id, { direction: "out", predicates, hops: 1 }),- client.expand(id, { direction: "in", predicates, hops: 1 }),- ]);+ const [outResult, inResult] = await next;- for (const n of [...outResult.nodes, ...inResult.nodes]) {- if (visited.has(n.id)) continue;- if (visited.size >= maxNodes) return { path: null, cut: true, cutReason: "node-cap" };- visited.add(n.id);- const name = n.name || n.attrs?.name || n.id.slice(0, 8);- if (!nodeMap.has(n.id)) {- nodeMap.set(n.id, { name, kind: n.kind ?? "unknown" });- }+ for (const n of [...outResult.nodes, ...inResult.nodes]) {+ if (visited.has(n.id)) continue;+ if (visited.size >= maxNodes) return { path: null, cut: true, cutReason: "node-cap" };+ visited.add(n.id);+ const name = n.name || n.attrs?.name || n.id.slice(0, 8);+ if (!nodeMap.has(n.id)) {+ nodeMap.set(n.id, { name, kind: n.kind ?? "unknown" });+ }- if (n.id === toId) {- const fullPath = [...path, n.id];- return {- path: fullPath.map((nodeId) => {- if (nodeId === fromId) return { id: nodeId, name: "", kind: "" }; // filled below- const meta = nodeMap.get(nodeId) ?? { name: nodeId.slice(0, 8), kind: "unknown" };- return { id: nodeId, ...meta };- }),- cut: false,- };- }+ if (n.id === toId) {+ const fullPath = [...path, n.id];+ return {+ path: fullPath.map((nodeId) => {+ if (nodeId === fromId) return { id: nodeId, name: "", kind: "" }; // filled below+ const meta = nodeMap.get(nodeId) ?? { name: nodeId.slice(0, 8), kind: "unknown" };+ return { id: nodeId, ...meta };+ }),+ cut: false,+ };+ }- queue.push({ id: n.id, path: [...path, n.id] });+ queue.push(enqueue(n.id, [...path, n.id]));+ }}+ } finally {+ // Whatever is still queued behind the limiter is not sent.+ done = true;}return { path: null, cut: depthCut, cutReason: depthCut ? "depth" : undefined };@@ -674,9 +653,11 @@ export function registerTraceCommand(program: Command): void {// ── Both: run up + down in parallel ────────────────────────if (doBoth) {+ // One limiter for both walks, so the in-flight bound is per command.+ const limiter = createLimiter(EXPAND_CONCURRENCY);const [upResult, downResult] = await Promise.all([- buildTraceTree(client, target.id, { direction: "in", predicates, maxDepth, maxNodes }),- buildTraceTree(client, target.id, { direction: "out", predicates, maxDepth, maxNodes }),+ buildTraceTree(client, target.id, { direction: "in", predicates, maxDepth, maxNodes, limiter }),+ buildTraceTree(client, target.id, { direction: "out", predicates, maxDepth, maxNodes, limiter }),]);// ── JSON ──────────────────────────────────────────────diff --git a/ix-cli/src/cli/tree-walk.ts b/ix-cli/src/cli/tree-walk.tsnew file mode 100644index 00000000..9a13aea8--- /dev/null+++ b/ix-cli/src/cli/tree-walk.ts@@ -0,0 +1,260 @@+// Copyright 2026 Ix Infrastructure Inc.++import { isRawId } from "./resolve.js";++/**+ * The one-hop tree walk behind `ix trace` (directional modes) and `ix depends`.+ *+ * Both used to recurse depth-first and await each child's whole subtree before+ * starting its sibling, so a walk cost one round trip per expanded node, in+ * series: on the Ix repo's own graph, 1.2-1.8 s of a command whose client work+ * was ~0.1 s. Here the fetching is breadth-first — a node's neighbours are+ * requested the moment the node is discovered, through a bounded limiter — and+ * the tree is built from the fetched lists in a fixed order, so which request+ * returns first never shows in the output.+ *+ * Which tree comes back:+ *+ * - **The walk fits the node cap** (always, when there is no cap). The+ * breadth-first pass has then fetched every node the old depth-first walk+ * would expand, and that walk is replayed over the fetched lists. The tree —+ * shape, child order, dedup, which occurrence of a shared node is expanded+ * and which is marked `cycle` — and the counters are the old walk's exactly,+ * except that a cap spent exactly on the last node is no longer reported as+ * `truncated` when nothing was left to drop.+ * Replaying matters: breadth-first order would expand a shared node at its+ * shallowest occurrence, depth-first order at its first one in pre-order.+ * It has a cost under a depth limit: a node the depth-first walk first met+ * at the limit, and so never expanded, is fetched anyway when it also sits+ * shallower. On `ix trace ingestFiles --upstream` that is 20 nodes fetched+ * for the old walk's 10 — still no slower, the requests being parallel.+ * - **The cap cuts the walk.** The breadth-first tree is returned as it stood+ * when the cap was reached: every node at depth d is kept before any node at+ * depth d+1, where the depth-first walk spent the whole budget down its first+ * branch. `truncated` is set only when a node was actually dropped.+ */++/** Runs a task when a slot is free; FIFO, so requests go out in walk order. */+export type Limiter = <T>(task: () => Promise<T>) => Promise<T>;++/**+ * How many expand requests one command keeps in flight. The backend's+ * throughput on 276 real expand bodies: 1.7 s at 1, 0.60 s at 6, 0.43 s at 8,+ * 0.29 s at 16. Eight is four times one-at-a-time without letting a hub flood+ * a backend other clients share.+ */+export const EXPAND_CONCURRENCY = 8;++export function createLimiter(max: number): Limiter {+ let active = 0;+ const waiting: Array<() => void> = [];+ const pump = (): void => {+ while (active < max && waiting.length > 0) {+ active++;+ waiting.shift()!();+ }+ };+ return <T>(task: () => Promise<T>) =>+ new Promise<T>((resolve, reject) => {+ waiting.push(() => {+ Promise.resolve()+ .then(task)+ .then(resolve, reject)+ .finally(() => {+ active--;+ pump();+ });+ });+ pump();+ });+}++export interface TreeWalkOptions<T extends { children: T[] }> {+ rootId: string;+ maxDepth: number;+ maxNodes: number;+ /** One expand per predicate; a node's children are merged in this order. */+ predicates: string[];+ expand: (nodeId: string, predicate: string) => Promise<{ nodes: any[] }>;+ /** Reorders one predicate's neighbours before the cap sees them. */+ order?: (nodes: any[]) => any[];+ makeNode: (raw: any, predicate: string, seen: { name: string; resolved: boolean; cycle: boolean }) => T;+ /** Shared when several walks run at once, so the bound holds across them. */+ limiter?: Limiter;+}++export interface TreeWalkResult<T> {+ tree: T[];+ truncated: boolean;+ depthLimited: boolean;+ nodesVisited: number;+ maxDepthReached: number;+}++type Neighbours = (nodeId: string) => Promise<any[][]>;++interface WalkState {+ visited: Set<string>;+ nodesVisited: number;+ truncated: boolean;+ depthLimited: boolean;+ maxDepthReached: number;+}++export async function walkTree<T extends { children: T[] }>(opts: TreeWalkOptions<T>): Promise<TreeWalkResult<T>> {+ const limit = opts.limiter ?? createLimiter(EXPAND_CONCURRENCY);+ const fetched = new Map<string, Promise<any[][]>>();+ // Set once the walk is decided: requests still queued behind the limiter are+ // then skipped instead of sent.+ let done = false;++ const neighbours: Neighbours = (nodeId) => {+ let lists = fetched.get(nodeId);+ if (!lists) {+ lists = Promise.all(+ opts.predicates.map((p) =>+ limit(async () => (done ? [] : (await opts.expand(nodeId, p)).nodes)),+ ),+ ).then((raw) => (opts.order ? raw.map(opts.order) : raw));+ // A prefetch the walk never reads must not surface as an unhandled+ // rejection; one it does read still throws where it is awaited.+ lists.catch(() => {});+ fetched.set(nodeId, lists);+ }+ return lists;+ };++ try {+ const levels = await breadthFirst(opts, neighbours);+ if (levels.truncated) return levels;+ return await depthFirst(opts, neighbours);+ } finally {+ done = true;+ }+}++function newState(rootId: string): WalkState {+ return { visited: new Set([rootId]), nodesVisited: 0, truncated: false, depthLimited: false, maxDepthReached: 0 };+}++/** Count and mark one neighbour, the way both walk orders do. */+function admit<T extends { children: T[] }>(+ opts: TreeWalkOptions<T>, state: WalkState, n: any, predicate: string,+): { node: T; followed: boolean } {+ const name = n.name || n.attrs?.name || "";+ const resolved = !!name && !isRawId(name);+ const cycle = state.visited.has(n.id);+ state.nodesVisited++;+ state.visited.add(n.id);+ return { node: opts.makeNode(n, predicate, { name, resolved, cycle }), followed: resolved && !cycle };+}++/**+ * The old recursive walk, unchanged except that it reads each node's+ * neighbours from the lists the breadth-first pass already fetched — which+ * also lets it tell a spent budget from a cut.+ */+async function depthFirst<T extends { children: T[] }>(+ opts: TreeWalkOptions<T>, neighbours: Neighbours,+): Promise<TreeWalkResult<T>> {+ const state = newState(opts.rootId);++ async function expand(nodeId: string, depth: number): Promise<T[]> {+ // Stopping at the depth bound is not the same as cutting something off:+ // there may have been nothing below. `truncated` stays a claim that nodes+ // were definitely lost — which only the node cap can know — and+ // `depthLimited` says the walk stopped descending.+ if (depth > opts.maxDepth) { state.depthLimited = true; return []; }+ const lists = await neighbours(nodeId);+ if (state.nodesVisited >= opts.maxNodes) {+ // The budget is spent, but a node with nothing below it loses nothing.+ // (The recursive walk used to say `truncated` here regardless, so a cap+ // spent exactly on the last node claimed a cut that dropped nothing.)+ if (lists.some((l) => l.length > 0)) state.truncated = true;+ return [];+ }+ state.maxDepthReached = Math.max(state.maxDepthReached, depth);++ const children: T[] = [];+ // A node reached through two predicates is one child, not a child and+ // then a spurious cycle.+ const levelSeen = new Set<string>();+ for (let i = 0; i < lists.length; i++) {+ for (const n of lists[i]) {+ if (state.nodesVisited >= opts.maxNodes) { state.truncated = true; break; }+ if (levelSeen.has(n.id)) continue;+ levelSeen.add(n.id);+ const { node, followed } = admit(opts, state, n, opts.predicates[i]);+ if (followed) node.children = await expand(n.id, depth + 1);+ children.push(node);+ }+ }+ return children;+ }++ const tree = await expand(opts.rootId, 1);+ return { tree, ...counters(state) };+}++/**+ * The same walk in breadth-first order: a FIFO queue of nodes to expand, each+ * one's neighbours requested when it is queued and read strictly in queue+ * order.+ */+async function breadthFirst<T extends { children: T[] }>(+ opts: TreeWalkOptions<T>, neighbours: Neighbours,+): Promise<TreeWalkResult<T>> {+ const state = newState(opts.rootId);+ const tree: T[] = [];+ const queue: Array<{ id: string; depth: number; into: T[] }> = [];+ const enqueue = (id: string, depth: number, into: T[]): void => {+ queue.push({ id, depth, into });+ // Written as the negation of the check below, so a NaN bound (an+ // unparseable --depth, which never stops the walk) still prefetches.+ if (!(depth > opts.maxDepth)) void neighbours(id);+ };++ enqueue(opts.rootId, 1, tree);+ for (let head = 0; head < queue.length; head++) {+ const { id, depth, into } = queue[head];+ if (depth > opts.maxDepth) { state.depthLimited = true; continue; }++ const lists = await neighbours(id);+ if (state.nodesVisited >= opts.maxNodes) {+ // The budget is spent, but a node with nothing below it loses nothing:+ // only a neighbour that would have been listed makes this a cut.+ if (lists.some((l) => l.length > 0)) state.truncated = true;+ } else {+ state.maxDepthReached = Math.max(state.maxDepthReached, depth);+ const levelSeen = new Set<string>();+ for (let i = 0; i < lists.length && !state.truncated; i++) {+ for (const n of lists[i]) {+ if (state.nodesVisited >= opts.maxNodes) { state.truncated = true; break; }+ if (levelSeen.has(n.id)) continue;+ levelSeen.add(n.id);+ const { node, followed } = admit(opts, state, n, opts.predicates[i]);+ if (followed) enqueue(n.id, depth + 1, node.children);+ into.push(node);+ }+ }+ }++ if (state.truncated) {+ // Nodes already kept at the last allowed depth were never descended+ // into, cap or no cap — the depth-first walk reported those too.+ if (queue.slice(head + 1).some((q) => q.depth > opts.maxDepth)) state.depthLimited = true;+ break;+ }+ }++ return { tree, ...counters(state) };+}++function counters(state: WalkState): Omit<TreeWalkResult<never>, "tree"> {+ return {+ truncated: state.truncated,+ depthLimited: state.depthLimited,+ nodesVisited: state.nodesVisited,+ maxDepthReached: state.maxDepthReached,+ };+}diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.mdindex cf36a627..970f83e1 100644--- a/skills/ix/references/flags.md+++ b/skills/ix/references/flags.md@@ -73,7 +73,11 @@ surfaces (#575).them per direction in each `summary`. When `ix trace --to` finds no route, asearch a bound cut short adds the same code after `no_path`; a bare `no_path`means the whole reachable graph was searched. `--depth` and `--cap` take- anything.+ anything. When the cap cuts a `depends` or directional `trace` walk, the+ nodes kept are the shallowest: every node at depth d before any at depth+ d+1, so the first level is complete before the second begins. (The walk+ used to be depth-first, and could spend the whole cap down its first+ branch.) A walk the cap does not cut is the same tree it always was.- **`ix ingest` honours `--exclude <glob>` and a `.ixignore` at the ingestroot.** A deliberate subset of `.gitignore`: `#` comments, `*`, `?`, `**`, aleading `/` to anchor at the root, a trailing `/` for directories only, and a