Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions __tests__/sync-framework-detection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import * as path from 'path';
import { CodeGraph } from '../src';
import { detectFrameworks } from '../src/resolution/frameworks';
import { clearDeclaredDependencies, declaredDependencies } from '../src/resolution/frameworks/package-deps';
import { readBoundedSourceSync } from '../src/file-limits';
import type { ResolutionContext } from '../src/resolution/types';

// Pass-through wrappers, so a test can count framework detections and see the git commands run.
Expand All @@ -29,6 +30,11 @@ vi.mock('../src/resolution/frameworks', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/resolution/frameworks')>();
return { ...actual, detectFrameworks: vi.fn(actual.detectFrameworks) };
});
// And one to see which files a detection reads from disk.
vi.mock('../src/file-limits', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/file-limits')>();
return { ...actual, readBoundedSourceSync: vi.fn(actual.readBoundedSourceSync) };
});

const EXPRESS = JSON.stringify({ dependencies: { express: '^4.18.0' } });
const ROUTES = "const app = express();\napp.get('/hello', function hello(req, res) {});\n";
Expand Down Expand Up @@ -171,6 +177,82 @@ describe('a scoped sync in a fresh process keeps off the full scan (#2516)', ()
});
});

describe('what framework detection read is kept only by a graph that watches (#2516)', () => {
// A one-off sync detects once. Keeping every file a detector read (Spring's
// reads every `.java` file of a project without Spring) only raised the
// sync's peak memory; a watching graph detects again, so it keeps them.
let root: string;
let cg: CodeGraph | undefined;
const write = (rel: string, body: string) => {
fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true });
fs.writeFileSync(path.join(root, rel), body);
};
type Reads = Map<string, { content?: string | null }>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const orchestrator = () => (cg as any).orchestrator as { detectionReads: Reads; keepDetectionContents: boolean };
// The files whose text is kept (a probe of a missing file keeps null).
const kept = () => [...orchestrator().detectionReads].filter(([, read]) => typeof read.content === 'string').map(([rel]) => rel).sort();

beforeEach(() => {
root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cg-sync-detect-keep-')));
write('src/Main.java', 'class Main { void run() {} }\n');
write('src/Util.java', 'class Util { int one() { return 1; } }\n');
});

afterEach(() => {
cg?.close();
cg = undefined;
fs.rmSync(root, { recursive: true, force: true });
});

it('keeps none of the files a detection read in a graph that does not watch', async () => {
cg = CodeGraph.initSync(root);
await cg.indexAll();
expect(orchestrator().detectionReads.size).toBeGreaterThan(0);
expect(kept()).toEqual([]);
write('src/Util.java', 'class Util { int two() { return 2; } }\n');
await cg.sync({ paths: ['src/Util.java'] });
expect(kept()).toEqual([]);
// The signatures stay, so a later sync still knows whether to detect again.
expect([...orchestrator().detectionReads.keys()]).toContain('src/Main.java');
});

it('keeps them while it watches, so detecting again reads only what changed, and lets them go after', async () => {
cg = CodeGraph.initSync(root);
await cg.indexAll();
expect(cg.watch({ debounceMs: 600_000 })).toBe(true);
expect(orchestrator().keepDetectionContents).toBe(true);
write('src/Util.java', 'class Util { int two() { return 2; } }\n');
await cg.sync({ paths: ['src/Util.java'] });
expect(kept()).toEqual(['src/Main.java', 'src/Util.java']);

// The files a detection reads, by name, while it runs.
const detect = vi.mocked(detectFrameworks).getMockImplementation()!;
const read = vi.mocked(readBoundedSourceSync).getMockImplementation()!;
let detecting = false;
const readWhileDetecting: string[] = [];
vi.mocked(detectFrameworks).mockImplementation((ctx) => { detecting = true; try { return detect(ctx); } finally { detecting = false; } });
vi.mocked(readBoundedSourceSync).mockImplementation((file, ...rest) => {
if (detecting) readWhileDetecting.push(path.basename(String(file)));
return read(file, ...rest);
});
try {
write('src/Util.java', 'class Util { int three() { return 3; } }\n');
vi.mocked(detectFrameworks).mockClear();
await cg.sync({ paths: ['src/Util.java'] });
expect(vi.mocked(detectFrameworks)).toHaveBeenCalledTimes(1);
expect(readWhileDetecting).toEqual(['Util.java']);
} finally {
vi.mocked(detectFrameworks).mockImplementation(detect);
vi.mocked(readBoundedSourceSync).mockImplementation(read);
}
expect(kept()).toEqual(['src/Main.java', 'src/Util.java']);
cg.unwatch();
expect(orchestrator().keepDetectionContents).toBe(false);
expect(kept()).toEqual([]);
});
});

