GitNexus/gitnexus/test/integration/parse-chunk-merge-order.test.ts
Abhinav Pandey 30dcdbb86a
fix(ingestion): merge each parse chunk in one canonical order (#3926)
* fix(ingestion): merge each parse chunk in one canonical order

What
- mergeChunkResults merges a chunk in one order whatever shape it arrived
  in: graph nodes in source order (path, line, id) across all of the
  chunk's results, and symbols plus every per-file list stably by file
  path (a file's own items keep the order its parse produced).
- Exported-type accumulation walks files in path order and each file's
  nodes in parse order, as before within a file.
- Route-fact positions are recomputed against the reordered decorator
  routes: a fact sits where its file's decorator routes begin, or where
  they would begin when the file has none.
- Input already in order costs one linear check and no copy; the
  caller's arrays (which the parse cache may persist) are never sorted in
  place.

Why
A chunk reaches the merge either as batched worker results (contiguous
job slices whose files the worker groups by detected language) or as one
result per file in path order (whenever the parse cache is on). Graph
node ids, the symbol table and the route registry are first-wins, so the
owner of an id that two files declare followed the arrival shape rather
than the files. The tie rule is now: within a chunk, the file first in
path order wins.

Results
Fixture tree (gitnexus/test/fixtures, 3,459 parseable files), sorted
dumps of every node and relationship row: base and branch are
byte-identical in all modes tried (parse cache on/off, replayed cache,
1/4/default workers). On this revision the only arrival that leaves path
order is a batch that mixes Objective-C-classified headers with C++
files (1 of 1,552 fixture chunks, 2 files), and those files share no
first-wins id, so no graph row changes.

Testing
- test/unit/merge-chunk-order.test.ts: batched, two-batch, per-file and
  reversed arrivals merge identically; path order with each file's own
  order kept; route positions follow their routes; caller arrays are
  untouched. 4 of 5 fail with the fix reverted; the caller-array guard
  fails when the copy is replaced by an in-place sort, and the position
  check fails when routes are reordered without recomputing positions.
- tsc --noEmit (src and tests), eslint, prettier.
- Targeted vitest run: 32 files, 516 tests.
- Full test/unit: 1,072 of 1,091 files pass. The 19 that fail are git,
  filesystem, hook and registry tests plus two scope-resolution files
  (scopes.imports?.edgesAt is not a function); each fails with this
  change reverted too, or passes on rerun of both builds.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(ingestion): order chunk relationships by file and pin the merge through the pipeline

Addresses the review on #3926.

mergeChunkResults
- When a chunk arrives out of path order, graph relationships are now added
  stably by the path of the file that emitted them. A worker relationship
  carries no path, so it is read from the relationship's target node in the
  same result. A chunk that arrives in path order takes the previous loop
  unchanged.
- Known limit, noted in the code: when two files of one batched result
  define the same node id, a relationship to it sorts with the first of them.
- Comments now say why a batched result is out of path order (a job is
  parsed one grammar at a time) and that the arriving routePosition is not
  read.

test/integration/parse-chunk-merge-order.test.ts (new)
- Two files that declare the same Express route, a .tsx that sorts before a
  .ts in the same chunk, analyzed without a parse cache at 1 worker and at 2.
  Both runs must give the route to the .tsx and insert the same nodes and
  relationships in the same order.
- With the merge from before this PR, 3 of the 4 cases fail (the route goes
  to the .ts file at 1 worker). With the PR's merge before this commit, the
  relationship-order case fails.

test/unit/merge-chunk-order.test.ts
- The fixture now has relationships, symbols out of name order, fact-only
  files before the first and after the last routed file, an uppercase path
  that leads only under the ordinal compare, and a chunk with no decorator
  routes.
- Arrival shapes run through it.each instead of loops inside a test.
- A type-level check fails typecheck when the merge returns a list this file
  does not cover.

Checked on gitnexus/test/fixtures (no parse cache): the graph at 1 worker and
at 4 workers is identical, including relationship insertion order. Against
the PR's merge at 1 worker, sorted nodes, sorted relationships and node order
are identical and 124 relationship rows change position.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
2026-11-15 06:34:42 +00:00

109 lines
3.8 KiB
TypeScript

/**
* The parse-chunk merge through the real pipeline and the real worker, without
* a parse cache: the graph must not depend on the worker count.
*
* With one worker a chunk is one job, and a job parses its `.ts` files before
* its `.tsx` files, so the chunk reaches the merge out of path order. With one
* file per job it arrives in path order. Two files that declare the same route
* are the tie: the file first in path order owns it in both runs.
*/
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js';
import { parseCacheBucketId } from '../../src/storage/parse-cache.js';
const TSX_FILE = 'src/a0.tsx';
/** A `.ts` path that sorts after {@link TSX_FILE} and shares its parse chunk. */
function tsFileInTheSameChunk(): string {
const bucket = parseCacheBucketId(TSX_FILE);
const candidates = Array.from({ length: 4096 }, (_, index) => `src/b${index}.ts`);
const match = candidates.find((candidate) => parseCacheBucketId(candidate) === bucket);
if (match === undefined) throw new Error(`No .ts path shares a chunk with ${TSX_FILE}`);
return match;
}
const TS_FILE = tsFileInTheSameChunk();
const routeFile = (handler: string, tail: string): string =>
[
"import express from 'express';",
'',
'const app = express();',
'',
`export function ${handler}(req: unknown, res: { json(value: unknown): void }): void {`,
' res.json({ ok: true });',
'}',
'',
`app.get('/shared', ${handler});`,
tail,
'',
].join('\n');
interface GraphDump {
routeOwners: string[];
nodes: string[];
relationships: string[];
}
async function analyze(repoDir: string, workerPoolSize: number): Promise<GraphDump> {
const result = await runPipelineFromRepo(repoDir, () => {}, {
workerPoolSize,
skipGraphPhases: true,
});
const nodes = [...result.graph.iterNodes()];
return {
routeOwners: nodes
.filter((node) => node.label === 'Route')
.map((node) => `${String(node.properties.name)} @ ${String(node.properties.filePath)}`),
nodes: nodes.map((node) => `${node.label} ${node.id} @ ${String(node.properties.filePath)}`),
relationships: [...result.graph.iterRelationships()].map(
(relationship) =>
`${relationship.type} ${relationship.sourceId} -> ${relationship.targetId} (${relationship.reason})`,
),
};
}
describe('parse-chunk merge order through the pipeline', () => {
let repoDir: string;
let oneJobPerChunk: GraphDump;
let oneFilePerJob: GraphDump;
beforeAll(async () => {
repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gn-merge-order-'));
fs.mkdirSync(path.join(repoDir, 'src'));
fs.writeFileSync(
path.join(repoDir, TSX_FILE),
routeFile('handleSharedInTsx', 'export const View = () => <div />;'),
);
fs.writeFileSync(
path.join(repoDir, TS_FILE),
routeFile('handleSharedInTs', 'export const loaded = true;'),
);
oneJobPerChunk = await analyze(repoDir, 1);
oneFilePerJob = await analyze(repoDir, 2);
}, 120_000);
afterAll(() => {
fs.rmSync(repoDir, { recursive: true, force: true });
});
it('gives a route two files declare to the file first in path order at one worker', () => {
expect(oneJobPerChunk.routeOwners).toEqual([`/shared @ ${TSX_FILE}`]);
});
it('gives the same route the same owner with one file per job', () => {
expect(oneFilePerJob.routeOwners).toEqual([`/shared @ ${TSX_FILE}`]);
});
it('inserts the same nodes in the same order at either worker count', () => {
expect(oneJobPerChunk.nodes).toEqual(oneFilePerJob.nodes);
});
it('inserts the same relationships in the same order at either worker count', () => {
expect(oneJobPerChunk.relationships).toEqual(oneFilePerJob.relationships);
});
});