Skip to content

armgit / Ix

Public Imported from GitHub
0

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

perf(context): skip the facts only `ix explain` reads

KageBinaryacdda2d9504d
diff --git a/ix-cli/src/cli/__tests__/facts-scope.test.ts b/ix-cli/src/cli/__tests__/facts-scope.test.ts
new file mode 100644
index 00000000..06ac7187
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/facts-scope.test.ts
@@ -0,0 +1,88 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { describe, expect, it } from "vitest";
+
+import type { IxClient } from "../../client/api.js";
+import { collectFacts } from "../explain/facts.js";
+
+const TARGET = "00000000-0000-0000-0000-000000000001";
+const CALLEE = "00000000-0000-0000-0000-000000000002";
+const DEPENDENT = "00000000-0000-0000-0000-000000000003";
+
+interface Call {
+ method: string;
+ id: string;
+ predicates?: string[];
+ hops?: number;
+}
+
+/**
+ * A graph where the target calls one function and is imported by one file,
+ * so every optional step `collectFacts` can take has something to do: the
+ * dependency tree has a node to walk, and the callee list has a callee to look
+ * up.
+ */
+function fakeClient(calls: Call[]): IxClient {
+ const node = (id: string, name: string, kind: string) => ({
+ id, name, kind, attrs: {}, provenance: { sourceUri: `src/${name}.ts` },
+ });
+ return {
+ async entity(id: string) {
+ calls.push({ method: "entity", id });
+ return {
+ node: node(id, id === TARGET ? "config" : "callee", "function"),
+ claims: [],
+ decisions: [],
+ edges: id === TARGET ? [{ src: TARGET, dst: CALLEE, predicate: "CALLS" }] : [],
+ };
+ },
+ async expand(id: string, opts?: { direction?: string; predicates?: string[]; hops?: number }) {
+ calls.push({ method: "expand", id, predicates: opts?.predicates, hops: opts?.hops });
+ const importedBy = id === TARGET && opts?.direction === "in" && opts.predicates?.includes("IMPORTS");
+ return importedBy
+ ? { nodes: [node(DEPENDENT, "user", "file")], edges: [{ src: DEPENDENT, dst: TARGET, predicate: "IMPORTS" }] }
+ : { nodes: [], edges: [] };
+ },
+ async provenance(id: string) {
+ calls.push({ method: "provenance", id });
+ return { entityId: id, chain: [{}, {}] };
+ },
+ } as unknown as IxClient;
+}
+
+describe("collectFacts scope", () => {
+ it("fetches only what `ix context` reads", async () => {
+ const calls: Call[] = [];
+
+ const facts = await collectFacts(fakeClient(calls), TARGET, "config", "function", "context");
+
+ // One entity, five fixed expands, one provenance -- and nothing that
+ // grows with the graph.
+ expect(calls.filter((c) => c.method === "expand")).toHaveLength(5);
+ expect(calls.filter((c) => c.method === "entity").map((c) => c.id)).toEqual([TARGET]);
+ expect(calls.some((c) => c.id === DEPENDENT)).toBe(false);
+ expect(calls.some((c) => c.predicates?.includes("IN_REGION"))).toBe(false);
+
+ expect(facts.topDependents).toEqual(["user"]);
+ expect(facts.historyLength).toBe(2);
+ // Handed on so `ix context` does not fetch the same provenance twice.
+ expect(calls.filter((c) => c.method === "provenance")).toHaveLength(1);
+ expect(facts.provenance).toEqual({ entityId: TARGET, chain: [{}, {}] });
+ // Absent, not zeroed: a skipped fact must not read as a measured one.
+ expect(facts).not.toHaveProperty("downstreamDependents");
+ expect(facts).not.toHaveProperty("callList");
+ expect(facts).not.toHaveProperty("systemPath");
+ });
+
+ it("still collects everything `ix explain` renders", async () => {
+ const calls: Call[] = [];
+
+ const facts = await collectFacts(fakeClient(calls), TARGET, "config", "function");
+
+ expect(calls.some((c) => c.id === DEPENDENT)).toBe(true);
+ expect(calls.some((c) => c.predicates?.includes("IN_REGION"))).toBe(true);
+ expect(calls.filter((c) => c.method === "entity").map((c) => c.id)).toContain(CALLEE);
+ expect(facts.downstreamDependents).toBeGreaterThan(0);
+ expect(facts.callList?.map((c) => c.name)).toEqual(["callee"]);
+ });
+});
diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.ts
index 21fd306b..94552a26 100644
--- a/ix-cli/src/cli/commands/context.ts
+++ b/ix-cli/src/cli/commands/context.ts
@@ -19,7 +19,7 @@ import type {
StructuredContext,
} from "../../client/types.js";
import { getEndpoint } from "../config.js";
-import { collectFacts, type EntityFacts } from "../explain/facts.js";
+import { collectFacts, type ContextFacts } from "../explain/facts.js";
import { llmLine, printLlmLines } from "../llm.js";
import { parseBudgetOption, parsePickOption, parseRevisionOption } from "../options.js";
import { resolveFileOrReport } from "../resolve.js";
@@ -315,8 +315,11 @@ export function registerContextCommand(program: Command): void {
const budgets = clampBudgets(opts);
const asOfRev = opts.asOfRev;
- const [facts, context, provenance] = await Promise.all([
- collectFacts(client, resolved.id, resolved.name, resolved.kind),
+ const [facts, context] = await Promise.all([
+ // Also carries the provenance response: `collectFacts` needs it for the
+ // history length, and fetching it again here doubled one of the
+ // slowest calls the command makes (~1.3s on the Ix repo's graph).
+ collectFacts(client, resolved.id, resolved.name, resolved.kind, "context"),
// By id, not by name. Seeding by name makes the backend re-run the
// search the resolver just did, and it can land on a different node of
// the same name. Both call sites in this file must use it: converting
@@ -326,8 +329,8 @@ export function registerContextCommand(program: Command): void {
asOfRev,
depth: opts.depth,
}),
- client.provenance(resolved.id),
]);
+ const provenance = facts.provenance;
const bundle = buildBundle({
resolved,
@@ -415,14 +418,13 @@ async function buildFreshBundle(
if (!resolved) return undefined;
const asOfRev = opts.asOfRev;
- const [facts, context, provenance] = await Promise.all([
- collectFacts(client, resolved.id, resolved.name, resolved.kind),
+ const [facts, context] = await Promise.all([
+ collectFacts(client, resolved.id, resolved.name, resolved.kind, "context"),
client.contextForNode(resolved.id, { asOfRev, depth: opts.depth }),
- client.provenance(resolved.id),
]);
return buildBundle({
- resolved, facts, context, provenance, asOfRev, depth: opts.depth, budgets,
+ resolved, facts, context, provenance: facts.provenance, asOfRev, depth: opts.depth, budgets,
graphCompleted: hasCompletedSourceGraphBaseline(),
});
}
@@ -1323,7 +1325,7 @@ export function renderInvestigationDiff(
interface BuildInput {
resolved: { id: string; name: string; kind: string; resolutionMode: string };
- facts: EntityFacts;
+ facts: ContextFacts;
context: StructuredContext;
provenance: unknown;
asOfRev?: number;
@@ -1528,7 +1530,7 @@ export function buildBundle(input: BuildInput): ContextBundle {
/** Deterministic evidence ranking: tier, then a stable id tiebreaker. */
function rankEvidence(input: {
resolved: { id: string; name: string; kind: string };
- facts: EntityFacts;
+ facts: ContextFacts;
context: StructuredContext;
relationships: Array<{ src: string; dst: string; predicate: string }>;
prov: Record<string, unknown>;
diff --git a/ix-cli/src/cli/explain/facts.ts b/ix-cli/src/cli/explain/facts.ts
index ca5f5b47..b7f17ecf 100644
--- a/ix-cli/src/cli/explain/facts.ts
+++ b/ix-cli/src/cli/explain/facts.ts
@@ -55,15 +55,59 @@ export interface EntityFacts {
diagnostics: Diagnostic[];
}
+/** Facts only `ix explain` renders. */
+type ExplainOnlyFact =
+ | "downstreamDependents"
+ | "downstreamDepth"
+ | "callList"
+ | "systemPath"
+ | "subsystemName"
+ | "moduleName";
+
+/**
+ * The facts `ix context` reads. The explain-only ones are absent from the type
+ * rather than zeroed, so nothing can render a skipped fact as a real count.
+ * `provenance` is the raw `/v1/provenance` response the history length was
+ * read from, handed on so the caller does not fetch it a second time.
+ */
+export type ContextFacts = Omit<EntityFacts, ExplainOnlyFact> & { provenance?: unknown };
+
+const NO_DOWNSTREAM = { tree: [], truncated: false, nodesVisited: 0, maxDepthReached: 0 };
+
+/**
+ * Collect the structural facts about one entity.
+ *
+ * `scope` exists because the explain-only facts are by far the most expensive.
+ * The downstream dependency tree walks up to 100 nodes with five expands each:
+ * measured on `ix context config.ts` against the Ix repo's own graph, 230 of
+ * the command's 246 HTTP requests and ~6 of its ~10 seconds, for two numbers
+ * `ix context` never reads. `"context"` skips that tree, the system path and
+ * the per-callee lookups.
+ */
+export function collectFacts(
+ client: IxClient,
+ targetId: string,
+ targetName: string,
+ targetKind: string,
+): Promise<EntityFacts>;
+export function collectFacts(
+ client: IxClient,
+ targetId: string,
+ targetName: string,
+ targetKind: string,
+ scope: "context",
+): Promise<ContextFacts>;
export async function collectFacts(
client: IxClient,
targetId: string,
targetName: string,
targetKind: string,
-): Promise<EntityFacts> {
+ scope: "explain" | "context" = "explain",
+): Promise<EntityFacts | ContextFacts> {
const diagnostics: Diagnostic[] = [];
+ const forExplain = scope === "explain";
- // Run parallel graph queries (including bounded downstream tree)
+ // Run parallel graph queries (including, for explain, a bounded downstream tree)
const [details, callersResult, calleesResult, dependentsResult, importersResult, membersResult, provenance, downstream, hierarchyPath] =
await Promise.all([
client.entity(targetId),
@@ -73,10 +117,10 @@ export async function collectFacts(
client.expand(targetId, { direction: "in", predicates: ["IMPORTS"] }),
client.expand(targetId, { direction: "out", predicates: ["CONTAINS"] }),
client.provenance(targetId).catch(() => ({ entityId: targetId, chain: [] })),
- buildDependencyTree(client, targetId, { maxDepth: 4, maxNodes: 100 }).catch(() => ({
- tree: [], truncated: false, nodesVisited: 0, maxDepthReached: 0,
- })),
- getSystemPath(client, targetId).catch(() => []),
+ forExplain
+ ? buildDependencyTree(client, targetId, { maxDepth: 4, maxNodes: 100 }).catch(() => NO_DOWNSTREAM)
+ : Promise.resolve(NO_DOWNSTREAM),
+ forExplain ? getSystemPath(client, targetId).catch(() => []) : Promise.resolve([]),
]);
const node = details.node as any;
@@ -134,7 +178,7 @@ export async function collectFacts(
(e: any) => e.predicate === "CALLS" && e.src === targetId,
);
let callList: EntityRef[] | undefined;
- if (calleeEdges.length > 0 && calleeEdges.length <= 20) {
+ if (forExplain && calleeEdges.length > 0 && calleeEdges.length <= 20) {
const refs = await Promise.all(
calleeEdges.map(async (e: any): Promise<EntityRef> => {
try {
@@ -204,7 +248,7 @@ export async function collectFacts(
const subsystemName = hierarchyPath.find((n: any) => n.kind === "subsystem")?.name;
const moduleName = hierarchyPath.find((n: any) => n.kind === "module")?.name;
- return {
+ const facts: EntityFacts = {
id: targetId,
name: node.name || node.attrs?.name || targetName,
kind: node.kind || targetKind,
@@ -231,4 +275,15 @@ export async function collectFacts(
stale,
diagnostics,
};
+ if (forExplain) return facts;
+ const {
+ downstreamDependents: _downstreamDependents,
+ downstreamDepth: _downstreamDepth,
+ callList: _callList,
+ systemPath: _systemPath,
+ subsystemName: _subsystemName,
+ moduleName: _moduleName,
+ ...contextFacts
+ } = facts;
+ return { ...contextFacts, provenance };
}