mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-11-29 23:37:41 +00:00
* feat(scope-resolution): ImportVisibility over shared import groups A second implementation of `ImportVisibility`. An import statement that resolves to a whole list of files and binds no name from them is stored once, as a group holding the statement and the provider's own list. Every scope importing the same package refers to one array and one membership set, so storage is one entry per statement plus one set per distinct list, not one edge per (importing scope, file). A group is left out of `edgesAt`, which is only sound for an import no reader can select by name, definition or kind; construction refuses any other group. Not wired into finalize yet: no provider produces groups, and nothing changes at run time. It runs the same 71 contract cases as the eager implementation. Refs #3695 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * feat(scope-resolution): finalize can store a wildcard import as one group New opt-in hook `FinalizeHooks.groupsWildcardTargets`. When a wildcard import resolves to a list of files, finalize records one group over the resolver's own list instead of one draft and one edge per file, and reports the scopes' edges and groups in statement order as `importEntries`. The orchestrator then builds the grouped `ImportVisibility`; without groups it builds the eager one as before. A statement is grouped only when the two forms cannot be told apart: the list is non-empty, no file of it binds a name through the wildcard (`expandsWildcardTo` is empty), none is reclassified by `isNamespaceImport`, and the provider sets neither `filterWildcardNames` nor `wildcardCollisionIsAmbiguous`. Anything else keeps one edge per file. What a group must still contribute is kept: - cycle analysis sees the group's files as neighbours at the statement's position, so `sccs` and their order are unchanged; a file listed in its own group is still a self-cycle - the per-SCC pass cap and progress count the files as before - `totalEdges` and `linkedEdges` count one per listed file - a file with a module-scope group is still a re-exporting file, and the re-export closure builder is handed the drafts the groups stand for, only for the duration of a build No provider opts in yet, so nothing changes at run time. Tests run the same input with the hook off and on (9 hand-written and 80 generated workspaces) and compare `sccs` with order, `stats`, bindings, the sequence of finalize phases, and every answer of the resulting `ImportVisibility`. Refs #3695 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * perf(java): store an on-demand import once per statement and per package Java opts into grouped wildcard imports (`groupsWildcardImportTargets`). `import pkg.*;` binds no name in the importing file, and `resolveJavaModule` answers every importer of a package with the same list, so finalize now records one group per statement over that shared list instead of one draft and one edge per (importing file, package file). `finalizeScopeModel` rebuilt its hooks object field by field and dropped the new hook; it now forwards it. A test looks at the stored form itself through the whole chain (provider flag, pipeline, orchestrator, finalize, `ImportVisibility`), because grouping changes no answer and its absence passes every behavioural test. `GITNEXUS_DISABLE_IMPORT_GROUPS=1` restores one edge per imported file, to compare the two forms on one build. Measured on one build with the switch on and off, 700 files each importing a 700-file package (490,000 pairs), heap after a forced GC: finalize imports growth +81 MB -> +1 MB finalize peak (bindings-end) 211 MB -> 84 MB after finalize 126 MB -> 84 MB end of the Java pass 138 MB -> 91 MB IMPORTS edges emitted 700 -> 700 The fourteen JLS scenarios pinned to pre-change edges are unchanged. Refs #3695 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * bench(scope-resolution): check Java on-demand import storage and retained heap `bench/import-emission` builds its edge map by hand and calls the emitter directly, so it never runs finalize, never sees a wildcard, and stays green whether on-demand imports are grouped or not. `wildcard-java.mts` runs the real Java pass over 700 files that each write `import big.*;` on a 700-file package (490,000 pairs, 700 IMPORTS edges). With `--check` it requires: - no wildcard import stored as one edge per package file - every importer still reaches every package file - the reviewed graph fingerprint, identical for both storage forms - at most 16 MiB of heap retained by the pass Measured in three fresh processes each: 4.3 MiB retained with groups, 54.5 MiB with `GITNEXUS_DISABLE_IMPORT_GROUPS=1`. The heap budget is what catches a later pass that rebuilds a per-importer structure over every package file while the graph stays the same. Runs in the existing scope-resolution benchmark job. Refs #3695 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(java): preserve grouped scope import edges Stream group targets when emitting the optional scope graph. Preserve explicit module links and skip unresolved or external targets. Update remaining receiver fixtures to the ImportVisibility contract. Make trailing-group bounds explicit and document the storage comparison switch with a forced rebuild. Refs #3909 * perf(scope-resolution): write out a group's drafts one file at a time for re-export closures The closure builder reads per-file drafts. For grouped wildcard imports it was handed a map holding one draft per (importer, listed file) pair for every file of the workspace, for as long as the build ran: the structure grouping removes. It now gets a view that writes out one file's drafts per lookup. On the 700 x 700 workload with one static import that starts the closure build, the pass completes in 160 MB of old space instead of failing at 200 MB. The graph is unchanged. The closure tables themselves are unchanged too. Refs #3695, review of #3934. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * refactor(scope-resolution): keep grouped imports out of the finalize fixpoint count The fixpoint counted each group target as an intra-SCC edge and seeded its first pass as progress, to run as many passes as with one edge per file. tryFinalize reads no other draft's state, so the number of passes changes no result, and no test could observe it. Without the two additions the loop and countEdgesWithin are the same as before grouped storage. Refs review of #3934. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * bench(scope-resolution): check on-demand import storage while re-export closures are built The 700 x 700 gate has no import that starts the re-export closure build and asserts heap retained after the pass, so it could not see what that build holds while it runs. --closure adds an enum with an on-demand import and a static import of one of its constants. CI runs that shape under --max-old-space-size=180: the pass completes in 160 MB (not in 150 MB) and did not complete in 200 MB with one draft per (importer, package file) pair. The graph fingerprint is the same with groups and with one edge per file. Refs #3695, review of #3934. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * perf(scope-resolution): answer import membership from one set past 16 shared lists membership().has probed one set per grouped import of the scope. Measured on a pass with 300,000 lookups, 10 lists cost nothing against a single set, 100 cost 8% and 1,000 tripled the pass. A scope with more than 16 lists now merges them on its first lookup. The contract suite gains a scope with 20 wildcards. Refs review of #3934. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * test(java): compare both import storage forms through the pipeline The storage-form tests pass onResolved, which keeps the reference-lookup cache off, so no checked-in test compared grouped storage with one edge per file while that cache was installed. The 14 JLS scenarios now run through the whole pipeline in both forms. The opt-in comment said finalize falls back wherever the forms could differ. Finalize can only check itself: a provider hook that reads wildcard targets from edgesAt would silently change behaviour. The comment now states that obligation, and a test pins Java as the only provider that opts in. java-import-groups.test.ts no longer fails when the shell exports GITNEXUS_DISABLE_IMPORT_GROUPS=1. Refs review of #3934. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
336 lines
12 KiB
TypeScript
336 lines
12 KiB
TypeScript
import { describe, expect, it } from 'vitest';
|
|
import {
|
|
createEagerImportVisibility,
|
|
createGroupedImportVisibility,
|
|
finalize,
|
|
importTargetDirectory,
|
|
type FinalizeFile,
|
|
type FinalizeHooks,
|
|
type FinalizeOutput,
|
|
type ImportEntry,
|
|
type ParsedImport,
|
|
type ScopeId,
|
|
type SymbolDefinition,
|
|
} from 'gitnexus-shared';
|
|
import { observeAsked, prng } from '../../helpers/import-visibility-contract.js';
|
|
|
|
/**
|
|
* `FinalizeHooks.groupsWildcardTargets` changes how a wildcard import is
|
|
* stored, never what finalize answers. Every case below runs the same input
|
|
* twice, hook off and hook on, and compares everything a consumer can observe.
|
|
*/
|
|
|
|
interface Workspace {
|
|
readonly name: string;
|
|
readonly files: readonly FinalizeFile[];
|
|
/** package name → the one array every importer of that package receives. */
|
|
readonly packages: ReadonlyMap<string, readonly string[]>;
|
|
}
|
|
|
|
const moduleScope = (filePath: string): ScopeId => `scope:${filePath}#module` as ScopeId;
|
|
const type = (filePath: string, name: string): SymbolDefinition => ({
|
|
nodeId: `def:${filePath}:${name}`,
|
|
filePath,
|
|
type: 'Class',
|
|
qualifiedName: name,
|
|
});
|
|
const at = (line: number) => ({ startLine: line, startCol: 0, endLine: line, endCol: 30 });
|
|
const wildcard = (pkg: string, line: number, extra: object = {}): ParsedImport =>
|
|
({ kind: 'wildcard', targetRaw: `pkg:${pkg}`, atRange: at(line), ...extra }) as ParsedImport;
|
|
const named = (name: string, targetRaw: string, line: number): ParsedImport =>
|
|
({
|
|
kind: 'named',
|
|
localName: name,
|
|
importedName: name,
|
|
targetRaw,
|
|
atRange: at(line),
|
|
}) as ParsedImport;
|
|
const source = (
|
|
filePath: string,
|
|
names: readonly string[],
|
|
imports: readonly ParsedImport[],
|
|
): FinalizeFile => ({
|
|
filePath,
|
|
moduleScope: moduleScope(filePath),
|
|
localDefs: names.map((name) => type(filePath, name)),
|
|
parsedImports: imports,
|
|
});
|
|
|
|
/** A provider whose wildcard names a package: every importer gets the same list. */
|
|
const hooks = (workspace: Workspace, overrides: Partial<FinalizeHooks> = {}): FinalizeHooks => ({
|
|
resolveImportTarget: (targetRaw) =>
|
|
targetRaw.startsWith('pkg:')
|
|
? (workspace.packages.get(targetRaw.slice(4)) ?? null)
|
|
: workspace.files.some((file) => file.filePath === targetRaw)
|
|
? targetRaw
|
|
: null,
|
|
expandsWildcardTo: () => [],
|
|
mergeBindings: (existing, incoming) => [...existing, ...incoming],
|
|
...overrides,
|
|
});
|
|
|
|
function run(workspace: Workspace, grouped: boolean, overrides: Partial<FinalizeHooks> = {}) {
|
|
const phases: string[] = [];
|
|
const output = finalize(
|
|
{
|
|
files: workspace.files,
|
|
workspaceIndex: undefined as never,
|
|
onProgress: (phase) => phases.push(phase),
|
|
},
|
|
hooks(workspace, { ...overrides, groupsWildcardTargets: grouped }),
|
|
);
|
|
return { output, phases };
|
|
}
|
|
|
|
const visibilityOf = (output: FinalizeOutput) =>
|
|
output.importEntries === undefined
|
|
? createEagerImportVisibility(output.imports)
|
|
: createGroupedImportVisibility(output.importEntries, output.imports);
|
|
|
|
/** Everything a consumer can observe about one finalize result. */
|
|
function observed(workspace: Workspace, result: ReturnType<typeof run>) {
|
|
const files = [
|
|
...new Set([
|
|
...workspace.files.map((file) => file.filePath),
|
|
...[...workspace.packages.values()].flat(),
|
|
'never/Imported.java',
|
|
]),
|
|
];
|
|
const scopes = [...new Set([...result.output.imports.keys(), 'scope:absent' as ScopeId])];
|
|
return {
|
|
phases: result.phases,
|
|
sccs: result.output.sccs,
|
|
stats: result.output.stats,
|
|
bindings: [...result.output.bindings].map(([scope, byName]) => [scope, [...byName]]),
|
|
visibility: observeAsked(
|
|
{ scopes, files, directories: [...new Set(files.map(importTargetDirectory))] },
|
|
visibilityOf(result.output),
|
|
),
|
|
};
|
|
}
|
|
|
|
const groupsIn = (output: FinalizeOutput): number =>
|
|
[...(output.importEntries?.values() ?? [])]
|
|
.flat()
|
|
.filter((entry: ImportEntry) => 'targetFiles' in entry).length;
|
|
const edgesIn = (output: FinalizeOutput): number => [...output.imports.values()].flat().length;
|
|
|
|
const PKG_A = ['a/One.java', 'a/Two.java', 'a/Three.java'];
|
|
const PKG_B = ['b/One.java', 'b/Four.java'];
|
|
const lexical = (scope: string) => ({
|
|
bindsAtLexicalScope: true,
|
|
declaredAtScope: scope as ScopeId,
|
|
});
|
|
|
|
const workspaces: readonly Workspace[] = [
|
|
{
|
|
name: 'one importer of one package',
|
|
packages: new Map([['a', PKG_A]]),
|
|
files: [
|
|
...PKG_A.map((path) => source(path, [path.slice(2, -5)], [])),
|
|
source('app/U.java', ['U'], [wildcard('a', 1)]),
|
|
],
|
|
},
|
|
{
|
|
name: 'explicit imports interleaved with two wildcards, one written twice',
|
|
packages: new Map([
|
|
['a', PKG_A],
|
|
['b', PKG_B],
|
|
]),
|
|
files: [
|
|
...PKG_A.map((path) => source(path, [path.slice(2, -5)], [])),
|
|
...PKG_B.map((path) => source(path, [path.slice(2, -5)], [])),
|
|
source(
|
|
'app/U.java',
|
|
['U'],
|
|
[
|
|
named('One', 'a/One.java', 1),
|
|
wildcard('b', 2),
|
|
named('Gone', 'missing/Gone.java', 3),
|
|
wildcard('a', 4),
|
|
wildcard('b', 5),
|
|
named('Two', 'a/Two.java', 6),
|
|
],
|
|
),
|
|
],
|
|
},
|
|
{
|
|
name: 'a file that imports its own package is a self-cycle',
|
|
packages: new Map([['app', ['app/U.java', 'app/V.java']]]),
|
|
files: [source('app/U.java', ['U'], [wildcard('app', 1)]), source('app/V.java', ['V'], [])],
|
|
},
|
|
{
|
|
name: 'two packages that import each other form one cycle',
|
|
packages: new Map([
|
|
['a', ['a/A.java', 'a/A2.java']],
|
|
['b', ['b/B.java']],
|
|
]),
|
|
files: [
|
|
source('a/A.java', ['A'], [wildcard('b', 1)]),
|
|
source('a/A2.java', ['A2'], []),
|
|
source('b/B.java', ['B'], [wildcard('a', 1), named('A', 'a/A.java', 2)]),
|
|
],
|
|
},
|
|
{
|
|
name: 'a package list that names a file outside the workspace',
|
|
packages: new Map([['a', ['a/One.java', 'external/Ghost.java']]]),
|
|
files: [source('a/One.java', ['One'], []), source('app/U.java', ['U'], [wildcard('a', 1)])],
|
|
},
|
|
{
|
|
name: 'a wildcard bound at a lexical scope, alone and beside a module wildcard',
|
|
packages: new Map([
|
|
['a', PKG_A],
|
|
['b', PKG_B],
|
|
]),
|
|
files: [
|
|
...PKG_A.map((path) => source(path, [path.slice(2, -5)], [])),
|
|
...PKG_B.map((path) => source(path, [path.slice(2, -5)], [])),
|
|
source(
|
|
'app/U.java',
|
|
['U'],
|
|
[wildcard('a', 1), wildcard('b', 9, lexical('scope:app/U.java#fn'))],
|
|
),
|
|
source('app/V.java', ['V'], [wildcard('a', 4, lexical('scope:app/V.java#fn'))]),
|
|
],
|
|
},
|
|
{
|
|
name: 'a named import that only resolves through its target wildcard (re-export closure)',
|
|
packages: new Map([['a', PKG_A]]),
|
|
files: [
|
|
...PKG_A.map((path) => source(path, [path.slice(2, -5)], [])),
|
|
source('hub/Hub.java', ['Hub'], [wildcard('a', 1)]),
|
|
source(
|
|
'app/U.java',
|
|
['U'],
|
|
[named('Two', 'hub/Hub.java', 1), named('Nope', 'hub/Hub.java', 2)],
|
|
),
|
|
],
|
|
},
|
|
{
|
|
name: 'presence flags on a wildcard',
|
|
packages: new Map([['a', PKG_A]]),
|
|
files: [
|
|
...PKG_A.map((path) => source(path, [path.slice(2, -5)], [])),
|
|
source('app/U.java', ['U'], [wildcard('a', 1, { runsOnlyWhenCalled: true })]),
|
|
],
|
|
},
|
|
{
|
|
name: 'a package with no files and an import that resolves to nothing',
|
|
packages: new Map([['empty', []]]),
|
|
files: [source('app/U.java', ['U'], [wildcard('empty', 1), wildcard('unknown', 2)])],
|
|
},
|
|
];
|
|
|
|
/** Same seed, same workspace. Small universe, so every shape above recurs. */
|
|
function generated(seed: number): Workspace {
|
|
const next = prng(seed);
|
|
const pick = (count: number): number => Math.floor(next() * count);
|
|
const packageNames = ['p0', 'p1', 'p2', 'p3'];
|
|
const paths = Array.from(
|
|
{ length: 4 + pick(8) },
|
|
(_, i) => `${packageNames[pick(4)]}/F${i}.java`,
|
|
);
|
|
const packages = new Map(
|
|
packageNames.map((pkg) => [
|
|
pkg,
|
|
[
|
|
...paths.filter((path) => path.startsWith(`${pkg}/`)),
|
|
...(pick(5) === 0 ? ['external/X.java'] : []),
|
|
],
|
|
]),
|
|
);
|
|
const files = paths.map((path, i) =>
|
|
source(
|
|
path,
|
|
[`T${i}`, ...(pick(3) === 0 ? ['Shared'] : [])],
|
|
Array.from({ length: pick(6) }, (_, line): ParsedImport => {
|
|
const shape = pick(6);
|
|
return shape < 3
|
|
? wildcard(packageNames[pick(4)]!, line, pick(4) === 0 ? lexical(`scope:${path}#fn`) : {})
|
|
: shape === 3
|
|
? named(`T${pick(paths.length)}`, paths[pick(paths.length)]!, line)
|
|
: shape === 4
|
|
? named('Shared', paths[pick(paths.length)]!, line)
|
|
: named('Gone', 'missing/Gone.java', line);
|
|
}),
|
|
),
|
|
);
|
|
return { name: `generated workspace, seed ${seed}`, files, packages };
|
|
}
|
|
|
|
const generatedWorkspaces = Array.from({ length: 80 }, (_, i) => generated(5000 + i));
|
|
|
|
describe('finalize: grouped wildcard imports change storage, not answers', () => {
|
|
it.each([...workspaces, ...generatedWorkspaces])('$name', (workspace) => {
|
|
expect(observed(workspace, run(workspace, true))).toEqual(
|
|
observed(workspace, run(workspace, false)),
|
|
);
|
|
});
|
|
|
|
it('stores one group per statement and no edge per package file', () => {
|
|
const workspace = workspaces[0]!;
|
|
const off = run(workspace, false).output;
|
|
const on = run(workspace, true).output;
|
|
expect([edgesIn(off), groupsIn(off)]).toEqual([PKG_A.length, 0]);
|
|
expect([edgesIn(on), groupsIn(on)]).toEqual([0, 1]);
|
|
});
|
|
|
|
it('keeps the list the resolver returned, by reference', () => {
|
|
const workspace = workspaces[0]!;
|
|
const entries = [...(run(workspace, true).output.importEntries?.values() ?? [])].flat();
|
|
expect(entries).toHaveLength(1);
|
|
expect((entries[0] as { targetFiles: readonly string[] }).targetFiles).toBe(PKG_A);
|
|
});
|
|
|
|
it('reports no entries at all when nothing was grouped', () => {
|
|
expect(run(workspaces[8]!, true).output.importEntries).toBeUndefined();
|
|
expect(run(workspaces[0]!, false).output.importEntries).toBeUndefined();
|
|
});
|
|
|
|
it('builds re-export closures in the same case with the hook on and off', () => {
|
|
const workspace = workspaces[6]!;
|
|
expect(run(workspace, true).phases).toContain('reexports-start');
|
|
expect(run(workspace, false).phases).toContain('reexports-start');
|
|
});
|
|
|
|
it('exercises groups, cycles and closures in the generated workspaces', () => {
|
|
const results = generatedWorkspaces.map((workspace) => run(workspace, true));
|
|
expect(results.filter((result) => groupsIn(result.output) > 0).length).toBeGreaterThan(60);
|
|
expect(
|
|
results.filter((result) => result.output.sccs.some((scc) => scc.isCycle)).length,
|
|
).toBeGreaterThan(10);
|
|
expect(
|
|
results.filter((result) => result.phases.includes('reexports-start')).length,
|
|
).toBeGreaterThan(5);
|
|
});
|
|
|
|
describe('a statement that could be told apart keeps one edge per file', () => {
|
|
const workspace = workspaces[1]!;
|
|
const cases: readonly { readonly name: string; readonly overrides: Partial<FinalizeHooks> }[] =
|
|
[
|
|
{
|
|
name: 'a target whose wildcard binds a name',
|
|
overrides: { expandsWildcardTo: () => ['One'] },
|
|
},
|
|
{
|
|
name: 'a provider that filters wildcard names',
|
|
overrides: { filterWildcardNames: (_scope, names) => names },
|
|
},
|
|
{
|
|
name: 'a provider whose wildcard collisions are ambiguous',
|
|
overrides: { wildcardCollisionIsAmbiguous: true },
|
|
},
|
|
{
|
|
name: 'a target reclassified as a namespace import',
|
|
overrides: { isNamespaceImport: () => true },
|
|
},
|
|
];
|
|
it.each(cases)('$name', ({ overrides }) => {
|
|
const on = run(workspace, true, overrides);
|
|
const off = run(workspace, false, overrides);
|
|
expect(on.output.importEntries).toBeUndefined();
|
|
expect(on.output.imports).toEqual(off.output.imports);
|
|
expect(observed(workspace, on)).toEqual(observed(workspace, off));
|
|
});
|
|
});
|
|
});
|