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
10 changes: 5 additions & 5 deletions benchmarks/corpus-targets.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,20 @@
"cpp": 15,
"dart": 75,
"database": 12,
"deno": 0,
"deno": 71,
"dotnet": 18,
"elixir": 0,
"elixir": 36,
"go": 43,
"java": 25,
"kubernetes": 19,
"kubernetes": 36,
"node": 200,
"node-actions": 34,
"php": 108,
"python": 200,
"ruby": 60,
"rust": 200,
"rust": 199,
"scala": 80,
"serverless": 21,
"serverless": 41,
"shell": 43,
"swift": 85,
"terraform": 12
Expand Down
404 changes: 0 additions & 404 deletions benchmarks/public-repositories/rust/0557--antono4--openmind.json

This file was deleted.

146 changes: 146 additions & 0 deletions benchmarks/scan-cache-speed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/**
* Proves incremental scan reuse on the public corpus: a warm unchanged rerun must return
* identical findings to a full scan and finish at least ten times faster on aggregate.
*
* Requires a warm checkout cache (`OFFING_CORPUS_CACHE` + `npm run corpus:warm`), then:
* npm run build --silent && node dist/benchmarks/scan-cache-speed.js --offline [--repo owner/name]
*/
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { performance } from "node:perf_hooks";
import { pathToFileURL } from "node:url";

import { builtInDetectors } from "../src/detectors/index.js";
import { scanRepository } from "../src/engine/index.js";
import { ensureCorpusCacheEntry, resolveCorpusCacheDir } from "./corpus-cache.js";
import { fetchWith, isCheckoutUsable, resolveFetchStrategy } from "./corpus-fetch.js";
import { parseCorpusFilter, selectCorpusEntries } from "./corpus-filter.js";
import { loadPublicCorpus } from "./public-corpus.js";
import type { CorpusRepositoryEntry } from "./corpus-harness.js";

export const SCAN_CACHE_SPEEDUP_FLOOR = 10;

export interface RepoSpeedMeasurement {
readonly repository: string;
readonly coldMs: number;
readonly warmMs: number;
readonly speedup: number;
readonly findings: number;
readonly identical: boolean;
}

export interface ScanCacheSpeedResult {
readonly schemaVersion: "offing.scan-cache-speed.v1";
readonly repositories: readonly RepoSpeedMeasurement[];
readonly aggregateSpeedup: number;
readonly allIdentical: boolean;
readonly withinBudget: boolean;
}

function findingIds(result: Awaited<ReturnType<typeof scanRepository>>): string {
return JSON.stringify(result.findings.map((finding) => finding.id).sort());
}

async function measureRepository(
path: string,
cacheDirectory: string,
): Promise<Omit<RepoSpeedMeasurement, "repository">> {
const pinned = "2026-01-01T00:00:00.000Z";
const coldStarted = performance.now();
const cold = await scanRepository(path, builtInDetectors, {
cacheDirectory,
noCache: true,
scannedAt: pinned,
});
const coldMs = performance.now() - coldStarted;

await scanRepository(path, builtInDetectors, { cacheDirectory, scannedAt: pinned });

const warmStarted = performance.now();
const warm = await scanRepository(path, builtInDetectors, { cacheDirectory, scannedAt: pinned });
const warmMs = performance.now() - warmStarted;

return {
coldMs,
warmMs,
speedup: coldMs / Math.max(warmMs, 0.001),
findings: cold.findings.length,
identical: findingIds(cold) === findingIds(warm),
};
}

