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
fix(ingest): remove nodes the extractor no longer emits on same-content rebuilds (IN-20) (#850)
Ian Hock8e0b0471b12a
diff --git a/docs-site/src/content/docs/reference/configuration.md b/docs-site/src/content/docs/reference/configuration.mdindex 26834088..71247fba 100644--- a/docs-site/src/content/docs/reference/configuration.md+++ b/docs-site/src/content/docs/reference/configuration.md@@ -27,6 +27,9 @@ ix config set format llm # set a value| `IX_COMMIT_BASE_REV_RETRIES=<n>` | Re-sends of a commit after another writer on the same backend moved the graph revision under it (default 8) || `IX_PARSE_BUDGET_MS=<ms>` | How long `ix map` / `ix ingest` may spend parsing one file before skipping it and naming it in the summary (default 10000). A skipped file is tried again on every run, and `ix status` warns about it until it is in the graph. `0` turns the budget off || `IX_PARSE_WORKERS=<n>` | Most parse workers `ix map` / `ix ingest` starts (default 8, never more than the cores less one). Workers start as files need them, one per 50 files |+| `IX_RECONCILE_ON_FORCE=1` | Makes an `ix map --force` (or `ix ingest --force`) also remove nodes an earlier extractor wrote and the current one no longer does, at the files' current content. `ix map` does this by itself on the run after an extractor change, on a backend from 1.0.33 that applies deletes in bulk. Set this to finish a cleanup that run could not do (an older backend, since upgraded) or did not finish (its budget ran out): it reads only what was left. Without a record of what was left, it reads the patch of the extractor before the current one for every file |+| `IX_ORPHAN_SWEEP_MAX_MS=<ms>` | Time budget of that cleanup in one run (default 60000). Files past it are committed without the cleanup and named for the next `IX_RECONCILE_ON_FORCE=1` run |+| `IX_ORPHAN_SWEEP_MAX_REQUESTS=<n>` | Request budget of that cleanup in one run (default 25000): one stored-patch read per file, one node read per 1000 candidates || `IX_PATCH_ACTOR=<actor>` | The `actor` stamped on each graph patch `ix map` / `ix ingest` sends (default `ix/ingestion`; `ix ingest --github` uses `ix/github-ingest`). Set it to empty (`IX_PATCH_ACTOR=`) for a backend that authenticates writers and stamps the verified principal itself: such a backend rejects a non-empty actor that differs from the principal with 403 `body actor ... conflicts with verified principal`. Any other value is sent as the actor || `IX_LOAD_ALL_COMMANDS=1` | Loads every command module on each call, as releases before the start-up fast path did. Without Ix Pro installed, `ix <command>` normally loads only that command; with Ix Pro installed every call already loads everything, so this changes nothing there. If a command misbehaves on an install without Pro, try it again with this set: a difference between the two is a bug worth reporting |diff --git a/docs/api/README.md b/docs/api/README.mdindex 47d22838..52ac9c72 100644--- a/docs/api/README.md+++ b/docs/api/README.md@@ -448,6 +448,16 @@ Fetch a node with its claims and edges.**Response** — `{ node: GraphNode, claims: unknown[], edges: unknown[] }`.+#### POST `/v1/nodes`++Many nodes in one read, at the latest revision (Ix-memory 1.0.33+). Body+`{ ids: string[], fields?: "full" }`, at most 1000 ids (413 above that).+`fields: "full"` returns whole nodes, attrs and provenance included. `ix map`+uses it once per batch to check the nodes an extractor change left behind.++**Response** — `{ rev: number, nodes: GraphNode[], missing: string[] }`; only+live nodes are returned, every other id is in `missing`.+#### GET `/v1/resolve-prefix/{prefix}`Resolve a shortened entity id prefix. Full UUIDs pass through untouched.diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex 2808fcc8..dafa21e7 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -387,6 +387,35 @@ paths:claims: { type: array, items: { type: object } }edges: { type: array, items: { $ref: "#/components/schemas/GraphEdge" } }+ /v1/nodes:+ post:+ tags: [entities]+ summary: Fetch many live nodes in one read (Ix-memory 1.0.33+)+ operationId: getNodes+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required: [ids]+ properties:+ ids: { type: array, items: { type: string }, maxItems: 1000, description: Node ids (UUIDs) }+ fields: { type: string, enum: [full], description: "full returns whole nodes, attrs and provenance included" }+ responses:+ "200":+ description: The live nodes, and the ids that are not live+ content:+ application/json:+ schema:+ type: object+ properties:+ rev: { type: integer }+ nodes: { type: array, items: { $ref: "#/components/schemas/GraphNode" } }+ missing: { type: array, items: { type: string } }+ "413":+ description: More than 1000 ids+/v1/resolve-prefix/{prefix}:get:tags: [entities]diff --git a/ix-cli/src/cli/__tests__/helpers/fake-backend.ts b/ix-cli/src/cli/__tests__/helpers/fake-backend.tsindex 4dc28531..eb749ee1 100644--- a/ix-cli/src/cli/__tests__/helpers/fake-backend.ts+++ b/ix-cli/src/cli/__tests__/helpers/fake-backend.ts@@ -6,7 +6,7 @@ import { createHash } from "node:crypto";type SentPatch = {patchId?: string;- source?: { uri?: string; sourceHash?: string; workspaceId?: string };+ source?: { uri?: string; sourceHash?: string; workspaceId?: string; extractor?: string };ops?: Array<Record<string, unknown>>;};@@ -121,6 +121,28 @@ export class FakeBackend {rememberHashes = false;/** Answer `/v1/source-hashes` with a 500, as a backend under load does. */failSourceHashes = false;+ /**+ * Answer `GET /v1/patches/{id}` with a 500, as a backend under load does:+ * every read when true, or the reads the predicate picks (given the id and+ * the stored ops, if any).+ */+ failPatchReads: boolean | ((patchId: string, ops: Array<Record<string, unknown>> | undefined) => boolean) = false;+ /** Answer `GET /v1/patches/{id}` with a 404 for every id, as if nothing were stored. */+ hidePatchReads = false;+ /** `GET /v1/patches/{id}` requests served, whatever their answer. */+ patchReads = 0;+ /** `GET /v1/entity/{id}` requests served, whatever their answer. */+ entityReads = 0;+ /** `POST /v1/nodes` requests served, whatever their answer. */+ nodesReads = 0;+ /** Serve `POST /v1/nodes` (Ix-memory 1.0.33+); false answers 404, as an older backend does. */+ serveNodes = true;+ /**+ * Answer `GET /v1/patches/{id}` for a patch committed in bulk as the real+ * bulk route stores it -- an id manifest (`entityIds`, `nodeIds`,+ * `nodeOpCount`), no ops -- instead of with its ops.+ */+ bulkManifests = false;private readonly hashes = new Map<string, { workspaceId: string | null; uri: string; hash: string }>();/**@@ -153,7 +175,7 @@ export class FakeBackend {* report none, as a pre-#157 backend does. `null` reports none in any mode.*/releaseVersion: string | null | undefined = undefined;- private readonly nodes = new Map<string, { kind: unknown; name: unknown; attrs?: unknown; live: boolean }>();+ private readonly nodes = new Map<string, { kind: unknown; name: unknown; attrs?: unknown; uri?: string; hash?: string; extractor?: string; live: boolean }>();private readonly edges = new Map<string, {src: unknown; dst: unknown; predicate: unknown; workspaceId: string; uri: string; live: boolean;}>();@@ -229,7 +251,10 @@ export class FakeBackend {if (!deletesApplied) this.applyDeletes(patch);for (const op of patch.ops ?? []) {const id = String(op.id);- if (op.type === "UpsertNode") this.nodes.set(id, { kind: op.kind, name: op.name, attrs: op.attrs, live: true });+ if (op.type === "UpsertNode") {+ // As the bulk route does, every upsert takes the patch's provenance.+ this.nodes.set(id, { kind: op.kind, name: op.name, attrs: op.attrs, uri, hash: patch.source?.sourceHash, extractor: patch.source?.extractor, live: true });+ }else if (op.type === "UpsertEdge") {this.edges.set(id, { src: op.src, dst: op.dst, predicate: op.predicate, workspaceId, uri, live: true });}@@ -523,11 +548,54 @@ export class FakeBackend {if (path.startsWith("/v1/stitch/system/")) return send(200, { systemId: null });// Read by `reconcileRemovedEntities`, which only an incremental run against// a stored graph reaches.- if (this.semantics !== undefined && path.startsWith("/v1/patches/")) {- const record = this.stored.get(decodeURIComponent(path.slice("/v1/patches/".length)));- return record ? send(200, { data: { ops: record.ops } }) : send(404, { error: "404: patch not found" });+ // Without semantics nothing is stored, so every patch is not found: what a+ // forced or rebuilt file's reconcile sees, and survives.+ if (path.startsWith("/v1/patches/")) {+ const patchId = decodeURIComponent(path.slice("/v1/patches/".length));+ this.patchReads++;+ const record = this.stored.get(patchId);+ const fail = typeof this.failPatchReads === "function"+ ? this.failPatchReads(patchId, record?.ops)+ : this.failPatchReads;+ if (fail) return send(500, { error: "500: transaction begin timeout" });+ if (this.hidePatchReads) return send(404, { error: "404: patch not found" });+ if (!record) return send(404, { error: "404: patch not found" });+ if (this.bulkManifests && record.bulkGroup !== null) {+ // BulkWriteApi.patchDocument: ids in op order, no ops.+ const entityIds: string[] = [];+ const nodeIds: string[] = [];+ let nodeOpCount = 0;+ for (const op of record.ops) {+ const opId = String(op["id"] ?? op["entityId"]);+ if (op["type"] === "UpsertNode" || op["type"] === "DeleteNode") nodeOpCount++;+ if (op["type"] === "UpsertNode" && !nodeIds.includes(opId)) nodeIds.push(opId);+ if (!entityIds.includes(opId)) entityIds.push(opId);+ }+ return send(200, { data: { entityIds, nodeIds, nodeOpCount } });+ }+ return send(200, { data: { ops: record.ops } });+ }+ if (path === "/v1/nodes") {+ this.nodesReads++;+ if (!this.serveNodes) {+ return send(404, { error: `404: no such endpoint ${path}` });+ }+ let ids: string[] = [];+ try {+ ({ ids = [] } = JSON.parse(body) as { ids?: string[] });+ } catch { /* none */ }+ if (ids.length > 1000) return send(413, { error: "payload_too_large" });+ const nodes = ids.flatMap((id) => {+ const n = this.nodes.get(id);+ return n?.live+ ? [{ id, kind: n.kind, name: n.name, attrs: n.attrs ?? {}, provenance: { sourceUri: n.uri ?? "", sourceHash: n.hash, extractor: n.extractor } }]+ : [];+ });+ const found = new Set(nodes.map((n) => n.id));+ return send(200, { rev: this.rev, nodes, missing: ids.filter((id) => !found.has(id)) });}if (this.semantics !== undefined && path.startsWith("/v1/entity/")) {+ this.entityReads++;const id = decodeURIComponent(path.slice("/v1/entity/".length));const node = this.nodes.get(id);if (!node?.live) return send(404, { error: "404: entity not found" });diff --git a/ix-cli/src/cli/__tests__/ingest-baseline-rev.test.ts b/ix-cli/src/cli/__tests__/ingest-baseline-rev.test.tsindex de47d427..9a5d0aef 100644--- a/ix-cli/src/cli/__tests__/ingest-baseline-rev.test.ts+++ b/ix-cli/src/cli/__tests__/ingest-baseline-rev.test.ts@@ -5,9 +5,10 @@ import * as fs from "node:fs";import * as os from "node:os";import * as path from "node:path";-import { clearIngestMtimeCache, ingestMtimeCachePath, ingestRebuildPath } from "../config.js";+import { clearIngestMtimeCache, ingestMtimeCachePath, ingestOrphanSweepPath, ingestRebuildPath } from "../config.js";import {clearRebuildProgress, extractorChanged, loadIngestBaseline, loadRebuildProgress, saveIngestBaseline, saveRebuildProgress,+ loadOrphanSweepPending, saveOrphanSweepPending,} from "../ingest-baseline.js";import { advanceRev } from "../commands/ingest.js";@@ -178,3 +179,32 @@ describe("ingest baseline atomic write", () => {expect(fs.readdirSync(path.dirname(target)).filter(name => name.endsWith(".tmp"))).toEqual([]);});});++describe("unfinished orphan sweeps", () => {+ it("round-trip per root, drop empty entries, and go with the mtime cache", () => {+ const root = path.join(home, "p");+ expect(loadOrphanSweepPending(root).size).toBe(0);+ saveOrphanSweepPending(root, new Map<string, Set<string> | null>([+ ["tree-sitter/9.8", null],+ ["tree-sitter/9.7", new Set(["b.ts", "a.ts"])],+ ["tree-sitter/9.6", new Set()],+ ]));+ expect(loadOrphanSweepPending(root)).toEqual(new Map([+ ["tree-sitter/9.8", null],+ ["tree-sitter/9.7", new Set(["a.ts", "b.ts"])],+ ]));+ expect(loadOrphanSweepPending(path.join(home, "q")).size).toBe(0);++ // Nothing left: the file goes.+ saveOrphanSweepPending(root, new Map([["tree-sitter/9.7", new Set<string>()]]));+ expect(fs.existsSync(ingestOrphanSweepPath(root))).toBe(false);++ saveOrphanSweepPending(root, new Map([["tree-sitter/9.8", null]]));+ fs.writeFileSync(ingestOrphanSweepPath(root), "{\"root\":");+ expect(loadOrphanSweepPending(root).size).toBe(0);++ saveOrphanSweepPending(root, new Map([["tree-sitter/9.8", null]]));+ clearIngestMtimeCache(root);+ expect(fs.existsSync(ingestOrphanSweepPath(root))).toBe(false);+ });+});diff --git a/ix-cli/src/cli/__tests__/ingest-extractor-orphans.test.ts b/ix-cli/src/cli/__tests__/ingest-extractor-orphans.test.tsnew file mode 100644index 00000000..70915b78--- /dev/null+++ b/ix-cli/src/cli/__tests__/ingest-extractor-orphans.test.ts@@ -0,0 +1,745 @@+// Copyright 2026 Ix Infrastructure Inc.++import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { cpSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";++import { ingestFiles } from "../commands/ingest.js";+import { loadIngestionModules } from "../commands/ingestion-loader.js";+import { FakeBackend } from "./helpers/fake-backend.js";+import { initialRepo, render } from "./helpers/edit-fixture.js";++/**+ * IN-20. An extractor change re-ingests every file with the same bytes, so the+ * hash is unchanged and nothing reconciled the nodes the old extractor wrote+ * and the new one does not: they stayed live with no edges, and file deletion+ * never reached them either. The previous extractor's patch is made here by the+ * current parser plus one extra node of a kind the current extractor does not+ * write ("ghost"), under PREVIOUS_EXTRACTORS[0]'s patch id.+ *+ * `shared.on` adds one more node, SHARED, with the same id in every file: the+ * old extractor writes it from every file, the current one from+ * pkg/service.py only. It is still emitted, so no sweep may delete it.+ */++const GHOST = "ghost";++/** A node id as the patch builder makes them: a UUID. */+function uuidOf(text: string): string {+ const h = createHash("sha256").update(text).digest("hex");+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-8${h.slice(17, 20)}-${h.slice(20, 32)}`;+}+const SHARED = uuidOf("shared-node");++// `index` picks which earlier extractor plays the old one: PREVIOUS_EXTRACTORS[index].+const old = vi.hoisted(() => ({ on: false, index: 0 }));+const shared = vi.hoisted(() => ({ on: false }));++vi.mock("../commands/ingestion-loader.js", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../commands/ingestion-loader.js")>();+ return {+ ...actual,+ loadIngestionModules: async () => {+ const [ingestion, patchBuilder, languages] = await actual.loadIngestionModules();+ const sharedNode = { type: "UpsertNode", id: SHARED, kind: "function", name: "shared", attrs: {} };+ if (!old.on) {+ if (!shared.on) return [ingestion, patchBuilder, languages];+ return [ingestion, {+ ...patchBuilder,+ buildPatchWithResolution: (parsed: any, ...rest: any[]) => {+ const patch = (patchBuilder.buildPatchWithResolution as any)(parsed, ...rest);+ if (parsed.filePath === "pkg/service.py") patch.ops.push(sharedNode);+ return patch;+ },+ }, languages];+ }+ const previous = (patchBuilder as unknown as { PREVIOUS_EXTRACTORS: string[] }).PREVIOUS_EXTRACTORS[old.index]!;+ const asOldExtractor = {+ ...patchBuilder,+ extractorName: () => previous,+ buildPatchWithResolution: (parsed: any, hash: string, workspaceId: string, ...rest: any[]) => {+ const patch = (patchBuilder.buildPatchWithResolution as any)(parsed, hash, workspaceId, ...rest);+ patch.ops.push({ type: "UpsertNode", id: uuidOf(`ghost-${parsed.filePath}`), kind: GHOST, name: `ghost ${parsed.filePath}`, attrs: {} });+ if (shared.on) patch.ops.push(sharedNode);+ patch.patchId = patchBuilder.sourcePatchIdCandidates(parsed.filePath, hash, workspaceId)[old.index + 1];+ patch.source.extractor = previous;+ return patch;+ },+ };+ return [ingestion, asOldExtractor, languages];+ },+ };+});++vi.mock("node:os", async (importOriginal) => {+ const actual = await importOriginal<typeof import("node:os")>();+ return { ...actual, cpus: () => actual.cpus().slice(0, 3) };+});++const ENV_KEYS = [+ "HOME", "USERPROFILE", "IX_ENDPOINT", "IX_LOCK_DIR", "IX_HOME", "IX_DEBUG",+ "IX_COMMIT_FAILURE_LIMIT", "IX_COMMIT_HTTP_MAX_FILES", "IX_COMMIT_CONCURRENCY",+ "IX_STITCH_COOLDOWN_MS", "IX_STITCH_WAIT_MS", "IX_MAP_DEADLINE_MS",+ "IX_RECONCILE_ON_FORCE", "IX_ORPHAN_SWEEP_MAX_MS", "IX_ORPHAN_SWEEP_MAX_REQUESTS", "IX_BULK_DELETES",+] as const;++const FILES = ["pkg/util.py", "pkg/service.py", "web/math.ts"];++function ghosts(backend: FakeBackend): string[] {+ return backend.graphSignature().nodes.filter((line) => line.split(" ")[1] === GHOST);+}++describe.each(["head", "legacy"] as const)("an extractor change over the %s backend", (semantics) => {+ vi.setConfig({ testTimeout: 120_000 });++ const root = realpathSync.native(mkdtempSync(join(tmpdir(), "ix-extractor-orphans-")));+ const repoDir = join(root, "repo");+ const saved: Record<string, string | undefined> = {};++ beforeAll(() => {+ for (const k of ENV_KEYS) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+ mkdirSync(repoDir);+ execFileSync("git", ["init", "-q"], { cwd: repoDir, stdio: "ignore" });+ writeFiles();+ });+ afterAll(() => {+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ rmSync(root, { recursive: true, force: true });+ });++ function writeFiles(): void {+ for (const [p, fns] of initialRepo()) {+ if (!FILES.includes(p)) continue;+ mkdirSync(dirname(join(repoDir, p)), { recursive: true });+ writeFileSync(join(repoDir, p), render(p, fns), "utf8");+ }+ execFileSync("git", ["add", "-A"], { cwd: repoDir, stdio: "ignore" });+ }++ /** The run's stderr; `lastExitCode` holds the exit code it set. */+ let lastExitCode: number | string | undefined;++ /**+ * `reconcileOnForce` opts a --force run at the current extractor into the+ * same-hash reconcile (IX_RECONCILE_ON_FORCE=1); without it only an+ * extractor change runs it.+ */+ async function run(+ home: string,+ endpoint: string,+ { reconcileOnForce, ...extra }: { force?: boolean; debug?: boolean; reconcileOnForce?: boolean } = {},+ ): Promise<string> {+ mkdirSync(home, { recursive: true });+ if (reconcileOnForce) process.env.IX_RECONCILE_ON_FORCE = "1";+ else delete process.env.IX_RECONCILE_ON_FORCE;+ process.env.HOME = home;+ process.env.USERPROFILE = home;+ process.env.IX_ENDPOINT = endpoint;+ process.env.IX_LOCK_DIR = join(home, "locks");+ const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ const exitCodeBefore = process.exitCode;+ process.exitCode = undefined;+ try {+ await ingestFiles(repoDir, { recursive: true, format: "json", printSummary: false, suppressOutput: true, mapMode: true, ...extra });+ return stderr.mock.calls.map(([chunk]) => String(chunk)).join("");+ } finally {+ lastExitCode = process.exitCode;+ process.exitCode = exitCodeBefore;+ stderr.mockRestore();+ }+ }++ async function mapAsOld(home: string, endpoint: string): Promise<void> {+ old.on = true;+ try {+ await run(home, endpoint);+ } finally {+ old.on = false;+ }+ }++ /** A backend that takes deletes in bulk and serves the batched node read. */+ function newBackend(): FakeBackend {+ const backend = new FakeBackend({ semantics });+ backend.releaseVersion = "1.0.34";+ return backend;+ }++ function deleteNodesSent(backend: FakeBackend): number {+ return FILES.reduce((n, f) => n + (backend.lastOps.get(f) ?? []).filter((op) => op["type"] === "DeleteNode").length, 0);+ }++ function sweepNotices(log: string): string[] {+ return log.split("\n").filter((line) => line.includes("[orphans kept]"));+ }++ function restoreAll(): void {+ for (const f of FILES) rmSync(join(repoDir, f), { force: true });+ writeFiles();+ }++ it("retires what the new extractor no longer writes, then everything of a deleted file", async () => {+ const current = (await loadIngestionModules())[1].extractorName();+ const backend = newBackend();+ const home = join(root, `home-rebuild-${semantics}`);+ restoreAll();+ try {+ const endpoint = await backend.start();+ await mapAsOld(home, endpoint);+ expect(ghosts(backend)).toHaveLength(FILES.length);++ const log = await run(home, endpoint);+ expect(log).toContain("[extractor changed]");+ expect(log).toContain(`-> ${current}`);+ expect(ghosts(backend)).toEqual([]);++ // Delete a file: nothing for it stays live.+ rmSync(join(repoDir, "pkg/util.py"));+ execFileSync("git", ["add", "-A"], { cwd: repoDir, stdio: "ignore" });+ await run(home, endpoint);+ expect(backend.graphSignature().nodes.filter((line) => line.includes("util.py"))).toEqual([]);+ } finally {+ await backend.stop();+ }+ });++ it("--force at the current extractor retires the dropped kind when its patch was never committed", async () => {+ const backend = newBackend();+ const home = join(root, `home-force-${semantics}`);+ restoreAll();+ try {+ const endpoint = await backend.start();+ await mapAsOld(home, endpoint);+ expect(ghosts(backend)).toHaveLength(FILES.length);+ await run(home, endpoint, { force: true });+ expect(ghosts(backend)).toEqual([]);+ } finally {+ await backend.stop();+ }+ });++ it("a graph a pre-fix rebuild polluted is cleaned when the file is deleted at the same hash", async () => {+ const backend = newBackend();+ const home = join(root, `home-polluted-${semantics}`);+ restoreAll();+ try {+ const endpoint = await backend.start();+ await mapAsOld(home, endpoint);++ // The rebuild as it was before the fix: the current patch lands, nothing reconciles.+ backend.hidePatchReads = true;+ const log = await run(home, endpoint);+ backend.hidePatchReads = false;+ expect(log).not.toContain("[patch build error]");+ expect(ghosts(backend)).toHaveLength(FILES.length);++ rmSync(join(repoDir, "web/math.ts"));+ execFileSync("git", ["add", "-A"], { cwd: repoDir, stdio: "ignore" });+ await run(home, endpoint);+ expect(backend.graphSignature().nodes.filter((line) => line.includes("math.ts"))).toEqual([]);+ expect(ghosts(backend)).toHaveLength(FILES.length - 1);+ } finally {+ await backend.stop();+ }+ });++ it("--force repairs a graph whose current patch is already committed, under a salted patch id", async () => {+ const backend = newBackend();+ const home = join(root, `home-salted-${semantics}`);+ restoreAll();+ try {+ const endpoint = await backend.start();+ await mapAsOld(home, endpoint);+ backend.hidePatchReads = true;+ await run(home, endpoint);+ backend.hidePatchReads = false;+ expect(ghosts(backend)).toHaveLength(FILES.length);++ // A plain --force at the current extractor leaves them: no reconcile, no reads.+ backend.patchReads = 0;+ await run(home, endpoint, { force: true });+ expect(backend.patchReads).toBe(0);+ expect(ghosts(backend)).toHaveLength(FILES.length);++ await run(home, endpoint, { force: true, reconcileOnForce: true });+ expect(ghosts(backend)).toEqual([]);+ } finally {+ await backend.stop();+ }+ });++ it("lands the deletes for a file an earlier run already committed at the new extractor, under a salted id, idempotently", async () => {+ const backend = newBackend();+ const home = join(root, `home-precommitted-${semantics}`);+ const PY = FILES.filter((f) => f.endsWith(".py"));+ restoreAll();+ try {+ const endpoint = await backend.start();+ await mapAsOld(home, endpoint);+ // A partial run at the new extractor commits the Python files under+ // their deterministic ids without the deletes (here its sweep finds no+ // stored patch), and keeps the old extractor in the baseline.+ backend.hidePatchReads = true;+ await run(home, endpoint, { lang: "python" } as Parameters<typeof run>[2]);+ backend.hidePatchReads = false;+ expect(ghosts(backend)).toHaveLength(FILES.length);+ const deterministic = new Map(PY.map((f) => [f, backend.lastPatchIds.get(f)!]));++ // The next full run is an extractor change, not a repair. Its deletes+ // for the Python files must not go under the ids the backend holds.+ const before = join(root, `home-precommitted-${semantics}-before`);+ cpSync(home, before, { recursive: true });+ process.env.IX_COMMIT_HTTP_MAX_FILES = "1";+ try {+ const log = await run(home, endpoint);+ expect(log).toContain("[extractor changed]");+ expect(ghosts(backend)).toEqual([]);+ for (const f of PY) {+ expect(backend.lastOps.get(f)?.some((op) => op["type"] === "DeleteNode" && op["id"] === uuidOf(`ghost-${f}`))).toBe(true);+ expect(backend.lastPatchIds.get(f)).not.toBe(deterministic.get(f));+ }+ // A file no earlier run committed: its deletes go under its deterministic id.+ const math = backend.lastPatchIds.get("web/math.ts");+ expect(backend.lastOps.get("web/math.ts")?.some((op) => op["type"] === "DeleteNode")).toBe(true);+ const graph = backend.graphSignature();++ // The same extractor-change run again, from the same local state: the+ // sweep finds nothing left to delete, no file is salted, and the graph+ // does not change.+ rmSync(home, { recursive: true, force: true });+ cpSync(before, home, { recursive: true });+ await run(home, endpoint);+ for (const f of FILES) {+ expect(backend.lastOps.get(f)?.filter((op) => op["type"] === "DeleteNode")).toEqual([]);+ }+ for (const f of PY) expect(backend.lastPatchIds.get(f)).toBe(deterministic.get(f));+ expect(backend.lastPatchIds.get("web/math.ts")).toBe(math);+ expect(backend.graphSignature()).toEqual(graph);+ } finally {+ delete process.env.IX_COMMIT_HTTP_MAX_FILES;+ }+ } finally {+ await backend.stop();+ }+ });++ it("emits no DeleteNode on a later same-hash rebuild for a node an earlier reconcile already deleted", async () => {+ const backend = newBackend();+ const home = join(root, `home-redelete-${semantics}`);+ restoreAll();+ try {+ const endpoint = await backend.start();+ await mapAsOld(home, endpoint);+ await run(home, endpoint);+ expect(ghosts(backend)).toEqual([]);+ // The rebuild's reconcile deleted the ghosts, so its stored patch names+ // them as DeleteNode targets.+ for (const f of FILES) {+ expect(backend.lastOps.get(f)?.some((op) => op["type"] === "DeleteNode" && op["id"] === uuidOf(`ghost-${f}`))).toBe(true);+ }++ backend.resetRequests();+ const log = await run(home, endpoint, { force: true, reconcileOnForce: true });+ expect(log).not.toContain("[patch build error]");+ for (const f of FILES) {+ expect(backend.lastOps.get(f)?.filter((op) => op["type"] === "DeleteNode")).toEqual([]);+ }+ expect(ghosts(backend)).toEqual([]);+ } finally {+ await backend.stop();+ }+ });++ it("commits a forced file whose old-extractor patch cannot be read, skipping only the orphan cleanup", async () => {+ const backend = newBackend();+ const home = join(root, `home-second5xx-${semantics}`);+ restoreAll();+ try {+ const endpoint = await backend.start();+ await mapAsOld(home, endpoint);+ backend.hidePatchReads = true;+ await run(home, endpoint);+ backend.hidePatchReads = false;+ expect(ghosts(backend)).toHaveLength(FILES.length);++ // The current extractor's patch reads fine; only the old one, which+ // names the ghosts, fails.+ backend.failPatchReads = (_id, ops) => ops?.some((op) => op["kind"] === GHOST) ?? false;+ const log = await run(home, endpoint, { force: true, debug: true, reconcileOnForce: true });+ backend.failPatchReads = false;+ expect(log).not.toContain("[patch build error]");+ expect(log).toContain("[orphan reconcile skipped]");+ expect(lastExitCode ?? 0).toBe(0);+ expect(ghosts(backend)).toHaveLength(FILES.length);++ await run(home, endpoint, { force: true, reconcileOnForce: true });+ expect(ghosts(backend)).toEqual([]);+ } finally {+ await backend.stop();+ }+ });++ it("commits a rebuilt file whose stored patches are not found, without a patch build error", async () => {+ const backend = newBackend();+ const home = join(root, `home-besteffort-${semantics}`);+ restoreAll();+ try {+ const endpoint = await backend.start();+ await mapAsOld(home, endpoint);+ backend.resetRequests();+ backend.hidePatchReads = true;+ const log = await run(home, endpoint);+ expect(log).not.toContain("[patch build error]");+ expect(backend.acceptedPatches()).toBe(FILES.length);+ } finally {+ await backend.stop();+ }+ });++ it("commits a rebuilt file whose stored patches answer 500, with one skip line, no parse error and exit code 0", async () => {+ const backend = newBackend();+ const home = join(root, `home-5xx-${semantics}`);+ restoreAll();+ try {+ const endpoint = await backend.start();+ await mapAsOld(home, endpoint);+ backend.resetRequests();+ backend.failPatchReads = true;+ const log = await run(home, endpoint, { debug: true });+ backend.failPatchReads = false;+ expect(log).not.toContain("[patch build error]");+ expect(lastExitCode ?? 0).toBe(0);+ expect(backend.acceptedPatches()).toBe(FILES.length);+ for (const f of FILES) {+ expect(log.split("\n").filter((line) => line.includes(`[orphan reconcile skipped] ${f}:`))).toHaveLength(1);+ }+ // Best effort: the orphans stay until the next extractor change or an+ // opted-in --force.+ expect(ghosts(backend)).toHaveLength(FILES.length);++ await run(home, endpoint, { force: true, reconcileOnForce: true });+ expect(ghosts(backend)).toEqual([]);+ } finally {+ await backend.stop();+ }+ });++ it.each([+ ["an older release", "1.0.31"],+ ["1.0.32, which applies bulk deletes but has no batched node read", "1.0.32"],+ ["no release (a dev or self-built image)", null],+ ] as const)("against %s: no sweep, no extra request, the patches as built, one notice", async (_label, release) => {+ const backend = new FakeBackend({ semantics });+ backend.releaseVersion = release;+ const home = join(root, `home-old-${semantics}-${String(release)}`);+ restoreAll();+ try {+ const endpoint = await backend.start();+ await mapAsOld(home, endpoint);+ const singlesBefore = backend.singleCount;+ backend.resetRequests();+ backend.patchReads = 0;+ backend.nodesReads = 0;+ backend.entityReads = 0;+ const log = await run(home, endpoint);+ expect(log).toContain("[extractor changed]");+ expect(deleteNodesSent(backend)).toBe(0);+ expect(backend.patchReads).toBe(0);+ expect(backend.nodesReads).toBe(0);+ expect(backend.entityReads).toBe(0);+ expect(backend.singleCount).toBe(0);+ expect(singlesBefore).toBe(0);+ expect(backend.acceptedPatches()).toBe(FILES.length);+ const notices = sweepNotices(log);+ expect(notices).toHaveLength(1);+ expect(notices[0]).toContain(release === null ? "unversioned" : `release ${release}`);+ expect(ghosts(backend)).toHaveLength(FILES.length);+ expect(lastExitCode ?? 0).toBe(0);+ } finally {+ await backend.stop();+ }+ });++ it("deletes the orphans in the bulk commit, with one stored-patch read per file, one node read and no entity reads", async () => {+ const backend = newBackend();+ backend.bulkManifests = true;+ const home = join(root, `home-bulk-${semantics}`);+ restoreAll();+ try {+ const endpoint = await backend.start();+ await mapAsOld(home, endpoint);+ backend.resetRequests();+ backend.patchReads = 0;+ backend.nodesReads = 0;+ backend.entityReads = 0;+ const log = await run(home, endpoint);+ expect(sweepNotices(log)).toEqual([]);+ expect(ghosts(backend)).toEqual([]);+ expect(deleteNodesSent(backend)).toBe(FILES.length);+ expect(backend.singleCount).toBe(0);+ expect(backend.bulkCount).toBeGreaterThan(0);+ expect(backend.patchReads).toBeLessThanOrEqual(FILES.length);+ expect(backend.nodesReads).toBe(1);+ expect(backend.entityReads).toBe(0);+ } finally {+ await backend.stop();+ }+ });++ it("never deletes a node another file still emits", async () => {+ const backend = newBackend();+ backend.bulkManifests = true;+ const home = join(root, `home-shared-${semantics}`);+ restoreAll();+ shared.on = true;+ try {+ const endpoint = await backend.start();+ await mapAsOld(home, endpoint);+ expect(backend.graphSignature().nodes.some((line) => line.startsWith(`${SHARED} `))).toBe(true);+ // One file per commit, so no delete can hide behind another patch's+ // upsert in the same bulk request.+ process.env.IX_COMMIT_HTTP_MAX_FILES = "1";+ try {+ await run(home, endpoint);+ } finally {+ delete process.env.IX_COMMIT_HTTP_MAX_FILES;+ }+ expect(ghosts(backend)).toEqual([]);+ expect(backend.graphSignature().nodes.some((line) => line.startsWith(`${SHARED} `))).toBe(true);+ for (const f of FILES) {+ expect(backend.lastOps.get(f)?.some((op) => op["type"] === "DeleteNode" && op["id"] === SHARED)).toBe(false);+ }+ } finally {+ shared.on = false;+ await backend.stop();+ }+ });++ it("stops at its budget: the files past it commit as built, counted in one line", async () => {+ const backend = newBackend();+ const home = join(root, `home-budget-${semantics}`);+ restoreAll();+ try {+ const endpoint = await backend.start();+ await mapAsOld(home, endpoint);+ backend.patchReads = 0;+ process.env.IX_ORPHAN_SWEEP_MAX_REQUESTS = "1";+ let log: string;+ try {+ log = await run(home, endpoint);+ } finally {+ delete process.env.IX_ORPHAN_SWEEP_MAX_REQUESTS;+ }+ expect(backend.patchReads).toBe(1);+ const notices = sweepNotices(log);+ expect(notices).toHaveLength(1);+ expect(notices[0]).toContain(`${FILES.length - 1} file(s) were committed without it`);+ expect(ghosts(backend)).toHaveLength(FILES.length - 1);+ expect(backend.acceptedPatches()).toBeGreaterThanOrEqual(FILES.length);+ expect(lastExitCode ?? 0).toBe(0);+ } finally {+ await backend.stop();+ }+ });++ it("a repair after a budget-cut sweep reads only the files left, and each run picks up where the last stopped", async () => {+ const backend = newBackend();+ const home = join(root, `home-budget-resume-${semantics}`);+ restoreAll();+ const withBudget = async (requests: number, extra: Parameters<typeof run>[2] = {}): Promise<string> => {+ process.env.IX_ORPHAN_SWEEP_MAX_REQUESTS = String(requests);+ try {+ return await run(home, endpoint, extra);+ } finally {+ delete process.env.IX_ORPHAN_SWEEP_MAX_REQUESTS;+ }+ };+ let endpoint = "";+ try {+ endpoint = await backend.start();+ await mapAsOld(home, endpoint);+ const log = await withBudget(1);+ expect(sweepNotices(log)[0]).toContain("picks up where the last stopped");+ expect(ghosts(backend)).toHaveLength(FILES.length - 1);++ // Each repair under the same budget reads only a file still left.+ for (let left = FILES.length - 2; left >= 0; left--) {+ backend.patchReads = 0;+ await withBudget(1, { force: true, reconcileOnForce: true });+ expect(backend.patchReads).toBe(1);+ expect(ghosts(backend)).toHaveLength(left);+ }++ // Nothing left on record: a repair reads the extractor before the current, for every file.+ backend.patchReads = 0;+ await run(home, endpoint, { force: true, reconcileOnForce: true });+ expect(backend.patchReads).toBe(FILES.length);+ expect(lastExitCode ?? 0).toBe(0);+ } finally {+ await backend.stop();+ }+ });++ it("a repair after a backend upgrade reaches orphans an extractor more than one version back left", async () => {+ const backend = new FakeBackend({ semantics });+ backend.releaseVersion = "1.0.31";+ const home = join(root, `home-two-back-${semantics}`);+ restoreAll();+ try {+ const endpoint = await backend.start();+ old.index = 1;+ try {+ await mapAsOld(home, endpoint);+ } finally {+ old.index = 0;+ }+ expect(ghosts(backend)).toHaveLength(FILES.length);++ const log = await run(home, endpoint);+ expect(sweepNotices(log)).toHaveLength(1);+ expect(sweepNotices(log)[0]).toContain("After upgrading the backend");+ expect(ghosts(backend)).toHaveLength(FILES.length);++ backend.releaseVersion = "1.0.34";+ backend.patchReads = 0;+ await run(home, endpoint, { force: true, reconcileOnForce: true });+ expect(ghosts(backend)).toEqual([]);+ // One read per file: the patch the recorded extractor wrote, not every candidate.+ expect(backend.patchReads).toBe(FILES.length);+ } finally {+ await backend.stop();+ }+ });++ it("turns itself off for the run, with one notice, when the backend does not serve the batched node read", async () => {+ const backend = newBackend();+ backend.serveNodes = false;+ const home = join(root, `home-nonodes-${semantics}`);+ restoreAll();+ try {+ const endpoint = await backend.start();+ await mapAsOld(home, endpoint);+ const log = await run(home, endpoint);+ expect(sweepNotices(log)).toHaveLength(1);+ expect(sweepNotices(log)[0]).toContain("POST /v1/nodes");+ expect(deleteNodesSent(backend)).toBe(0);+ expect(ghosts(backend)).toHaveLength(FILES.length);+ expect(lastExitCode ?? 0).toBe(0);+ } finally {+ await backend.stop();+ }+ });+});++/**+ * The same-hash reconcile reads stored patches, so it must cost nothing where+ * no extractor changed: a plain --force made no patch reads before IN-20 and+ * an edited file made one, and both stay so.+ */+describe("the orphan reconcile's patch reads at an unchanged extractor", () => {+ vi.setConfig({ testTimeout: 120_000 });++ const COUNT = 200;+ const root = realpathSync.native(mkdtempSync(join(tmpdir(), "ix-reconcile-cost-")));+ const repoDir = join(root, "repo");+ const home = join(root, "home");+ const saved: Record<string, string | undefined> = {};++ beforeAll(() => {+ for (const k of ENV_KEYS) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+ mkdirSync(join(repoDir, "pkg"), { recursive: true });+ for (let i = 0; i < COUNT; i++) {+ writeFileSync(join(repoDir, "pkg", `m${i}.py`), `def f${i}(x):\n return x + ${i}\n`, "utf8");+ }+ execFileSync("git", ["init", "-q"], { cwd: repoDir, stdio: "ignore" });+ execFileSync("git", ["add", "-A"], { cwd: repoDir, stdio: "ignore" });+ mkdirSync(home, { recursive: true });+ });+ afterAll(() => {+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ rmSync(root, { recursive: true, force: true });+ });++ async function run(endpoint: string, force = false, runHome = home): Promise<void> {+ mkdirSync(runHome, { recursive: true });+ process.env.HOME = runHome;+ process.env.USERPROFILE = runHome;+ process.env.IX_ENDPOINT = endpoint;+ process.env.IX_LOCK_DIR = join(runHome, "locks");+ const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ const exitCodeBefore = process.exitCode;+ try {+ await ingestFiles(repoDir, { recursive: true, format: "json", printSummary: false, suppressOutput: true, mapMode: true, force });+ expect(process.exitCode ?? 0).toBe(0);+ } finally {+ process.exitCode = exitCodeBefore;+ stderr.mockRestore();+ }+ }++ it("an extractor upgrade over 200 files makes at most one stored-patch read per file, one node read per batch and no entity reads", async () => {+ const backend = new FakeBackend({ semantics: "head" });+ backend.bulkManifests = true;+ try {+ const endpoint = await backend.start();+ const upgradeHome = join(root, "home-upgrade");+ old.on = true;+ try {+ await run(endpoint, false, upgradeHome);+ } finally {+ old.on = false;+ }+ expect(backend.graphSignature().nodes.filter((line) => line.split(" ")[1] === GHOST)).toHaveLength(COUNT);+ backend.patchReads = 0;+ backend.nodesReads = 0;+ backend.entityReads = 0;+ const bulksBefore = backend.bulkCount;+ await run(endpoint, false, upgradeHome);+ expect(backend.patchReads).toBeLessThanOrEqual(COUNT);+ expect(backend.entityReads).toBe(0);+ // One batched node read per build batch that had candidates, and no+ // more batches than bulk commits.+ expect(backend.nodesReads).toBeGreaterThanOrEqual(1);+ expect(backend.nodesReads).toBeLessThanOrEqual(backend.bulkCount - bulksBefore);+ expect(backend.singleCount).toBe(0);+ expect(backend.graphSignature().nodes.filter((line) => line.split(" ")[1] === GHOST)).toEqual([]);+ } finally {+ await backend.stop();+ }+ });++ it("makes no patch reads on a plain --force over 200 files, and one for a single edited file", async () => {+ const backend = new FakeBackend({ semantics: "head" });+ try {+ const endpoint = await backend.start();+ await run(endpoint);+ expect(backend.acceptedPatches()).toBe(COUNT);++ backend.patchReads = 0;+ await run(endpoint, true);+ expect(backend.patchReads).toBe(0);++ writeFileSync(join(repoDir, "pkg", "m7.py"), "def f7(x):\n return x * 7\n", "utf8");+ backend.patchReads = 0;+ await run(endpoint);+ expect(backend.patchReads).toBe(1);+ } finally {+ await backend.stop();+ }+ });+});diff --git a/ix-cli/src/cli/__tests__/ingest-reconcile.test.ts b/ix-cli/src/cli/__tests__/ingest-reconcile.test.tsindex 66fcaf33..51cc68e3 100644--- a/ix-cli/src/cli/__tests__/ingest-reconcile.test.ts+++ b/ix-cli/src/cli/__tests__/ingest-reconcile.test.ts@@ -3,13 +3,18 @@import { describe, expect, it, vi } from "vitest";import * as nodePath from "node:path";-import type { GraphPatchPayload } from "../../client/types.js";+import type { GraphNode, GraphPatchPayload } from "../../client/types.js";import {+ BATCH_NODE_READS_SINCE,BULK_DELETES_SINCE,+ BatchNodeReadsUnsupported,backendAppliesBulkDeletes,+ orphanSweepBudget,+ orphanSweepUnsupportedReason,patchRequiresPerFileCommit,planDeletedFileRecovery,reconcileRemovedEntities,+ sweepOrphanNodes,} from "../commands/ingest.js";import { createLimiter } from "../tree-walk.js";@@ -324,4 +329,341 @@ describe("reconcileRemovedEntities", () => {).rejects.toThrow("has no entity manifest");expect(entity).not.toHaveBeenCalled();});++ describe("across the first two stored patches", () => {+ const notFound = () => Object.assign(new Error("404: patch not found"), { status: 404 });+ const ops = (...ids: string[]) => ({ data: { ops: ids.map(id => ({ type: "UpsertNode", id, kind: id.startsWith("h") ? "heading" : "function" })) } });+ const liveEntity = () => vi.fn().mockResolvedValue({ node: { kind: "function" }, claims: [], edges: [] });+ const deleted = (p: GraphPatchPayload) => p.ops.filter(o => o.type === "DeleteNode").map(o => o["id"]);++ it("emits DeleteNode on an unchanged-hash rebuild for ids the old extractor's patch has and the new one lacks", async () => {+ const getPatch = vi.fn(async (id: string) => {+ if (id === "current@H") throw notFound();+ return ops("a", "h1", "h2");+ });+ const entity = vi.fn().mockResolvedValue({+ node: { kind: "heading" }, claims: [],+ edges: [{ id: "e-h1", predicate: "CONTAINS", provenance: { sourceUri: "src/example.ts" } }],+ });+ const patch = patchWith([{ type: "UpsertNode", id: "a", kind: "function" }]);++ const reconciled = await reconcileRemovedEntities({ getPatch, entity }, patch, ["current@H", "old@H", "legacy@H"]);++ expect(deleted(reconciled)).toEqual(["h1", "h2"]);+ expect(reconciled.ops.filter(o => o.type === "DeleteEdge").map(o => o["id"])).toEqual(["e-h1"]);+ expect(entity.mock.calls.map(c => c[0])).toEqual(["h1", "h2"]);+ });++ it("merges the manifests of the first two existing candidates, primary order first", async () => {+ const getPatch = vi.fn(async (id: string) => (id === "current@H" ? ops("a", "b") : ops("a", "b", "h1", "h2")));+ const entity = liveEntity();+ const patch = patchWith([{ type: "UpsertNode", id: "a", kind: "function" }]);++ const reconciled = await reconcileRemovedEntities({ getPatch, entity }, patch, ["current@H", "old@H", "legacy@H"]);++ expect(deleted(reconciled)).toEqual(["b", "h1", "h2"]);+ });++ it("gives an id only the second manifest names no DeleteNode when it is already gone, but still deletes an absent primary id", async () => {+ const getPatch = vi.fn(async (id: string) => (id === "current@H" ? ops("b") : ops("b", "h1")));+ const entity = vi.fn().mockRejectedValue(notFound());+ const patch = patchWith([]);++ const reconciled = await reconcileRemovedEntities({ getPatch, entity }, patch, ["current@H", "old@H"]);++ expect(deleted(reconciled)).toEqual(["b"]);+ });++ it("reads no further than the window when a window candidate exists", async () => {+ const ids = Array.from({ length: 30 }, (_, i) => `c${i}`);+ const getPatch = vi.fn(async (id: string) => {+ if (id === "c0") return ops("a");+ throw notFound();+ });+ await reconcileRemovedEntities({ getPatch, entity: liveEntity() }, patchWith([]), ids);+ expect(getPatch.mock.calls.map(c => c[0]).sort()).toEqual(["c0", "c1"]);+ });++ it("walks the rest of the candidates when neither window candidate exists", async () => {+ const ids = ["c0", "c1", "c2", "c3"];+ const getPatch = vi.fn(async (id: string) => {+ if (id === "c2") return ops("a");+ throw notFound();+ });+ const reconciled = await reconcileRemovedEntities({ getPatch, entity: liveEntity() }, patchWith([]), ids);+ expect(deleted(reconciled)).toEqual(["a"]);+ expect(getPatch.mock.calls.map(c => c[0])).toEqual(["c0", "c1", "c2"]);++ await expect(+ reconcileRemovedEntities({ getPatch: vi.fn().mockRejectedValue(notFound()), entity: liveEntity() }, patchWith([]), ids),+ ).rejects.toThrow("Previous source patch was not found");+ });++ it("leaves chunks alone in map mode, across merged manifests", async () => {+ const getPatch = vi.fn(async (id: string) => {+ if (id === "current@H") return ops("a");+ return { data: { ops: [+ { type: "UpsertNode", id: "a", kind: "function" },+ { type: "UpsertNode", id: "chunk-L9", kind: "chunk" },+ { type: "UpsertNode", id: "h1", kind: "heading" },+ ] } };+ });+ const entity = vi.fn().mockResolvedValue({+ node: { kind: "heading" }, claims: [],+ edges: [{ id: "chunk-edge", predicate: "NEXT", provenance: { sourceUri: "src/example.ts" } }],+ });++ const reconciled = await reconcileRemovedEntities({ getPatch, entity }, patchWith([]), ["current@H", "old@H"], undefined, true);++ expect(entity.mock.calls.map(c => c[0]).sort()).toEqual(["a", "h1"]);+ expect(deleted(reconciled).sort()).toEqual(["a", "h1"]);+ expect(reconciled.ops.some(o => o["id"] === "chunk-L9")).toBe(false);+ expect(reconciled.ops.filter(o => o.type === "DeleteEdge")).toEqual([]);+ });++ it("skips a second patch with no entity manifest or a failed read, but fails when the read before any found patch fails", async () => {+ const entity = liveEntity();+ const noManifest = vi.fn(async (id: string) => (id === "current@H" ? ops("a") : { data: {} }));+ expect(deleted(await reconcileRemovedEntities({ getPatch: noManifest, entity }, patchWith([]), ["current@H", "old@H"]))).toEqual(["a"]);++ // The patch found first is the one the first-hit walk always used; a+ // backend error on the extra one only loses its extra ids, and says so.+ const second5xx = vi.fn(async (id: string) => {+ if (id === "current@H") return ops("a");+ throw Object.assign(new Error("500"), { status: 500 });+ });+ const onWindowSkipped = vi.fn();+ const reconciled = await reconcileRemovedEntities(+ { getPatch: second5xx, entity }, patchWith([]), ["current@H", "old@H"], undefined, false, undefined, { onWindowSkipped },+ );+ expect(deleted(reconciled)).toEqual(["a"]);+ expect(onWindowSkipped).toHaveBeenCalledTimes(1);+ expect(String(onWindowSkipped.mock.calls[0]![0])).toContain("old@H");++ // Nothing found before the failed read: the first-hit walk failed here too.+ const firstMissingSecond5xx = vi.fn(async (id: string) => {+ if (id === "current@H") throw notFound();+ throw Object.assign(new Error("500"), { status: 500 });+ });+ await expect(reconcileRemovedEntities({ getPatch: firstMissingSecond5xx, entity }, patchWith([]), ["current@H", "old@H"])).rejects.toThrow("500");++ const first5xx = vi.fn(async (id: string) => {+ if (id === "current@H") throw Object.assign(new Error("500"), { status: 500 });+ return ops("a");+ });+ await expect(reconcileRemovedEntities({ getPatch: first5xx, entity }, patchWith([]), ["current@H", "old@H"])).rejects.toThrow("500");+ });++ it("leaves the changed-hash path re-emitting an already-absent primary id, as before", async () => {+ const getPatch = vi.fn(async (id: string) => {+ if (id === "current@H") return { data: { ops: [{ type: "DeleteNode", id: "x" }, { type: "UpsertNode", id: "a", kind: "function" }] } };+ throw notFound();+ });+ const entity = vi.fn().mockRejectedValue(notFound());+ const reconciled = await reconcileRemovedEntities({ getPatch, entity }, patchWith([]), ["current@H", "old@H"]);+ expect(deleted(reconciled)).toEqual(["x", "a"]);+ });+ });+});++describe("sweepOrphanNodes (IN-20 same-hash sweep)", () => {+ const notFound = () => Object.assign(new Error("404: patch not found"), { status: 404 });+ const id = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`;+ const A = id(1), B = id(2), C = id(3), D = id(4), E = id(5), F = id(6), G = id(7);+ const node = (nid: string, over: Record<string, unknown> = {}): GraphNode => ({+ id: nid, kind: "function", name: nid, attrs: {}, provenance: { sourceUri: "src/example.ts" }, ...over,+ }) as unknown as GraphNode;+ const fileWith = (ops: GraphPatchPayload["ops"], uri = "src/example.ts") => {+ const patch = patchWith(ops);+ return { patch: { ...patch, source: { ...patch.source, uri } }, previousPatchIds: [`old@${uri}`] };+ };++ it("derives orphans from the stored node list with one patch read per file and one batched node read, no entity reads", async () => {+ // Bulk-stored manifests: ids only, no kinds.+ const getPatch = vi.fn(async (pid: string) => (pid === "old@src/example.ts"+ ? { data: { nodeIds: [A, B, C] } }+ : { data: { nodeIds: [D, E] } }));+ const nodes = vi.fn(async (ids: string[], _fields?: "full") => ({+ rev: 1,+ nodes: [node(B), node(C, { attrs: { external: true } }), node(E, { provenance: { sourceUri: "src/other.ts" } })]+ .filter(n => ids.includes(n.id)),+ missing: [],+ }));+ const budget = orphanSweepBudget({});+ const files = [+ fileWith([{ type: "UpsertNode", id: A, kind: "function" }]),+ fileWith([{ type: "UpsertNode", id: D, kind: "function" }], "src/other.ts"),+ ];++ const orphans = await sweepOrphanNodes({ getPatch, nodes }, files, { mapMode: false, budget });++ // B: live, written by this file -> deleted. C: external -> kept.+ // E: live and written by src/other.ts -> deleted for that file.+ expect(orphans).toEqual([[B], [E]]);+ expect(getPatch).toHaveBeenCalledTimes(2);+ expect(nodes).toHaveBeenCalledTimes(1);+ expect(nodes.mock.calls[0]![1]).toBe("full");+ expect(budget.requests).toBe(3);+ });++ it("never deletes a node another file wrote last, one a patch of the batch upserts, an absent one, or a chunk in map mode", async () => {+ const getPatch = vi.fn(async () => ({ data: { nodeIds: [A, B, C, D, E] } }));+ const nodes = vi.fn(async (_ids: string[], _fields?: "full") => ({+ rev: 1,+ nodes: [+ node(A, { provenance: { sourceUri: "src/elsewhere.ts" } }),+ node(B),+ node(D, { kind: "chunk" }),+ node(E),+ ],+ missing: [C],+ }));+ const orphans = await sweepOrphanNodes(+ { getPatch, nodes }, [fileWith([])], { mapMode: true, budget: orphanSweepBudget({}), batchUpserts: new Set([E]) },+ );+ expect(orphans).toEqual([[B]]);+ // E is upserted by the batch: not even looked up.+ expect((nodes.mock.calls[0] as unknown as [string[]])[0]).not.toContain(E);+ });++ it("uses the kinds a stored patch with ops recorded: no lookup for its externals or, in map mode, its chunks", async () => {+ const getPatch = vi.fn(async () => ({ data: { ops: [+ { type: "UpsertNode", id: A, kind: "function" },+ { type: "UpsertNode", id: B, kind: "chunk" },+ { type: "UpsertNode", id: C, kind: "function", attrs: { external: true } },+ { type: "DeleteNode", id: D },+ ] } }));+ const nodes = vi.fn(async (ids: string[], _fields?: "full") => ({ rev: 1, nodes: ids.map(i => node(i)), missing: [] }));+ const orphans = await sweepOrphanNodes({ getPatch, nodes }, [fileWith([])], { mapMode: true, budget: orphanSweepBudget({}) });+ // D was only deleted by the stored patch: not a node it wrote.+ expect(orphans).toEqual([[A]]);+ expect((nodes.mock.calls[0] as unknown as [string[]])[0]).toEqual([A]);+ });++ it("makes no node read when no file has a candidate, and skips a file whose patch is not found", async () => {+ const getPatch = vi.fn(async (pid: string) => {+ if (pid === "old@src/gone.ts") throw notFound();+ return { data: { nodeIds: [A] } };+ });+ const nodes = vi.fn();+ const onSkip = vi.fn();+ const orphans = await sweepOrphanNodes(+ { getPatch, nodes },+ [fileWith([{ type: "UpsertNode", id: A, kind: "function" }]), fileWith([], "src/gone.ts")],+ { mapMode: false, budget: orphanSweepBudget({}), onSkip },+ );+ expect(orphans).toEqual([[], []]);+ expect(nodes).not.toHaveBeenCalled();+ expect(onSkip).not.toHaveBeenCalled();+ });++ it("reports a failed patch or node read for the files it covers and deletes nothing for them", async () => {+ const getPatch = vi.fn(async (pid: string) => {+ if (pid === "old@src/bad.ts") throw new Error("500: transaction begin timeout");+ return { data: { nodeIds: [A] } };+ });+ const onSkip = vi.fn();+ const failingNodes = vi.fn().mockRejectedValue(new Error("500: busy"));+ const orphans = await sweepOrphanNodes(+ { getPatch, nodes: failingNodes }, [fileWith([]), fileWith([], "src/bad.ts")],+ { mapMode: false, budget: orphanSweepBudget({}), onSkip },+ );+ expect(orphans).toEqual([[], []]);+ expect(onSkip.mock.calls.map(c => String(c[1]))).toEqual(["500: transaction begin timeout", "node read failed: 500: busy"]);+ });++ it("throws BatchNodeReadsUnsupported when the backend has no batched node read", async () => {+ const getPatch = vi.fn(async () => ({ data: { nodeIds: [A] } }));+ const nodes = vi.fn().mockRejectedValue(new Error("404: no such endpoint /v1/nodes"));+ await expect(sweepOrphanNodes({ getPatch, nodes }, [fileWith([])], { mapMode: false, budget: orphanSweepBudget({}) }))+ .rejects.toBeInstanceOf(BatchNodeReadsUnsupported);+ });++ it("turns itself off, not silently empty, when the batched read leaves out provenance", async () => {+ const getPatch = vi.fn(async () => ({ data: { nodeIds: [A] } }));+ const nodes = vi.fn(async (ids: string[], _fields?: "full") => ({+ rev: 1, nodes: ids.map(i => node(i, { provenance: undefined })), missing: [],+ }));+ await expect(sweepOrphanNodes({ getPatch, nodes }, [fileWith([])], { mapMode: false, budget: orphanSweepBudget({}) }))+ .rejects.toThrow(/provenance/);+ const snake = vi.fn(async (ids: string[], _fields?: "full") => ({+ rev: 1, nodes: ids.map(i => node(i, { provenance: { source_uri: "src/example.ts" } })), missing: [],+ }));+ expect(await sweepOrphanNodes({ getPatch, nodes: snake }, [fileWith([])], { mapMode: false, budget: orphanSweepBudget({}) }))+ .toEqual([[A]]);+ });++ it("reads every stored patch a file names, merging their candidates, and reports the files it did not finish", async () => {+ const getPatch = vi.fn(async (pid: string) => {+ if (pid === "older@src/example.ts") return { data: { nodeIds: [B, C] } };+ if (pid === "old@src/bad.ts") throw new Error("500: busy");+ if (pid === "older@src/gone.ts") throw notFound();+ return { data: { nodeIds: [A, B] } };+ });+ const nodes = vi.fn(async (ids: string[], _fields?: "full") => ({ rev: 1, nodes: ids.map(i => node(i)), missing: [] }));+ const two = { ...fileWith([]), previousPatchIds: ["old@src/example.ts", "older@src/example.ts"] };+ const bad = fileWith([], "src/bad.ts");+ const gone = { ...fileWith([], "src/gone.ts"), previousPatchIds: ["older@src/gone.ts"] };+ const late = fileWith([]);+ const budget = orphanSweepBudget({ IX_ORPHAN_SWEEP_MAX_REQUESTS: "4" });+ const onUnswept = vi.fn();+ const orphans = await sweepOrphanNodes(+ { getPatch, nodes }, [two, bad, gone, late], { mapMode: false, budget, concurrency: 1, onUnswept },+ );+ expect(orphans[0]!.sort()).toEqual([A, B, C]);+ expect(orphans.slice(1)).toEqual([[], [], []]);+ // bad: its read failed. late: past the budget. gone: not found, nothing to sweep.+ expect(onUnswept.mock.calls.map(c => c[0])).toEqual([bad, late]);+ expect(budget.skipped).toBe(1);+ });++ it("reads at most 1000 ids per node read", async () => {+ const many = Array.from({ length: 2500 }, (_, i) => id(100 + i));+ const getPatch = vi.fn(async () => ({ data: { nodeIds: many } }));+ const nodes = vi.fn(async (ids: string[], _fields?: "full") => ({ rev: 1, nodes: [], missing: ids }));+ await sweepOrphanNodes({ getPatch, nodes }, [fileWith([])], { mapMode: false, budget: orphanSweepBudget({}) });+ expect(nodes.mock.calls.map(c => (c[0] as string[]).length)).toEqual([1000, 1000, 500]);+ });++ it("stops at its request budget and counts the files it skipped, across batches", async () => {+ const getPatch = vi.fn(async () => ({ data: { nodeIds: [F] } }));+ const nodes = vi.fn(async (ids: string[], _fields?: "full") => ({ rev: 1, nodes: ids.map(i => node(i)), missing: [] }));+ const budget = orphanSweepBudget({ IX_ORPHAN_SWEEP_MAX_REQUESTS: "3" });+ const batch = () => [fileWith([]), fileWith([]), fileWith([])];+ const first = await sweepOrphanNodes({ getPatch, nodes }, batch(), { mapMode: false, budget, concurrency: 1 });+ expect(first.filter(ids => ids.length > 0)).toHaveLength(3);+ expect(budget.requests).toBe(4);+ const second = await sweepOrphanNodes({ getPatch, nodes }, batch(), { mapMode: false, budget, concurrency: 1 });+ expect(second).toEqual([[], [], []]);+ expect(budget.skipped).toBe(3);+ expect(getPatch).toHaveBeenCalledTimes(3);+ });++ it("stops at its time budget", async () => {+ let clock = 0;+ const getPatch = vi.fn(async () => { clock += 40; return { data: { nodeIds: [G] } }; });+ const nodes = vi.fn(async (ids: string[], _fields?: "full") => ({ rev: 1, nodes: ids.map(i => node(i)), missing: [] }));+ const budget = orphanSweepBudget({ IX_ORPHAN_SWEEP_MAX_MS: "100" });+ const orphans = await sweepOrphanNodes(+ { getPatch, nodes }, [fileWith([]), fileWith([]), fileWith([]), fileWith([])],+ { mapMode: false, budget, concurrency: 1, now: () => clock },+ );+ expect(orphans.filter(ids => ids.length > 0)).toHaveLength(3);+ expect(budget.skipped).toBe(1);+ expect(budget.usedMs).toBe(120);+ });+});++describe("orphanSweepUnsupportedReason", () => {+ it("allows the sweep from the release that serves batched node reads, and not before", () => {+ expect(orphanSweepUnsupportedReason({ release_version: "1.0.34" }, {})).toBeNull();+ expect(orphanSweepUnsupportedReason({ release_version: BATCH_NODE_READS_SINCE }, {})).toBeNull();+ expect(orphanSweepUnsupportedReason({ release_version: "1.0.32" }, {})).toContain("older than 1.0.33");+ expect(orphanSweepUnsupportedReason({ release_version: "1.0.31" }, {})).toContain("release 1.0.31");+ expect(orphanSweepUnsupportedReason({}, {})).toContain("unversioned");+ expect(orphanSweepUnsupportedReason(null, {})).toContain("unversioned");+ // Forced onto bulk deletes: tried, and turned off at run time if /v1/nodes is missing.+ expect(orphanSweepUnsupportedReason({}, { IX_BULK_DELETES: "1" })).toBeNull();+ expect(orphanSweepUnsupportedReason({ release_version: "1.0.34" }, { IX_BULK_DELETES: "0" })).not.toBeNull();+ });});diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.tsindex 4cf8a945..9ce32893 100644--- a/ix-cli/src/cli/commands/ingest.ts+++ b/ix-cli/src/cli/commands/ingest.ts@@ -11,7 +11,7 @@ import { ParsePool } from './parse-pool.js';import chalk from 'chalk';import { IxClient } from '../../client/api.js';import { combineSignals, currentRunSignal } from '../../client/run-signal.js';-import type { GraphPatchPayload } from '../../client/types.js';+import type { GraphNode, GraphPatchPayload } from '../../client/types.js';import { canonicalWorkspacePath, isPathInside, resolveWorkspaceRoot, clearMapResultCache, clearStitchScopeCache } from '../config.js';import { resolveIngestRootWithSource } from '../map-root.js';import { acquireMapLock, requestMapRerun, takeMapRerun } from '../single-flight.js';@@ -22,6 +22,7 @@ import {import {clearRebuildProgress, extractorChanged, isRev, loadIngestBaseline, loadRebuildProgress,saveIngestBaseline, saveRebuildProgress, type BaselineFileNotes,+ loadOrphanSweepPending, saveOrphanSweepPending, type OrphanSweepPending,} from '../ingest-baseline.js';import { resolveGitHubToken } from '../github/auth.js';import { parseGitHubRepo, fetchGitHubData } from '../github/fetch.js';@@ -287,6 +288,10 @@ interface StoredPatchEntities {kinds: Map<string, string>;/** External package nodes (`attrs.external`) the stored patch wrote. */external: Set<string>;+ /** Ids only a later window manifest named; an absent one gets no DeleteNode. */+ extraOnly?: Set<string>;+ /** Why a later window manifest was left out: a backend error reading it. */+ extraSkipped?: string;}/**@@ -337,11 +342,68 @@ function readStoredPatchEntities(raw: unknown): StoredPatchEntities | null {};}+/**+ * How many leading candidates `loadStoredPatchEntities` reads and merges: the+ * current extractor and the one before it. An extractor rebuild leaves its+ * orphans in the previous extractor's patch, and a graph a pre-fix rebuild+ * polluted holds them there too. There is no batch patch GET, so merging all+ * ~30 candidates would cost ~30 reads per reconciled file.+ */+const RECONCILE_MANIFEST_WINDOW = 2;+async function loadStoredPatchEntities(client: Pick<IxClient, 'getPatch'>,patchIds: string[],+ window: number = RECONCILE_MANIFEST_WINDOW,): Promise<StoredPatchEntities> {- for (const patchId of patchIds) {+ const windowIds = patchIds.slice(0, window);+ const windowResults = await Promise.all(windowIds.map(async patchId => {+ try {+ return { patchId, raw: await client.getPatch(patchId) as unknown, failed: false, error: undefined as unknown };+ } catch (err) {+ if (isNotFoundError(err)) return { patchId, raw: null, failed: false, error: undefined as unknown };+ return { patchId, raw: null, failed: true, error: err };+ }+ }));++ // Results are walked in candidate order. A backend error before any patch+ // was found fails the reconcile, as the first-hit walk always did. One on a+ // later window patch only loses its extra ids: the patch found first is the+ // one a first-hit walk would have used, so the file reconciles at least as+ // fully as it did before the merge, and the skip is reported, not fatal.+ let primary: StoredPatchEntities | null = null;+ for (const result of windowResults) {+ if (result.failed) {+ if (primary === null) throw result.error;+ primary.extraSkipped = `patch ${result.patchId} unread: ${result.error instanceof Error ? result.error.message : String(result.error)}`;+ continue;+ }+ if (result.raw === null) continue;+ const entities = readStoredPatchEntities(result.raw);+ if (primary === null) {+ if (!entities) throw new Error(`Patch ${result.patchId} has no entity manifest`);+ primary = {+ nodeIds: [...entities.nodeIds],+ kinds: new Map(entities.kinds),+ external: new Set(entities.external),+ extraOnly: new Set(),+ };+ continue;+ }+ if (!entities) continue;+ const seen = new Set(primary.nodeIds);+ for (const id of entities.nodeIds) {+ if (seen.has(id)) continue;+ seen.add(id);+ primary.nodeIds.push(id);+ primary.extraOnly!.add(id);+ }+ for (const [id, kind] of entities.kinds) if (!primary.kinds.has(id)) primary.kinds.set(id, kind);+ for (const id of entities.external) primary.external.add(id);+ }+ if (primary) return primary;++ for (const patchId of patchIds.slice(window)) {try {const entities = readStoredPatchEntities(await client.getPatch(patchId));if (entities) return entities;@@ -353,6 +415,17 @@ async function loadStoredPatchEntities(throw new Error('Previous source patch was not found');}+interface ReconcileOptions {+ /** Told when a later stored manifest could not be read and was left out. */+ onWindowSkipped?: (reason: string) => void;+ /**+ * How many leading candidates to read and merge (default+ * RECONCILE_MANIFEST_WINDOW). 1 is the first-hit walk: one read when the+ * current candidate exists, which is what an ordinary edit pays.+ */+ window?: number;+}+export async function reconcileRemovedEntities(client: Pick<IxClient, 'getPatch' | 'entity'>,patch: GraphPatchPayload,@@ -369,8 +442,10 @@ export async function reconcileRemovedEntities(// Bounds the entity lookups. One limiter shared by every file a run// reconciles keeps the whole run to its slots, however many files run at once.lookupLimit: Limiter = task => task(),+ options: ReconcileOptions = {},): Promise<GraphPatchPayload> {- const previous = await loadStoredPatchEntities(client, previousPatchIds);+ const previous = await loadStoredPatchEntities(client, previousPatchIds, options.window);+ if (previous.extraSkipped) options.onWindowSkipped?.(previous.extraSkipped);const currentNodeIds = new Set(patch.ops.filter(op => op.type === 'UpsertNode')@@ -404,6 +479,9 @@ export async function reconcileRemovedEntities(for (const { nodeId, entity } of lookups) {if (entity === null) {+ // An id only the second window manifest named, already absent: nothing+ // to delete, and the patch stays free of extra deletes.+ if (previous.extraOnly?.has(nodeId)) continue;// Already absent. Emitting the delete anyway keeps the patch a complete// statement of intent and costs nothing.removedNodeIds.push(nodeId);@@ -475,6 +553,281 @@ export async function reconcileRemovedEntities(};}+/**+ * The same-hash orphan sweep (IN-20). An extractor change rebuilds every file+ * with unchanged bytes, and the nodes the old extractor wrote and the new one+ * does not stay live. The sweep finds them from the old extractor's stored+ * patch for the file -- one read per file -- and checks every candidate of a+ * batch with one batched node read, then adds a DeleteNode for each that is+ * still live, was last written by this file, and is neither an external+ * package node (shared by every file calling into the package) nor, under+ * `ix map`, a chunk. It costs nothing per node, and a run's budget bounds it.+ */+export interface OrphanSweepBudget {+ maxMs: number;+ maxRequests: number;+ /** Wall time the sweep has spent so far in this run. */+ usedMs: number;+ /** Stored-patch and batched node reads made so far in this run. */+ requests: number;+ /** Files the sweep skipped because the budget ran out. */+ skipped: number;+}++/** Default time budget of a run's orphan sweep (`IX_ORPHAN_SWEEP_MAX_MS`). */+export const ORPHAN_SWEEP_MAX_MS = 60_000;+/** Default request budget of a run's orphan sweep (`IX_ORPHAN_SWEEP_MAX_REQUESTS`). */+export const ORPHAN_SWEEP_MAX_REQUESTS = 25_000;++export function orphanSweepBudget(env: NodeJS.ProcessEnv = process.env): OrphanSweepBudget {+ const read = (raw: string | undefined, fallback: number): number => {+ if (raw === undefined || raw.trim() === '') return fallback;+ const n = Number(raw);+ return Number.isFinite(n) && n >= 0 ? n : fallback;+ };+ return {+ maxMs: read(env.IX_ORPHAN_SWEEP_MAX_MS, ORPHAN_SWEEP_MAX_MS),+ maxRequests: read(env.IX_ORPHAN_SWEEP_MAX_REQUESTS, ORPHAN_SWEEP_MAX_REQUESTS),+ usedMs: 0,+ requests: 0,+ skipped: 0,+ };+}++export interface OrphanSweepFile {+ /** The file's patch as built, before map mode strips it. */+ patch: GraphPatchPayload;+ /**+ * The stored patch ids, one per earlier extractor, that may name the file's+ * orphans for its (unchanged) hash: usually just the previous extractor's.+ */+ previousPatchIds: string[];+}++/**+ * The backend does not serve `POST /v1/nodes`, or answers it without the+ * provenance the ownership check needs: the sweep is off for the run.+ */+export class BatchNodeReadsUnsupported extends Error {}++/** `POST /v1/nodes` takes at most this many ids. */+const NODES_PER_READ = 1000;+/** Node ids are UUIDs; the batched read refuses the whole request over one that is not. */+const NODE_ID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++/**+ * The node ids a stored patch upserted, with the kinds and external flags it+ * recorded. A patch stored with its ops (`/v1/patch`) has all three; a bulk+ * patch keeps only ids (`nodeIds`, or the older `entityIds` manifest), which+ * is why the batched read checks kind and ownership.+ */+function storedUpserts(raw: unknown): { ids: string[]; kinds: Map<string, string>; external: Set<string> } | null {+ const data = (raw as { data?: unknown } | null)?.data as { ops?: unknown; nodeIds?: unknown } | undefined;+ if (!data) return null;+ if (Array.isArray(data.ops)) {+ const ids: string[] = [];+ const kinds = new Map<string, string>();+ const external = new Set<string>();+ for (const op of data.ops as Array<{ type?: unknown; id?: unknown; kind?: unknown; attrs?: unknown }>) {+ if (op.type !== 'UpsertNode' || typeof op.id !== 'string') continue;+ ids.push(op.id);+ if (typeof op.kind === 'string') kinds.set(op.id, op.kind);+ if (isExternalNode(op)) external.add(op.id);+ }+ return { ids, kinds, external };+ }+ if (Array.isArray(data.nodeIds)) {+ return { ids: data.nodeIds.filter((id): id is string => typeof id === 'string'), kinds: new Map(), external: new Set() };+ }+ const manifest = readStoredPatchEntities(raw);+ return manifest ? { ids: manifest.nodeIds, kinds: manifest.kinds, external: manifest.external } : null;+}++/** The file that last wrote a node, from the provenance the backend keeps. */+function nodeSourceUri(node: GraphNode): unknown {+ const provenance = node.provenance as { sourceUri?: unknown; source_uri?: unknown } | undefined;+ return provenance?.sourceUri ?? provenance?.source_uri;+}++/**+ * One node the file's patch upserts, read beside the orphan candidates to tell+ * whether a patch for these very bytes and this extractor already landed: the+ * file node if there is one, else the first other non-chunk node.+ */+function currentPatchProbe(patch: GraphPatchPayload): string | undefined {+ let fallback: string | undefined;+ for (const op of patch.ops) {+ if (op.type !== 'UpsertNode' || typeof op['id'] !== 'string' || !NODE_ID_SHAPE.test(op['id'])) continue;+ if (op['kind'] === 'chunk' || isExternalNode(op)) continue;+ if (op['kind'] === 'file') return op['id'];+ fallback ??= op['id'];+ }+ return fallback;+}++/**+ * Whether the backend reports `node` last written by a patch for `patch`'s+ * file, hash and extractor. The bulk route rewrites every node a patch+ * upserts with that patch's provenance, so this holds once such a patch has+ * landed -- under its deterministic id or a salted one.+ */+function writtenBy(node: GraphNode | undefined, patch: GraphPatchPayload): boolean {+ if (!node || (node.deletedRev !== undefined && node.deletedRev !== null)) return false;+ const provenance = node.provenance as { extractor?: unknown; sourceHash?: unknown; source_hash?: unknown } | undefined;+ return nodeSourceUri(node) === patch.source.uri+ && provenance?.extractor === patch.source.extractor+ && (provenance?.sourceHash ?? provenance?.source_hash) === patch.source.sourceHash;+}++function isUnsupportedRouteError(error: unknown): boolean {+ return /^(?:Error:\s*)?(?:404|405|501):/.test(String(error));+}++/**+ * The orphan node ids to delete for each file, in `files` order. Never one a+ * patch of this batch upserts (`batchUpserts`), and never one the backend does+ * not report live, last written by this very file, non-external and (in map+ * mode) not a chunk. A file whose reads fail, or that the budget no longer+ * covers, gets none: the sweep is best effort and the file commits as built.+ * Throws `BatchNodeReadsUnsupported` when the backend has no batched node read.+ */+export async function sweepOrphanNodes(+ client: Pick<IxClient, 'getPatch' | 'nodes'>,+ files: OrphanSweepFile[],+ opts: {+ mapMode: boolean;+ budget: OrphanSweepBudget;+ batchUpserts?: Set<string>;+ concurrency?: number;+ onSkip?: (file: OrphanSweepFile, reason: string) => void;+ /**+ * Told of each file the sweep did not finish: past the budget, or a read+ * failed. Every other file was swept (or had nothing to sweep).+ */+ onUnswept?: (file: OrphanSweepFile) => void;+ /**+ * Told of each file given orphans whose current patch the backend may+ * already hold: one node of it (`currentPatchProbe`, read in the same+ * batched node read) was last written by this file at this hash and+ * extractor, or could not be read. A patch id the backend already holds+ * is answered `Idempotent` and its deletes dropped, so such a file's+ * deletes need a salted id.+ */+ onWrittenBefore?: (file: OrphanSweepFile) => void;+ now?: () => number;+ },+): Promise<string[][]> {+ const now = opts.now ?? (() => performance.now());+ const { budget } = opts;+ const started = now();+ const spent = (): number => budget.usedMs + (now() - started);+ const result: string[][] = files.map(() => []);+ try {+ const candidates = await mapLimit(files, opts.concurrency ?? RECONCILE_CONCURRENCY, async (file): Promise<string[] | null> => {+ if (file.previousPatchIds.length === 0) return null;+ if (budget.requests >= budget.maxRequests || spent() >= budget.maxMs) {+ budget.skipped++;+ opts.onUnswept?.(file);+ return null;+ }+ budget.requests += file.previousPatchIds.length;+ const reads = await Promise.all(file.previousPatchIds.map(async patchId => {+ try {+ return { raw: await client.getPatch(patchId) as unknown, error: null as string | null };+ } catch (err) {+ return { raw: null, error: isNotFoundError(err) ? null : (err instanceof Error ? err.message : String(err)) };+ }+ }));+ const failed = reads.find(r => r.error !== null);+ if (failed) {+ opts.onSkip?.(file, failed.error!);+ opts.onUnswept?.(file);+ return null;+ }+ const current = new Set(+ file.patch.ops.filter(op => op.type === 'UpsertNode').map(op => op['id']).filter((id): id is string => typeof id === 'string'),+ );+ const ids = new Set<string>();+ for (const { raw } of reads) {+ const stored = raw === null ? null : storedUpserts(raw);+ if (!stored) continue;+ for (const id of stored.ids) {+ if (!current.has(id)+ && !opts.batchUpserts?.has(id)+ && NODE_ID_SHAPE.test(id)+ && !stored.external.has(id)+ && !(opts.mapMode && stored.kinds.get(id) === 'chunk')) ids.add(id);+ }+ }+ return [...ids];+ });++ const unique = [...new Set(candidates.flatMap(c => c ?? []))];+ if (unique.length === 0) return result;+ const probes = files.map((file, i) =>+ opts.onWrittenBefore && candidates[i] && candidates[i]!.length > 0 ? currentPatchProbe(file.patch) : undefined);+ const seen = new Set(unique);+ for (const probe of probes) {+ if (probe !== undefined && !seen.has(probe)) {+ seen.add(probe);+ unique.push(probe);+ }+ }+ const live = new Map<string, GraphNode>();+ const unread = new Set<string>();+ let unreadReason = '';+ for (let i = 0; i < unique.length; i += NODES_PER_READ) {+ const ids = unique.slice(i, i + NODES_PER_READ);+ budget.requests++;+ try {+ const answer = await client.nodes(ids, 'full');+ for (const node of answer?.nodes ?? []) {+ if (node && typeof node.id === 'string') live.set(node.id, node);+ }+ } catch (err) {+ if (isUnsupportedRouteError(err)) {+ throw new BatchNodeReadsUnsupported('the backend does not serve the batched node read (POST /v1/nodes)');+ }+ for (const id of ids) unread.add(id);+ unreadReason = err instanceof Error ? err.message : String(err);+ }+ }++ // Ownership is read from each node's provenance. A backend whose batched+ // read leaves it out would make every candidate look foreign, and the+ // sweep a silent no-op; say so and turn it off instead.+ for (const node of live.values()) {+ if (typeof nodeSourceUri(node) !== 'string') {+ throw new BatchNodeReadsUnsupported('the batched node read (POST /v1/nodes) returned nodes without provenance.sourceUri');+ }+ }++ files.forEach((file, i) => {+ const ids = candidates[i];+ if (!ids || ids.length === 0) return;+ if (ids.some(id => unread.has(id))) {+ opts.onSkip?.(file, `node read failed: ${unreadReason}`);+ opts.onUnswept?.(file);+ return;+ }+ result[i] = ids.filter(id => {+ const node = live.get(id);+ if (!node || (node.deletedRev !== undefined && node.deletedRev !== null)) return false;+ if (isExternalNode(node)) return false;+ if (opts.mapMode && node.kind === 'chunk') return false;+ return nodeSourceUri(node) === file.patch.source.uri;+ });+ const probe = probes[i];+ if (result[i]!.length > 0 && probe !== undefined && (unread.has(probe) || writtenBy(live.get(probe), file.patch))) {+ opts.onWrittenBefore?.(file);+ }+ });+ return result;+ } finally {+ budget.usedMs += now() - started;+ }+}+/*** Files reconciled at once, and entity lookups in flight across all of them:* the graph walkers' cap (`EXPAND_CONCURRENCY`), for the same reason.@@ -512,19 +865,54 @@ export function backendAppliesBulkDeletes(const forced = env.IX_BULK_DELETES;if (forced === '1') return true;if (forced === '0') return false;+ return releaseAtLeast(health, BULK_DELETES_SINCE) === true;+}++/**+ * Whether the release the backend reports is at least `min`: null when it+ * reports none, or one that does not parse.+ */+function releaseAtLeast(health: { release_version?: unknown } | null | undefined, min: string): boolean | null {const release = health?.release_version;- if (typeof release !== 'string') return false;+ if (typeof release !== 'string') return null;const parse = (v: string): number[] | null => {const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(v.trim());return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;};const have = parse(release);- const need = parse(BULK_DELETES_SINCE)!;- if (have === null) return false;+ const need = parse(min)!;+ if (have === null) return null;for (let i = 0; i < 3; i++) if (have[i] !== need[i]) return have[i] > need[i];return true;}+/** The first release that serves `POST /v1/nodes` (Ix-memory batch reads). */+export const BATCH_NODE_READS_SINCE = '1.0.33';++/**+ * Why the same-hash orphan sweep (IN-20) cannot run against this backend, or+ * null when it can. The sweep adds DeleteNode ops to rebuild patches, which+ * only the bulk route of a backend that applies deletes takes without falling+ * back to one `/v1/patch` per file, and it checks its candidates with one+ * batched `POST /v1/nodes`. A backend that reports no release but is forced+ * onto bulk deletes (`IX_BULK_DELETES=1`) is tried; if it does not serve the+ * batch read, the sweep turns itself off for the run.+ */+export function orphanSweepUnsupportedReason(+ health: { release_version?: unknown } | null | undefined,+ env: NodeJS.ProcessEnv = process.env,+): string | null {+ const release = health?.release_version;+ const described = typeof release === 'string' ? `release ${release}` : 'unversioned';+ if (!backendAppliesBulkDeletes(health, env)) {+ return `the backend (${described}) is older than ${BATCH_NODE_READS_SINCE} or does not apply deletes in bulk`;+ }+ if (releaseAtLeast(health, BATCH_NODE_READS_SINCE) === false) {+ return `the backend (${described}) is older than ${BATCH_NODE_READS_SINCE}`;+ }+ return null;+}+export function planDeletedFileRecovery(projectRoot: string,filePaths: string[],@@ -1787,6 +2175,7 @@ export async function ingestFiles(fileNodeId,symbolNodeId,extractorName,+ PREVIOUS_EXTRACTORS,},{ languageFromPath },] = await loadIngestionModules();@@ -2007,10 +2396,13 @@ export async function ingestFiles(// Read from the same health answer. Unknown (the check failed) keeps the// per-file route for delete-bearing patches.let bulkDeletes = false;+ // Why the same-hash orphan sweep cannot run here; null when it can.+ let orphanSweepBlocker: string | null = 'the backend release could not be read';const reconcileLookups = createLimiter(RECONCILE_CONCURRENCY);try {const health = await readBackendHealth(client);bulkDeletes = backendAppliesBulkDeletes(health);+ orphanSweepBlocker = orphanSweepUnsupportedReason(health);if (debug) process.stderr.write(`\n [commit] delete-bearing patches via ${bulkDeletes ? 'bulk' : '/v1/patch'}\n`);const serverVersion = (health as any)?.schema_version;if (typeof serverVersion === 'number' && serverVersion !== CLIENT_EXPECTED_SCHEMA_VERSION) {@@ -2376,6 +2768,85 @@ export async function ingestFiles(extractorRebuild = true;clearMapResultCache(projectRoot);}+ // The same-hash orphan sweep (IN-20, `sweepOrphanNodes`) costs one+ // stored-patch read per file, and only an extractor change leaves orphans+ // behind. So it runs only when the baseline says this workspace's files+ // were last written by another extractor -- whether this run was forced+ // or not -- and not on a plain --force at the current extractor. The+ // baseline is the only signal that costs no read. IX_RECONCILE_ON_FORCE=1+ // opts a --force run in, to repair a graph a pre-fix rebuild left+ // polluted. On a backend that takes deletes in bulk, the same runs widen+ // an edited file's reconcile to the second stored patch; an ordinary edit+ // reads only the first, as before IN-20.+ const reconcileOrphans = extractorChanged(previousBaseline, currentExtractor)+ || (Boolean(opts.force) && process.env.IX_RECONCILE_ON_FORCE === '1');+ // The same-hash sweep reads, per file, the stored patch an earlier+ // extractor wrote for the file's hash. On an extractor change that is the+ // extractor the baseline recorded. On an opted-in --force at the current+ // extractor (a repair) it is whatever an earlier run recorded as left+ // unswept (`loadOrphanSweepPending`: a sweep the backend could not run, or+ // one that ran out of budget), for only the files it recorded; with+ // nothing recorded, the extractor before the current, for every file. An+ // extractor change also reads what is recorded, for the files recorded.+ const orphanRepair = reconcileOrphans && !extractorChanged(previousBaseline, currentExtractor);+ const knownPreviousExtractors: readonly string[] = PREVIOUS_EXTRACTORS ?? [];+ const orphanCandidateIndex = (extractor: string): number | null => {+ const at = knownPreviousExtractors.indexOf(extractor);+ return at < 0 ? null : at + 1;+ };+ const orphanPending: OrphanSweepPending = reconcileOrphans && !workspaceMigrated+ ? loadOrphanSweepPending(projectRoot)+ : new Map();+ for (const extractor of [...orphanPending.keys()]) {+ if (extractor === currentExtractor || orphanCandidateIndex(extractor) === null) orphanPending.delete(extractor);+ }+ const orphanBaseExtractor: string | null = (() => {+ if (!reconcileOrphans) return null;+ const base = orphanRepair+ ? (orphanPending.size > 0 ? null : knownPreviousExtractors[0] ?? null)+ : previousBaseline?.extractor ?? null;+ return base !== null && orphanCandidateIndex(base) !== null ? base : null;+ })();+ /** The earlier extractors whose stored patch for this file the sweep reads. */+ const orphanSourcesFor = (filePath: string): string[] => {+ const sources = orphanBaseExtractor === null ? [] : [orphanBaseExtractor];+ for (const [extractor, files] of orphanPending) {+ if (!sources.includes(extractor) && (files === null || files.has(filePath))) sources.push(extractor);+ }+ return sources;+ };+ const orphanSweep = {+ blocker: orphanSweepBlocker ?? (reconcileOrphans && !orphanRepair && orphanBaseExtractor === null && orphanPending.size === 0+ ? `the previous extractor (${previousBaseline?.extractor ?? 'unrecorded'}) is not one this CLI knows`+ : null),+ budget: orphanSweepBudget(),+ noticed: false,+ // Only a whole-workspace run records what it left unswept. A partial+ // extractor-change run keeps the old extractor in the baseline, so the+ // next full map sweeps its files anyway.+ track: reconcileOrphans && !partialRun && !workspaceMigrated,+ /** Per extractor read this run, the files it did not finish. */+ unswept: new Map<string, Set<string>>(),+ /** Recorded "every file" entries this run read for every file. */+ allAtStart: new Set([...orphanPending].filter(([, files]) => files === null).map(([extractor]) => extractor)),+ };+ // One line per run when the sweep is wanted and cannot run: the orphans+ // stay, and nothing else about the run changes. A whole-workspace+ // extractor change records the previous extractor for every file, so a+ // repair after a backend upgrade reads the patch that names them.+ const noteOrphanSweepBlocked = (): void => {+ if (orphanSweep.noticed || orphanSweep.blocker === null) return;+ orphanSweep.noticed = true;+ if (orphanSweep.track && !orphanRepair && orphanBaseExtractor !== null) {+ orphanPending.set(orphanBaseExtractor, null);+ saveOrphanSweepPending(projectRoot, orphanPending);+ }+ process.stderr.write(+ `\n [orphans kept] nodes the previous extractor wrote and this one does not were not removed: ` ++ `${orphanSweep.blocker}.` ++ (orphanSweepBlocker !== null ? ' After upgrading the backend, run IX_RECONCILE_ON_FORCE=1 ix map --force to remove them.' : '') + '\n',+ );+ };const previousMtimes = previousBaseline?.files ?? new Map<string, number>();const {previousDeletedFiles,@@ -2539,7 +3010,11 @@ export async function ingestFiles(// entirely if nothing changed (common "ix map" re-run case).// B) No baseline / force → load modules, parse + stream-commit all files.- type ParsedFile = { filePath: string; parsed: any; hash: string; previousHash: string | undefined };+ type ParsedFile = {+ filePath: string; parsed: any; hash: string; previousHash: string | undefined;+ /** The hash the backend holds for the file, changed or not. Feeds only reconcile. */+ knownHash?: string | undefined;+ };let resolveEdgesFn: Function | null = null;let buildPatchFn: Function | null = null;@@ -3530,11 +4005,14 @@ export async function ingestFiles(* file at a time it was a serial chain of entity lookups per batch. The* patches come back in file order, without the ones that failed to build.*/+ const noteOrphanSkip = (filePath: string, reason: string): void => {+ if (debug) process.stderr.write(`\n [orphan reconcile skipped] ${filePath}: ${reason}\n`);+ };const buildFilePatches = async (files: ParsedFile[],edgesByFile: Map<string, any[]>,): Promise<PreparedPatch[]> => {- const built = await mapLimit(files, RECONCILE_CONCURRENCY, async ({ parsed: p, hash, previousHash }, j) => {+ const built = await mapLimit(files, RECONCILE_CONCURRENCY, async ({ parsed: p, hash, previousHash, knownHash }, j) => {try {const fileWorkspace = fileWorkspaceId(p.filePath);let patch = buildPatchFn!(p, hash, fileWorkspace, edgesByFile.get(p.filePath) ?? emptyEdges, previousHash, fileMultiRepo(p.filePath));@@ -3546,20 +4024,127 @@ export async function ingestFiles(undefined,mapMode,reconcileLookups,+ { onWindowSkipped: reason => noteOrphanSkip(p.filePath, reason), window: reconcileOrphans && orphanSweepBlocker === null ? RECONCILE_MANIFEST_WINDOW : 1 },);}+ // Same content, new extractor (or an opted-in --force): the+ // previous extractor's patch for this hash names what the sweep+ // below may retire. Without a backend that takes deletes in bulk+ // and serves the batched node read the file is committed exactly as+ // built, as before IN-20.+ let orphanSources: string[] | undefined;+ let previousPatchIds: string[] | undefined;+ if (!previousHash && knownHash && reconcileOrphans) {+ if (orphanSweep.blocker !== null) noteOrphanSweepBlocked();+ else {+ orphanSources = orphanSourcesFor(p.filePath);+ const candidates = sourcePatchIdCandidates(p.filePath, knownHash, fileWorkspace);+ previousPatchIds = orphanSources.map(extractor => candidates[orphanCandidateIndex(extractor)!]!);+ if (previousPatchIds.length === 0) previousPatchIds = undefined;+ }+ }+ return { p, hash, j, previousHash, patch: patch as GraphPatchPayload, previousPatchIds, orphanSources };+ } catch (err) {+ parseErrors++;+ process.stderr.write(`\n [patch build error] ${p.filePath}: ${err}\n`);+ return null;+ }+ });++ // The orphan sweep, for the whole batch at once: one stored-patch read+ // per file and one batched node read. Best effort -- whatever fails here+ // leaves the patches to commit as built, with no parse error and no+ // change to the exit code.+ const sweepable = built.filter((b): b is NonNullable<typeof b> & { previousPatchIds: string[]; orphanSources: string[] } =>+ b !== null && b.previousPatchIds !== undefined);+ if (sweepable.length > 0 && orphanSweep.blocker === null) {+ const batchUpserts = new Set<string>();+ for (const b of built) {+ if (b === null) continue;+ for (const op of b.patch.ops) if (op.type === 'UpsertNode' && typeof op['id'] === 'string') batchUpserts.add(op['id']);+ }+ const unswept = new Set<number>();+ const writtenBefore = new Set<number>();+ try {+ const sweepFiles = sweepable.map(b => ({ patch: b.patch, previousPatchIds: b.previousPatchIds }));+ const orphans = await sweepOrphanNodes(+ client,+ sweepFiles,+ {+ mapMode,+ budget: orphanSweep.budget,+ batchUpserts,+ onSkip: (file, reason) => noteOrphanSkip(file.patch.source.uri, reason),+ onUnswept: file => unswept.add(sweepFiles.indexOf(file)),+ onWrittenBefore: file => writtenBefore.add(sweepFiles.indexOf(file)),+ },+ );+ sweepable.forEach((b, i) => {+ const ids = orphans[i]!;+ if (ids.length === 0) return;+ b.patch = { ...b.patch, ops: [...ids.map(id => ({ type: 'DeleteNode', id })), ...b.patch.ops] };+ if (orphanRepair || writtenBefore.has(i)) {+ // The backend already holds this file's patch id: a repair runs+ // at the current extractor, and an extractor-change run may+ // follow an earlier one (a partial run, a run cut short) that+ // committed the file without the deletes. Sent under that id+ // the deletes would be answered Idempotent and dropped, so they+ // go under an id salted with them. Every other patch keeps its+ // deterministic id, the one a later edit, deletion or sweep+ // reads back.+ const salt = `orphans-${sha256(Buffer.from([...ids].sort().join('\n'))).slice(0, 12)}`;+ const salted = buildPatchFn!(b.p, b.hash, fileWorkspaceId(b.p.filePath), edgesByFile.get(b.p.filePath) ?? emptyEdges, undefined, fileMultiRepo(b.p.filePath), salt);+ b.patch = { ...b.patch, patchId: salted.patchId };+ }+ });+ } catch (err) {+ if (err instanceof BatchNodeReadsUnsupported) {+ orphanSweep.blocker = err.message;+ noteOrphanSweepBlocked();+ } else {+ for (const b of sweepable) noteOrphanSkip(b.p.filePath, err instanceof Error ? err.message : String(err));+ }+ sweepable.forEach((_, i) => unswept.add(i));+ }+ // What this batch left unswept stays recorded for a repair run, and+ // what it finished comes off the record. Saved per batch, so a run cut+ // short keeps what it learned.+ if (orphanSweep.track) {+ let changed = false;+ sweepable.forEach((b, i) => {+ for (const extractor of b.orphanSources) {+ const files = orphanPending.get(extractor);+ if (unswept.has(i)) {+ let mine = orphanSweep.unswept.get(extractor);+ if (!mine) orphanSweep.unswept.set(extractor, mine = new Set());+ mine.add(b.p.filePath);+ if (files === undefined) orphanPending.set(extractor, new Set([b.p.filePath]));+ else files?.add(b.p.filePath);+ changed = true;+ } else if (files?.delete(b.p.filePath)) {+ changed = true;+ }+ }+ });+ if (changed) saveOrphanSweepPending(projectRoot, orphanPending);+ }+ }++ return built.map(b => {+ if (b === null) return null;+ try {+ let patch = b.patch;if (mapMode) patch = stripMapModeOps(patch);- noteResolution(p.filePath, patch);+ noteResolution(b.p.filePath, patch);// source.uri (workspace-relative) and source.workspaceId are set// inside buildPatch; the backend stores both as opaque attributes.- return makePreparedPatch(patch, j + 1, p.filePath, previousHash !== undefined || isForced(p.filePath));+ return makePreparedPatch(patch, b.j + 1, b.p.filePath, b.previousHash !== undefined || isForced(b.p.filePath));} catch (err) {parseErrors++;- process.stderr.write(`\n [patch build error] ${p.filePath}: ${err}\n`);+ process.stderr.write(`\n [patch build error] ${b.p.filePath}: ${err}\n`);return null;}- });- return built.filter((pp): pp is PreparedPatch => pp !== null);+ }).filter((pp): pp is PreparedPatch => pp !== null);};/** Resolve edges within a batch, build patches, and commit in sub-chunks. */@@ -3631,7 +4216,7 @@ export async function ingestFiles(// Path A: has baseline or all mtime-clean → pre-scan to detect changes before loading modules.// If nothing changed, module load is skipped entirely. A file with no// backend hash is new: it is parsed and sent with no reconcile.- const changedPaths: Array<{ filePath: string; bytes: Buffer; hash: string; previousHash: string | undefined }> = [];+ const changedPaths: Array<{ filePath: string; bytes: Buffer; hash: string; previousHash: string | undefined; knownHash: string | undefined }> = [];for (const filePath of mtimeChangedPaths) {try {const bytes = fs.readFileSync(filePath);@@ -3645,7 +4230,7 @@ export async function ingestFiles(continue;}const previousHash = knownHashes.get(filePath);- changedPaths.push({ filePath, bytes, hash, previousHash: previousHash !== hash ? previousHash : undefined });+ changedPaths.push({ filePath, bytes, hash, previousHash: previousHash !== hash ? previousHash : undefined, knownHash: previousHash });} catch (err) {parseErrors++;progressCurrent++;@@ -3664,8 +4249,8 @@ export async function ingestFiles(// filePath here is the workspace-relative path (what goes to parseFile// and downstream into buildPatch → source_uri). absFilePath is the// absolute path retained for any on-disk ops (reads already happened).- const parseable: Array<{ filePath: string; absFilePath: string; source: string; hash: string; previousHash: string | undefined }> = [];- for (const { filePath, bytes, hash, previousHash } of changedPaths) {+ const parseable: Array<{ filePath: string; absFilePath: string; source: string; hash: string; previousHash: string | undefined; knownHash: string | undefined }> = [];+ for (const { filePath, bytes, hash, previousHash, knownHash } of changedPaths) {const sourceText = bytes.toString('utf-8');if (isLikelyMinifiedSource(sourceText)) {minifiedLikely++;@@ -3679,7 +4264,7 @@ export async function ingestFiles(// deterministic ID derived in buildPatch (node/edge/chunk/patch)// hashes relative paths. This makes graph IDs portable across// machines and removes backend dependence on host paths.- parseable.push({ filePath: toWorkspaceRelative(filePath), absFilePath: filePath, source: sourceText, hash, previousHash });+ parseable.push({ filePath: toWorkspaceRelative(filePath), absFilePath: filePath, source: sourceText, hash, previousHash, knownHash });}progressPhase = 'Parsing';@@ -3715,7 +4300,7 @@ export async function ingestFiles(const parsed = parseResults[j] as any;if (!parsed) { filesSkipped++; filesSkippedUnparsed++; unparsedRel.add(chunk[j].filePath); continue; }entitiesParsed += parsed.entities.length;- batch.push({ filePath: chunk[j].filePath, parsed, hash: chunk[j].hash, previousHash: chunk[j].previousHash });+ batch.push({ filePath: chunk[j].filePath, parsed, hash: chunk[j].hash, previousHash: chunk[j].previousHash, knownHash: chunk[j].knownHash });noteSummary(chunk[j].filePath, chunk[j].hash, parsed, currentMtimes.get(chunk[j].absFilePath));if (parsed.hasParseErrors) filesWithParseErrors++;}@@ -3770,7 +4355,7 @@ export async function ingestFiles(let pendingFlushB: Promise<void> = Promise.resolve();for (let i = 0; i < filePaths.length; i += PARSE_STREAM_CHUNK) {const chunk = filePaths.slice(i, i + PARSE_STREAM_CHUNK);- type FileData = { filePath: string; source: string; hash: string; previousHash: string | undefined } | null;+ type FileData = { filePath: string; source: string; hash: string; previousHash: string | undefined; knownHash: string | undefined } | null;const fileData: FileData[] = new Array(chunk.length).fill(null);const parsePromises: Promise<unknown>[] = new Array(chunk.length).fill(Promise.resolve(null));@@ -3860,7 +4445,7 @@ export async function ingestFiles(return;}const relFilePath = toWorkspaceRelative(absFilePath);- const fd: NonNullable<FileData> = { filePath: relFilePath, source: sourceText, hash, previousHash: previousHash !== hash ? previousHash : undefined };+ const fd: NonNullable<FileData> = { filePath: relFilePath, source: sourceText, hash, previousHash: previousHash !== hash ? previousHash : undefined, knownHash: previousHash };fileData[idx] = fd;parsePromises[idx] = ensureParsePool(filePaths.length).parse(fd.filePath, fd.source).then(r => { progressCurrent++; return r; });} catch (err) {@@ -3878,7 +4463,7 @@ export async function ingestFiles(const parsed = parseResults[j] as any;if (!parsed) { filesSkipped++; filesSkippedUnparsed++; unparsedRel.add(f.filePath); continue; }entitiesParsed += parsed.entities.length;- batch.push({ filePath: f.filePath, parsed, hash: f.hash, previousHash: f.previousHash });+ batch.push({ filePath: f.filePath, parsed, hash: f.hash, previousHash: f.previousHash, knownHash: f.knownHash });noteSummary(f.filePath, f.hash, parsed, currentMtimes.get(chunk[j]));if (parsed.hasParseErrors) filesWithParseErrors++;}@@ -3892,6 +4477,24 @@ export async function ingestFiles(timings.parseMs = Math.round(parsed - hashed);// Clear the parse barif (interval) process.stderr.write('\r' + ' '.repeat(PROG_LINE_WIDTH) + '\r');+ // A recorded "every file" entry this run swept file by file now holds+ // only the files it left.+ if (orphanSweep.track && orphanSweep.blocker === null && orphanSweep.allAtStart.size > 0) {+ for (const extractor of orphanSweep.allAtStart) {+ if (orphanPending.get(extractor) === null) orphanPending.set(extractor, orphanSweep.unswept.get(extractor) ?? new Set());+ }+ saveOrphanSweepPending(projectRoot, orphanPending);+ }+ if (orphanSweep.budget.skipped > 0) {+ process.stderr.write(+ `\n [orphans kept] the orphan cleanup reached its budget (${Math.round(orphanSweep.budget.maxMs / 1000)}s / ` ++ `${orphanSweep.budget.maxRequests} requests); ${orphanSweep.budget.skipped} file(s) were committed without it. ` ++ (orphanSweep.track+ ? `Run IX_RECONCILE_ON_FORCE=1 ix map --force to continue: it sweeps only the files left, and each run picks up where the last stopped. ` ++ `IX_ORPHAN_SWEEP_MAX_MS and IX_ORPHAN_SWEEP_MAX_REQUESTS raise the budget.\n`+ : orphanRepair ? `Run the same command again to retry them.\n` : `The next full ix map sweeps them.\n`),+ );+ }if (deletedPaths.length > 0) {progressPhase = 'Saving';@@ -3932,6 +4535,13 @@ export async function ingestFiles(dependentSourceUris,mapMode,reconcileLookups,+ {+ onWindowSkipped: reason => noteOrphanSkip(relFilePath, reason),+ // The second stored patch (a graph a pre-fix rebuild left+ // polluted) is merged only where its extra deletes can go in+ // bulk; elsewhere the first-hit walk, as before IN-20.+ window: orphanSweepBlocker === null ? RECONCILE_MANIFEST_WINDOW : 1,+ },);if (mapMode) patch = stripMapModeOps(patch);deletedPatches.push(makePreparedPatch(patch, i + 1, relFilePath, true));diff --git a/ix-cli/src/cli/commands/ingestion-loader.ts b/ix-cli/src/cli/commands/ingestion-loader.tsindex 1e7015a7..de5c6a46 100644--- a/ix-cli/src/cli/commands/ingestion-loader.ts+++ b/ix-cli/src/cli/commands/ingestion-loader.ts@@ -24,6 +24,8 @@ type PatchBuilderModule = {fileNodeId: (workspaceId: string, filePath: string) => string;symbolNodeId: (workspaceId: string, filePath: string, qualifiedKey: string) => string;extractorName: () => string;+ /** Earlier extractor names, newest first: `sourcePatchIdCandidates` order after the current one. */+ PREVIOUS_EXTRACTORS?: readonly string[];};type LanguagesModule = {diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.tsindex 9e22d20e..e8039859 100644--- a/ix-cli/src/cli/config.ts+++ b/ix-cli/src/cli/config.ts@@ -54,6 +54,16 @@ export function ingestRebuildPath(projectRoot: string): string {return join(ixHome(), `ingest_rebuild_${key}.json`);}+/**+ * Path to the orphan sweeps an earlier run could not finish (see+ * `loadOrphanSweepPending`). Cleared with the mtime cache, since it describes+ * the same graph.+ */+export function ingestOrphanSweepPath(projectRoot: string): string {+ const key = rootKey(projectRoot);+ return join(ixHome(), `ingest_orphans_${key}.json`);+}+/*** Path to the per-file symbol summaries an incremental map resolves against* (see `ingest-symbols.ts`). Cleared, with its journal, with the mtime cache.@@ -160,6 +170,7 @@ export function clearMapBaseline(projectRoot: string): void {export function clearIngestMtimeCache(projectRoot: string): void {try { rmSync(ingestMtimeCachePath(projectRoot), { force: true }); } catch { /* non-critical */ }try { rmSync(ingestRebuildPath(projectRoot), { force: true }); } catch { /* non-critical */ }+ try { rmSync(ingestOrphanSweepPath(projectRoot), { force: true }); } catch { /* non-critical */ }try { rmSync(ingestSymbolsPath(projectRoot), { force: true }); } catch { /* non-critical */ }try { rmSync(ingestSymbolsJournalPath(projectRoot), { force: true }); } catch { /* non-critical */ }clearMapBaseline(projectRoot);diff --git a/ix-cli/src/cli/ingest-baseline.ts b/ix-cli/src/cli/ingest-baseline.tsindex df72df96..16a560b6 100644--- a/ix-cli/src/cli/ingest-baseline.ts+++ b/ix-cli/src/cli/ingest-baseline.ts@@ -2,7 +2,7 @@import * as fs from "node:fs";import * as path from "node:path";-import { ingestMtimeCachePath, ingestRebuildPath } from "./config.js";+import { ingestMtimeCachePath, ingestOrphanSweepPath, ingestRebuildPath } from "./config.js";interface SerializedIngestBaseline {root: string;@@ -247,3 +247,50 @@ export function saveRebuildProgress(projectRoot: string, extractor: string, fileexport function clearRebuildProgress(projectRoot: string): void {try { fs.rmSync(ingestRebuildPath(projectRoot), { force: true }); } catch { /* non-critical */ }}++/**+ * Orphan sweeps (IN-20) an earlier run left unfinished, by the extractor whose+ * stored patches name the orphans: the workspace-relative files still to+ * sweep, or null for every file. An extractor change whose sweep could not run+ * (a backend without bulk deletes or the batched node read) records the+ * previous extractor for every file; one that ran out of budget records the+ * files it skipped. A repair run (`IX_RECONCILE_ON_FORCE=1 ix map --force`)+ * then reads only these patches, for only these files, so it reaches orphans+ * more than one extractor back and picks up where the last run stopped.+ */+export type OrphanSweepPending = Map<string, Set<string> | null>;++export function loadOrphanSweepPending(projectRoot: string): OrphanSweepPending {+ const pending: OrphanSweepPending = new Map();+ try {+ const data = JSON.parse(fs.readFileSync(ingestOrphanSweepPath(projectRoot), "utf-8")) as {+ root?: unknown; pending?: Record<string, unknown>;+ };+ if (data.root !== projectRoot || !data.pending || typeof data.pending !== "object") return pending;+ for (const [extractor, files] of Object.entries(data.pending)) {+ if (files === null) pending.set(extractor, null);+ else if (Array.isArray(files)) pending.set(extractor, new Set(stringList(files)));+ }+ } catch {+ // None recorded, or unreadable: a repair falls back to its default.+ }+ return pending;+}++export function saveOrphanSweepPending(projectRoot: string, pending: OrphanSweepPending): void {+ try {+ const target = ingestOrphanSweepPath(projectRoot);+ const entries = [...pending].filter(([, files]) => files === null || files.size > 0);+ if (entries.length === 0) {+ fs.rmSync(target, { force: true });+ return;+ }+ fs.mkdirSync(path.dirname(target), { recursive: true });+ const tmp = `${target}.${process.pid}.tmp`;+ const serialized = Object.fromEntries(entries.map(([extractor, files]) => [extractor, files === null ? null : [...files].sort()]));+ fs.writeFileSync(tmp, JSON.stringify({ root: projectRoot, pending: serialized }));+ fs.renameSync(tmp, target);+ } catch {+ // Losing it costs a repair that reads the default patch, not data.+ }+}diff --git a/ix-cli/src/client/api.ts b/ix-cli/src/client/api.tsindex 0b858268..a9104f7f 100644--- a/ix-cli/src/client/api.ts+++ b/ix-cli/src/client/api.ts@@ -346,6 +346,19 @@ export class IxClient {return this.get(`/v1/patches/${encodeURIComponent(id)}`);}+ /**+ * Many nodes in one read, at the latest revision (Ix-memory 1.0.33+). Only+ * live nodes come back; `missing` names the other ids. At most 1000 ids per+ * call (the backend answers 413 above that). `fields: "full"` returns whole+ * nodes, attrs and provenance included.+ */+ async nodes(+ ids: string[],+ fields?: "full",+ ): Promise<{ rev: number; nodes: GraphNode[]; missing: string[] }> {+ return this.post("/v1/nodes", fields ? { ids, fields } : { ids });+ }+/*** The backend's head revision: every committed patch, in any workspace,* advances it. One indexed lookup on the backend, so it is cheap enough todiff --git a/ix-cli/test/e2e/scenarios.e2e.ts b/ix-cli/test/e2e/scenarios.e2e.tsindex be85bdf0..61578bd5 100644--- a/ix-cli/test/e2e/scenarios.e2e.ts+++ b/ix-cli/test/e2e/scenarios.e2e.ts@@ -12,7 +12,8 @@// earlier takes its own id out of the title and the list. Any other error (a// crashed map, an unreachable database) fails the run either way.-import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";+import { createHash } from "node:crypto";+import { readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";import { join } from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import {@@ -28,7 +29,10 @@ import {resetBackend,expectSameGraph,signature,+ workspaceId,} from "./harness.js";+import { IxClient } from "../../src/client/api.js";+import { loadIngestionModules } from "../../src/cli/commands/ingestion-loader.js";let env: E2eEnv;@@ -264,3 +268,122 @@ describe("agent outcomes", () => {expect(JSON.parse(many.stdout).targets.map((t: { exitCode: number }) => t.exitCode)).toEqual([0, 2, 3]);});});++describe("an extractor upgrade over a real backend (IN-20)", () => {+ // The orphan sweep decides ownership from what POST /v1/nodes returns+ // (provenance.sourceUri, attrs.external, deletedRev). The unit suite proves+ // it against a hand-written fake; this proves the real route's answer.+ const uuidOf = (text: string): string => {+ const h = createHash("sha256").update(text).digest("hex");+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-8${h.slice(17, 20)}-${h.slice(20, 32)}`;+ };++ it("retires a node the previous extractor wrote and the current one does not, and keeps an external one", async () => {+ const co = checkout("polyglot");+ const fresh = await freshSignature(env, co);+ map(env, co);++ // What the previous extractor left for app/pricing.py at its current+ // bytes: a stored patch, under that extractor's patch id, upserting a+ // node the current extractor does not write, an external package node and+ // an edge between them. Committed through the bulk route, as the CLI does.+ const [, patchBuilder] = await loadIngestionModules();+ const previous = (patchBuilder as unknown as { PREVIOUS_EXTRACTORS: string[] }).PREVIOUS_EXTRACTORS[0]!;+ const file = "app/pricing.py";+ const hash = createHash("sha256").update(readFileSync(join(co.dir, file))).digest("hex");+ const ws = workspaceId(co);+ const ghost = uuidOf(`e2e-ghost-${ws}`);+ const external = uuidOf(`e2e-ghost-external-${ws}`);+ const client = new IxClient(env.endpoint);+ await client.commitPatchBulk([{+ patchId: patchBuilder.sourcePatchIdCandidates(file, hash, ws)[1]!,+ actor: "ix-e2e",+ timestamp: new Date().toISOString(),+ baseRev: 0,+ source: { uri: file, sourceHash: hash, extractor: previous, sourceType: "code", workspaceId: ws },+ ops: [+ { type: "UpsertNode", id: ghost, kind: "function", name: "e2e_ghost", attrs: {} },+ { type: "UpsertNode", id: external, kind: "module", name: "e2e-ghost-external", attrs: { external: true } },+ { type: "UpsertEdge", id: uuidOf(`e2e-ghost-edge-${ws}`), src: ghost, dst: external, predicate: "CALLS", attrs: {} },+ ],+ replaces: [],+ intent: "e2e: a previous extractor's output",+ }]);+ const before = await client.nodes([ghost, external], "full");+ expect(before.nodes.map((n) => n.id).sort()).toEqual([ghost, external].sort());+ // The fields the sweep reads, as the real route names them.+ const ghostNode = before.nodes.find((n) => n.id === ghost)!;+ expect((ghostNode.provenance as { sourceUri?: string }).sourceUri).toBe(file);+ expect((before.nodes.find((n) => n.id === external)!.attrs as { external?: boolean }).external).toBe(true);++ // The baseline says the workspace was last mapped by the previous extractor.+ const baselineFile = readdirSync(co.ixHome).find((f) => f.startsWith("ingest_mtimes_"));+ expect(baselineFile).toBeDefined();+ const baselinePath = join(co.ixHome, baselineFile!);+ const baseline = JSON.parse(readFileSync(baselinePath, "utf8")) as { extractor?: string };+ baseline.extractor = previous;+ writeFileSync(baselinePath, JSON.stringify(baseline));++ const res = map(env, co);+ expect(res.stderr).not.toContain("[orphans kept]");++ const after = await client.nodes([ghost, external], "full");+ expect(after.missing).toContain(ghost);+ expect(after.nodes.map((n) => n.id)).toEqual([external]);+ // Everything else, the ghost's edge included, matches a fresh ingest.+ const actual = await signature(env, co);+ expectSameGraph(+ "extractor upgrade retires the dropped node",+ { nodes: actual.nodes.filter((line) => !line.includes("e2e-ghost-external")), edges: actual.edges },+ fresh,+ );+ });++ it("retires the orphan of a file whose patch at the current extractor already landed without the delete", async () => {+ const co = checkout("polyglot");+ const fresh = await freshSignature(env, co);+ const [, patchBuilder] = await loadIngestionModules();+ const previous = (patchBuilder as unknown as { PREVIOUS_EXTRACTORS: string[] }).PREVIOUS_EXTRACTORS[0]!;+ const file = "app/pricing.py";+ const hash = createHash("sha256").update(readFileSync(join(co.dir, file))).digest("hex");+ map(env, co);+ const ws = workspaceId(co);+ const ghost = uuidOf(`e2e-precommitted-ghost-${ws}`);+ const client = new IxClient(env.endpoint);++ // The previous extractor's output, then a forced ingest of the file at+ // the current extractor that commits it again under its deterministic+ // patch id with no sweep: the current patch is the head and the ghost is+ // still live.+ await client.commitPatchBulk([{+ patchId: patchBuilder.sourcePatchIdCandidates(file, hash, ws)[1]!,+ actor: "ix-e2e",+ timestamp: new Date().toISOString(),+ baseRev: 0,+ source: { uri: file, sourceHash: hash, extractor: previous, sourceType: "code", workspaceId: ws },+ ops: [{ type: "UpsertNode", id: ghost, kind: "function", name: "e2e_precommitted_ghost", attrs: {} }],+ replaces: [],+ intent: "e2e: a previous extractor's output",+ }]);+ ix(env, co, ["ingest", "--path", join(co.dir, file), "--force"]);+ expect((await client.nodes([ghost], "full")).nodes.map((n) => n.id)).toEqual([ghost]);++ // The baseline says the previous extractor: the next map is an extractor+ // change, not a repair. Its delete for app/pricing.py must not go under+ // the patch id the backend already holds, or it is answered Idempotent.+ const baselineFile = readdirSync(co.ixHome).find((f) => f.startsWith("ingest_mtimes_"));+ const baselinePath = join(co.ixHome, baselineFile!);+ const baseline = JSON.parse(readFileSync(baselinePath, "utf8")) as { extractor?: string };+ baseline.extractor = previous;+ writeFileSync(baselinePath, JSON.stringify(baseline));+ const res = map(env, co);+ expect(res.stderr).not.toContain("[orphans kept]");++ expect((await client.nodes([ghost], "full")).missing).toContain(ghost);+ // The forced ingest wrote chunk nodes a map does not; everything else+ // matches a fresh map.+ const actual = await signature(env, co);+ const noChunks = (sig: typeof actual) => ({ nodes: sig.nodes.filter((line) => !line.startsWith("chunk|")), edges: sig.edges });+ expectSameGraph("a precommitted file's orphan is retired", noChunks(actual), noChunks(fresh));+ });+});