targeted-mutation 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/NOTICE +21 -0
- package/README.md +111 -2
- package/bin/tmt-compile.mjs +46 -0
- package/bin/tmt.mjs +117 -0
- package/build/typescript-syntax/LICENSE.txt +55 -0
- package/build/typescript-syntax/ThirdPartyNoticeText.txt +193 -0
- package/build/typescript-syntax/typescript-syntax.cjs +43 -0
- package/docs/analysis.md +218 -0
- package/docs/compiler.md +462 -0
- package/docs/development.md +61 -0
- package/docs/how-it-works.svg +188 -0
- package/docs/l1.md +94 -0
- package/docs/performance.md +647 -0
- package/docs/releasing.md +48 -0
- package/package.json +49 -4
- package/src/analysis.mjs +689 -0
- package/src/assertion-session.mjs +93 -0
- package/src/assertion-strength.mjs +795 -0
- package/src/builtin-mutations.mjs +755 -0
- package/src/builtin-switches.mjs +642 -0
- package/src/change-undone.mjs +524 -0
- package/src/cli-output.mjs +166 -0
- package/src/compiler-compat.cjs +108 -0
- package/src/compiler-maps.cjs +60 -0
- package/src/compiler-routes.cjs +391 -0
- package/src/compiler.cjs +98 -0
- package/src/compiler.mjs +1 -0
- package/src/conventional.mjs +172 -0
- package/src/displacement.mjs +19 -0
- package/src/extract.mjs +135 -0
- package/src/fallback-process.mjs +14 -0
- package/src/in-parallel.mjs +20 -0
- package/src/lean-replay.mjs +39 -0
- package/src/operator-analysis.mjs +123 -0
- package/src/playwright.mjs +139 -0
- package/src/probe-runtime.mjs +50 -0
- package/src/probe.mjs +170 -0
- package/src/prototype.mjs +230 -0
- package/src/regex-mutations.mjs +102 -0
- package/src/runner-process.mjs +59 -0
- package/src/runtime-binaries.mjs +50 -0
- package/src/scope.mjs +202 -0
- package/src/source-text.mjs +49 -0
- package/src/standard-plan.mjs +308 -0
- package/src/standard-runner.mjs +185 -0
- package/src/standard-session.mjs +362 -0
- package/src/standard-setup.mjs +20 -0
- package/src/targeted-gaps.mjs +85 -0
- package/src/threshold.mjs +185 -0
- package/src/trace-buffer.mjs +126 -0
- package/src/typescript-bindings.mjs +243 -0
- package/src/typescript-compiler.mjs +59 -0
- package/src/typescript-extraction.mjs +354 -0
- package/src/typescript-grammar.mjs +923 -0
- package/src/vitest-reporter.mjs +64 -0
- package/src/vitest.mjs +262 -0
- package/src/witness-analysis.mjs +234 -0
- package/src/witness-contracts.mjs +110 -0
- package/src/witness-discovery.mjs +239 -0
- package/src/witness-fixtures.mjs +148 -0
- package/src/witness-order.mjs +83 -0
- package/src/witness-rules.mjs +254 -0
package/src/scope.mjs
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { isUtf8 } from 'node:buffer';
|
|
3
|
+
import { closeSync, mkdtempSync, openSync, readSync, readdirSync, rmSync } from 'node:fs';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { relative, resolve, sep } from 'node:path';
|
|
6
|
+
import { copyPathIsExcluded, inside, resolveCopyExclusions } from './vitest.mjs';
|
|
7
|
+
|
|
8
|
+
const sourceName = /(?<!\.d|\.test|\.spec)\.(?:[cm]?[jt]s|[jt]sx)$/;
|
|
9
|
+
const runnerConfig = /^(?:vite|vitest|playwright)(?:\.[^.]+)*\.config\.[cm]?[jt]s$/;
|
|
10
|
+
|
|
11
|
+
function listSource(root, exclusions, dir = root) {
|
|
12
|
+
const result = [];
|
|
13
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
14
|
+
if (entry.name.startsWith('.') || ['node_modules', 'build', 'dist', 'coverage'].includes(entry.name)) continue;
|
|
15
|
+
const path = resolve(dir, entry.name);
|
|
16
|
+
if (copyPathIsExcluded(root, path, exclusions)) continue;
|
|
17
|
+
if (entry.isDirectory()) result.push(...listSource(root, exclusions, path));
|
|
18
|
+
if (entry.isFile() && sourceName.test(entry.name) && !runnerConfig.test(entry.name)) result.push(relative(root, path));
|
|
19
|
+
}
|
|
20
|
+
return result;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function git(root, args, stdout = 'pipe') {
|
|
24
|
+
return execFileSync('git', ['--literal-pathspecs', '-C', root, ...args], {
|
|
25
|
+
encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, stdio: ['ignore', stdout, 'pipe'],
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const gitEscapes = { a: '\x07', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t', v: '\v', '"': '"', '\\': '\\' };
|
|
30
|
+
|
|
31
|
+
function patchFile(header) {
|
|
32
|
+
// Renames and copies are disabled, so the two names differ only in their prefixes.
|
|
33
|
+
const middle = (header.length - 1) / 2;
|
|
34
|
+
if (!Number.isInteger(middle) || header[middle] !== ' ') return;
|
|
35
|
+
const left = header.slice(0, middle);
|
|
36
|
+
const right = header.slice(middle + 1);
|
|
37
|
+
if (left.startsWith('a/') && right.startsWith('b/') && left.slice(2) === right.slice(2)) return left.slice(2);
|
|
38
|
+
if (!left.startsWith('"a/') || !right.startsWith('"b/') || !left.endsWith('"') || left.slice(3) !== right.slice(3)) return;
|
|
39
|
+
const path = left.slice(3, -1);
|
|
40
|
+
const octets = path.replace(/\\([abfnrtv"\\]|[0-3][0-7]{2})/g, (_, escape) =>
|
|
41
|
+
gitEscapes[escape] ?? String.fromCharCode(Number.parseInt(escape, 8)));
|
|
42
|
+
const bytes = Buffer.from(octets, 'latin1');
|
|
43
|
+
if (isUtf8(bytes)) return bytes.toString('utf8');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function fromGitPath(file) {
|
|
47
|
+
return sep === '/' ? file : file.replaceAll('/', sep);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function readPatchRanges(chunks, files) {
|
|
51
|
+
const ranges = new Map(files.map(file => [file, []]));
|
|
52
|
+
const seen = new Set();
|
|
53
|
+
let current = files.length === 1 ? ranges.get(files[0]) : null;
|
|
54
|
+
for (const chunk of chunks) {
|
|
55
|
+
for (const [, header, start, count] of chunk.matchAll(/(?:^|\n)(?:diff --git ([^\n]*)|@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@)/g)) {
|
|
56
|
+
if (header !== undefined) {
|
|
57
|
+
if (files.length === 1) continue;
|
|
58
|
+
const path = patchFile(header);
|
|
59
|
+
if (path === undefined) return;
|
|
60
|
+
const file = fromGitPath(path);
|
|
61
|
+
if (!ranges.has(file) || seen.has(file)) return;
|
|
62
|
+
seen.add(file);
|
|
63
|
+
current = ranges.get(file);
|
|
64
|
+
} else {
|
|
65
|
+
if (current === null) return;
|
|
66
|
+
const first = Number(start);
|
|
67
|
+
const length = count === undefined ? 1 : Number(count);
|
|
68
|
+
if (length) current.push([first, first + length - 1]);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return ranges;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function* patchLines(fd) {
|
|
76
|
+
const block = Buffer.allocUnsafe(64 * 1024);
|
|
77
|
+
let position = 0;
|
|
78
|
+
let prefix = '';
|
|
79
|
+
for (;;) {
|
|
80
|
+
const length = readSync(fd, block, 0, block.length, position);
|
|
81
|
+
if (!length) break;
|
|
82
|
+
position += length;
|
|
83
|
+
let from = 0;
|
|
84
|
+
while (from < length) {
|
|
85
|
+
const next = block.subarray(from, length).indexOf(10);
|
|
86
|
+
const end = next === -1 ? length : from + next;
|
|
87
|
+
// Git quotes non-ASCII paths. Line headers fit inside this prefix even in
|
|
88
|
+
// patches with source lines larger than the in-memory output limit.
|
|
89
|
+
if (prefix.length < block.length) {
|
|
90
|
+
prefix += block.toString('latin1', from, Math.min(end, from + block.length - prefix.length));
|
|
91
|
+
}
|
|
92
|
+
if (next === -1) break;
|
|
93
|
+
yield prefix;
|
|
94
|
+
prefix = '';
|
|
95
|
+
from = end + 1;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (prefix) yield prefix;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function diffRanges(root, revision, files) {
|
|
102
|
+
const pathspecs = sep === '/' ? files : files.map(file => file.replaceAll(sep, '/'));
|
|
103
|
+
const args = ['-c', 'core.quotePath=true', 'diff', '--relative', '--no-ext-diff', '--no-textconv', '--no-color', '--no-renames',
|
|
104
|
+
'--src-prefix=a/', '--dst-prefix=b/', '--unified=0', revision, '--', ...pathspecs];
|
|
105
|
+
try {
|
|
106
|
+
return readPatchRanges([git(root, args)], files);
|
|
107
|
+
} catch (error) {
|
|
108
|
+
if (error.code !== 'ENOBUFS') throw error;
|
|
109
|
+
}
|
|
110
|
+
const directory = mkdtempSync(resolve(tmpdir(), 'tmt-diff-'));
|
|
111
|
+
try {
|
|
112
|
+
const fd = openSync(resolve(directory, 'patch'), 'wx+');
|
|
113
|
+
try {
|
|
114
|
+
git(root, args, fd);
|
|
115
|
+
return readPatchRanges(patchLines(fd), files);
|
|
116
|
+
} finally {
|
|
117
|
+
closeSync(fd);
|
|
118
|
+
}
|
|
119
|
+
} finally {
|
|
120
|
+
rmSync(directory, { recursive: true, force: true });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function changedRanges(root, revision, files) {
|
|
125
|
+
const ranges = new Map();
|
|
126
|
+
// Leave room for Git's fixed arguments, workspace path and quoting on Windows.
|
|
127
|
+
const pathBudget = process.platform === 'win32' ? Math.min(16 * 1024, Math.max(0, 30_000 - root.length)) : 32 * 1024;
|
|
128
|
+
let batch = [];
|
|
129
|
+
let bytes = 0;
|
|
130
|
+
function readBatch() {
|
|
131
|
+
if (!batch.length) return;
|
|
132
|
+
const result = diffRanges(root, revision, batch);
|
|
133
|
+
if (result) {
|
|
134
|
+
for (const [file, lines] of result) ranges.set(file, lines);
|
|
135
|
+
} else {
|
|
136
|
+
// Custom submodule diff formats can interleave nested file headers.
|
|
137
|
+
for (const file of batch) ranges.set(file, diffRanges(root, revision, [file]).get(file));
|
|
138
|
+
}
|
|
139
|
+
batch = [];
|
|
140
|
+
bytes = 0;
|
|
141
|
+
}
|
|
142
|
+
for (const file of files) {
|
|
143
|
+
const size = Buffer.byteLength(file) + 3;
|
|
144
|
+
if (bytes + size > pathBudget) readBatch();
|
|
145
|
+
batch.push(file);
|
|
146
|
+
bytes += size;
|
|
147
|
+
}
|
|
148
|
+
readBatch();
|
|
149
|
+
return ranges;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function selectScope(root, files, { lines = [], since, 'copy-exclude': copyExclude } = {}) {
|
|
153
|
+
const exclusions = resolveCopyExclusions(root, copyExclude);
|
|
154
|
+
function sourceFile(file) {
|
|
155
|
+
const path = inside(root, file);
|
|
156
|
+
if (copyPathIsExcluded(root, resolve(root, file), exclusions) || copyPathIsExcluded(root, path, exclusions)) {
|
|
157
|
+
throw new Error(`Source is excluded from trial copies: ${file}`);
|
|
158
|
+
}
|
|
159
|
+
return relative(root, path);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const ranges = new Map();
|
|
163
|
+
for (const entry of lines) {
|
|
164
|
+
const match = /^(.*):(\d+)(?:-(\d+))?$/.exec(entry);
|
|
165
|
+
if (match) match[3] ??= match[2];
|
|
166
|
+
if (!match || !Number.isSafeInteger(+match[2]) || !Number.isSafeInteger(+match[3]) || +match[2] < 1 || +match[2] > +match[3]) {
|
|
167
|
+
throw new Error('Expected --lines FILE:FROM-TO');
|
|
168
|
+
}
|
|
169
|
+
const file = sourceFile(match[1]);
|
|
170
|
+
ranges.set(file, [...(ranges.get(file) ?? []), [+match[2], +match[3]]]);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const selection = files.length ? files : lines.length ? [...ranges.keys()] : listSource(root, exclusions);
|
|
174
|
+
const paths = [...new Set(selection.map(sourceFile))].sort().filter(file => !lines.length || ranges.has(file));
|
|
175
|
+
let tracked;
|
|
176
|
+
let patches;
|
|
177
|
+
let discovered;
|
|
178
|
+
if (since !== undefined) {
|
|
179
|
+
let revision;
|
|
180
|
+
try {
|
|
181
|
+
revision = git(root, ['rev-parse', '--verify', '--end-of-options', since + '^{commit}']).trim();
|
|
182
|
+
} catch {
|
|
183
|
+
throw new Error(`Cannot resolve Git revision: ${since}`);
|
|
184
|
+
}
|
|
185
|
+
tracked = new Set(git(root, ['ls-files', '-z']).split('\0').map(fromGitPath));
|
|
186
|
+
const changedPaths = new Set(git(root, ['diff', '--name-only', '-z', '--relative', '--no-ext-diff', '--no-renames', revision, '--']).split('\0').map(fromGitPath));
|
|
187
|
+
patches = changedRanges(root, revision, paths.filter(file => tracked.has(file) && changedPaths.has(file)));
|
|
188
|
+
// A new file counts as changed. A file Git ignores (generated code, build output) is not new work, so
|
|
189
|
+
// discovery leaves it out; naming it on the command line still selects it.
|
|
190
|
+
if (!files.length && !lines.length) {
|
|
191
|
+
const added = new Set(git(root, ['ls-files', '--others', '--exclude-standard', '-z']).split('\0').map(fromGitPath));
|
|
192
|
+
discovered = file => tracked.has(file) || added.has(file);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return paths.filter(file => !discovered || discovered(file)).map(file => {
|
|
196
|
+
const changed = tracked?.has(file) ? patches.get(file) ?? [] : undefined;
|
|
197
|
+
return { file, selected: line =>
|
|
198
|
+
(!changed || changed.some(([a, b]) => a <= line && line <= b)) &&
|
|
199
|
+
(!ranges.has(file) || ranges.get(file).some(([a, b]) => a <= line && line <= b)), changed,
|
|
200
|
+
};
|
|
201
|
+
}).filter(({ changed }) => changed?.length !== 0);
|
|
202
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export function byteOffsets(source) {
|
|
2
|
+
const offsets = new Uint32Array(source.length + 1);
|
|
3
|
+
let byte = 0;
|
|
4
|
+
for (let unit = 0; unit < source.length; unit++) {
|
|
5
|
+
offsets[unit] = byte;
|
|
6
|
+
const code = source.charCodeAt(unit);
|
|
7
|
+
if (code < 0x80) byte++;
|
|
8
|
+
else if (code < 0x800) byte += 2;
|
|
9
|
+
else if (code >= 0xd800 && code <= 0xdbff) {
|
|
10
|
+
const next = source.charCodeAt(unit + 1);
|
|
11
|
+
if (next >= 0xdc00 && next <= 0xdfff) {
|
|
12
|
+
byte += 4;
|
|
13
|
+
unit++;
|
|
14
|
+
} else byte += 3;
|
|
15
|
+
} else byte += 3;
|
|
16
|
+
}
|
|
17
|
+
offsets[source.length] = byte;
|
|
18
|
+
return offsets;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function sourceDialect(file) {
|
|
22
|
+
return /\.[jt]sx$/.test(file) ? 'tsx' : 'ts';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
26
|
+
|
|
27
|
+
export function optionsFor(options) {
|
|
28
|
+
const dialect = options.dialect ?? sourceDialect(options.file);
|
|
29
|
+
const mode = options.mode ?? 'module';
|
|
30
|
+
if (!['ts', 'tsx'].includes(dialect) || !['script', 'module'].includes(mode)) {
|
|
31
|
+
throw new Error('Expected ts/tsx and script/module dialect options');
|
|
32
|
+
}
|
|
33
|
+
return { dialect, mode };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function normalize(input) {
|
|
37
|
+
if (typeof input === 'string') return input.isWellFormed() ? input : null;
|
|
38
|
+
try {
|
|
39
|
+
return decoder.decode(input);
|
|
40
|
+
} catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function invalidEncoding() {
|
|
46
|
+
return { path: 'diagnostic', reason: 'invalid-utf8', candidates: [], diagnostics: [
|
|
47
|
+
{ severity: 'error', message: 'Expected well-formed UTF-8', start: 0, end: 0 },
|
|
48
|
+
] };
|
|
49
|
+
}
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
|
|
3
|
+
export function indexCoverage(records, tests) {
|
|
4
|
+
const plans = new Map();
|
|
5
|
+
function entry(id) {
|
|
6
|
+
let plan = plans.get(id);
|
|
7
|
+
if (!plan) {
|
|
8
|
+
plan = { hits: 0, staticHits: 0, unknown: false, perTestHits: new Map() };
|
|
9
|
+
plans.set(id, plan);
|
|
10
|
+
}
|
|
11
|
+
return plan;
|
|
12
|
+
}
|
|
13
|
+
for (const { coverage } of records) {
|
|
14
|
+
if (!coverage) continue;
|
|
15
|
+
for (const [id, hits] of Object.entries(coverage.static ?? {})) {
|
|
16
|
+
if (hits) entry(id).staticHits += hits;
|
|
17
|
+
}
|
|
18
|
+
for (const [testId, mutations] of Object.entries(coverage.perTest ?? {})) {
|
|
19
|
+
const unknown = !tests.has(testId);
|
|
20
|
+
for (const [id, hits] of Object.entries(mutations)) {
|
|
21
|
+
if (!hits) continue;
|
|
22
|
+
const plan = entry(id);
|
|
23
|
+
plan.hits += hits;
|
|
24
|
+
plan.unknown ||= unknown;
|
|
25
|
+
plan.perTestHits.set(testId, (plan.perTestHits.get(testId) ?? 0) + hits);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
for (const [id, { hits, staticHits, unknown, perTestHits }] of plans) {
|
|
30
|
+
plans.set(id, { hits: hits + staticHits, staticActivation: staticHits > 0 || unknown,
|
|
31
|
+
covered: new Set(perTestHits.keys()), perTestHits });
|
|
32
|
+
}
|
|
33
|
+
return id => plans.get(String(id)) ?? { hits: 0, staticActivation: false, covered: new Set(), perTestHits: new Map() };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// What the probes of the targeted rules recorded, per edit: the passing tests in which the edit would have given
|
|
37
|
+
// the same as the original every time, those in which it would not, those in which that is not known, and
|
|
38
|
+
// whether it would not, or that is not known, outside any of them (while a file loads, in a hook, in a test
|
|
39
|
+
// that did not pass).
|
|
40
|
+
export function indexAgreement(records, tests) {
|
|
41
|
+
const merged = new Map();
|
|
42
|
+
for (const { observed } of records) {
|
|
43
|
+
for (const [id, entry] of Object.entries(observed ?? {})) {
|
|
44
|
+
if (!merged.has(id)) merged.set(id, { agreeing: new Set(), differing: new Set(), unsure: new Set(), outside: false, outsideUnsure: false, typed: false, realCopy: false, nonArray: false, nonPlain: false, sequence: false, nonSequence: false, threw: false });
|
|
45
|
+
const into = merged.get(id);
|
|
46
|
+
for (const [test, [, differed, unknown = 0]] of Object.entries(entry.tests ?? {})) {
|
|
47
|
+
if (!tests.has(test)) (into.outside ||= differed > 0, into.outsideUnsure ||= unknown > 0);
|
|
48
|
+
else if (differed > 0) into.differing.add(test);
|
|
49
|
+
else if (unknown > 0) into.unsure.add(test);
|
|
50
|
+
else into.agreeing.add(test);
|
|
51
|
+
}
|
|
52
|
+
into.differ ??= entry.differ;
|
|
53
|
+
into.agree ??= entry.agree;
|
|
54
|
+
into.unknown ??= entry.unsure;
|
|
55
|
+
into.typed ||= entry.typed === true;
|
|
56
|
+
into.realCopy ||= entry.realCopy === true;
|
|
57
|
+
into.nonArray ||= entry.nonArray === true;
|
|
58
|
+
into.nonPlain ||= entry.nonPlain === true;
|
|
59
|
+
into.sequence ||= entry.sequence === true;
|
|
60
|
+
into.nonSequence ||= entry.nonSequence === true;
|
|
61
|
+
into.threw ||= entry.threw === true;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
// A test belongs to the strongest of what it saw, over all the files that recorded it.
|
|
65
|
+
for (const into of merged.values()) {
|
|
66
|
+
for (const test of into.differing) (into.unsure.delete(test), into.agreeing.delete(test));
|
|
67
|
+
for (const test of into.unsure) into.agreeing.delete(test);
|
|
68
|
+
}
|
|
69
|
+
return merged;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Which switches each passing test reached in the baseline, and which each test file reached while it loaded.
|
|
73
|
+
export function indexReach(records) {
|
|
74
|
+
const byTest = new Map();
|
|
75
|
+
const whileLoading = new Map();
|
|
76
|
+
for (const { modules = [], coverage } of records) {
|
|
77
|
+
const loaded = Object.entries(coverage?.static ?? {}).filter(([, hits]) => hits).map(([id]) => id);
|
|
78
|
+
for (const module of modules) whileLoading.set(JSON.stringify(module), new Set(loaded));
|
|
79
|
+
for (const [test, counts] of Object.entries(coverage?.perTest ?? {})) {
|
|
80
|
+
if (!byTest.has(test)) byTest.set(test, new Set());
|
|
81
|
+
for (const [id, hits] of Object.entries(counts)) if (hits) byTest.get(test).add(id);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return { byTest, whileLoading };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// What a surviving edit changed in the code its tests run: per test, the switches it reaches only with the edit
|
|
88
|
+
// and those it reached only without it. `runs` holds, per test file, what each test reached with the edit
|
|
89
|
+
// (under an empty name: while the file loaded).
|
|
90
|
+
export function changedReach({ byTest, whileLoading }, runs, limit = 8) {
|
|
91
|
+
const now = [];
|
|
92
|
+
const gone = [];
|
|
93
|
+
for (const { module, reached } of runs) {
|
|
94
|
+
for (const [test, ids] of Object.entries(reached)) {
|
|
95
|
+
const before = (test === '' ? whileLoading.get(module) : byTest.get(test)) ?? new Set();
|
|
96
|
+
const after = new Set(ids);
|
|
97
|
+
for (const id of after) if (!before.has(id)) now.push({ test, id });
|
|
98
|
+
// A trial runs only the tests that reach the edit, so the hooks of the others do not run: what is missing
|
|
99
|
+
// outside the tests says nothing about the edit.
|
|
100
|
+
if (test !== '') for (const id of before) if (!after.has(id)) gone.push({ test, id });
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return { now: now.slice(0, limit), gone: gone.slice(0, limit) };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// The same from the records of a fresh run of the given tests: per test file, what each test reached.
|
|
107
|
+
export function reachOfRecords(records, tests) {
|
|
108
|
+
const runs = records.flatMap(({ modules = [], coverage }) => modules.map(module => ({ module: JSON.stringify(module), reached: {
|
|
109
|
+
...Object.fromEntries(Object.entries(coverage?.perTest ?? {}).map(([test, counts]) => [test, Object.keys(counts).filter(id => counts[id])])),
|
|
110
|
+
'': Object.keys(coverage?.static ?? {}).filter(id => coverage.static[id]) } })));
|
|
111
|
+
const seen = new Set(runs.flatMap(({ reached }) => Object.keys(reached)));
|
|
112
|
+
// A test that ran and reached no switch at all is listed with none.
|
|
113
|
+
return [...runs, { module: null, reached: Object.fromEntries([...tests].filter(test => !seen.has(test)).map(test => [test, []])) }];
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function coveredTests(id, records, tests) {
|
|
117
|
+
return indexCoverage(records, tests)(id);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function agreesWithCoverage(rows, plan) {
|
|
121
|
+
if (!rows || plan.staticActivation || rows.length !== plan.hits) return false;
|
|
122
|
+
const rowCounts = new Map();
|
|
123
|
+
for (const [id] of rows) rowCounts.set(id, (rowCounts.get(id) ?? 0) + 1);
|
|
124
|
+
return rowCounts.size === plan.covered.size &&
|
|
125
|
+
[...rowCounts].every(([id, hits]) => plan.perTestHits.get(id) === hits);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function assessTrial(trial, expectedTests, hitLimit) {
|
|
129
|
+
const { errors, reason } = trial.snapshot;
|
|
130
|
+
const moduleKey = test => JSON.stringify([test.project, test.file]);
|
|
131
|
+
const failed = trial.snapshot.tests.filter(test => test.status === 'failed');
|
|
132
|
+
const actualPassed = new Set(trial.snapshot.tests.filter(test => test.status === 'passed').map(test => test.id));
|
|
133
|
+
const registered = new Set(trial.snapshot.tests.map(test => test.id));
|
|
134
|
+
const collectedModules = new Set(trial.snapshot.tests.map(moduleKey));
|
|
135
|
+
const hitCount = trial.records.reduce((sum, row) => sum + row.hits, 0);
|
|
136
|
+
if (hitCount > hitLimit || failed.some(test => test.timeout)) {
|
|
137
|
+
return { status: 'timeout', statusReason: hitCount > hitLimit ? 'Mutation hit limit reached' : 'Vitest test timeout' };
|
|
138
|
+
}
|
|
139
|
+
if (errors.length) return { status: 'error', statusReason: errors.join('\n') };
|
|
140
|
+
if (hitCount > 0 && ['failed', 'interrupted'].includes(reason) && failed.length &&
|
|
141
|
+
failed.every(test => expectedTests.has(test.id)) && [...expectedTests].every(([id, test]) =>
|
|
142
|
+
registered.has(id) || reason === 'interrupted' && !collectedModules.has(moduleKey(test)))) {
|
|
143
|
+
return { status: 'killed', tests: failed.map(({ id, name, file, project }) => ({ id, name, file, project })) };
|
|
144
|
+
}
|
|
145
|
+
if (hitCount > 0 && reason === 'passed' && !failed.length && [...expectedTests.keys()].every(id => actualPassed.has(id))) {
|
|
146
|
+
return { status: 'survived' };
|
|
147
|
+
}
|
|
148
|
+
return { status: 'unstable', statusReason: 'Vitest did not observe the active mutation with the expected test inventory' };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Splits each pending mutation over the test files that reach it. A test file runs its share inside one worker.
|
|
152
|
+
// Returns null when the baseline did not report exactly one record per test file.
|
|
153
|
+
export function planInThread(records, tests, pending, workspace, timing = { tests: {}, collection: {} }) {
|
|
154
|
+
const modules = new Map();
|
|
155
|
+
for (const record of records) {
|
|
156
|
+
if (record.modules?.length !== 1) return null;
|
|
157
|
+
const [project, file] = record.modules[0];
|
|
158
|
+
const key = JSON.stringify([project, file]);
|
|
159
|
+
if (modules.has(key)) return null;
|
|
160
|
+
const own = new Map([...tests].filter(([, test]) => test.project === project && resolve(workspace, test.file) === file));
|
|
161
|
+
modules.set(key, { coverage: indexCoverage([record], own), own: [...own.keys()] });
|
|
162
|
+
}
|
|
163
|
+
const plans = {};
|
|
164
|
+
for (const { mutant, plan } of pending) {
|
|
165
|
+
for (const [key, { coverage, own }] of modules) {
|
|
166
|
+
// An extra trial has its own id and runs a switch that another entry may also use.
|
|
167
|
+
const local = coverage(mutant.active ?? mutant.id);
|
|
168
|
+
if (!local.hits) continue;
|
|
169
|
+
// One run of this entry: loading the test file, then the tests it selects.
|
|
170
|
+
const cost = (timing.collection[key] ?? 0) + (local.staticActivation ? own : [...local.covered])
|
|
171
|
+
.reduce((sum, test) => sum + (timing.tests[test] ?? 0), 0);
|
|
172
|
+
// A mutation that is active while the file loads runs every test of the file.
|
|
173
|
+
(plans[key] ??= []).push({ id: mutant.id, hits: local.hits, hitLimit: plan.hits * 100, static: local.staticActivation, cost,
|
|
174
|
+
tests: local.staticActivation ? own : [...local.covered],
|
|
175
|
+
...(mutant.active === undefined ? {} : { active: mutant.active, shift: mutant.shift }), ...(mutant.effects ? { effects: true } : {}) });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return plans;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function classify(plan, event) {
|
|
182
|
+
if (!event) return 'open';
|
|
183
|
+
if (event.stuck) return 'timeout';
|
|
184
|
+
if (event.stuckControl) return 'open';
|
|
185
|
+
if (event.unhandled || event.errors?.length || event.foreign || event.missing) return 'open';
|
|
186
|
+
if (event.hits > plan.hitLimit || event.timeout) return 'timeout';
|
|
187
|
+
if (event.hits > 0 && event.failed.length) return 'killed';
|
|
188
|
+
if (event.hits > 0 && event.passed === event.expected) return 'survived';
|
|
189
|
+
return 'open';
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// A mutation is settled when one test file killed it, or when every test file that reaches it answered.
|
|
193
|
+
// The others are left for an isolated run.
|
|
194
|
+
export function settleInThread(plans, events, tests) {
|
|
195
|
+
const answers = new Map(events.filter(event => event.id !== undefined).map(event => [JSON.stringify([event.module, event.id]), event]));
|
|
196
|
+
const parts = new Map();
|
|
197
|
+
for (const [module, list] of Object.entries(plans)) {
|
|
198
|
+
for (const plan of list) {
|
|
199
|
+
const event = answers.get(JSON.stringify([module, plan.id]));
|
|
200
|
+
if (!parts.has(plan.id)) parts.set(plan.id, []);
|
|
201
|
+
parts.get(plan.id).push({ verdict: classify(plan, event), event });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
const settled = new Map();
|
|
205
|
+
for (const [id, list] of parts) {
|
|
206
|
+
const killers = list.filter(part => part.verdict === 'killed').flatMap(part => part.event.failed);
|
|
207
|
+
if (killers.length) {
|
|
208
|
+
settled.set(id, { status: 'killed', tests: killers.map(test => tests.get(test)).filter(Boolean)
|
|
209
|
+
.map(({ id: test, name, file, project }) => ({ id: test, name, file, project })) });
|
|
210
|
+
} else if (list.some(part => part.verdict === 'open')) continue;
|
|
211
|
+
else if (list.some(part => part.verdict === 'timeout')) {
|
|
212
|
+
settled.set(id, { status: 'timeout', statusReason: list.some(part => part.event.stuck) ? 'The worker stopped answering'
|
|
213
|
+
: list.some(part => part.event.timeout) ? 'Vitest test timeout' : 'Mutation hit limit reached' });
|
|
214
|
+
} else settled.set(id, { status: 'survived' });
|
|
215
|
+
}
|
|
216
|
+
return settled;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Cuts each test file's list into parts of near-equal estimated cost, one part per lane. A lane runs its test
|
|
220
|
+
// files beside each other, so every lane gets a part of every file that is long enough to cut.
|
|
221
|
+
export function sharePlans(plans, count) {
|
|
222
|
+
const shares = [];
|
|
223
|
+
for (const [module, list] of Object.entries(plans)) {
|
|
224
|
+
const lanes = Math.max(1, Math.min(count, list.length));
|
|
225
|
+
const weight = plan => (plan.cost ?? 0) + 1;
|
|
226
|
+
const total = list.reduce((sum, plan) => sum + weight(plan), 0);
|
|
227
|
+
let spent = 0;
|
|
228
|
+
for (const plan of list) {
|
|
229
|
+
// An entry belongs to the lane in which its midpoint falls.
|
|
230
|
+
const lane = Math.min(lanes - 1, Math.floor((spent + weight(plan) / 2) * lanes / total));
|
|
231
|
+
spent += weight(plan);
|
|
232
|
+
((shares[lane] ??= {})[module] ??= []).push(plan);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return [...shares].filter(Boolean);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// The first step runs each mutation only in the test file where it is cheapest. Most mutations are killed there,
|
|
239
|
+
// and the other test files then run only what is left.
|
|
240
|
+
export function cheapestFirst(plans) {
|
|
241
|
+
const cheapest = new Map();
|
|
242
|
+
for (const [module, list] of Object.entries(plans)) {
|
|
243
|
+
for (const plan of list) {
|
|
244
|
+
const best = cheapest.get(plan.id);
|
|
245
|
+
if (!best || (plan.cost ?? 0) < (best.plan.cost ?? 0)) cheapest.set(plan.id, { module, plan });
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
const first = {};
|
|
249
|
+
const rest = {};
|
|
250
|
+
for (const [module, list] of Object.entries(plans)) {
|
|
251
|
+
for (const plan of list) ((cheapest.get(plan.id).module === module ? first : rest)[module] ??= []).push(plan);
|
|
252
|
+
}
|
|
253
|
+
return { first, rest };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// The plan without the entries of the given mutations.
|
|
257
|
+
export function withoutMutations(plans, ids) {
|
|
258
|
+
return Object.fromEntries(Object.entries(plans).map(([module, list]) => [module, list.filter(plan => !ids.has(plan.id))])
|
|
259
|
+
.filter(([, list]) => list.length));
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// What the runs so far left for another one: entries without an answer. A test file whose control run differed
|
|
263
|
+
// starts again in a new worker without the mutation it stopped at, up to `restarts` times; after that its
|
|
264
|
+
// unanswered entries wait for fresh runs. A worker that hung has its mutation settled.
|
|
265
|
+
export function unanswered(plans, events, restarts = 0) {
|
|
266
|
+
const stops = new Map();
|
|
267
|
+
for (const event of events) {
|
|
268
|
+
if (event.stop === undefined) continue;
|
|
269
|
+
if (!stops.has(event.module)) stops.set(event.module, new Set());
|
|
270
|
+
stops.get(event.module).add(event.stop);
|
|
271
|
+
}
|
|
272
|
+
const done = new Set(events.filter(event => event.id !== undefined).map(event => JSON.stringify([event.module, event.id])));
|
|
273
|
+
return Object.fromEntries(Object.entries(plans).filter(([module]) => (stops.get(module)?.size ?? 0) <= restarts)
|
|
274
|
+
.map(([module, list]) => [module, list.filter(plan => !done.has(JSON.stringify([module, plan.id])) && !stops.get(module)?.has(plan.id))])
|
|
275
|
+
.filter(([, list]) => list.length));
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Why a worker left a mutation for a fresh run, for the report. The first reason found among its test files is given.
|
|
279
|
+
export function openReasons(plans, events) {
|
|
280
|
+
const answers = new Map(events.filter(event => event.id !== undefined).map(event => [JSON.stringify([event.module, event.id]), event]));
|
|
281
|
+
const stops = new Map();
|
|
282
|
+
for (const event of events) {
|
|
283
|
+
if (event.stop !== undefined) stops.set(event.module, (stops.get(event.module) ?? new Set()).add(event.stop));
|
|
284
|
+
}
|
|
285
|
+
const reasons = new Map();
|
|
286
|
+
for (const [module, list] of Object.entries(plans)) {
|
|
287
|
+
for (const plan of list) {
|
|
288
|
+
if (reasons.has(plan.id)) continue;
|
|
289
|
+
const event = answers.get(JSON.stringify([module, plan.id]));
|
|
290
|
+
const reason = !event ? (stops.get(module)?.has(plan.id) ? 'control-differs' : stops.has(module) ? 'worker-stopped' : 'not-answered')
|
|
291
|
+
: event.stuckControl ? 'control-hung'
|
|
292
|
+
: event.stuck ? null
|
|
293
|
+
: event.unhandled ? 'unhandled-error'
|
|
294
|
+
: event.errors?.length ? 'error-outside-tests'
|
|
295
|
+
: event.foreign || event.missing ? 'tests-changed'
|
|
296
|
+
: classify(plan, event) === 'open' ? 'inconclusive' : null;
|
|
297
|
+
if (reason) reasons.set(plan.id, reason);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return reasons;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// Evenly spaced picks from the mutations a worker settled, for checking them against fresh runs.
|
|
304
|
+
export function sampleSettled(ids, count) {
|
|
305
|
+
if (!(count > 0) || !ids.length) return [];
|
|
306
|
+
const step = Math.max(1, Math.floor(ids.length / count));
|
|
307
|
+
return ids.filter((_, index) => index % step === 0).slice(0, count);
|
|
308
|
+
}
|