diff --git a/scripts/__tests__/daemon-fixture-launch-guard.test.ts b/scripts/__tests__/daemon-fixture-launch-guard.test.ts index 4e7a6d4a5a..b0761fe368 100644 --- a/scripts/__tests__/daemon-fixture-launch-guard.test.ts +++ b/scripts/__tests__/daemon-fixture-launch-guard.test.ts @@ -105,6 +105,26 @@ for (const specifier of ['..', '.', String.raw`.\u002e`]) { }); } +for (const [fixture, consumer, specifier] of [ + ['src/support.ts', 'src/support/consumer.test.ts', '.'], + ['src/support.ts', 'src/support/nested/consumer.test.ts', '..'], + ['src/support.ts', 'src/support.js/consumer.test.ts', '.'], + ['src/support/.ts', 'src/support/consumer.test.ts', './.ts'], +] as const) { + test(`the repo scan follows '${specifier}' from ${consumer} to ${fixture}`, () => { + const bad = `import { runCmdDetachedMonitored } from '@agent-device/host-kit/command'; const spawn = vi.mocked(runCmdDetachedMonitored); spawn.mockImplementation(() => { throw new Error('raw'); });`; + const violations = scanDaemonFixtureLaunches([ + { + file: fixture, + source: `import { createRegisteredDaemonFixtures } from '@agent-device/test-kit'; export const fixtures = createRegisteredDaemonFixtures({});`, + }, + { file: consumer, source: `import { fixtures } from '${specifier}'; ${bad}` }, + ]); + assert.equal(violations.length, 1); + assert.ok(violations[0]!.includes(consumer)); + }); +} + for (const expression of [ '(spawn as any)', 'spawn!', diff --git a/scripts/fuzz/run.ts b/scripts/fuzz/run.ts index e675d58871..ef46d9021f 100644 --- a/scripts/fuzz/run.ts +++ b/scripts/fuzz/run.ts @@ -14,7 +14,6 @@ import { writeFuzzEnvelope, } from './envelope.ts'; import { runCases } from './execute.ts'; -import { generateAndCheck } from './generate.ts'; import { describeFailure, type FuzzFailure } from './invariant.ts'; import { fallbackFuzzOptions, FUZZ_USAGE, readFuzzOptions, type FuzzOptions } from './options.ts'; import { getFuzzTarget } from './registry.ts'; @@ -34,12 +33,15 @@ function corpusCasesFor(target: FuzzTarget): string[] { .map((entry) => entry.input); } -/** One target's run: generated (fast-check, shrinking) or a replay of the checked-in corpus. */ +type GenerateAndCheck = typeof import('./generate.ts').generateAndCheck; + +/** One target's run: generated (fast-check, shrinking), or without a generator a corpus replay. */ async function runOneTarget( target: FuzzTarget, options: FuzzOptions, + generateAndCheck: GenerateAndCheck | undefined, ): Promise<{ cases: number; failures: FuzzFailure[]; replayHint?: string }> { - if (options.replayCorpus) { + if (generateAndCheck === undefined) { const cases = corpusCasesFor(target); return { cases: cases.length, failures: await runCases(target, cases, options.caseTimeoutMs) }; } @@ -57,9 +59,18 @@ async function runOneTarget( async function fuzzTargets(targets: readonly FuzzTarget[], options: FuzzOptions) { const failures: FuzzFailure[] = []; const targetRuns: FuzzTargetRun[] = []; + // fast-check and the arbitraries take about a second to load, and only generation needs them. + // Loading them before the first timer keeps that cost out of every target's duration. + const generateAndCheck = options.replayCorpus + ? undefined + : (await import('./generate.ts')).generateAndCheck; for (const target of targets) { const started = Date.now(); - const { cases, failures: found, replayHint } = await runOneTarget(target, options); + const { + cases, + failures: found, + replayHint, + } = await runOneTarget(target, options, generateAndCheck); const durationMs = Date.now() - started; targetRuns.push({ target: target.name, cases, failures: found.length, durationMs }); process.stdout.write( diff --git a/scripts/lib/daemon-fixture-launch-guard.ts b/scripts/lib/daemon-fixture-launch-guard.ts index b303c60221..68e31e81ec 100644 --- a/scripts/lib/daemon-fixture-launch-guard.ts +++ b/scripts/lib/daemon-fixture-launch-guard.ts @@ -14,24 +14,75 @@ type FixtureSource = Readonly<{ file: string; source: string }>; /** Follows local fixture imports so a renamed helper or a new consumer cannot leave the guard. */ export function scanDaemonFixtureLaunches(files: readonly FixtureSource[]): string[] { const paths = new Set(files.map(({ file }) => file)); - const parsed = new Map(files.map(({ file, source }) => [file, parseFixtureSource(file, source)])); - const importers = new Map(); - for (const [file, { dependencies }] of parsed) { - for (const specifier of dependencies) { - const dependency = resolveLocalImport(file, specifier, paths); - if (dependency) importers.set(dependency, [...(importers.get(dependency) ?? []), file]); + const parsed = new Map(); + const parse = ({ file, source }: FixtureSource): ParsedFixtureSource => { + let entry = parsed.get(file); + if (!entry) parsed.set(file, (entry = parseFixtureSource(file, source))); + return entry; + }; + const resolvedImports = new Map>(); + const importsOf = (entry: FixtureSource): ReadonlySet => { + let imports = resolvedImports.get(entry.file); + if (!imports) { + imports = new Set( + parse(entry).dependencies.flatMap( + (specifier) => resolveLocalImport(entry.file, specifier, paths) ?? [], + ), + ); + resolvedImports.set(entry.file, imports); } - } + return imports; + }; // Only a file that could name the seed needs its tree walked; everything else joins through imports. - const seeds = files - .filter(({ file, source }) => mayNameSeed(source) && namesSeed(parsed.get(file)!.program())) - .map(({ file }) => file); - const family = reachedFrom(seeds, importers); + const family = new Set( + files + .filter((entry) => mayNameSeed(entry.source) && namesSeed(parse(entry).program())) + .map(({ file }) => file), + ); + // Parsing every file to build the whole import graph costs seconds, so only a file that could + // import a family member is parsed. An escape can spell any request, so every file with one is a + // candidate. + const escaped = files.filter(({ source }) => source.includes('\\')); + const unescaped = files.filter(({ source }) => !source.includes('\\')); + const pending = [...family]; + while (pending.length > 0) { + const member = pending.pop()!; + const candidates = [...escaped, ...unescaped.filter(mayImport(member))]; + for (const candidate of candidates) { + if (family.has(candidate.file) || !importsOf(candidate).has(member)) continue; + family.add(candidate.file); + pending.push(candidate.file); + } + } return files .filter(({ file }) => family.has(file)) .flatMap(({ file, source }) => daemonFixtureLaunchViolations(source, file)); } +/** + * A cheap superset of the unescaped files whose relative request resolves to `member`. + * {@link resolveLocalImport} reaches `member` from the member path, its `.js` alias, or its + * extensionless path. Each segment of a resolved path is spelled by the request, unless `.` and `..` + * steps take it from the importer's own path, which puts the importer under that path. A request to + * an index passes through its directory, so the directory stands for every form of an index. + */ +function mayImport(member: string): (entry: FixtureSource) => boolean { + const stem = member.replace(/\.ts$/, ''); + const targets = + lastSegment(stem) === 'index' ? [path.posix.dirname(member)] : [member, `${stem}.js`, stem]; + // Every target's last segment contains this name. A module named `.ts` has an empty one, which + // admits every file. + const name = lastSegment(targets.at(-1)!); + const ancestors = targets.map((target) => `${target}/`); + return ({ file, source }) => + source.includes(name) || ancestors.some((ancestor) => file.startsWith(ancestor)); +} + +/** Unlike `path.basename`, keeps an empty segment empty (`src/fixtures/` gives ``). */ +function lastSegment(target: string): string { + return target.slice(target.lastIndexOf('/') + 1); +} + type ParsedFixtureSource = Readonly<{ program: () => AstNode; dependencies: readonly string[] }>; /** Relative module requests come from the parser's module record, so escaped specifiers resolve too. */ @@ -76,22 +127,6 @@ function namesSeed(program: AstNode): boolean { return found; } -function reachedFrom( - seeds: readonly string[], - importers: ReadonlyMap, -): Set { - const reached = new Set(seeds); - const pending = [...seeds]; - while (pending.length > 0) { - for (const importer of importers.get(pending.pop()!) ?? []) { - if (reached.has(importer)) continue; - reached.add(importer); - pending.push(importer); - } - } - return reached; -} - function resolveLocalImport( file: string, specifier: string, diff --git a/test/repo-guards/snapshot-producer-emitters.test.ts b/test/repo-guards/snapshot-producer-emitters.test.ts index cfccca3470..3991a329e0 100644 --- a/test/repo-guards/snapshot-producer-emitters.test.ts +++ b/test/repo-guards/snapshot-producer-emitters.test.ts @@ -96,6 +96,9 @@ function publishArgument(call: AstNode): AstNode | undefined { } function scanModule(file: string, source: string): ProducerScan { + // Only a `producer` key or a `*_PRODUCER` binding records anything, and an escape can spell either. + // Skipping the other modules unparsed keeps each repo scan well under the test timeout. + if (!/producer|PRODUCER|\\/.test(source)) return { emissions: [], references: [] }; const program = parseSync(file, source).program as unknown as AstNode; const constants = moduleConstants(program); const producerOf = (node: unknown) => {