-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathincremental-benchmark.ts
More file actions
210 lines (182 loc) · 7.11 KB
/
Copy pathincremental-benchmark.ts
File metadata and controls
210 lines (182 loc) · 7.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/usr/bin/env node
/**
* Incremental build benchmark — measures build tiers and import resolution.
*
* Each engine (native / WASM) runs in a forked subprocess so that a segfault
* in the native addon only kills the child — the parent survives and collects
* partial results from whichever engines succeeded.
*
* Usage: node scripts/incremental-benchmark.js > result.json
*/
import fs from 'node:fs';
import path from 'node:path';
import { performance } from 'node:perf_hooks';
import { fileURLToPath } from 'node:url';
import { resolveBenchmarkSource, srcImport } from './lib/bench-config.js';
import { isWorker, workerEngine, forkEngines } from './lib/fork-engine.js';
// ── Parent process: fork one child per engine, assemble final output ─────
if (!isWorker()) {
const { version, srcDir: parentSrcDir, cleanup: parentCleanup } = await resolveBenchmarkSource();
let wasm, native;
try {
({ wasm, native } = await forkEngines(import.meta.url, process.argv.slice(2)));
} catch (err) {
console.error(`Error: ${err.message}`);
parentCleanup();
process.exit(1);
}
// Import resolution runs in the parent — it tests both native and JS
// fallback in a single pass and doesn't need engine isolation.
const __dirParent = path.dirname(fileURLToPath(import.meta.url));
const rootParent = path.resolve(__dirParent, '..');
const dbPathParent = path.join(rootParent, '.codegraph', 'graph.db');
const { statsData: parentStats } = await import(srcImport(parentSrcDir, 'domain/queries.js'));
const { resolveImportsBatch: parentBatch, resolveImportPathJS: parentJS } = await import(
srcImport(parentSrcDir, 'domain/graph/resolve.js')
);
const { isNativeAvailable: parentNativeCheck } = await import(
srcImport(parentSrcDir, 'infrastructure/native.js')
);
const RUNS = 3;
function median(arr) {
const sorted = [...arr].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
}
function round1(n) { return Math.round(n * 10) / 10; }
function collectImportPairs() {
const srcRoot = path.join(rootParent, 'src');
const importRe = /(?:^|\n)\s*import\s+.*?\s+from\s+['"]([^'"]+)['"]/g;
const pairs = [];
function walk(dir) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (entry.isDirectory()) { walk(path.join(dir, entry.name)); continue; }
if (!entry.name.endsWith('.js')) continue;
const absFile = path.join(dir, entry.name);
const content = fs.readFileSync(absFile, 'utf8');
let match;
while ((match = importRe.exec(content)) !== null) {
pairs.push({ fromFile: absFile, importSource: match[1] });
}
}
}
walk(srcRoot);
return pairs;
}
let stats = null;
try { stats = parentStats(dbPathParent); } catch { /* DB may not exist if both engines failed */ }
const files = stats?.files?.total ?? (wasm?.files || native?.files || 0);
console.error('Benchmarking import resolution...');
const inputs = collectImportPairs();
console.error(` ${inputs.length} import pairs collected`);
let nativeBatchMs = null;
let perImportNativeMs = null;
if (parentNativeCheck()) {
const timings = [];
for (let i = 0; i < RUNS; i++) {
const start = performance.now();
parentBatch(inputs, rootParent, null);
timings.push(performance.now() - start);
}
nativeBatchMs = round1(median(timings));
perImportNativeMs = inputs.length > 0 ? round1(nativeBatchMs / inputs.length) : 0;
}
const jsTimings = [];
for (let i = 0; i < RUNS; i++) {
const start = performance.now();
for (const { fromFile, importSource } of inputs) {
parentJS(fromFile, importSource, rootParent, null);
}
jsTimings.push(performance.now() - start);
}
const jsFallbackMs = round1(median(jsTimings));
const perImportJsMs = inputs.length > 0 ? round1(jsFallbackMs / inputs.length) : 0;
const resolve = { imports: inputs.length, nativeBatchMs, jsFallbackMs, perImportNativeMs, perImportJsMs };
console.error(` native=${resolve.nativeBatchMs}ms js=${resolve.jsFallbackMs}ms`);
const result = {
version,
date: new Date().toISOString().slice(0, 10),
files,
wasm: wasm
? {
fullBuildMs: wasm.fullBuildMs,
noopRebuildMs: wasm.noopRebuildMs,
oneFileRebuildMs: wasm.oneFileRebuildMs,
oneFilePhases: wasm.oneFilePhases,
}
: null,
native: native
? {
fullBuildMs: native.fullBuildMs,
noopRebuildMs: native.noopRebuildMs,
oneFileRebuildMs: native.oneFileRebuildMs,
oneFilePhases: native.oneFilePhases,
}
: null,
resolve,
};
console.log(JSON.stringify(result, null, 2));
parentCleanup();
process.exit(0);
}
// ── Worker process: benchmark build tiers for a single engine ────────────
const engine = workerEngine();
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(__dirname, '..');
const { srcDir, cleanup } = await resolveBenchmarkSource();
const dbPath = path.join(root, '.codegraph', 'graph.db');
const { buildGraph } = await import(srcImport(srcDir, 'domain/graph/builder.js'));
// Redirect console.log to stderr so only JSON goes to stdout
const origLog = console.log;
console.log = (...args) => console.error(...args);
const RUNS = 3;
const PROBE_FILE = path.join(root, 'src', 'domain', 'queries.js');
function median(arr) {
const sorted = [...arr].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
}
console.error(`Benchmarking ${engine} engine...`);
// Full build (delete DB first)
const fullTimings = [];
for (let i = 0; i < RUNS; i++) {
if (fs.existsSync(dbPath)) fs.unlinkSync(dbPath);
const start = performance.now();
await buildGraph(root, { engine, incremental: false });
fullTimings.push(performance.now() - start);
}
const fullBuildMs = Math.round(median(fullTimings));
// No-op rebuild (nothing changed)
const noopTimings = [];
for (let i = 0; i < RUNS; i++) {
const start = performance.now();
await buildGraph(root, { engine, incremental: true });
noopTimings.push(performance.now() - start);
}
const noopRebuildMs = Math.round(median(noopTimings));
// 1-file change rebuild
const original = fs.readFileSync(PROBE_FILE, 'utf8');
let oneFileRebuildMs;
let oneFilePhases = null;
try {
const oneFileRuns = [];
for (let i = 0; i < RUNS; i++) {
fs.writeFileSync(PROBE_FILE, original + `\n// probe-${i}\n`);
const start = performance.now();
const res = await buildGraph(root, { engine, incremental: true });
oneFileRuns.push({ ms: performance.now() - start, phases: res?.phases || null });
}
oneFileRuns.sort((a, b) => a.ms - b.ms);
const medianRun = oneFileRuns[Math.floor(oneFileRuns.length / 2)];
oneFileRebuildMs = Math.round(medianRun.ms);
oneFilePhases = medianRun.phases;
} finally {
fs.writeFileSync(PROBE_FILE, original);
await buildGraph(root, { engine, incremental: true });
}
console.error(` full=${fullBuildMs}ms noop=${noopRebuildMs}ms 1-file=${oneFileRebuildMs}ms`);
// Restore console.log for JSON output
console.log = origLog;
const workerResult = { fullBuildMs, noopRebuildMs, oneFileRebuildMs, oneFilePhases };
console.log(JSON.stringify(workerResult));
cleanup();