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
156 changes: 130 additions & 26 deletions .github/scripts/mutation-reports.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import path from 'node:path';
import { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';

const compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0);

const RANGE = /^(.*?):((\d+)(?::(\d+))?-(\d+)(?::(\d+))?)$/;

export const normalise = (file, cwd = process.cwd()) =>
Expand Down Expand Up @@ -287,28 +289,143 @@ export function renderHtml(report, cwd = process.cwd()) {
`;
}

// Weighs a mutant by the tests it ran, plus one for the run itself.
export const mutantWeight = (mutant) => 1 + (mutant.testsCompleted ?? mutant.coveredBy?.length ?? 0);
// Each test's cost as the number of mutants it covers against the average test's: a test that drives the whole
// application runs far longer than one that drives a single function, and the report records no test times.
export function testCosts(report) {
const covers = new Map();
for (const result of Object.values(report.files ?? {})) {
for (const mutant of result.mutants ?? []) {
for (const id of mutant.coveredBy ?? []) {
covers.set(id, (covers.get(id) ?? 0) + 1);
}
}
}
const mean = [...covers.values()].reduce((sum, count) => sum + count, 0) / covers.size;
return new Map([...covers].map(([id, count]) => [id, count / mean]));
}

// Weighs a mutant by the cost of the tests it ran, plus one for the run itself. A static mutant runs every
// test, so each counts as the average.
export function mutantWeight(mutant, costs = new Map()) {
const covering = mutant.coveredBy ?? [];
const each = mutant.static || covering.length === 0
? 1
: covering.reduce((sum, id) => sum + (costs.get(id) ?? 1), 0) / covering.length;
return 1 + (mutant.testsCompleted ?? covering.length) * each;
}

// Seconds per file for the next plan, each shard's measured time shared out by the weight of its own mutants.
export function measureFiles(report, shards) {
// Seconds per file and per mutated line for the next plans, each shard's measured time shared out by the
// weight of its own mutants. Lines are [line, mutants, seconds], by the line each mutant starts on.
export function measureSweep(report, shards) {
const costs = testCosts(report);
const files = {};
const lines = {};
for (const { scope, seconds } of shards) {
const weights = new Map([...scope.keys()].map((file) => [file, 0]));
const time = Number.isFinite(seconds) && seconds > 0 ? seconds : 0;
const weighed = [];
for (const [file, result] of Object.entries(report.files)) {
for (const mutant of result.mutants ?? []) {
if (inScope(scope, file, mutant)) {
weights.set(normalise(file), weights.get(normalise(file)) + mutantWeight(mutant));
weighed.push({ file: normalise(file), mutant, weight: mutantWeight(mutant, costs) });
}
}
}
const total = [...weights.values()].reduce((sum, weight) => sum + weight, 0);
const time = seconds > 0 ? seconds : 0;
for (const [file, weight] of weights) {
files[file] = (files[file] ?? 0) + (total > 0 ? (weight / total) * time : time / weights.size);
const total = weighed.reduce((sum, { weight }) => sum + weight, 0);
for (const file of scope.keys()) {
files[file] = (files[file] ?? 0) + (total > 0 ? 0 : time / scope.size);
}
for (const { file, mutant, weight } of total > 0 ? weighed : []) {
const share = (weight / total) * time;
const line = mutant.location.start.line;
files[file] += share;
lines[file] ??= new Map();
const [count, sum] = lines[file].get(line) ?? [0, 0];
lines[file].set(line, [count + 1, sum + share]);
}
}
return files;
const listed = Object.fromEntries(Object.entries(lines).map(([file, byLine]) => [file, [...byLine]
.sort(([a], [b]) => a - b)
.map(([line, [count, sum]]) => [line, count, Math.round(sum * 1000) / 1000])]));
return { files, lines: listed };
}

const isSeconds = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0;

// Estimated seconds for each scope entry ({ path, range, start, end }) from the last full sweep, or null when
// there is no usable sweep. A measured file costs what it took; a range costs the larger of what its lines took
// and the file's average per line, so code added since the sweep still counts; a file the sweep never saw costs
// the sweep's average per line. `lineCount` gives a file's lines, or null when it is gone.
export function estimateScope(entries, history, lineCount) {
const files = isObject(history?.files) ? history.files : {};
let seconds = 0;
let total = 0;
for (const [file, time] of Object.entries(files)) {
const count = isSeconds(time) ? lineCount(file) : null;
if (count > 0) {
seconds += time;
total += count;
}
}
if (total === 0) {
return null;
}
const recorded = (file, start, end) => {
const lines = isObject(history.lines) && Array.isArray(history.lines[file]) ? history.lines[file] : [];
return lines.reduce((sum, line) => (Array.isArray(line) && line[0] >= start && line[0] <= end
&& isSeconds(line[2]) ? sum + line[2] : sum), 0);
};
const costs = entries.map(({ path: file, range, start, end }) => {
const count = lineCount(file) || 1;
const size = range ? end - start + 1 : count;
if (!isSeconds(files[file])) {
return size * (seconds / total);
}
if (!range) {
return files[file];
}
return Math.max(recorded(file, start, end), size * (files[file] / count));
});
return costs.every(Number.isFinite) && Number.isFinite(costs.reduce((sum, cost) => sum + cost, 0)) ? costs : null;
}

const disjoint = (entries) => entries.every(({ range }) => range) && [...entries]
.sort((a, b) => a.start - b.start)
.every((entry, index, sorted) => index === 0 || entry.start > sorted[index - 1].end);

// Packs units ({ key, weight }), heaviest first, onto the least loaded of `count` shards.
export function pack(units, count) {
const sorted = [...units].sort((a, b) => b.weight - a.weight || compare(a.key, b.key));
const bins = Array.from({ length: Math.min(count, sorted.length) }, () => ({ weight: 0, units: [] }));
for (const unit of sorted) {
const bin = bins.reduce((least, other) => (other.weight < least.weight
|| (other.weight === least.weight && other.units.length < least.units.length) ? other : least));
bin.weight += unit.weight;
bin.units.push(unit);
}
return bins;
}

// Splits scope entries ({ path, text, range, start, end }) into at most `count` shards by their weights. A file
// heavier than a shard's fair share is split by its ranges when no two overlap, so no mutant runs on two shards;
// a range is never cut.
export function planScope(entries, weights, count) {
const byPath = new Map();
entries.forEach((entry, index) => {
byPath.set(entry.path, [...(byPath.get(entry.path) ?? []), { entry, weight: weights[index] }]);
});
const weigh = (items) => items.reduce((sum, { weight }) => sum + weight, 0);
const total = weigh([...byPath.values()].flat());
const units = [...byPath.keys()].sort(compare).flatMap((file) => {
const items = byPath.get(file);
return weigh(items) > total / count && items.length > 1 && disjoint(items.map(({ entry }) => entry))
? items.map(({ entry, weight }) => ({ key: entry.text, weight, entries: [entry] }))
: [{ key: file, weight: weigh(items), entries: items.map(({ entry }) => entry) }];
});
return pack(units, count).map((bin) => ({
weight: bin.weight,
entries: bin.units.flatMap((unit) => unit.entries)
.sort((a, b) => compare(a.path, b.path) || a.start - b.start),
}));
}

// Stryker's `mutate` patterns as the files on disk they select, in order, as Stryker reads them: a later `!`
Expand Down Expand Up @@ -345,21 +462,8 @@ export function expandMutate(patterns, cwd = process.cwd()) {
}

// Packs whole files, heaviest first, onto the least loaded of `count` shards.
export function packFiles(weights, count) {
const compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
const units = [...weights].sort(([a, wa], [b, wb]) => wb - wa || compare(a, b));
const bins = Array.from({ length: Math.min(count, units.length) }, () => ({ weight: 0, files: [] }));
for (const [file, weight] of units) {
const bin = bins.reduce((least, other) => (other.weight < least.weight
|| (other.weight === least.weight && other.files.length < least.files.length) ? other : least));
bin.weight += weight;
bin.files.push(file);
}
for (const bin of bins) {
bin.files.sort(compare);
}
return bins;
}
export const packFiles = (weights, count) => pack([...weights].map(([key, weight]) => ({ key, weight })), count)
.map((bin) => ({ weight: bin.weight, files: bin.units.map(({ key }) => key).sort(compare) }));

if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
const [command, ...args] = process.argv.slice(2);
Expand Down
125 changes: 121 additions & 4 deletions .github/scripts/mutation-reports.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,19 @@ import {
breaks,
collectShards,
escape,
estimateScope,
expandMutate,
inScope,
measureFiles,
measureSweep,
mergeReports,
mutantWeight,
packFiles,
parseScope,
planScope,
readFresh,
reportProblems,
scoreReport,
testCosts,
} from './mutation-reports.mjs';

const temp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'mutation-reports-'));
Expand Down Expand Up @@ -220,14 +224,35 @@ describe('packFiles', () => {
});
});

describe('measureFiles', () => {
describe('testCosts and mutantWeight', () => {
it('weighs a mutant by how much of the code its tests cover', () => {
const merged = report({
'a.ts': [mutant(1, 'Killed', { coveredBy: ['wide'], testsCompleted: 1 })],
'b.ts': [1, 2, 3, 4].map((line) => mutant(line, 'Killed', { coveredBy: ['wide', 'narrow'] })),
});
const costs = testCosts(merged);
assert.deepEqual([costs.get('wide'), costs.get('narrow')], [5 / 4.5, 4 / 4.5]);
assert.equal(mutantWeight(merged.files['a.ts'].mutants[0], costs), 1 + 5 / 4.5);
assert.equal(mutantWeight(merged.files['b.ts'].mutants[0], costs), 3);
});

it('counts each test of a static mutant as the average, and falls back to the test count', () => {
const costs = new Map([['wide', 4]]);
assert.equal(mutantWeight(mutant(1, 'Killed', { static: true, coveredBy: ['wide'], testsCompleted: 9 }),
costs), 10);
assert.equal(mutantWeight(mutant(1, 'Survived', { testsCompleted: 3 })), 4);
assert.equal(mutantWeight(mutant(1, 'NoCoverage')), 1);
});
});

describe('measureSweep', () => {
it("shares each shard's seconds out by the weight of its files' mutants", () => {
const merged = report({
'a.ts': [mutant(1, 'Killed', { testsCompleted: 2 })],
'b.ts': [mutant(1, 'Killed', { testsCompleted: 0 })],
'c.ts': [mutant(1, 'Killed')],
});
const files = measureFiles(merged, [
const { files } = measureSweep(merged, [
{ scope: parseScope('a.ts,b.ts'), seconds: 400 },
{ scope: parseScope('c.ts,types.ts'), seconds: 60 },
{ scope: parseScope('d.ts'), seconds: 0 },
Expand All @@ -240,10 +265,102 @@ describe('measureFiles', () => {
'a.ts': [mutant(1, 'Killed', { testsCompleted: 0 }), mutant(20, 'Killed', { testsCompleted: 98 })],
'b.ts': [mutant(1, 'Killed', { testsCompleted: 0 })],
});
const files = measureFiles(merged, [
const { files, lines } = measureSweep(merged, [
{ scope: parseScope('a.ts:1-1,b.ts'), seconds: 20 },
{ scope: parseScope('a.ts:2-30'), seconds: 30 },
]);
assert.deepEqual(files, { 'a.ts': 40, 'b.ts': 10 });
assert.deepEqual(lines, { 'a.ts': [[1, 1, 10], [20, 1, 30]], 'b.ts': [[1, 1, 10]] });
});

it('gives a file covered by a wide test more of the shard than one covered by many narrow tests', () => {
const narrow = Array.from({ length: 8 }, (_, index) => `n${index}`);
const merged = report({
'app.ts': [1, 2].map((line) => mutant(line, 'Killed', { coveredBy: ['app'], testsCompleted: 1 })),
'unit.ts': [1, 2].map((line) => mutant(line, 'Killed', { coveredBy: narrow, testsCompleted: 8 })),
'rest.ts': Array.from({ length: 40 }, (_, index) => mutant(index + 1, 'Killed', { coveredBy: ['app'] })),
});
const { files } = measureSweep(merged, [{ scope: parseScope('app.ts,unit.ts'), seconds: 100 }]);
assert.ok(files['app.ts'] > 2 * files['unit.ts']);
});

it('records nothing for a shard whose time is not a finite number', () => {
const merged = report({ 'a.ts': [mutant(1, 'Killed')] });
for (const seconds of [Infinity, Number.NaN, -5]) {
assert.deepEqual(measureSweep(merged, [{ scope: parseScope('a.ts'), seconds }]).files, { 'a.ts': 0 });
}
});
});

describe('estimateScope', () => {
const counts = { 'a.ts': 100, 'b.ts': 100, 'new.ts': 50 };
const lineCount = (file) => counts[file] ?? null;
const entry = (file, start, end) => (start
? { path: file, range: true, start, end, text: `${file}:${start}-${end}` }
: { path: file, range: false, start: 0, end: 0, text: file });
const history = {
version: 2,
files: { 'a.ts': 600, 'b.ts': 20, 'gone.ts': 999 },
lines: { 'a.ts': [[10, 3, 500], [80, 1, 100]], 'b.ts': [[10, 2, 20]] },
};

it('costs a measured file at what it took, and a range at what its lines took', () => {
assert.deepEqual(estimateScope([entry('a.ts'), entry('b.ts'), entry('a.ts', 5, 15)], history, lineCount),
[600, 20, 500]);
});

it("costs new lines at the file's average, and a file the sweep never saw at the sweep's", () => {
const [added, unseen] = estimateScope([entry('a.ts', 40, 59), entry('new.ts')], history, lineCount);
assert.equal(added, 20 * 6);
assert.equal(unseen, 50 * (620 / 200));
});

it('reads a history without lines by the file average', () => {
const [range] = estimateScope([entry('a.ts', 5, 15)], { version: 1, files: history.files }, lineCount);
assert.equal(range, 11 * 6);
});

it('returns null without a usable history, and skips malformed lines', () => {
for (const missing of [null, {}, { files: [] }, { files: { 'gone.ts': 5 } }, { files: { 'a.ts': 'x' } }]) {
assert.equal(estimateScope([entry('a.ts')], missing, lineCount), null);
}
assert.equal(estimateScope([entry('new.ts')], { files: { 'a.ts': 1e308, 'b.ts': 1e308 } }, lineCount), null);
assert.equal(estimateScope([entry('a.ts'), entry('b.ts')], { files: { 'a.ts': 1e308, 'b.ts': 1e308 } },
lineCount), null);
const odd = { files: { 'a.ts': 600 }, lines: { 'a.ts': [null, [10, 1, 'x'], [12, 1, 30]] } };
assert.deepEqual(estimateScope([entry('a.ts', 1, 20)], odd, lineCount), [120]);
});
});

describe('planScope', () => {
const entry = (file, lines, range) => (range
? { path: file, range: true, start: range[0], end: range[1], text: `${file}:${range[0]}-${range[1]}` }
: { path: file, range: false, start: 0, end: 0, text: file, lines });
const paths = (bins) => bins.map((bin) => bin.entries.map(({ text }) => text));

it('balances files of like size but unlike cost by cost', () => {
const entries = [entry('a.ts'), entry('b.ts'), entry('c.ts'), entry('d.ts')];
assert.deepEqual(paths(planScope(entries, [100, 100, 90, 90], 2)), [['a.ts', 'c.ts'], ['b.ts', 'd.ts']]);
const bins = planScope(entries, [6000, 300, 5800, 290], 2);
assert.deepEqual(paths(bins), [['a.ts', 'd.ts'], ['b.ts', 'c.ts']]);
assert.deepEqual(bins.map(({ weight }) => weight), [6290, 6100]);
});

it('splits a file heavier than its share across shards by range, and never cuts a range', () => {
const entries = [entry('big.ts', 0, [1, 10]), entry('big.ts', 0, [50, 60]), entry('small.ts')];
assert.deepEqual(paths(planScope(entries, [100, 90, 10], 2)), [['big.ts:1-10'], ['big.ts:50-60', 'small.ts']]);
assert.deepEqual(paths(planScope(entries, [1, 1, 100], 2)), [['small.ts'], ['big.ts:1-10', 'big.ts:50-60']]);
});

it('keeps overlapping ranges of a file on one shard, so no mutant runs twice', () => {
const entries = [entry('a.ts', 0, [1, 10]), entry('a.ts', 0, [5, 15])];
assert.deepEqual(paths(planScope(entries, [10, 11], 2)), [['a.ts:1-10', 'a.ts:5-15']]);
const touching = [entry('a.ts', 0, [1, 10]), entry('a.ts', 0, [10, 15])];
assert.deepEqual(paths(planScope(touching, [10, 11], 2)), [['a.ts:1-10', 'a.ts:10-15']]);
});

it('keeps zero-cost units spread and never plans more shards than units', () => {
const entries = [entry('a.ts'), entry('b.ts'), entry('c.ts')];
assert.deepEqual(paths(planScope(entries, [0, 0, 0], 6)), [['a.ts'], ['b.ts'], ['c.ts']]);
});
});
Loading
Loading