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
44 changes: 44 additions & 0 deletions .github/workflows/p3-profile.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
name: P3 5k/50k synthetic performance evidence (not release)
on:
pull_request:
paths:
- benchmarks/p3-profile.mjs
- .github/workflows/p3-profile.yml
- packages/core/src/**
push:
branches: [main, 'test/p3-linear-module-resolution-*']
paths:
- benchmarks/p3-profile.mjs
- .github/workflows/p3-profile.yml
- packages/core/src/**
workflow_dispatch:
permissions:
contents: read
jobs:
profile:
name: 5k x3 + 50k x3 repeated, cold/warm/edit, p50/p95/RSS
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/setup-node@v4
with:
node-version: '22'
- name: Verify exact frozen dependencies
run: node ci/verify-frozen-lock.mjs
- name: npm ci, no lifecycle scripts
run: npm ci --ignore-scripts --no-audit --no-fund
- name: Compile exact source
run: npm run build
- name: Run standalone 5k and 50k profiles
run: node --expose-gc benchmarks/p3-profile.mjs --large --output ci/.artifacts/p3-profile.json
- name: Upload machine-readable results even on failure
if: always()
uses: actions/upload-artifact@v4
with:
name: blastradius-p3-performance
path: ci/.artifacts/p3-profile.json
if-no-files-found: warn
retention-days: 30
52 changes: 52 additions & 0 deletions benchmarks/p3-profile.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#!/usr/bin/env node
/** Bounded local-only synthetic 5k/50k cold/warm/edit-index profiling. */
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {performance} from 'node:perf_hooks';
import {BlastRadius} from '../dist/packages/core/src/index.js';
const args=process.argv.slice(2),i=args.indexOf('--output');
const output=path.resolve(i<0?'p3-performance.json':args[i+1]);
const report={schemaVersion:1,status:'INCOMPLETE',node:process.version,platform:process.platform,
methodology:'Synthetic TypeScript chain: 5000 files x3 or 50000 x1; independent cold/warm/single-source-edit timings and RSS. Not a real-repo speed claim.',
startedAt:new Date().toISOString(),results:[]};
const time=()=>performance.now(),rss=()=>Math.round(process.memoryUsage().rss/1048576);
const perc=(a,p)=>a.length<2?null:[...a].sort((x,y)=>x-y)[Math.ceil(p*a.length)-1];
function once(n){
const created=fs.mkdtempSync(path.join(os.tmpdir(),'br-p3-profile-')),root=fs.realpathSync(created);
let br;
try{
const dir=path.join(root,'src');fs.mkdirSync(dir);
for(let k=0;k<n;k++)fs.writeFileSync(path.join(dir,'f'+k+'.ts'),
k===n-1?'export function f'+k+'(){return 1;}\n':
"import {f"+(k+1)+"} from './f"+(k+1)+"';export function f"+k+"(){return f"+(k+1)+"();}\n");
fs.writeFileSync(path.join(dir,'main.ts'),"import {f0} from './f0';f0();\n");
br=new BlastRadius(root);
let t=time();const a=br.index(),coldMs=Math.round(time()-t),r0=rss();
if(a.facts.length!==n+1||!a.coverage.complete)throw Error('INCOMPLETE_GRAPH '+JSON.stringify({files:a.facts.length,coverage:a.coverage}));
t=time();br.index();const warmMs=Math.round(time()-t),r1=rss();
fs.writeFileSync(path.join(dir,'f'+(n-1)+'.ts'),'export function f'+(n-1)+'(){return 2;}\n');
t=time();const b=br.index(),editMs=Math.round(time()-t),r2=rss();
if(b.id===a.id||b.facts.length!==n+1)throw Error('EDIT_NOT_INVALIDATED');
return {coldMs,warmMs,editMs,rssMB:Math.max(r0,r1,r2),indexedFiles:a.facts.length,edges:a.edges.length};
}finally{try{br?.close();}finally{fs.rmSync(created,{recursive:true,force:true,maxRetries:8,retryDelay:200});}}
}
try{
for(const n of args.includes('--large')?[5000,50000]:[5000]){
const repeats=3,rows=[];
for(let j=0;j<repeats;j++){global.gc?.();const m=once(n);rows.push(m);console.log(JSON.stringify({size:n,iteration:j+1,values:m}));}
const metrics={count:n,repeats,samples:rows,peakRssMB:Math.max(...rows.map(z=>z.rssMB)),
p50ColdMs:perc(rows.map(z=>z.coldMs),.5),p95ColdMs:perc(rows.map(z=>z.coldMs),.95),
p50WarmMs:perc(rows.map(z=>z.warmMs),.5),p95WarmMs:perc(rows.map(z=>z.warmMs),.95),
p50EditMs:perc(rows.map(z=>z.editMs),.5),p95EditMs:perc(rows.map(z=>z.editMs),.95),
caveat:'Three synthetic repetitions; p50/p95 from exactly three observed runs, not population latency'};
report.results.push(metrics);
}
report.status='MEASURED';
}catch(e){report.status='FAILED';report.error=String(e?.stack||e);process.exitCode=1;}
finally{
report.completedAt=new Date().toISOString();
fs.mkdirSync(path.dirname(output),{recursive:true});
fs.writeFileSync(output,JSON.stringify(report,null,2)+'\n');
console.log(JSON.stringify({status:report.status,output,error:report.error||null}));
}
15 changes: 15 additions & 0 deletions docs/evidence/P3_DIRECTORY_SCALE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# P3 — one-time snapshot directory index (no graph narrowing)

