Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix(cli): honest paging at the /v1/expand edge cap (HR-02A)

KageBinary6cc2024b0080
diff --git a/ix-cli/src/cli/__tests__/edge-server-cap.test.ts b/ix-cli/src/cli/__tests__/edge-server-cap.test.ts
new file mode 100644
index 00000000..efc31a57
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/edge-server-cap.test.ts
@@ -0,0 +1,120 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Command } from "commander";
+
+import {
+ EXPAND_MAX_EDGES, expandCapped, renderEdgeResultsLlm, sliceEdgeResults, truncationHint,
+} from "../format.js";
+import { registerContainsCommand } from "../commands/contains.js";
+
+/**
+ * /v1/expand returns at most EXPAND_MAX_EDGES edges. A list that reached the
+ * cap is not known to end there, so paging must not call an offset past the
+ * end, and the count it prints is a floor.
+ */
+
+const { expand } = vi.hoisted(() => ({ expand: vi.fn() }));
+vi.mock("../../client/factory.js", () => ({
+ createClient: () => ({ expand: (...args: unknown[]) => expand(...args) }),
+}));
+vi.mock("../resolve.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../resolve.js")>(),
+ resolveFileOrReport: async () => ({ id: "11111111-0000-0000-0000-000000000000", kind: "class", name: "Big", resolutionMode: "exact" }),
+ printResolved: () => {},
+}));
+
+function node(i: number) {
+ return { id: `${i.toString(16).padStart(8, "0")}-2222-0000-0000-000000000000`, name: `m${i}`, kind: "method", provenance: { source_uri: "src/big.ts" } };
+}
+
+const full = () => Array.from({ length: EXPAND_MAX_EDGES }, (_, i) => node(i));
+
+describe("expandCapped", () => {
+ it("trusts the server's truncated flag", () => {
+ expect(expandCapped({ nodes: [node(1)], edges: [{}], truncated: true })).toBe(true);
+ });
+
+ it("treats a full cap of edges or nodes as cut, for servers that send no flag", () => {
+ expect(expandCapped({ nodes: [node(1)], edges: Array.from({ length: EXPAND_MAX_EDGES }, () => ({})) })).toBe(true);
+ expect(expandCapped({ nodes: full(), edges: [] })).toBe(true);
+ });
+
+ it("is false below the cap", () => {
+ expect(expandCapped({ nodes: full().slice(1), edges: full().slice(1) })).toBe(false);
+ });
+});
+
+describe("edge paging at the server cap", () => {
+ it("an offset at the cap is not past the end", () => {
+ const s = sliceEdgeResults(full(), 50, EXPAND_MAX_EDGES, true);
+ expect(s).toMatchObject({ rows: [], total: EXPAND_MAX_EDGES, truncated: true, capped: true });
+ expect(s.nextOffset).toBeUndefined();
+ const lines = renderEdgeResultsLlm(s, "callers", "t", "graph");
+ expect(lines.some((l) => l.includes("offset_past_end") || l.includes("no_edges"))).toBe(false);
+ expect(lines[1]).toBe(
+ "diagnostic code=results_truncated message=\"At least 1000 callers (the server returns at most 1000 edges); "
+ + "--offset 1000 is beyond the rows it returned. Narrow the target with --kind or --path to see the rest.\"",
+ );
+ });
+
+ it("the page that reaches the cap stays truncated and says why there is no next page", () => {
+ const s = sliceEdgeResults(full(), 50, 950, true);
+ expect(s).toMatchObject({ shown: 50, truncated: true });
+ expect(s.nextOffset).toBeUndefined();
+ expect(truncationHint(s, "callers")).toBe(
+ "At least 1000 callers (the server returns at most 1000 edges); showing 951-1000, the end of what it returned. "
+ + "Narrow the target with --kind or --path to see the rest.",
+ );
+ });
+
+ it("a page inside the cap still points at the next page, with the count as a floor", () => {
+ const s = sliceEdgeResults(full(), 50, 0, true);
+ expect(s.nextOffset).toBe(50);
+ expect(truncationHint(s, "callers")).toBe("At least 1000 callers (the server returns at most 1000 edges); showing 50. next: --offset 50");
+ });
+
+ it("leaves an uncapped list alone", () => {
+ const s = sliceEdgeResults(full().slice(1), 50, 2000);
+ expect(s.capped).toBeUndefined();
+ expect(renderEdgeResultsLlm(s, "callers", "t", "graph").some((l) => l.startsWith("diagnostic code=offset_past_end"))).toBe(true);
+ });
+});
+
+describe("ix contains against a capped expand", () => {
+ beforeEach(() => { expand.mockReset(); });
+ afterEach(() => vi.restoreAllMocks());
+
+ async function run(args: string[]): Promise<string[]> {
+ const program = new Command().name("ix").exitOverride();
+ registerContainsCommand(program);
+ const output: string[] = [];
+ vi.spyOn(console, "log").mockImplementation((...parts) => { output.push(parts.join(" ")); });
+ await program.parseAsync(["contains", "Big", ...args], { from: "user" });
+ return output;
+ }
+
+ it("llm: --offset past the cap keeps truncated and names the cap", async () => {
+ expand.mockResolvedValue({ nodes: full(), edges: [], truncated: true });
+ const out = await run(["--offset", "1500", "--format", "llm"]);
+ expect(out[0]).toBe("contains target=Big offset=1500 shown=0 total=1000 resolved=0");
+ expect(out[1]).toContain("code=results_truncated");
+ expect(out[1]).toContain("the server returns at most 1000 edges");
+ expect(out.some((l) => l.includes("offset_past_end"))).toBe(false);
+ });
+
+ it("json: the summary marks the total as capped", async () => {
+ expand.mockResolvedValue({ nodes: full(), edges: [] });
+ const json = JSON.parse((await run(["--offset", "1000", "--format", "json"])).join("\n"));
+ expect(json.summary).toMatchObject({ shown: 0, total: 1000, truncated: true, capped: true, offset: 1000 });
+ expect(json.summary.nextOffset).toBeUndefined();
+ expect(json.diagnostics.map((d: { code: string }) => d.code)).toEqual(["results_truncated"]);
+ });
+
+ it("an uncapped list still reports offset_past_end", async () => {
+ expand.mockResolvedValue({ nodes: full().slice(0, 10), edges: [], truncated: false });
+ const json = JSON.parse((await run(["--offset", "20", "--format", "json"])).join("\n"));
+ expect(json.summary.capped).toBeUndefined();
+ expect(json.diagnostics.map((d: { code: string }) => d.code)).toEqual(["offset_past_end"]);
+ });
+});
diff --git a/ix-cli/src/cli/commands/callers.ts b/ix-cli/src/cli/commands/callers.ts
index 034384c0..67d93da7 100644
--- a/ix-cli/src/cli/commands/callers.ts
+++ b/ix-cli/src/cli/commands/callers.ts
@@ -6,7 +6,7 @@ import type { Command } from "commander";
import chalk from "chalk";
import { createClient } from "../../client/factory.js";
import { resolveWorkspaceRoot } from "../config.js";
-import { formatEdgeResults, printJson, relativePath, sliceEdgeResults, type Diagnostic } from "../format.js";
+import { expandCapped, formatEdgeResults, printJson, relativePath, sliceEdgeResults, type Diagnostic } from "../format.js";
import { checkGraphHealth, graphHealthProse, isUnhealthy, type GraphHealth } from "../graph-health.js";
import { parsePickOption } from "../options.js";
import { nextPageCommand, OFFSET_FLAG, parseOffset } from "../paging.js";
@@ -167,7 +167,7 @@ export function registerCallersCommand(program: Command): void {
// Both graph and text empty (also the health-gated path: --offset does not apply).
formatEdgeResults(sliceEdgeResults([], limit), "callers", target.name, opts.format, target, "graph", health.diagnostics);
} else {
- const slice = sliceEdgeResults(result.nodes, limit, offset);
+ const slice = sliceEdgeResults(result.nodes, limit, offset, expandCapped(result));
if (slice.nextOffset !== undefined) slice.next = nextPageCommand(cmd, [symbol], slice.nextOffset);
const site = await edgeTargetFor(client, target, "callers");
formatEdgeResults({ ...slice, rows: withEdgeSites(slice.rows, "callers", site) }, "callers", target.name, opts.format, target, "graph", health.diagnostics);
@@ -200,7 +200,7 @@ export function registerCallersCommand(program: Command): void {
});
const health = await healthDiagnostics(healthCheck);
bannerOverRows(health, opts.format, result.nodes.length);
- const slice = sliceEdgeResults(result.nodes, calleeLimit, calleeOffset);
+ const slice = sliceEdgeResults(result.nodes, calleeLimit, calleeOffset, expandCapped(result));
if (slice.nextOffset !== undefined) slice.next = nextPageCommand(cmd, [symbol], slice.nextOffset);
const site = await edgeTargetFor(client, target, "callees");
formatEdgeResults({ ...slice, rows: withEdgeSites(slice.rows, "callees", site) }, "callees", target.name, opts.format, target, "graph", health.diagnostics);
diff --git a/ix-cli/src/cli/commands/contains.ts b/ix-cli/src/cli/commands/contains.ts
index f41a7b7c..61e5a996 100644
--- a/ix-cli/src/cli/commands/contains.ts
+++ b/ix-cli/src/cli/commands/contains.ts
@@ -2,7 +2,7 @@
import type { Command } from "commander";
import { createClient } from "../../client/factory.js";
-import { formatEdgeResults, sliceEdgeResults } from "../format.js";
+import { expandCapped, formatEdgeResults, sliceEdgeResults } from "../format.js";
import { parsePickOption } from "../options.js";
import { nextPageCommand, OFFSET_FLAG, parseOffset } from "../paging.js";
import { resolveFileOrReport, printResolved } from "../resolve.js";
@@ -27,7 +27,7 @@ export function registerContainsCommand(program: Command): void {
if (!target) return;
if (opts.format === "text") printResolved(target);
const result = await client.expand(target.id, { direction: "out", predicates: ["CONTAINS"] });
- const slice = sliceEdgeResults(result.nodes, limit, offset);
+ const slice = sliceEdgeResults(result.nodes, limit, offset, expandCapped(result));
if (slice.nextOffset !== undefined) slice.next = nextPageCommand(cmd, [symbol], slice.nextOffset);
formatEdgeResults(slice, "contains", target.name, opts.format, target, "graph");
});
diff --git a/ix-cli/src/cli/commands/imports.ts b/ix-cli/src/cli/commands/imports.ts
index d44fd8e7..8de20b99 100644
--- a/ix-cli/src/cli/commands/imports.ts
+++ b/ix-cli/src/cli/commands/imports.ts
@@ -2,7 +2,7 @@
import type { Command } from "commander";
import { createClient } from "../../client/factory.js";
-import { formatEdgeResults, sliceEdgeResults } from "../format.js";
+import { expandCapped, formatEdgeResults, sliceEdgeResults } from "../format.js";
import { resolveFileOrReport, printResolved } from "../resolve.js";
import { parsePickOption } from "../options.js";
import { nextPageCommand, OFFSET_FLAG, parseOffset } from "../paging.js";
@@ -28,7 +28,7 @@ export function registerImportsCommand(program: Command): void {
if (!target) return;
if (opts.format === "text") printResolved(target);
const result = await client.expand(target.id, { direction: "out", predicates: ["IMPORTS"] });
- const slice = sliceEdgeResults(result.nodes, limit, offset);
+ const slice = sliceEdgeResults(result.nodes, limit, offset, expandCapped(result));
if (slice.nextOffset !== undefined) slice.next = nextPageCommand(cmd, [symbol], slice.nextOffset);
const site = await edgeTargetFor(client, target, "imports");
formatEdgeResults({ ...slice, rows: withEdgeSites(slice.rows, "imports", site) }, "imports", target.name, opts.format, target, "graph");
@@ -53,7 +53,7 @@ export function registerImportsCommand(program: Command): void {
if (!target) return;
if (opts.format === "text") printResolved(target);
const result = await client.expand(target.id, { direction: "in", predicates: ["IMPORTS"] });
- const slice = sliceEdgeResults(result.nodes, limit, offset);
+ const slice = sliceEdgeResults(result.nodes, limit, offset, expandCapped(result));
if (slice.nextOffset !== undefined) slice.next = nextPageCommand(cmd, [symbol], slice.nextOffset);
const site = await edgeTargetFor(client, target, "imported-by");
formatEdgeResults({ ...slice, rows: withEdgeSites(slice.rows, "imported-by", site) }, "imported-by", target.name, opts.format, target, "graph");
diff --git a/ix-cli/src/cli/format.ts b/ix-cli/src/cli/format.ts
index 803af16d..879dc885 100644
--- a/ix-cli/src/cli/format.ts
+++ b/ix-cli/src/cli/format.ts
@@ -111,6 +111,11 @@ export interface Slice<T> {
nextOffset?: number;
/** The command that prints the next page, when the caller can build one. */
next?: string;
+ /**
+ * The server cut the list before this layer saw it, so `total` is a lower
+ * bound: more rows may exist past it, and no `--offset` can reach them.
+ */
+ capped?: boolean;
}
/**
@@ -165,26 +170,69 @@ function edgeRowPriority(node: any): number {
* caller a `locate` before it can be read. Neither should displace a row that
* carries both.
*/
-export function sliceEdgeResults(nodes: any[], limit: number, offset = 0): Slice<any> {
- return sliceRanked(nodes, limit, edgeRowPriority, offset);
+export function sliceEdgeResults(nodes: any[], limit: number, offset = 0, capped = false): Slice<any> {
+ const slice = sliceRanked(nodes, limit, edgeRowPriority, offset);
+ if (capped) {
+ slice.capped = true;
+ // The list is not known to end here, whatever this page holds.
+ slice.truncated = true;
+ }
+ return slice;
+}
+
+/**
+ * The most edges one /v1/expand call returns. The backend clamps the request's
+ * `limit` to this (Ix-memory ArangoGraphQueryApi.expand / expandWith:
+ * `maxEdges = min(limit, 1000)`, and ExpandRoutes defaults `limit` to 1000).
+ */
+export const EXPAND_MAX_EDGES = 1000;
+
+/**
+ * Whether an expand result may have been cut by the server's edge cap. The
+ * server says so in `truncated` when it is new enough to; an older one only
+ * shows it by returning a full cap's worth of edges or nodes.
+ */
+export function expandCapped(result: { nodes?: unknown[]; edges?: unknown[]; truncated?: unknown }): boolean {
+ return result.truncated === true
+ || (result.edges?.length ?? 0) >= EXPAND_MAX_EDGES
+ || (result.nodes?.length ?? 0) >= EXPAND_MAX_EDGES;
}
/** What was left out, and the one flag that gets it. */
export function truncationHint(slice: Slice<unknown>, relation: string): string {
const offset = slice.offset ?? 0;
+ if (slice.capped) return cappedHint(slice, relation);
const range = offset > 0 ? `${offset + 1}-${offset + slice.shown}` : `${slice.shown}`;
if (slice.nextOffset === undefined) return `${slice.total} ${relation}; showing ${range}. Raise --limit to see them.`;
const next = slice.next ?? `--offset ${slice.nextOffset}`;
return `${slice.total} ${relation}; showing ${range}. next: ${next}`;
}
+/**
+ * The hint for a list the server cut at EXPAND_MAX_EDGES: the count is a
+ * floor, and paging stops where the server's rows do.
+ */
+function cappedHint(slice: Slice<unknown>, relation: string): string {
+ const offset = slice.offset ?? 0;
+ const head = `At least ${slice.total} ${relation} (the server returns at most ${EXPAND_MAX_EDGES} edges)`;
+ if (slice.nextOffset !== undefined) {
+ const range = offset > 0 ? `${offset + 1}-${offset + slice.shown}` : `${slice.shown}`;
+ return `${head}; showing ${range}. next: ${slice.next ?? `--offset ${slice.nextOffset}`}`;
+ }
+ const where = slice.shown > 0
+ ? `showing ${offset > 0 ? `${offset + 1}-${offset + slice.shown}` : slice.shown}, the end of what it returned`
+ : offset > 0 ? `--offset ${offset} is beyond the rows it returned` : "showing 0";
+ return `${head}; ${where}. Narrow the target with --kind or --path to see the rest.`;
+}
+
/** The message for a page that starts at or past the end of the list. */
function pastEndMessage(slice: Slice<unknown>, relation: string): string {
return `${slice.total} ${relation}; --offset ${slice.offset ?? 0} is past the end.`;
}
function isPastEnd(slice: Slice<unknown>): boolean {
- return slice.total > 0 && (slice.offset ?? 0) >= slice.total;
+ // A capped list has no known end, so no offset is known to be past it.
+ return !slice.capped && slice.total > 0 && (slice.offset ?? 0) >= slice.total;
}
// ── Row locations ──────────────────────────────────────────────────────────
@@ -839,6 +887,8 @@ export function formatEdgeResults(
truncated: slice.truncated,
offset: slice.offset ?? 0,
...(slice.nextOffset !== undefined ? { nextOffset: slice.nextOffset } : {}),
+ // `total` is then a lower bound: the server stopped at its edge cap.
+ ...(slice.capped ? { capped: true } : {}),
};
printJson(output);
return;