export async function runScanCacheSpeed(
entries: readonly CorpusRepositoryEntry[],
options: { offline?: boolean } = {},
): Promise<ScanCacheSpeedResult> {
const cacheDir = resolveCorpusCacheDir();
if (!cacheDir) {
throw new Error(`Set ${"OFFING_CORPUS_CACHE"} to a warm checkout cache before proving scan-cache speed.`);
}
const offline = options.offline === true || process.argv.includes("--offline");
const strategy = resolveFetchStrategy();
const measurements: RepoSpeedMeasurement[] = [];
const scanCacheRoot = await mkdtemp(join(tmpdir(), "offing-scan-cache-speed-"));

try {
for (const entry of entries) {
const checkout = await ensureCorpusCacheEntry(
cacheDir,
entry,
async (directory) => {
if (offline) throw new Error(`Missing cached checkout for ${entry.repository}; run corpus:warm first.`);
await fetchWith(strategy, directory, entry);
},
(existing) => isCheckoutUsable(existing, strategy),
);
const measured = await measureRepository(checkout.path, join(scanCacheRoot, entry.repository.replace("/", "__")));
measurements.push({ repository: entry.repository, ...measured });
const status = measured.identical ? "identical" : "DRIFT";
console.error(
`${entry.repository}: cold ${measured.coldMs.toFixed(0)} ms, warm ${measured.warmMs.toFixed(0)} ms, ` +
`${measured.speedup.toFixed(2)}×, ${measured.findings} findings (${status})`,
);
}
} finally {
await rm(scanCacheRoot, { recursive: true, force: true });
}

const totalCold = measurements.reduce((sum, row) => sum + row.coldMs, 0);
const totalWarm = measurements.reduce((sum, row) => sum + row.warmMs, 0);
const aggregateSpeedup = totalCold / Math.max(totalWarm, 0.001);
const allIdentical = measurements.every((row) => row.identical);
return {
schemaVersion: "offing.scan-cache-speed.v1",
repositories: measurements,
aggregateSpeedup,
allIdentical,
withinBudget: allIdentical && aggregateSpeedup >= SCAN_CACHE_SPEEDUP_FLOOR,
};
}

async function main(argv = process.argv.slice(2)): Promise<void> {
const corpus = await loadPublicCorpus();
const filter = parseCorpusFilter(argv);
const selection = selectCorpusEntries(corpus.repositories, filter, []);
// Default to a small Node sample so a local proof stays short; pass --ecosystem / --repo to widen.
const entries =
filter.ecosystems.length > 0 || filter.repositories.length > 0
? selection.entries
: selection.entries.filter((entry) => entry.ecosystem === "node").slice(0, 5);
if (entries.length === 0) throw new Error("No corpus repositories selected.");

const result = await runScanCacheSpeed(entries, { offline: argv.includes("--offline") });
if (argv.includes("--json")) console.log(JSON.stringify(result, null, 2));
else {
console.log(
`Aggregate warm speedup ${result.aggregateSpeedup.toFixed(2)}× over ${result.repositories.length} repositories ` +
`(floor ${SCAN_CACHE_SPEEDUP_FLOOR}×, identical=${result.allIdentical}) — ${result.withinBudget ? "PASSED" : "FAILED"}`,
);
}
if (!result.withinBudget) process.exitCode = 1;
}

