|
| 1 | +/** |
| 2 | + * Proves incremental scan reuse on the public corpus: a warm unchanged rerun must return |
| 3 | + * identical findings to a full scan and finish at least ten times faster on aggregate. |
| 4 | + * |
| 5 | + * Requires a warm checkout cache (`OFFING_CORPUS_CACHE` + `npm run corpus:warm`), then: |
| 6 | + * npm run build --silent && node dist/benchmarks/scan-cache-speed.js --offline [--repo owner/name] |
| 7 | + */ |
| 8 | +import { mkdtemp, rm } from "node:fs/promises"; |
| 9 | +import { tmpdir } from "node:os"; |
| 10 | +import { join, resolve } from "node:path"; |
| 11 | +import { performance } from "node:perf_hooks"; |
| 12 | +import { pathToFileURL } from "node:url"; |
| 13 | + |
| 14 | +import { builtInDetectors } from "../src/detectors/index.js"; |
| 15 | +import { scanRepository } from "../src/engine/index.js"; |
| 16 | +import { ensureCorpusCacheEntry, resolveCorpusCacheDir } from "./corpus-cache.js"; |
| 17 | +import { fetchWith, isCheckoutUsable, resolveFetchStrategy } from "./corpus-fetch.js"; |
| 18 | +import { parseCorpusFilter, selectCorpusEntries } from "./corpus-filter.js"; |
| 19 | +import { loadPublicCorpus } from "./public-corpus.js"; |
| 20 | +import type { CorpusRepositoryEntry } from "./corpus-harness.js"; |
| 21 | + |
| 22 | +export const SCAN_CACHE_SPEEDUP_FLOOR = 10; |
| 23 | + |
| 24 | +export interface RepoSpeedMeasurement { |
| 25 | + readonly repository: string; |
| 26 | + readonly coldMs: number; |
| 27 | + readonly warmMs: number; |
| 28 | + readonly speedup: number; |
| 29 | + readonly findings: number; |
| 30 | + readonly identical: boolean; |
| 31 | +} |
| 32 | + |
| 33 | +export interface ScanCacheSpeedResult { |
| 34 | + readonly schemaVersion: "offing.scan-cache-speed.v1"; |
| 35 | + readonly repositories: readonly RepoSpeedMeasurement[]; |
| 36 | + readonly aggregateSpeedup: number; |
| 37 | + readonly allIdentical: boolean; |
| 38 | + readonly withinBudget: boolean; |
| 39 | +} |
| 40 | + |
| 41 | +function findingIds(result: Awaited<ReturnType<typeof scanRepository>>): string { |
| 42 | + return JSON.stringify(result.findings.map((finding) => finding.id).sort()); |
| 43 | +} |
| 44 | + |
| 45 | +async function measureRepository( |
| 46 | + path: string, |
| 47 | + cacheDirectory: string, |
| 48 | +): Promise<Omit<RepoSpeedMeasurement, "repository">> { |
| 49 | + const pinned = "2026-01-01T00:00:00.000Z"; |
| 50 | + const coldStarted = performance.now(); |
| 51 | + const cold = await scanRepository(path, builtInDetectors, { |
| 52 | + cacheDirectory, |
| 53 | + noCache: true, |
| 54 | + scannedAt: pinned, |
| 55 | + }); |
| 56 | + const coldMs = performance.now() - coldStarted; |
| 57 | + |
| 58 | + await scanRepository(path, builtInDetectors, { cacheDirectory, scannedAt: pinned }); |
| 59 | + |
| 60 | + const warmStarted = performance.now(); |
| 61 | + const warm = await scanRepository(path, builtInDetectors, { cacheDirectory, scannedAt: pinned }); |
| 62 | + const warmMs = performance.now() - warmStarted; |
| 63 | + |
| 64 | + return { |
| 65 | + coldMs, |
| 66 | + warmMs, |
| 67 | + speedup: coldMs / Math.max(warmMs, 0.001), |
| 68 | + findings: cold.findings.length, |
| 69 | + identical: findingIds(cold) === findingIds(warm), |
| 70 | + }; |
| 71 | +} |
| 72 | + |
| 73 | +export async function runScanCacheSpeed( |
| 74 | + entries: readonly CorpusRepositoryEntry[], |
| 75 | + options: { offline?: boolean } = {}, |
| 76 | +): Promise<ScanCacheSpeedResult> { |
| 77 | + const cacheDir = resolveCorpusCacheDir(); |
| 78 | + if (!cacheDir) { |
| 79 | + throw new Error(`Set ${"OFFING_CORPUS_CACHE"} to a warm checkout cache before proving scan-cache speed.`); |
| 80 | + } |
| 81 | + const offline = options.offline === true || process.argv.includes("--offline"); |
| 82 | + const strategy = resolveFetchStrategy(); |
| 83 | + const measurements: RepoSpeedMeasurement[] = []; |
| 84 | + const scanCacheRoot = await mkdtemp(join(tmpdir(), "offing-scan-cache-speed-")); |
| 85 | + |
| 86 | + try { |
| 87 | + for (const entry of entries) { |
| 88 | + const checkout = await ensureCorpusCacheEntry( |
| 89 | + cacheDir, |
| 90 | + entry, |
| 91 | + async (directory) => { |
| 92 | + if (offline) throw new Error(`Missing cached checkout for ${entry.repository}; run corpus:warm first.`); |
| 93 | + await fetchWith(strategy, directory, entry); |
| 94 | + }, |
| 95 | + (existing) => isCheckoutUsable(existing, strategy), |
| 96 | + ); |
| 97 | + const measured = await measureRepository(checkout.path, join(scanCacheRoot, entry.repository.replace("/", "__"))); |
| 98 | + measurements.push({ repository: entry.repository, ...measured }); |
| 99 | + const status = measured.identical ? "identical" : "DRIFT"; |
| 100 | + console.error( |
| 101 | + `${entry.repository}: cold ${measured.coldMs.toFixed(0)} ms, warm ${measured.warmMs.toFixed(0)} ms, ` + |
| 102 | + `${measured.speedup.toFixed(2)}×, ${measured.findings} findings (${status})`, |
| 103 | + ); |
| 104 | + } |
| 105 | + } finally { |
| 106 | + await rm(scanCacheRoot, { recursive: true, force: true }); |
| 107 | + } |
| 108 | + |
| 109 | + const totalCold = measurements.reduce((sum, row) => sum + row.coldMs, 0); |
| 110 | + const totalWarm = measurements.reduce((sum, row) => sum + row.warmMs, 0); |
| 111 | + const aggregateSpeedup = totalCold / Math.max(totalWarm, 0.001); |
| 112 | + const allIdentical = measurements.every((row) => row.identical); |
| 113 | + return { |
| 114 | + schemaVersion: "offing.scan-cache-speed.v1", |
| 115 | + repositories: measurements, |
| 116 | + aggregateSpeedup, |
| 117 | + allIdentical, |
| 118 | + withinBudget: allIdentical && aggregateSpeedup >= SCAN_CACHE_SPEEDUP_FLOOR, |
| 119 | + }; |
| 120 | +} |
| 121 | + |
| 122 | +async function main(argv = process.argv.slice(2)): Promise<void> { |
| 123 | + const corpus = await loadPublicCorpus(); |
| 124 | + const filter = parseCorpusFilter(argv); |
| 125 | + const selection = selectCorpusEntries(corpus.repositories, filter, []); |
| 126 | + // Default to a small Node sample so a local proof stays short; pass --ecosystem / --repo to widen. |
| 127 | + const entries = |
| 128 | + filter.ecosystems.length > 0 || filter.repositories.length > 0 |
| 129 | + ? selection.entries |
| 130 | + : selection.entries.filter((entry) => entry.ecosystem === "node").slice(0, 5); |
| 131 | + if (entries.length === 0) throw new Error("No corpus repositories selected."); |
| 132 | + |
| 133 | + const result = await runScanCacheSpeed(entries, { offline: argv.includes("--offline") }); |
| 134 | + if (argv.includes("--json")) console.log(JSON.stringify(result, null, 2)); |
| 135 | + else { |
| 136 | + console.log( |
| 137 | + `Aggregate warm speedup ${result.aggregateSpeedup.toFixed(2)}× over ${result.repositories.length} repositories ` + |
| 138 | + `(floor ${SCAN_CACHE_SPEEDUP_FLOOR}×, identical=${result.allIdentical}) — ${result.withinBudget ? "PASSED" : "FAILED"}`, |
| 139 | + ); |
| 140 | + } |
| 141 | + if (!result.withinBudget) process.exitCode = 1; |
| 142 | +} |
| 143 | + |
| 144 | +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { |
| 145 | + await main(); |
| 146 | +} |
0 commit comments