mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-12-04 00:17:24 +00:00
* perf(group): load route handler symbols for many files in one query What - Add CONTAINING_FILES_QUERY: CONTAINING_QUERY's three-label UNION ALL with `sym.filePath IN $filePaths`, at most 500 files per query. - The HTTP route extractor's per-file symbol cache now takes a list of files it should expect to be asked for. The graph provider pass names every file whose HANDLES_ROUTE row carries a handlerSymbolId; after the project scans, the files with project-scan detections are named too. The first cache miss loads all of them, plus the file asked for, in one query and groups the rows by file. A file with no rows caches [], which is what its own query returns. A batch whose query fails caches nothing, so each of its files falls back to its own CONTAINING_QUERY. A file that was never named still gets its own CONTAINING_QUERY, as before. - CONTAINING_QUERY and CONTAINING_FILES_QUERY are exported so an integration test can run both against a real LadybugDB. The batch has no ORDER BY, the same as CONTAINING_QUERY. Rows are grouped by file in arrival order, so each file keeps the row order its own query gives (Function, then Method, then CodeElement rows, each in scan order). resolveSymbolByName and resolveContainingSymbol depend on that order to break ties, so it is left as it was. Why `filePath` is not indexed, so each CONTAINING_QUERY scans the Function, Method and CodeElement tables to find the rows of one file, and the extractor issued one of these for every file it resolved a symbol in. Results 18 route fixtures from gitnexus/test/fixtures, each analyzed once, with the extractor of origin/main and of this branch run alternately (one warm-up, then 3 runs each). Both builds were given the same HANDLES_ROUTE and FETCHES rows, so they saw the same input order. - Output: byte-identical in all 6 runs for every repository (87 HTTP contracts). - Symbol queries: 41 per-file -> 11 batched + 7 per-file. - Median extract time summed over the 18 repositories: 217.8 ms -> 169.4 ms, of which time in symbol queries 85.4 ms -> 39.5 ms. - `gitnexus group sync` over a group of the 18 repositories: 108 contracts and 8 cross-links in every run, and the sorted contracts.json is identical across 3 runs per build. The unsorted file differs between two runs of origin/main as well, because HANDLES_ROUTE_QUERY and FETCHES_QUERY have no ORDER BY. This repository's own graph at 5c7da84f (3,565 files, 124,815 nodes, 118 HTTP contracts): - Symbol queries: 22 per-file -> 2 batched (8 files) + 14 per-file, covering the same 22 files and returning the same 681 rows. - Replaying each build's recorded symbol queries, 7 alternating runs: median 197.3 ms -> 145.7 ms. - The remaining 14 per-file queries are files reached through FETCHES rows, which are not named in advance. Testing - Unit (http-route-extractor.test.ts): one handler-file batch and no per-file queries; a file never named gets its own query; a failing batch falls back to one query per file with identical contracts; a file the batch has no rows for caches [] with no further query; batched and per-file runs resolve the same symbols, including an equal-span tie that only row order decides. - Express stubs that matched on $filePath also answer $filePaths, and the failed-lookup test in http-route-graph-method.test.ts now expects the failing batch followed by one per-file query, still with no retry per route. - Integration (http-route-symbol-batch.test.ts): real pipeline and LadybugDB; for every file, the batch returns exactly that file's CONTAINING_QUERY rows in the same order, and the extractor gives the same contracts with and without the batch, in fewer queries. - With the source change reverted, 8 of these tests fail. - tsc --noEmit; vitest on test/unit/group, test/integration/group and the route integration tests: 83 files, 1462 tests passed. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * perf(group): enforce linear symbol loading Bound selective lookups, reuse one symbol snapshot for larger workloads, and index handler IDs per file. Add a native scaling gate with exact contract checks and before/after evidence. Refs #3929 * perf(group): load named symbol files with one hash-join query Above 500 files the loader switched to a scan that returned every symbol row of the repository. Row transfer costs far more per row than the scan, so on a 120,000-symbol database 501 handler files took 9.3 s against 0.42 s for the 500-file IN batches before it and 6.3 s for one query per file, and files discovered late paid 500 per-file queries and then the scan. Replace both the capped IN batches and the complete scan with one UNWIND join per group of named files. The engine plans it as a hash join: one scan per table whatever the length of the list, and only the named files' rows come back. Every pass now names its files first (all route files, then every scanned file with a detection), so a healthy extraction issues two symbol queries. Same shapes after the change: 501 handler files 0.24 s, 501 late files 0.48 s (was 16 s), identical contracts. Sort each file's rows on node table and scan offset when they enter the cache. On a multi-thread connection the engine returns a file's rows in an order that changes between calls, so the first-match resolvers could pick a different symbol from run to run; the three load paths now give one order by construction. Bench: every fixture holds as many unrequested symbols again and each run asserts the queries returned exactly the requested files' rows; returned rows join the gated metrics; median averages the two middle values for an even sample count. The integration test compares row sets for every file, adds a mixed-label file with an equal-span tie, asserts exact query counts, and is registered in the lbug-db project and the cross-platform list. Refs #3929 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * docs(bench): re-measure the route symbol gate at the join loader Regenerate the committed evidence with the harness ofe6fa28fcbfrom clean checkouts: baseline5340562f5(500-file IN batches) fails the gate on scanned tuples (9.00) and handler-ID reads (15.94); candidatee6fa28fcbpasses every comparison, with scanned tuples, returned rows and ID reads at exactly 1.00. RESULTS.md names both commits, records that the complete-scan revision2ebbdd79dfails the returned-rows check at N=1,024, and drops the wording that described5340562f5as the PR head. Refs #3929 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>
265 lines
12 KiB
TypeScript
265 lines
12 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
import fs from 'node:fs';
|
|
import * as globModule from 'glob';
|
|
import * as fsUtils from '../../../src/core/group/extractors/fs-utils.js';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import { HttpRouteExtractor } from '../../../src/core/group/extractors/http-route-extractor.js';
|
|
import type { RepoHandle } from '../../../src/core/group/types.js';
|
|
import {
|
|
getRelationships,
|
|
runPipelineFromRepo,
|
|
writeFixtureRepo,
|
|
} from '../../integration/resolvers/helpers.js';
|
|
|
|
vi.mock('glob', { spy: true });
|
|
|
|
describe('Express group provider provenance', () => {
|
|
let root: string;
|
|
const extractor = new HttpRouteExtractor();
|
|
beforeEach(() => {
|
|
root = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-group-express-'));
|
|
});
|
|
afterEach(() => {
|
|
vi.resetAllMocks();
|
|
vi.restoreAllMocks();
|
|
fs.rmSync(root, { recursive: true, force: true });
|
|
});
|
|
const write = (files: Record<string, string>) => writeFixtureRepo(root, files);
|
|
const repo = (): RepoHandle => ({
|
|
id: 'test',
|
|
path: root,
|
|
repoPath: root,
|
|
storagePath: path.join(root, '.gitnexus'),
|
|
});
|
|
const providers = (contracts: Awaited<ReturnType<HttpRouteExtractor['extract']>>) =>
|
|
contracts
|
|
.filter((contract) => contract.role === 'provider')
|
|
.map((contract) => contract.contractId)
|
|
.sort();
|
|
|
|
it('composes imported Express routers instead of publishing their local paths', async () => {
|
|
write({
|
|
'server.ts': `import express from 'express'; import router from './router'; const app = express(); app.use('/api', router);`,
|
|
'router.ts': `import { Router } from 'express'; const router = Router(); router.get('/users', () => {}); export default router;`,
|
|
});
|
|
expect(providers(await extractor.extract(null, root, repo()))).toEqual([
|
|
'http::GET::/api/users',
|
|
]);
|
|
});
|
|
|
|
it('retains project providers when the filesystem supplies Windows separators', async () => {
|
|
write({
|
|
'src/server.ts': `import express from 'express'; import router from './router'; const app = express(); app.use('/api', router);`,
|
|
'src/router.ts': `import { Router } from 'express'; const router = Router(); router.get('/users', () => {}); export default router;`,
|
|
});
|
|
vi.spyOn(globModule, 'glob').mockResolvedValue(['src\\server.ts', 'src\\router.ts']);
|
|
const readSafe = fsUtils.readSafe;
|
|
vi.spyOn(fsUtils, 'readSafe').mockImplementation((repoPath, rel) =>
|
|
readSafe(repoPath, rel.replace(/\\/g, '/')),
|
|
);
|
|
expect(providers(await extractor.extract(null, root, repo()))).toEqual([
|
|
'http::GET::/api/users',
|
|
]);
|
|
});
|
|
|
|
it('does not admit arbitrary receivers named app or router', async () => {
|
|
write({
|
|
'server.ts': `const router = new Map(); router.get('/not-http', 'fallback'); const app = { post() {} }; app.post('/also-not-http', () => {});`,
|
|
});
|
|
expect(providers(await extractor.extract(null, root, repo()))).toEqual([]);
|
|
});
|
|
|
|
it('uses lexical ownership for closure writes and parameter redeclarations', async () => {
|
|
write({
|
|
'server.ts': `import express from 'express';
|
|
let app = express(); function replace() { app = new Map(); }
|
|
app.get('/let-closure', handler);
|
|
function overwritten(app) { var app = storage; app.get('/overwritten', handler); }
|
|
function ambiguous(app, { value = 1 }) { var app; app.get('/ambiguous', handler); }
|
|
function retained(app) { var app; function nested(app) { app = new Map(); } app.get('/retained', handler); }
|
|
overwritten(express()); ambiguous(express()); retained(express());`,
|
|
});
|
|
expect(providers(await extractor.extract(null, root, repo()))).toEqual([
|
|
'http::GET::/retained',
|
|
]);
|
|
});
|
|
|
|
it('agrees with ingestion across mixed extensions, aliases and multiple mounts while preserving consumers and other providers', async () => {
|
|
write({
|
|
'tsconfig.json': JSON.stringify({
|
|
compilerOptions: { baseUrl: '.', paths: { '@routes/*': ['src/*'] } },
|
|
}),
|
|
'server.ts': `import express from 'express'; import { middle } from '@routes/middle'; import hidden from './src/hidden'; const app = express(); app.use(['/v1', '/v2'], auth, middle); app.use(runtimePrefix, middle); app.use(runtimePrefix, hidden);`,
|
|
'src/middle.js': `import { Router } from 'express'; import { nested } from './leaf'; export const middle = Router(); middle.use('/admin', nested);`,
|
|
'src/leaf.tsx': `import { Router } from 'express'; import axios from 'axios'; export const nested = Router(); nested.get('/users', () => {}); export async function outbound() { await fetch('/remote'); return axios.post('/outbound'); }`,
|
|
'src/hidden.js': `import { Router } from 'express'; const hidden = Router(); hidden.get('/hidden', () => {}); export default hidden;`,
|
|
'src/other.ts': `import { Hono } from 'hono'; import { Controller, Get } from '@nestjs/common'; const edge = new Hono(); edge.get('/hono', () => {}); @Controller('nest') class ControllerClass { @Get('list') list() {} } const routes = [{ path: '/table', method: 'POST', handler: tableHandler }]; function tableHandler() {} for (const route of routes) { if (route.path === request.path && route.method === request.method) route.handler(); }`,
|
|
});
|
|
const expected = [
|
|
'http::GET::/hono',
|
|
'http::GET::/nest/list',
|
|
'http::GET::/v1/admin/users',
|
|
'http::GET::/v2/admin/users',
|
|
'http::POST::/table',
|
|
];
|
|
const sourceOnly = await extractor.extract(null, root, repo());
|
|
expect(providers(sourceOnly)).toEqual(expected);
|
|
expect(
|
|
sourceOnly
|
|
.filter((contract) => contract.role === 'consumer')
|
|
.map((contract) => contract.contractId)
|
|
.sort(),
|
|
).toEqual(['http::GET::/remote', 'http::POST::/outbound']);
|
|
|
|
const ingested = await runPipelineFromRepo(root, () => {});
|
|
const rows = getRelationships(ingested, 'HANDLES_ROUTE')
|
|
.filter((edge) => edge.sourceLabel === 'File')
|
|
.map((edge) => {
|
|
const route = ingested.graph.getNode(edge.rel.targetId)!;
|
|
return {
|
|
fileId: edge.rel.sourceId,
|
|
filePath: edge.sourceFilePath,
|
|
routePath: edge.target,
|
|
routeMethod: route.properties.method,
|
|
routeSource: edge.rel.reason,
|
|
handlerSymbolId: route.properties.handlerSymbolId,
|
|
};
|
|
});
|
|
expect(rows.map((row) => `http::${row.routeMethod}::${row.routePath}`).sort()).toEqual(
|
|
expected,
|
|
);
|
|
const db = async (query: string) => (query.includes("type: 'HANDLES_ROUTE'") ? rows : []);
|
|
expect(providers(await extractor.extract(db, root, repo()))).toEqual(expected);
|
|
|
|
// A later run rebuilds project relationships even when router files are unchanged.
|
|
write({
|
|
'server.ts': `import express from 'express'; import { middle } from '@routes/middle'; import hidden from './src/hidden'; const app = express(); app.use('/v3', middle); app.use(runtimePrefix, hidden);`,
|
|
});
|
|
expect(providers(await extractor.extract(null, root, repo()))).toEqual([
|
|
'http::GET::/hono',
|
|
'http::GET::/nest/list',
|
|
'http::GET::/v3/admin/users',
|
|
'http::POST::/table',
|
|
]);
|
|
}, 60000);
|
|
|
|
it('enriches composed graph routes from exact same-line registrations and imported handler aliases', async () => {
|
|
write({
|
|
'server.ts': `import express from 'express'; import router from './router'; const app = express(); app.use('/api', router);`,
|
|
'router.ts': `import { Router } from 'express'; import { list as imported } from './handlers'; const router = Router(); function local() {} router.get('/local', local); router.get('/imported', imported); export default router;`,
|
|
'handlers.ts': `export function list() {}`,
|
|
});
|
|
const db = async (
|
|
query: string,
|
|
params?: Record<string, unknown>,
|
|
): Promise<Record<string, unknown>[]> => {
|
|
if (query.includes("type: 'HANDLES_ROUTE'"))
|
|
return ['/local', '/imported'].map((route) => ({
|
|
fileId: 'router-file',
|
|
filePath: 'router.ts',
|
|
routePath: `/api${route}`,
|
|
routeMethod: 'GET',
|
|
handlerSymbolId: '',
|
|
}));
|
|
// One `$filePath`, or the `$filePaths` list the extractor names route files with.
|
|
const askedFiles = Array.isArray(params?.filePaths) ? params.filePaths : [params?.filePath];
|
|
if (query.includes('UNION ALL') && askedFiles.includes('router.ts'))
|
|
return [
|
|
{
|
|
uid: 'local-uid',
|
|
name: 'local',
|
|
filePath: 'router.ts',
|
|
startLine: 0,
|
|
endLine: 0,
|
|
labels: ['Function'],
|
|
},
|
|
];
|
|
if (query.includes('STARTS WITH') && params?.name === 'list')
|
|
return [{ uid: 'list-uid', name: 'list', filePath: 'handlers.ts' }];
|
|
return [];
|
|
};
|
|
const contracts = await extractor.extract(db, root, repo());
|
|
expect(providers(contracts)).toEqual(['http::GET::/api/imported', 'http::GET::/api/local']);
|
|
expect(
|
|
contracts.find((contract) => contract.contractId === 'http::GET::/api/imported'),
|
|
).toMatchObject({
|
|
symbolUid: 'list-uid',
|
|
symbolRef: { filePath: 'handlers.ts' },
|
|
meta: { extractionStrategy: 'graph_assisted' },
|
|
});
|
|
expect(
|
|
contracts.find((contract) => contract.contractId === 'http::GET::/api/local')?.symbolUid,
|
|
).toBe('local-uid');
|
|
});
|
|
|
|
it('does not borrow global handlers or the enclosing registrar for unresolved handler designators', async () => {
|
|
write({
|
|
'router.ts': `import { Router } from 'express';
|
|
import { imported } from './handlers';
|
|
const router = Router();
|
|
function handler() {}
|
|
function install(handler, imported, object) {
|
|
router.get('/parameter', handler); router.get('/shadowed-import', imported); router.get('/member', object.handler);
|
|
router.get('/inline', () => {});
|
|
}
|
|
function unknown() { router.get('/unknown', missing); }
|
|
export default router;`,
|
|
});
|
|
const db = async (query: string): Promise<Record<string, unknown>[]> =>
|
|
query.includes('UNION ALL')
|
|
? [
|
|
{
|
|
uid: 'global-handler',
|
|
name: 'handler',
|
|
filePath: 'router.ts',
|
|
startLine: 3,
|
|
endLine: 3,
|
|
labels: ['Function'],
|
|
},
|
|
{
|
|
uid: 'registrar',
|
|
name: 'install',
|
|
filePath: 'router.ts',
|
|
startLine: 4,
|
|
endLine: 7,
|
|
labels: ['Function'],
|
|
},
|
|
{
|
|
uid: 'unknown-registrar',
|
|
name: 'unknown',
|
|
filePath: 'router.ts',
|
|
startLine: 8,
|
|
endLine: 8,
|
|
labels: ['Function'],
|
|
},
|
|
]
|
|
: [];
|
|
const contracts = await extractor.extract(db, root, repo());
|
|
expect(providers(contracts)).toEqual([
|
|
'http::GET::/inline',
|
|
'http::GET::/member',
|
|
'http::GET::/parameter',
|
|
'http::GET::/shadowed-import',
|
|
'http::GET::/unknown',
|
|
]);
|
|
for (const contract of contracts.filter(
|
|
(contract) => contract.contractId !== 'http::GET::/inline',
|
|
))
|
|
expect(contract.symbolUid).toBe('');
|
|
expect(
|
|
contracts.find((contract) => contract.contractId === 'http::GET::/inline')?.symbolUid,
|
|
).toBe('registrar');
|
|
});
|
|
|
|
it('fails closed when configured internal modules shadow framework package names', async () => {
|
|
write({
|
|
'tsconfig.json': JSON.stringify({
|
|
compilerOptions: { baseUrl: '.', paths: { express: ['./local.ts'], hono: ['./local.ts'] } },
|
|
}),
|
|
'local.ts': `export default function storage() { return new Map(); } export class Hono { get() {} }`,
|
|
'server.ts': `import express from 'express'; import { Hono } from 'hono'; const app = express(); const edge = new Hono(); app.get('/not-http', 'fallback'); edge.get('/also-not-http', () => {});`,
|
|
});
|
|
expect(providers(await extractor.extract(null, root, repo()))).toEqual([]);
|
|
});
|
|
});
|