Skip to content
Merged
Show file tree
Hide file tree
Changes from 49 commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
2b6a00d
fix: scope codegraph batch complexity targets to file paths
carlos-alm Jul 5, 2026
b28051a
fix: exclude parameters and interface/type members from dead-role cla…
carlos-alm Jul 5, 2026
17fbcba
fix: credit import-type usages as exports consumers
carlos-alm Jul 5, 2026
26918bb
fix: prevent fn-impact/query crash when -f/--file is passed
carlos-alm Jul 5, 2026
be6432c
fix: correct exported-symbol detection for literal and object-literal…
carlos-alm Jul 5, 2026
4ead840
fix: exclude primitive type keywords from ast --kind string matching
carlos-alm Jul 5, 2026
f6326bf
fix: resolve call edges through renamed import specifiers
carlos-alm Jul 5, 2026
590f560
fix: couple file_hashes updates with edge regeneration in incremental…
carlos-alm Jul 5, 2026
d3ea4a4
fix: compare signature-change diffs using new-file line ranges
carlos-alm Jul 5, 2026
c306812
feat: add environment doctor check for stale native binary and missin…
carlos-alm Jul 5, 2026
8bb5893
fix: eliminate non-deterministic ordering in community detection
carlos-alm Jul 6, 2026
46037b1
fix: sync update-graph.sh hook extension allowlist with EXTENSIONS
carlos-alm Jul 6, 2026
6a84cf9
fix: recompute directory structure metrics for affected directories o…
carlos-alm Jul 6, 2026
8d936d1
refactor: register hardcoded execFileSync/execSync maxBuffer values i…
carlos-alm Jul 6, 2026
11c84be
fix: gate blast-radius check on newly introduced risk, not pre-existi…
carlos-alm Jul 6, 2026
963301a
fix: gate identifier-argument dynamic call edges on callback-acceptin…
carlos-alm Jul 6, 2026
3e8035d
fix: gate Array.from's callback arg by position, not just callee name
carlos-alm Jul 6, 2026
879635e
fix: scope reexportedSymbols to actually-named re-export specifiers
carlos-alm Jul 6, 2026
0fe9fc3
fix: stop CFG block/edge count from overriding AST-derived cyclomatic…
carlos-alm Jul 6, 2026
ccf3c19
fix: backfill edges.technique for incrementally-inserted calls edges
carlos-alm Jul 6, 2026
d5b1162
fix: wrap remote embedding JSON parse failure in EngineError
carlos-alm Jul 6, 2026
8971017
refactor: extract shared platform-default-path helper in config.ts
carlos-alm Jul 6, 2026
056c5e4
refactor: decompose loadConfig and related high-effort functions in c…
carlos-alm Jul 6, 2026
0738171
refactor: decompose findDbPath and openRepo in db/connection.ts (docs…
carlos-alm Jul 6, 2026
6f2423c
refactor: dedupe busy/locked error detection into isBusyOrLockedError
carlos-alm Jul 6, 2026
4c02378
fix: log statSync failures in findDbPath instead of silently swallowi…
carlos-alm Jul 6, 2026
0698e16
test: add direct unit coverage for closeDbPair/closeDbPairDeferred/cl…
carlos-alm Jul 6, 2026
4ac3b99
fix: correct blast-radius/fn-impact computation for line-shifted decl…
carlos-alm Jul 6, 2026
6767f09
feat: wire points-to solver max-iterations cap through DEFAULTS.analy…
carlos-alm Jul 6, 2026
5f6f30a
refactor: route console.log calls in domain/search through logger
carlos-alm Jul 6, 2026
b479318
refactor: reduce cyclomatic complexity of computeDeltaModularityDirected
carlos-alm Jul 6, 2026
c39ac40
refactor: unify impact-level rendering format between audit and fn-im…
carlos-alm Jul 6, 2026
067674f
refactor: dedupe computeSavings via pct helper and persist partial to…
carlos-alm Jul 6, 2026
f6807b4
fix: add main.rs driver to rust dynamic tracer fixture
carlos-alm Jul 6, 2026
1c07a54
fix: scope diff file-header detection to between-hunk positions
carlos-alm Jul 6, 2026
bf82aa2
fix: update titan-grind's dead-symbol script for current roles --json…
carlos-alm Jul 6, 2026
cd02d27
fix: thread configured busyTimeoutMs through remaining read-only quer…
carlos-alm Jul 6, 2026
980b5dc
fix: resolve computed string-literal keys in object-literal extractio…
carlos-alm Jul 6, 2026
4a873a3
fix: add same-class bare-call fallback to incremental rebuild path (d…
carlos-alm Jul 6, 2026
8f3348a
fix: unify Object.defineProperty accessor fallback kind-filtering bet…
carlos-alm Jul 6, 2026
acf804c
refactor: share chunked statement-cache primitive between builder and…
carlos-alm Jul 6, 2026
986c851
refactor: cache prepared statements in applyEdgeTechniquesAfterNative…
carlos-alm Jul 6, 2026
71e9174
fix: replace fixed-depth directory-proximity check with symmetric dis…
carlos-alm Jul 6, 2026
d2935cc
refactor: remove unreachable Partition delta-computation interface me…
carlos-alm Jul 6, 2026
6515186
fix: emit reference edges for function identifiers used as object-lit…
carlos-alm Jul 6, 2026
30c491a
refactor: unify call-ref and tests rendering format between audit and…
carlos-alm Jul 6, 2026
9db911b
fix: classify destructured bindings as constant, not function (docs c…
carlos-alm Jul 6, 2026
70559fc
refactor: adopt timeMedian in remaining benchmark timing loops
carlos-alm Jul 6, 2026
86e006b
fix: resolve merge conflicts with main
carlos-alm Jul 8, 2026
aada045
fix: guard timeMedianWithValue against runs=0 (#2016)
carlos-alm Jul 8, 2026
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
47 changes: 23 additions & 24 deletions scripts/benchmark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { fileURLToPath } from 'node:url';
import Database from 'better-sqlite3';
import { resolveBenchmarkExcludes, resolveBenchmarkSource, srcImport } from './lib/bench-config.js';
import { isWorker, workerEngine, workerTargets, forkEngines } from './lib/fork-engine.js';
import { median, round1, timeMedian } from './lib/bench-timing.js';
import { round1, timeMedian, timeMedianWithValue } from './lib/bench-timing.js';

// ── Parent process: fork one child per engine, assemble final output ─────
if (!isWorker()) {
Expand Down Expand Up @@ -134,7 +134,7 @@ const buildTimeMs = performance.now() - buildStart;
// query latency with NAPI/rusqlite/OS-page-cache init costs (~65ms on
// macOS) and inflated growth from test-fixture files pulled in by new
// native extractors. See #1113 for the methodology rationale.
const queryTimeMs = benchQuery(fnDepsData, 'buildGraph', dbPath, { depth: 3, noTests: true });
const queryTimeMs = await benchQuery(fnDepsData, 'buildGraph', dbPath, { depth: 3, noTests: true });

const stats = statsData(dbPath);
const totalFiles = stats.files.total;
Expand Down Expand Up @@ -168,17 +168,16 @@ try {
fs.writeFileSync(PROBE_FILE, original + `\n// warmup-${i}\n`);
await buildGraph(root, { engine, incremental: true, exclude: BENCH_EXCLUDE });
}
const oneFileRuns = [];
for (let i = 0; i < INCREMENTAL_RUNS; i++) {
fs.writeFileSync(PROBE_FILE, original + `\n// probe-${i}\n`);
const start = performance.now();
const res = await buildGraph(root, { engine, incremental: true, exclude: BENCH_EXCLUDE });
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)];
const medianRun = await timeMedianWithValue(
async () => {
const res = await buildGraph(root, { engine, incremental: true, exclude: BENCH_EXCLUDE });
return res?.phases || null;
},
INCREMENTAL_RUNS,
(i) => fs.writeFileSync(PROBE_FILE, original + `\n// probe-${i}\n`),
);
oneFileRebuildMs = Math.round(medianRun.ms);
oneFilePhases = medianRun.phases;
oneFilePhases = medianRun.value;
} catch (err) {
console.error(` [${engine}] 1-file rebuild failed: ${(err as Error).message}`);
} finally {
Expand All @@ -195,26 +194,26 @@ console.error(` [${engine}] Benchmarking queries...`);
const targets = workerTargets() || selectTargets();
console.error(` hub=${targets.hub}, leaf=${targets.leaf}`);

function benchQuery(fn, ...args) {
async function benchQuery(fn, ...args) {
// Warmup runs prime NAPI bindings, the rusqlite statement cache, and the
// OS page cache so the timed loop measures steady-state query latency
// rather than first-call init (~65ms on macOS). Each call site warms
// independently — methodology does not rely on call ordering elsewhere.
for (let i = 0; i < QUERY_WARMUP_RUNS; i++) fn(...args);
const timings = [];
for (let i = 0; i < QUERY_RUNS; i++) {
const start = performance.now();
fn(...args);
timings.push(performance.now() - start);
}
return round1(median(timings));
return round1(await timeMedian(() => fn(...args), QUERY_RUNS));
}

const queries = {
fnDepsMs: fnDepsData ? benchQuery(fnDepsData, targets.hub, dbPath, { depth: 3, noTests: true }) : null,
fnImpactMs: fnImpactData ? benchQuery(fnImpactData, targets.hub, dbPath, { depth: 3, noTests: true }) : null,
pathMs: pathData ? benchQuery(pathData, targets.hub, targets.leaf, dbPath, { noTests: true }) : null,
rolesMs: rolesData ? benchQuery(rolesData, dbPath, { noTests: true }) : null,
fnDepsMs: fnDepsData
? await benchQuery(fnDepsData, targets.hub, dbPath, { depth: 3, noTests: true })
: null,
fnImpactMs: fnImpactData
? await benchQuery(fnImpactData, targets.hub, dbPath, { depth: 3, noTests: true })
: null,
pathMs: pathData
? await benchQuery(pathData, targets.hub, targets.leaf, dbPath, { noTests: true })
: null,
rolesMs: rolesData ? await benchQuery(rolesData, dbPath, { noTests: true }) : null,
};

// Restore console.log for JSON output
Expand Down
45 changes: 18 additions & 27 deletions scripts/incremental-benchmark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { performance } from 'node:perf_hooks';
import { fileURLToPath } from 'node:url';
import { resolveBenchmarkExcludes, resolveBenchmarkSource, srcImport } from './lib/bench-config.js';
import { isWorker, workerEngine, forkEngines } from './lib/fork-engine.js';
import { median, round1, timeMedian } from './lib/bench-timing.js';
import { round1, timeMedian, timeMedianWithValue } from './lib/bench-timing.js';

// ── Parent process: fork one child per engine, assemble final output ─────
if (!isWorker()) {
Expand Down Expand Up @@ -87,29 +87,21 @@ if (!isWorker()) {
for (let i = 0; i < WARMUP_RUNS; i++) {
parentBatch(inputs, rootParent, null);
}
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));
nativeBatchMs = round1(await timeMedian(() => parentBatch(inputs, rootParent, null), RUNS));
perImportNativeMs = inputs.length > 0 ? round1(nativeBatchMs / inputs.length) : 0;
}
for (let i = 0; i < WARMUP_RUNS; i++) {
for (const { fromFile, importSource } of inputs) {
parentJS(fromFile, importSource, rootParent, null);
}
}
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 jsFallbackMs = round1(
await timeMedian(() => {
for (const { fromFile, importSource } of inputs) {
parentJS(fromFile, importSource, rootParent, null);
}
}, RUNS),
);
const perImportJsMs = inputs.length > 0 ? round1(jsFallbackMs / inputs.length) : 0;

const resolve = { imports: inputs.length, nativeBatchMs, jsFallbackMs, perImportNativeMs, perImportJsMs };
Expand Down Expand Up @@ -217,17 +209,16 @@ try {
fs.writeFileSync(PROBE_FILE, original + `\n// warmup-${i}\n`);
await buildGraph(root, { ...BUILD_OPTS, incremental: true });
}
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, { ...BUILD_OPTS, 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)];
const medianRun = await timeMedianWithValue(
async () => {
const res = await buildGraph(root, { ...BUILD_OPTS, incremental: true });
return res?.phases || null;
},
RUNS,
(i) => fs.writeFileSync(PROBE_FILE, original + `\n// probe-${i}\n`),
);
oneFileRebuildMs = Math.round(medianRun.ms);
oneFilePhases = medianRun.phases;
oneFilePhases = medianRun.value;
} catch (err) {
console.error(` [${engine}] 1-file rebuild failed: ${(err as Error).message}`);
} finally {
Expand Down
33 changes: 33 additions & 0 deletions scripts/lib/bench-timing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@
* const fullBuildMs = Math.round(
* await timeMedian(() => buildGraph(root, { engine, incremental: false }), RUNS),
* );
*
* `timeMedianWithValue` covers the same loop shape for call sites that also
* need side data from whichever run turned out to be the median-duration one
* (e.g. the build-phase breakdown of a "1-file rebuild" measurement) — data
* `timeMedian`'s bare `Promise<number>` return can't carry.
*/
import { performance } from 'node:perf_hooks';

Expand Down Expand Up @@ -51,3 +56,31 @@ export async function timeMedian(fn: () => unknown, runs: number): Promise<numbe
}
return median(timings);
}

/**
* Runs `fn` `runs` times, recording elapsed milliseconds and `fn`'s return
* value per run, and returns the `{ ms, value }` pair for the median-duration
* run. An optional `beforeEach(i)` hook runs immediately before each timed
* call — its cost is *not* included in the timed duration — for per-iteration
* setup like writing a probe file with iteration-varying content ahead of an
* incremental rebuild.
*
* Unlike `median()`, this does not average the two middle samples when `runs`
* is even — it returns one real sampled run (sorted by `ms`, middle index),
* so `value` always stays attributable to an actual execution.
*/
export async function timeMedianWithValue<T>(
fn: (i: number) => T | Promise<T>,
runs: number,
beforeEach?: (i: number) => void | Promise<void>,
): Promise<{ ms: number; value: T }> {
const samples: { ms: number; value: T }[] = [];
Comment on lines +72 to +77

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 When runs is 0, samples is empty and samples[Math.floor(0 / 2)] evaluates to undefined, silently violating the Promise<{ ms: number; value: T }> return type. Any caller then accessing .ms or .value would throw at runtime. A guard at the top mirrors what median() already does for the empty-array case in timeMedian.

Suggested change
export async function timeMedianWithValue<T>(
fn: (i: number) => T | Promise<T>,
runs: number,
beforeEach?: (i: number) => void | Promise<void>,
): Promise<{ ms: number; value: T }> {
const samples: { ms: number; value: T }[] = [];
export async function timeMedianWithValue<T>(
fn: (i: number) => T | Promise<T>,
runs: number,
beforeEach?: (i: number) => void | Promise<void>,
): Promise<{ ms: number; value: T }> {
if (runs <= 0) throw new RangeError(`timeMedianWithValue: runs must be > 0, got ${runs}`);
const samples: { ms: number; value: T }[] = [];

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — added an early throw when runs is 0 (no sensible sentinel exists for a generic {ms, value: T} return, so failing fast beats returning undefined) in aada0450.

for (let i = 0; i < runs; i++) {
if (beforeEach) await beforeEach(i);
const start = performance.now();
const value = await fn(i);
samples.push({ ms: performance.now() - start, value });
}
samples.sort((a, b) => a.ms - b.ms);
return samples[Math.floor(samples.length / 2)];
}
43 changes: 19 additions & 24 deletions scripts/query-benchmark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { fileURLToPath } from 'node:url';
import Database from 'better-sqlite3';
import { resolveBenchmarkExcludes, resolveBenchmarkSource, srcImport } from './lib/bench-config.js';
import { isWorker, workerEngine, workerTargets, forkEngines } from './lib/fork-engine.js';
import { median, round1 } from './lib/bench-timing.js';
import { round1, timeMedian } from './lib/bench-timing.js';

// ── Parent process: fork one child per engine, assemble final output ─────
if (!isWorker()) {
Expand Down Expand Up @@ -169,19 +169,15 @@ function selectTargets() {
}
}

function benchDepths(fn, name, depths) {
async function benchDepths(fn, name, depths) {
const result = {};
for (const depth of depths) {
for (let i = 0; i < WARMUP_RUNS; i++) {
fn(name, dbPath, { depth, noTests: true });
}
const timings = [];
for (let i = 0; i < RUNS; i++) {
const start = performance.now();
fn(name, dbPath, { depth, noTests: true });
timings.push(performance.now() - start);
}
result[`depth${depth}Ms`] = round1(median(timings));
result[`depth${depth}Ms`] = round1(
await timeMedian(() => fn(name, dbPath, { depth, noTests: true }), RUNS),
);
}
return result;
}
Expand All @@ -201,7 +197,7 @@ function resolveDbFile(rootDir: string, dbFile: string): string | null {
return null;
}

function benchDiffImpact(hubName) {
async function benchDiffImpact(hubName) {
const db = new Database(dbPath, { readonly: true });
const row = db
.prepare(`SELECT file FROM nodes WHERE name = ? LIMIT 1`)
Expand All @@ -224,16 +220,15 @@ function benchDiffImpact(hubName) {
fs.writeFileSync(hubFile, original + '\n// benchmark-probe\n');
execFileSync('git', ['add', hubFile], { cwd: root, stdio: 'pipe' });

const timings = [];
let lastResult = null;
for (let i = 0; i < RUNS; i++) {
const start = performance.now();
lastResult = diffImpactData(dbPath, { staged: true, depth: 3, noTests: true });
timings.push(performance.now() - start);
}
const latencyMs = round1(
await timeMedian(() => {
lastResult = diffImpactData(dbPath, { staged: true, depth: 3, noTests: true });
}, RUNS),
);

return {
latencyMs: round1(median(timings)),
latencyMs,
affectedFunctions: lastResult?.affectedFunctions?.length || 0,
affectedFiles: lastResult?.affectedFiles?.length || 0,
};
Expand All @@ -253,15 +248,15 @@ console.error(`Targets: hub=${targets.hub}, mid=${targets.mid}, leaf=${targets.l
const fnDeps = {};
const fnImpact = {};

fnDeps.depth1Ms = benchDepths(fnDepsData, targets.hub, [1]).depth1Ms;
fnDeps.depth3Ms = benchDepths(fnDepsData, targets.hub, [3]).depth3Ms;
fnDeps.depth5Ms = benchDepths(fnDepsData, targets.hub, [5]).depth5Ms;
fnDeps.depth1Ms = (await benchDepths(fnDepsData, targets.hub, [1])).depth1Ms;
fnDeps.depth3Ms = (await benchDepths(fnDepsData, targets.hub, [3])).depth3Ms;
fnDeps.depth5Ms = (await benchDepths(fnDepsData, targets.hub, [5])).depth5Ms;

fnImpact.depth1Ms = benchDepths(fnImpactData, targets.hub, [1]).depth1Ms;
fnImpact.depth3Ms = benchDepths(fnImpactData, targets.hub, [3]).depth3Ms;
fnImpact.depth5Ms = benchDepths(fnImpactData, targets.hub, [5]).depth5Ms;
fnImpact.depth1Ms = (await benchDepths(fnImpactData, targets.hub, [1])).depth1Ms;
fnImpact.depth3Ms = (await benchDepths(fnImpactData, targets.hub, [3])).depth3Ms;
fnImpact.depth5Ms = (await benchDepths(fnImpactData, targets.hub, [5])).depth5Ms;

const diffImpact = benchDiffImpact(targets.hub);
const diffImpact = await benchDiffImpact(targets.hub);

// Restore console.log for JSON output
console.log = origLog;
Expand Down
Loading