## Original repeatable red evidence

Pinned public source-first evaluation at first P7 commit `b9b53cc053bf0978c50d86a463ddcdc8d677ec1b`, [independent run #45155575563](https://github.com/levencode-labs/blastradius/actions/runs/45155575563), archived artifact 14808372815 ZIP SHA256 `0b6d8487d37376f5d862cf8806d69cdc0f4187df02e6853c91d814bc6f622913`: full-graph cold index TanStack Query 2194 source files/13702 ms, Ark UI 5006/84660 ms, shadcn-ui 4426/96434 ms. These are single samples and not p50/p95; the full graphs are all incomplete. Previous exposed TanStack Table ~3146 files/26452 ms.

Separate test-only PR #24 original SHA `52e39abb98887b58d7deb579b172cb505d58e0a3`: [Ubuntu Node22 CI run #45156809769](https://github.com/levencode-labs/blastradius/actions/runs/45156809769), job 137631725924, 175 tests **174 PASS / 1 FAIL**. In 400 source files with 200 independently verified static reference edges, `Map.keys()` yielded **160000 file keys** versus the frozen acceptance bound `<=8000`; the source graph still had all 200 proven edges and no unresolved import. This is a deterministic algorithmic work counter, not a brittle wall-clock threshold. Do not change it to obtain green.

## Bounded optimization

Use one directory set built from the exact immutable source snapshot, preserving the original `directoryExists` semantics (directory exists only if it contains a snapshot file). Stop spreading the full file keys for each TypeScript module-resolver lookup. Cache pure per-source TypeScript compiler options within one graph build only, without sharing across snapshots. Keep module-resolution negatives, aliases, exports, test/story roots, UNKNOWN and source evidence unchanged. No engine-model version change is necessary because semantic results must be identical.

All eight OS/Node combinations and package-byte parity, independent compiler/Knip corpus with unchanged sources/labels, and exact merge-SHA acceptance are mandatory. After the optimizer uses initial P7 time evidence, P7 is **exposed for later release claims**; preserve original independent first-score report, then select P8 before release-gate generalization. No release/tag/npm publishing or automatic deletion.

Actual corrected SHA acceptance and before/after measurements pending.
17 changes: 15 additions & 2 deletions packages/core/src/graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,17 @@ export function buildGraph({root,files,config={},reuseFacts,saveFacts,extraDiagn
const f=analyzeFile(file,content);saveFacts?.(f);return f;
});
const byFile=new Map(facts.map(f=>[f.file,f]));
// Build the exact directory set ONCE from the immutable source snapshot.
// TypeScript calls ModuleResolutionHost.directoryExists for many imports;
// spreading every file key on each lookup scaled as O(files * imports).
const snapshotDirectories=new Set<string>(['.']);
for(const filename of files.keys()){
let dir=path.posix.dirname(filename);
while(dir!=='.'&&!snapshotDirectories.has(dir)){
snapshotDirectories.add(dir);
dir=path.posix.dirname(dir);
}
}
const nodes=new Map<string,GraphNode>();const edges=new Map<string,GraphEdge>();
const roots:Record<RootKind,string[]>={production:[],test:[],story:[],publicApi:[]};
const diagnostics:Diagnostic[]=[...extraDiagnostics,...facts.flatMap(f=>f.diagnostics)];
Expand All @@ -52,14 +63,16 @@ export function buildGraph({root,files,config={},reuseFacts,saveFacts,extraDiagn
const workspacePackages=new Map<string,{dir:string;manifest:Record<string,unknown>}>();
for(const [filename,content] of files){if(!filename.endsWith('package.json'))continue;try{const manifest=JSON.parse(content) as Record<string,unknown>;if(typeof manifest.name==='string')workspacePackages.set(manifest.name,{dir:path.posix.dirname(filename),manifest});}catch{}}
const resolvedModules=new Map<string,string|null>();
const resolvedOptions=new Map<string,ts.CompilerOptions>();
function resolve(source:string,specifier:string):string|undefined{
const key=source+'\0'+specifier;
if(resolvedModules.has(key))return resolvedModules.get(key)||undefined;
const abs=path.resolve(root,source);
let result:string|undefined;
let declaredPathAlias=false;
try{
const opts=projectOptions(root,files,source);
let opts=resolvedOptions.get(source);
if(!opts){opts=projectOptions(root,files,source);resolvedOptions.set(source,opts);}
// A failed configured source alias is an unresolved project dependency,
// not an innocent external npm import. Exclude the global "*" fallback,
// which may legitimately route unmatched packages to node_modules.
Expand All @@ -70,7 +83,7 @@ export function buildGraph({root,files,config={},reuseFacts,saveFacts,extraDiagn
const prefix=pattern.slice(0,wildcard),suffix=pattern.slice(wildcard+1);
return specifier.startsWith(prefix)&&specifier.endsWith(suffix)&&specifier.length>=prefix.length+suffix.length;
});
const host:ts.ModuleResolutionHost={fileExists(p){return files.has(toPosix(path.relative(root,p)));},readFile(p){return files.get(toPosix(path.relative(root,p)));},directoryExists(p){const rel=toPosix(path.relative(root,p));return rel==='.'||[...files.keys()].some(f=>f.startsWith(rel+'/'));},realpath(p){return p;},getCurrentDirectory(){return root;},getDirectories(){return [];}};
const host:ts.ModuleResolutionHost={fileExists(p){return files.has(toPosix(path.relative(root,p)));},readFile(p){return files.get(toPosix(path.relative(root,p)));},directoryExists(p){const rel=toPosix(path.relative(root,p));return rel==='.'||snapshotDirectories.has(rel);},realpath(p){return p;},getCurrentDirectory(){return root;},getDirectories(){return [];}};
const r=ts.resolveModuleName(specifier,abs,opts,host).resolvedModule?.resolvedFileName;
if(r){const rel=toPosix(path.relative(root,r));if(byFile.has(rel))result=rel;}
// TypeScript resolution can miss a JSX file when a source snapshot is syntactically partial.
Expand Down
33 changes: 33 additions & 0 deletions tests/p3-module-resolution-scale.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {buildGraph} from '../dist/packages/core/src/index.js';

// Source-backed original P7 CI indexing: 2194 files/13.7s (TanStack Query),
// 5006 files/84.7s (Ark UI), 4426 files/96.4s (shadcn-ui).
// The previous exposed TanStack Table has 3146 files/26.5s.
class CountingMap extends Map {
visitedKeys=0;
*keys(){
for(const key of super.keys()){this.visitedKeys++;yield key;}
}
}
test('P3: 200 distinct module imports must not enumerate O(files^2) keys',t=>{
const root=fs.mkdtempSync(path.join(os.tmpdir(),'br-p3-scaled-resolve-'));
t.after(()=>fs.rmSync(root,{recursive:true,force:true,maxRetries:5,retryDelay:100}));
const files=new CountingMap();
for(let i=0;i<200;i++){
files.set('src/consumer'+i+'.ts',"import {value} from './provider"+i+"'; export function run"+i+"(){return value;}");
files.set('src/provider'+i+'.ts','export const value='+i+';');
}
const g=buildGraph({root,files});
const verified=g.edges.filter(e=>e.certainty==='verified'&&e.kind==='references'&&
/^src\/consumer\d+\.ts$/.test(e.sourceFile)&&/^export:src\/provider\d+\.ts#value$/.test(e.to));
assert.equal(verified.length,200,'optimization must not remove proven dependency edges');
assert.equal(g.coverage.unresolvedImports,0);
// Deterministic work counter, not a flaky timing-based test.
assert.ok(files.visitedKeys<=files.size*20,
'Quadratic snapshot enumeration: '+files.visitedKeys+' key visits for '+files.size+' files');
});
Loading