Skip to content

Commit 8205922

Browse files
feat: incremental scans that reuse unchanged results (#93)
* feat: make unchanged re-scans reuse results with fingerprint warm hits Skip content hashing when size and mtime still match the cached detector manifest, index detector inputs once per scan, and prove ≥10× warm speedup with identical findings on a corpus-shaped fixture and offline corpus sample. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: harden incremental scan cache for CodeQL, mutation, and corpus Strip trailing slashes without a ReDoS-prone regex, unit-test fingerprint and input-index helpers so changed-line mutation stays above the floor, and drop the deleted antono4/openmind corpus pin that failed affected runs. Co-authored-by: Cursor <cursoragent@cursor.com> * chore: ratchet corpus targets after dropping deleted rust pin Record rust at 199 after removing antono4/openmind (GitHub 404), and raise other bucket floors to the current pinned counts. Co-authored-by: Cursor <cursoragent@cursor.com> * test: kill more incremental-scan mutants for the changed-line floor Cover Windows path normalization, duplicate basename/extension indexing, and fingerprint warm hits that preserve unclassified references. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent c79ce82 commit 8205922

16 files changed

Lines changed: 656 additions & 448 deletions

‎benchmarks/corpus-targets.json‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,20 @@
88
"cpp": 15,
99
"dart": 75,
1010
"database": 12,
11-
"deno": 0,
11+
"deno": 71,
1212
"dotnet": 18,
13-
"elixir": 0,
13+
"elixir": 36,
1414
"go": 43,
1515
"java": 25,
16-
"kubernetes": 19,
16+
"kubernetes": 36,
1717
"node": 200,
1818
"node-actions": 34,
1919
"php": 108,
2020
"python": 200,
2121
"ruby": 60,
22-
"rust": 200,
22+
"rust": 199,
2323
"scala": 80,
24-
"serverless": 21,
24+
"serverless": 41,
2525
"shell": 43,
2626
"swift": 85,
2727
"terraform": 12

‎benchmarks/public-repositories/rust/0557--antono4--openmind.json‎

Lines changed: 0 additions & 404 deletions
This file was deleted.

‎benchmarks/scan-cache-speed.ts‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
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+
}

‎changes/incremental-scan-cache.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
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.

‎docs/CLI.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ Every command runs locally. Scans read repository files and bundled lifecycle da
2424
offing scan [path...] [--json | --format <format>]
2525
```
2626

27-
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.
27+
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.
2828

2929
| Flag | What it does |
3030
| --- | --- |

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@
104104
"benchmark:large-monorepos": "npm run build --silent && node dist/benchmarks/large-monorepos.js",
105105
"benchmark:detector-cost": "npm run build --silent && node dist/benchmarks/detector-cost.js",
106106
"benchmark:first-run": "npm run build --silent && node dist/benchmarks/first-run.js",
107+
"benchmark:scan-cache": "npm run build --silent && node dist/benchmarks/scan-cache-speed.js",
107108
"bench:staleness:run": "npm run build --silent && node dist/benchmarks/agent-staleness/run.js",
108109
"bench:staleness:score": "npm run build --silent && node dist/benchmarks/agent-staleness/score.js",
109110
"eval:skill-triggers": "npm run build --silent && node dist/benchmarks/skill-trigger-eval.js",

‎src/detector-inputs.ts‎

Lines changed: 53 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,53 @@
11
import type { DetectorInputs } from "./sdk.js";
22

3+
const wildcardCache = new Map<string, RegExp>();
4+
35
function wildcard(pattern: string): RegExp {
6+
const cached = wildcardCache.get(pattern);
7+
if (cached) return cached;
48
const source = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
5-
return new RegExp(`^${source}$`, "i");
9+
const compiled = new RegExp(`^${source}$`, "i");
10+
wildcardCache.set(pattern, compiled);
11+
return compiled;
12+
}
13+
14+
/**
15+
* Drops trailing `/` characters in linear time. Directory names are untrusted detector input, so a
16+
* loop is used instead of `/\/+$/` which backtracks on a long run of slashes (`js/polynomial-redos`).
17+
*/
18+
export function trimTrailingSlashes(value: string): string {
19+
let end = value.length;
20+
while (end > 0 && value.charCodeAt(end - 1) === 0x2f) end -= 1;
21+
return end === value.length ? value : value.slice(0, end);
22+
}
23+
24+
/** Lowercased extensions derived once per `inputs` object. Directory prefixes stay lazy — they can be huge. */
25+
interface CompiledInputs {
26+
readonly namePatterns: readonly RegExp[];
27+
readonly extensions: readonly string[];
28+
directoryPrefixes?: readonly string[];
29+
}
30+
31+
const compiledInputs = new WeakMap<DetectorInputs, CompiledInputs>();
32+
33+
function compileInputs(inputs: DetectorInputs): CompiledInputs {
34+
const cached = compiledInputs.get(inputs);
35+
if (cached) return cached;
36+
const compiled: CompiledInputs = {
37+
namePatterns: (inputs.fileNames ?? []).map(wildcard),
38+
extensions: [...(inputs.extensions ?? []), ...(inputs.sourceExtensions ?? [])].map((extension) =>
39+
extension.toLowerCase(),
40+
),
41+
};
42+
compiledInputs.set(inputs, compiled);
43+
return compiled;
44+
}
45+
46+
function directoryPrefixes(inputs: DetectorInputs, compiled: CompiledInputs): readonly string[] {
47+
if (compiled.directoryPrefixes) return compiled.directoryPrefixes;
48+
const prefixes = (inputs.directories ?? []).map((directory) => `${trimTrailingSlashes(directory)}/`);
49+
compiled.directoryPrefixes = prefixes;
50+
return prefixes;
651
}
752

853
/**
@@ -13,11 +58,11 @@ function wildcard(pattern: string): RegExp {
1358
export function declaresInput(inputs: DetectorInputs, path: string): boolean {
1459
const normalized = path.split("\\").join("/").replace(/^\.\//, "");
1560
const base = normalized.slice(normalized.lastIndexOf("/") + 1).toLowerCase();
16-
if (inputs.fileNames?.some((name) => wildcard(name).test(base))) return true;
17-
if (inputs.extensions?.some((extension) => base.endsWith(extension.toLowerCase()))) return true;
18-
if (inputs.sourceExtensions?.some((extension) => base.endsWith(extension.toLowerCase()))) return true;
19-
return (inputs.directories ?? []).some((directory) => {
20-
const prefix = `${directory.replace(/\/+$/, "")}/`;
21-
return normalized.startsWith(prefix) || normalized.includes(`/${prefix}`);
22-
});
61+
const compiled = compileInputs(inputs);
62+
// Names and extensions first: directory prefixes can be pathological (see coverage slash tests).
63+
if (compiled.namePatterns.some((pattern) => pattern.test(base))) return true;
64+
if (compiled.extensions.some((extension) => base.endsWith(extension))) return true;
65+
return directoryPrefixes(inputs, compiled).some(
66+
(prefix) => normalized.startsWith(prefix) || normalized.includes(`/${prefix}`),
67+
);
2368
}

0 commit comments

Comments
 (0)