describe('declared dependencies in a long-lived graph (#2519)', () => {
let root: string;
let cg: CodeGraph | undefined;
Expand Down
26 changes: 24 additions & 2 deletions src/extraction/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2158,8 +2158,18 @@ export class ExtractionOrchestrator {
* source file until a sync changes it, any other path while its signature
* holds. Detecting again then reads only what changed, not the couple of
* hundred files some detectors sample (react-native-bridge reads up to 200).
* The contents are kept only while {@link keepDetectionContents} says so.
*/
private detectionReads = new Map<string, { full: string; signature: string; content?: string | null }>();
/**
* Whether detection keeps what it read for the next detection: in a graph
* that watches the project, which detects again as files change. A one-off
* sync detects once, and what Spring's detector reads (every `.java` file of
* a project without Spring, 50 MB on elasticsearch) would only sit in memory
* through the rest of the sync, raising its peak. The signatures are kept
* either way; they are what tells a later sync whether to detect again.
*/
private keepDetectionContents = false;
/**
* Scope matcher for SCOPED syncs, memoized on the mtimes of the two root
* files it is derived from (`codegraph.json`, `.gitignore`). See
Expand Down Expand Up @@ -2308,9 +2318,11 @@ export class ExtractionOrchestrator {
this.detectionFileListChanged = false;
this.detectedFrameworkNames = detectFrameworks(context).map((r) => r.name);
const declared = declaredDependencies(context);
// Keep only what this detection read.
for (const rel of this.detectionReads.keys()) {
// Keep only what this detection read, and its contents only for a graph
// that will detect again (see keepDetectionContents).
for (const [rel, known] of this.detectionReads) {
if (!inputs.sourceFiles.has(rel) && !inputs.diskPaths.has(rel)) this.detectionReads.delete(rel);
else if (!this.keepDetectionContents) known.content = undefined;
}
this.gatedFrameworks = new Map();
for (const name of this.detectedFrameworkNames) {
Expand Down Expand Up @@ -2387,6 +2399,16 @@ export class ExtractionOrchestrator {
return declared;
}

/**
* Keep what framework detection reads for the next detection (a graph that
* watches the project), or stop keeping it and let it go (see
* keepDetectionContents).
*/
setKeepDetectionContents(keep: boolean): void {
this.keepDetectionContents = keep;
if (!keep) for (const known of this.detectionReads.values()) known.content = undefined;
}

/** The frameworks extraction last detected, or null before any detection. */
getDetectedFrameworkNames(): string[] | null {
return this.detectedFrameworkNames;
Expand Down
15 changes: 13 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,12 @@ export class CodeGraph {
private builtResolver: ReferenceResolver | null = null;

private get orchestrator(): ExtractionOrchestrator {
return (this.builtOrchestrator ??= new (engine().ExtractionOrchestrator)(this.projectRoot, this.queries));
if (!this.builtOrchestrator) {
this.builtOrchestrator = new (engine().ExtractionOrchestrator)(this.projectRoot, this.queries);
// A graph that watches detects again as files change (see watch()).
if (this.watcher) this.builtOrchestrator.setKeepDetectionContents(true);
}
return this.builtOrchestrator;
}

private get resolver(): ReferenceResolver {
Expand Down Expand Up @@ -2038,7 +2043,12 @@ export class CodeGraph {
: undefined
);

return this.watcher.start();
// A watching graph detects frameworks again as files change: keep what
// detection reads, so that reads only what changed (#2516).
this.orchestrator.setKeepDetectionContents(true);
const started = this.watcher.start();
if (!started) this.orchestrator.setKeepDetectionContents(false);
return started;
}

/**
Expand All @@ -2049,6 +2059,7 @@ export class CodeGraph {
this.watcher.stop();
this.watcher = null;
}
if (this.builtOrchestrator) this.builtOrchestrator.setKeepDetectionContents(false);
}

/**
Expand Down