if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
await main();
}
1 change: 1 addition & 0 deletions changes/incremental-scan-cache.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Speed up unchanged re-scans by reusing results keyed on file fingerprints, detector version, and data version; a warm hit skips content hashing when size and mtime still match.
2 changes: 1 addition & 1 deletion docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ Every command runs locally. Scans read repository files and bundled lifecycle da
offing scan [path...] [--json | --format <format>]
```

Finds lifecycle risks in a repository and prints each one with its severity, exact file and line, replacement, and evidence source. Results are cached locally; the scan itself is read-only.
Finds lifecycle risks in a repository and prints each one with its severity, exact file and line, replacement, and evidence source. Results are cached locally by file content hash, detector version, and data version; an unchanged re-scan reuses those results after a size and mtime check and skips re-reading file bytes. The scan itself is read-only.

| Flag | What it does |
| --- | --- |
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@
"benchmark:monorepo": "npm run build --silent && node dist/benchmarks/monorepo.js",
"benchmark:detector-cost": "npm run build --silent && node dist/benchmarks/detector-cost.js",
"benchmark:first-run": "npm run build --silent && node dist/benchmarks/first-run.js",
"benchmark:scan-cache": "npm run build --silent && node dist/benchmarks/scan-cache-speed.js",
"bench:staleness:run": "npm run build --silent && node dist/benchmarks/agent-staleness/run.js",
"bench:staleness:score": "npm run build --silent && node dist/benchmarks/agent-staleness/score.js",
"eval:skill-triggers": "npm run build --silent && node dist/benchmarks/skill-trigger-eval.js",
Expand Down
61 changes: 53 additions & 8 deletions src/detector-inputs.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,53 @@
import type { DetectorInputs } from "./sdk.js";

const wildcardCache = new Map<string, RegExp>();

function wildcard(pattern: string): RegExp {
const cached = wildcardCache.get(pattern);
if (cached) return cached;
const source = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
return new RegExp(`^${source}$`, "i");
const compiled = new RegExp(`^${source}$`, "i");
wildcardCache.set(pattern, compiled);
return compiled;
}

/**
* Drops trailing `/` characters in linear time. Directory names are untrusted detector input, so a
* loop is used instead of `/\/+$/` which backtracks on a long run of slashes (`js/polynomial-redos`).
*/
export function trimTrailingSlashes(value: string): string {
let end = value.length;
while (end > 0 && value.charCodeAt(end - 1) === 0x2f) end -= 1;
return end === value.length ? value : value.slice(0, end);
}

/** Lowercased extensions derived once per `inputs` object. Directory prefixes stay lazy — they can be huge. */
interface CompiledInputs {
readonly namePatterns: readonly RegExp[];
readonly extensions: readonly string[];
directoryPrefixes?: readonly string[];
}

const compiledInputs = new WeakMap<DetectorInputs, CompiledInputs>();

function compileInputs(inputs: DetectorInputs): CompiledInputs {
const cached = compiledInputs.get(inputs);
if (cached) return cached;
const compiled: CompiledInputs = {
namePatterns: (inputs.fileNames ?? []).map(wildcard),
extensions: [...(inputs.extensions ?? []), ...(inputs.sourceExtensions ?? [])].map((extension) =>
extension.toLowerCase(),
),
};
compiledInputs.set(inputs, compiled);
return compiled;
}

function directoryPrefixes(inputs: DetectorInputs, compiled: CompiledInputs): readonly string[] {
if (compiled.directoryPrefixes) return compiled.directoryPrefixes;
const prefixes = (inputs.directories ?? []).map((directory) => `${trimTrailingSlashes(directory)}/`);
compiled.directoryPrefixes = prefixes;
return prefixes;
}

/**
Expand All @@ -13,11 +58,11 @@ function wildcard(pattern: string): RegExp {
export function declaresInput(inputs: DetectorInputs, path: string): boolean {
const normalized = path.split("\\").join("/").replace(/^\.\//, "");
const base = normalized.slice(normalized.lastIndexOf("/") + 1).toLowerCase();
if (inputs.fileNames?.some((name) => wildcard(name).test(base))) return true;
if (inputs.extensions?.some((extension) => base.endsWith(extension.toLowerCase()))) return true;
if (inputs.sourceExtensions?.some((extension) => base.endsWith(extension.toLowerCase()))) return true;
return (inputs.directories ?? []).some((directory) => {
const prefix = `${directory.replace(/\/+$/, "")}/`;
return normalized.startsWith(prefix) || normalized.includes(`/${prefix}`);
});
const compiled = compileInputs(inputs);
// Names and extensions first: directory prefixes can be pathological (see coverage slash tests).
if (compiled.namePatterns.some((pattern) => pattern.test(base))) return true;
if (compiled.extensions.some((extension) => base.endsWith(extension))) return true;
return directoryPrefixes(inputs, compiled).some(
(prefix) => normalized.startsWith(prefix) || normalized.includes(`/${prefix}`),
);
}
Loading
Loading