diff --git a/.github/workflows/p3-profile.yml b/.github/workflows/p3-profile.yml new file mode 100644 index 0000000..f6e43c7 --- /dev/null +++ b/.github/workflows/p3-profile.yml @@ -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 diff --git a/benchmarks/p3-profile.mjs b/benchmarks/p3-profile.mjs new file mode 100644 index 0000000..52e59e8 --- /dev/null +++ b/benchmarks/p3-profile.mjs @@ -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;kz.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})); +} diff --git a/docs/evidence/P3_DIRECTORY_SCALE.md b/docs/evidence/P3_DIRECTORY_SCALE.md new file mode 100644 index 0000000..1948962 --- /dev/null +++ b/docs/evidence/P3_DIRECTORY_SCALE.md @@ -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. diff --git a/packages/core/src/graph.ts b/packages/core/src/graph.ts index 178cd69..5ac5431 100644 --- a/packages/core/src/graph.ts +++ b/packages/core/src/graph.ts @@ -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(['.']); + 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();const edges=new Map(); const roots:Record={production:[],test:[],story:[],publicApi:[]}; const diagnostics:Diagnostic[]=[...extraDiagnostics,...facts.flatMap(f=>f.diagnostics)]; @@ -52,6 +63,7 @@ export function buildGraph({root,files,config={},reuseFacts,saveFacts,extraDiagn const workspacePackages=new Map}>(); for(const [filename,content] of files){if(!filename.endsWith('package.json'))continue;try{const manifest=JSON.parse(content) as Record;if(typeof manifest.name==='string')workspacePackages.set(manifest.name,{dir:path.posix.dirname(filename),manifest});}catch{}} const resolvedModules=new Map(); + const resolvedOptions=new Map(); function resolve(source:string,specifier:string):string|undefined{ const key=source+'\0'+specifier; if(resolvedModules.has(key))return resolvedModules.get(key)||undefined; @@ -59,7 +71,8 @@ export function buildGraph({root,files,config={},reuseFacts,saveFacts,extraDiagn 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. @@ -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. diff --git a/tests/p3-module-resolution-scale.test.mjs b/tests/p3-module-resolution-scale.test.mjs new file mode 100644 index 0000000..77eb531 --- /dev/null +++ b/tests/p3-module-resolution-scale.test.mjs @@ -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'); +});