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
20 changes: 20 additions & 0 deletions scripts/__tests__/daemon-fixture-launch-guard.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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!',
Expand Down
19 changes: 15 additions & 4 deletions scripts/fuzz/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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) };
}
Expand All @@ -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(
Expand Down
89 changes: 62 additions & 27 deletions scripts/lib/daemon-fixture-launch-guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string[]>();
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<string, ParsedFixtureSource>();
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<string, ReadonlySet<string>>();
const importsOf = (entry: FixtureSource): ReadonlySet<string> => {
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. */
Expand Down Expand Up @@ -76,22 +127,6 @@ function namesSeed(program: AstNode): boolean {
return found;
}

function reachedFrom(
seeds: readonly string[],
importers: ReadonlyMap<string, string[]>,
): Set<string> {
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,
Expand Down
3 changes: 3 additions & 0 deletions test/repo-guards/snapshot-producer-emitters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
Loading