Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat(client): send X-Correlation-Id

KageBinary5694a34ba6ad
diff --git a/docs-site/src/content/docs/reference/configuration.md b/docs-site/src/content/docs/reference/configuration.md
index 629218f5..18b0e98a 100644
--- a/docs-site/src/content/docs/reference/configuration.md
+++ b/docs-site/src/content/docs/reference/configuration.md
@@ -20,7 +20,7 @@ ix config set format llm # set a value
| `IX_HOME` | Relocates everything under `~/.ix`, configuration included. Useful for giving a CI job or a second install its own state. It's read at use, not at install, so move `~/.ix` there rather than expecting the old configuration to be found |
| `IX_FORMAT` | Default output format: `text`, `json` or `llm`. Overrides the config file. `--format` overrides it |
| `IX_TOKEN=<token>` | Bearer token sent to the backend on every request, to any endpoint. Overrides the stored local token (see [Local token](#local-token)) |
-| `IX_DEBUG=1` | Prints full stack traces on errors |
+| `IX_DEBUG=1` | Prints full stack traces on errors, and one stderr line per backend request with the `X-Correlation-Id` it sent (the backend tags its request and slow-query logs with it). Every request of one `ix` run shares the id's prefix |
| `IX_READ_DEADLINE_MS=<ms>` | How long one command's reads may take in all before it fails (default 60000), so a hung backend fails a query in a minute rather than after each request's 2-minute timeout. The clock restarts after each write the command makes. `ix map`, `ix ingest` and `ix stats` have no read deadline. `0` turns it off. A read that meets a refused or dropped connection, or a 502/503/504, is retried once; writes never are |
| `IX_MCP_SUBPROCESS=1` | Runs each MCP tool call in its own `ix` process |
| `IX_COMMIT_FAILURE_LIMIT=<n>` | Consecutive failed commits before `ix map` stops (default 5). `0` never stops |
diff --git a/ix-cli/src/client/__tests__/correlation-id.test.ts b/ix-cli/src/client/__tests__/correlation-id.test.ts
new file mode 100644
index 00000000..3916bd3e
--- /dev/null
+++ b/ix-cli/src/client/__tests__/correlation-id.test.ts
@@ -0,0 +1,105 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { createServer, type IncomingHttpHeaders, type Server } from "node:http";
+import { IxClient } from "../api.js";
+import {
+ ACCEPTED_CORRELATION_ID,
+ CORRELATION_ID_HEADER,
+ debugRequest,
+ invocationCorrelationId,
+ nextCorrelationId,
+} from "../correlation.js";
+
+/**
+ * Every request carries an X-Correlation-Id the backend will keep (it
+ * replaces anything outside 1-64 of `[A-Za-z0-9._-]` with its own UUID), so
+ * its slow-query and request logs can be matched to one `ix` run.
+ */
+
+let server: Server;
+let endpoint: string;
+const seen: Array<{ method?: string; url?: string; headers: IncomingHttpHeaders }> = [];
+
+beforeAll(async () => {
+ server = createServer((req, res) => {
+ seen.push({ method: req.method, url: req.url, headers: req.headers });
+ req.resume();
+ req.on("end", () => {
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ status: "ok", results: [], nodes: [], edges: [], rev: 1 }));
+ });
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ const addr = server.address();
+ endpoint = `http://127.0.0.1:${typeof addr === "object" && addr ? addr.port : 0}`;
+});
+
+afterAll(async () => {
+ await new Promise<void>((r) => server.close(() => r()));
+});
+
+afterEach(() => {
+ seen.length = 0;
+ vi.restoreAllMocks();
+});
+
+const header = (h: IncomingHttpHeaders) => h[CORRELATION_ID_HEADER.toLowerCase()] as string | undefined;
+
+describe("correlation ids", () => {
+ it("are <invocation>.<n>, always within what the backend accepts", () => {
+ const a = nextCorrelationId();
+ const b = nextCorrelationId();
+ expect(a).not.toBe(b);
+ for (const id of [a, b]) {
+ expect(id).toMatch(ACCEPTED_CORRELATION_ID);
+ expect(id.startsWith(`${invocationCorrelationId()}.`)).toBe(true);
+ }
+ expect(Number(b.split(".")[1])).toBe(Number(a.split(".")[1]) + 1);
+ // Room to spare: a 36-character UUID, a dot, and a sequence number.
+ expect(`${invocationCorrelationId()}.${Number.MAX_SAFE_INTEGER}`.length).toBeLessThanOrEqual(64);
+ });
+
+ it("go out on every request, GET and POST, one per request", async () => {
+ const client = new IxClient(endpoint);
+ await client.health();
+ await client.search("x");
+ await client.commitPatchBulk([]);
+ expect(seen).toHaveLength(3);
+ const ids = seen.map((r) => header(r.headers));
+ for (const id of ids) {
+ expect(id).toMatch(ACCEPTED_CORRELATION_ID);
+ expect(id?.startsWith(`${invocationCorrelationId()}.`)).toBe(true);
+ }
+ expect(new Set(ids).size).toBe(3);
+ });
+
+ it("go out alongside the token, not instead of it", async () => {
+ const client = new IxClient(endpoint, undefined, { token: "t" });
+ await client.health();
+ expect(seen[0].headers.authorization).toBe("Bearer t");
+ expect(header(seen[0].headers)).toMatch(ACCEPTED_CORRELATION_ID);
+ });
+
+ it("are written to stderr under IX_DEBUG=1, without the query string", () => {
+ const lines: string[] = [];
+ vi.spyOn(process.stderr, "write").mockImplementation((s: string | Uint8Array) => { lines.push(String(s)); return true; });
+ debugRequest("POST", "/v1/search?q=secret", "abc.1", { IX_DEBUG: "1" });
+ debugRequest("GET", "/v1/health", "abc.2", {});
+ expect(lines).toEqual(["[debug] POST /v1/search X-Correlation-Id: abc.1\n"]);
+ });
+
+ it("the client logs each request's id under IX_DEBUG=1", async () => {
+ const saved = process.env.IX_DEBUG;
+ process.env.IX_DEBUG = "1";
+ const lines: string[] = [];
+ vi.spyOn(process.stderr, "write").mockImplementation((s: string | Uint8Array) => { lines.push(String(s)); return true; });
+ try {
+ await new IxClient(endpoint).health();
+ } finally {
+ if (saved === undefined) delete process.env.IX_DEBUG;
+ else process.env.IX_DEBUG = saved;
+ }
+ expect(lines).toEqual([`[debug] GET /v1/health X-Correlation-Id: ${header(seen[0].headers)}\n`]);
+ });
+});
diff --git a/ix-cli/src/client/api.ts b/ix-cli/src/client/api.ts
index 491ba17c..1fea468c 100644
--- a/ix-cli/src/client/api.ts
+++ b/ix-cli/src/client/api.ts
@@ -2,6 +2,7 @@
import { isPreConnectionFailure, RESET_RECONCILIATION_ERROR } from "./transport.js";
import { Limiter, RequestMemo } from "./request-memo.js";
+import { CORRELATION_ID_HEADER, debugRequest, nextCorrelationId } from "./correlation.js";
import type {
IngestResult,
StructuredContext,
@@ -119,13 +120,18 @@ export class IxClient {
/**
* The headers of every request: the JSON content type when there is a body,
- * and the bearer token when the client has one. The one place either is set,
- * so no request can go out without the token.
+ * the bearer token when the client has one, and a fresh X-Correlation-Id
+ * (see correlation.ts). The one place any of them is set, so no request can
+ * go out without the token. Under IX_DEBUG the request and its id are
+ * written to stderr, to match against the backend's logs.
*/
- private headers(json: boolean): Record<string, string> {
+ private headers(json: boolean, method: string, path: string): Record<string, string> {
const headers: Record<string, string> = {};
if (json) headers["Content-Type"] = "application/json";
if (this.token) headers.Authorization = `Bearer ${this.token}`;
+ const id = nextCorrelationId();
+ headers[CORRELATION_ID_HEADER] = id;
+ debugRequest(method, path, id);
return headers;
}
@@ -184,7 +190,7 @@ export class IxClient {
async ingest(path: string, recursive?: boolean, force?: boolean): Promise<IngestResult> {
const resp = await fetch(`${this.endpoint}/v1/ingest`, {
method: "POST",
- headers: this.headers(true),
+ headers: this.headers(true, "POST", "/v1/ingest"),
body: JSON.stringify({ path, recursive, force: force || undefined }),
signal: this.signalFor(30 * 60 * 1000), // 30 minute timeout for large repos
});
@@ -377,7 +383,7 @@ export class IxClient {
async commitPatch(patch: GraphPatchPayload): Promise<PatchCommitResult> {
const resp = await fetch(`${this.endpoint}/v1/patch`, {
method: 'POST',
- headers: this.headers(true),
+ headers: this.headers(true, "POST", "/v1/patch"),
body: JSON.stringify(patch),
signal: this.signalFor(5 * 60 * 1000), // 5 min — matches commitPatchBulk
});
@@ -445,7 +451,7 @@ export class IxClient {
if (opts?.systemId) body.system_id = opts.systemId;
const resp = await fetch(`${this.endpoint}/v1/map`, {
method: "POST",
- headers: this.headers(true),
+ headers: this.headers(true, "POST", "/v1/map"),
body: JSON.stringify(body),
signal: this.signalFor(30 * 60 * 1000), // 30 minute timeout
});
@@ -459,7 +465,7 @@ export class IxClient {
async commitPatchBulk(patches: GraphPatchPayload[]): Promise<PatchCommitResult> {
const resp = await fetch(`${this.endpoint}/v1/patches/bulk`, {
method: 'POST',
- headers: this.headers(true),
+ headers: this.headers(true, "POST", "/v1/patches/bulk"),
body: JSON.stringify({ patches }),
signal: this.signalFor(5 * 60 * 1000), // 5 min — prevents hang when k8s ingress closes idle connections
});
@@ -591,7 +597,7 @@ export class IxClient {
// A redirect can replay a destructive POST or hide an accepted reset
// behind a later connection failure/404. Inspect the first response.
redirect: "manual",
- headers: this.headers(true),
+ headers: this.headers(true, "POST", asyncPath),
body: JSON.stringify({}),
signal: AbortSignal.timeout(30 * 1000),
});
@@ -637,7 +643,7 @@ export class IxClient {
statusResp = await fetch(`${this.endpoint}/v1/reset/status/${opId}`, {
method: "GET",
redirect: "manual",
- headers: this.headers(false),
+ headers: this.headers(false, "GET", `/v1/reset/status/${opId}`),
signal: AbortSignal.timeout(30 * 1000),
});
} catch (error) {
@@ -714,7 +720,7 @@ export class IxClient {
const resp = await fetch(`${this.endpoint}${syncPath}`, {
method: "POST",
redirect: "manual",
- headers: this.headers(true),
+ headers: this.headers(true, "POST", syncPath),
body: JSON.stringify({}),
signal: AbortSignal.timeout(10 * 60 * 1000),
});
@@ -737,7 +743,7 @@ export class IxClient {
async savingsReset(): Promise<any> {
const resp = await fetch(`${this.endpoint}/v1/savings`, {
method: "DELETE",
- headers: this.headers(false),
+ headers: this.headers(false, "DELETE", "/v1/savings"),
});
if (!resp.ok) {
const text = await resp.text();
@@ -787,7 +793,7 @@ export class IxClient {
return this.read<T>("POST", path, payload, () =>
fetch(`${this.endpoint}${path}`, {
method: "POST",
- headers: this.headers(true),
+ headers: this.headers(true, "POST", path),
body: payload,
// These small reads/writes (source-hashes, stitch, list, ...) had no
// timeout, so a stalled connection could hang the process indefinitely.
@@ -800,7 +806,7 @@ export class IxClient {
private async get<T>(path: string, timeoutMs = 2 * 60 * 1000): Promise<T> {
return this.read<T>("GET", path, "", () =>
fetch(`${this.endpoint}${path}`, {
- headers: this.headers(false),
+ headers: this.headers(false, "GET", path),
signal: this.signalFor(timeoutMs, true),
}));
}
diff --git a/ix-cli/src/client/correlation.ts b/ix-cli/src/client/correlation.ts
new file mode 100644
index 00000000..e1970846
--- /dev/null
+++ b/ix-cli/src/client/correlation.ts
@@ -0,0 +1,48 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { randomUUID } from "node:crypto";
+
+/**
+ * The X-Correlation-Id this CLI sends on every backend request.
+ *
+ * The backend tags its request log, error bodies and slow-query log (AQL that
+ * runs long) with the request's correlation id, and reuses an inbound one only
+ * when it is 1-64 characters of `[A-Za-z0-9._-]`; anything else is replaced by
+ * a fresh UUID. So the id is `<invocation>.<n>`: one random UUID per process
+ * (36 characters), then the request's sequence number. Every request of one
+ * `ix` run shares the prefix, so the backend's log for that run is one grep,
+ * and each request is still told apart.
+ *
+ * Sent to every endpoint. It is an opaque random value tied to nothing on the
+ * machine, kOS's edge forwards it untouched, and Ix-memory validates it as
+ * above.
+ */
+export const CORRELATION_ID_HEADER = "X-Correlation-Id";
+
+/** What the backend accepts as an inbound id (Ix-memory CorrelationIdMiddleware). */
+export const ACCEPTED_CORRELATION_ID = /^[A-Za-z0-9._-]{1,64}$/;
+
+const invocationId = randomUUID();
+let sequence = 0;
+
+/** This process's prefix: every request id it sends starts with it. */
+export function invocationCorrelationId(): string {
+ return invocationId;
+}
+
+/** The id for the next request: `<invocation>.<n>`. */
+export function nextCorrelationId(): string {
+ sequence += 1;
+ return `${invocationId}.${sequence}`;
+}
+
+/**
+ * Under IX_DEBUG=1, one stderr line per request naming its id, so a failure or
+ * a slow query can be found in the backend's log. The query string is left
+ * out: it can carry the user's search text.
+ */
+export function debugRequest(method: string, path: string, id: string, env: NodeJS.ProcessEnv = process.env): void {
+ if (env.IX_DEBUG !== "1") return;
+ const bare = path.split("?", 1)[0];
+ process.stderr.write(`[debug] ${method} ${bare} ${CORRELATION_ID_HEADER}: ${id}\n`);
+}