From d0f56d0a90cb11a08aed027f7b057f642df85790 Mon Sep 17 00:00:00 2001 From: Ben Carey Date: Sun, 11 Oct 2026 18:44:07 -0400 Subject: [PATCH 1/2] feat(mutation): balance the scoped shards by expected time The scoped plan split the changed files by line count, so shards with similar counts could take very different times when some files are covered only by slow, wide tests. Stryker's report records no test times, so the full sweep now shares each shard's measured time out per mutant by the tests it ran, each weighed by how many mutants it covers, and saves seconds per mutated line alongside seconds per file. The scoped plan restores those timings and estimates each file or range from them: a measured file at what it took, a range at the larger of its lines' time and the file's average per line, and a file the sweep never saw at the sweep's average per line. It packs the units longest first onto the least loaded shard, still splitting an expensive file by its ranges, and logs each shard's estimated minutes. Without timings, or with unreadable ones, it balances by line count as before. No caller changes are needed. --- .github/scripts/mutation-reports.mjs | 151 +++++++++++++++++---- .github/scripts/mutation-reports.test.mjs | 109 +++++++++++++++- .github/workflows/node-quality-gates.yml | 152 +++++++++++++--------- 3 files changed, 317 insertions(+), 95 deletions(-) diff --git a/.github/scripts/mutation-reports.mjs b/.github/scripts/mutation-reports.mjs index 8ba057d..6ee16e8 100644 --- a/.github/scripts/mutation-reports.mjs +++ b/.github/scripts/mutation-reports.mjs @@ -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()) => @@ -287,28 +289,138 @@ 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 = 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]); + } + } + 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) ? costs : null; +} + +// 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 files; + return bins; +} + +// Splits scope entries ({ path, text, range, start }) into at most `count` shards by their weights. A file +// heavier than a shard's fair share is split by its ranges; 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 && items.every(({ entry }) => entry.range) + ? 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 `!` @@ -345,21 +457,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); diff --git a/.github/scripts/mutation-reports.test.mjs b/.github/scripts/mutation-reports.test.mjs index 630d572..93d6c34 100644 --- a/.github/scripts/mutation-reports.test.mjs +++ b/.github/scripts/mutation-reports.test.mjs @@ -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-')); @@ -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 }, @@ -240,10 +265,86 @@ 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']); + }); +}); + +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); + 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 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']]); }); }); diff --git a/.github/workflows/node-quality-gates.yml b/.github/workflows/node-quality-gates.yml index 2a2a1ba..4230109 100644 --- a/.github/workflows/node-quality-gates.yml +++ b/.github/workflows/node-quality-gates.yml @@ -13,23 +13,27 @@ # `test:mutation` scripts for the jobs it runs. # # The scoped gate splits the changed files across up to `mutation-shards` -# runners, and each shard must meet the break threshold both in Stryker's -# figure and on its own scope. With Stryker's `incremental` option each -# shard's report is cached, and the reports are merged and restored only from -# the branch's own runs. Cached survivors and static non-kills always rerun, -# and so does a kill whose test file changed at all: Stryker only sees an edit -# that falls inside a test's own lines. Cached timeouts are left to Stryker's -# own reuse rules: it scores them as detected, and retesting one costs a full -# timeout. The key covers the tooling and the test helpers, fixtures, data -# files and snapshots. The scheduled sweep forces a full rerun. +# runners, balanced by the time the last sharded full sweep measured on those +# files and lines, or by line count until there is one. Each shard must meet +# the break threshold both in Stryker's figure and on its own scope. With +# Stryker's `incremental` option each shard's report is cached, and the +# reports are merged and restored only from the branch's own runs. Cached +# survivors and static non-kills always rerun, and so does a kill whose test +# file changed at all: Stryker only sees an edit that falls inside a test's +# own lines. Cached timeouts are left to Stryker's own reuse rules: it scores +# them as detected, and retesting one costs a full timeout. The key covers the +# tooling and the test helpers, fixtures, data files and snapshots. The +# scheduled sweep forces a full rerun. # # A full sweep too long for one job splits across `mutation-full-shards` -# runners by whole files, heaviest first by the last sweep's timings. Each -# shard defers the break threshold, and the `Mutation (full)` job merges the -# reports, fails on any missing, stale or unfinished one, and applies the -# threshold once to the merged score. With one shard the sweep runs as one -# job, as it always has. Report freshness, merging and scoring live in -# `.github/scripts`, which the jobs check out at this workflow's own commit. +# runners by whole files, heaviest first by the last sweep's timings. Within a +# shard, its time is shared out by the tests each mutant ran, each test +# weighed by how much of the code it covers. Each shard defers the break +# threshold, and the `Mutation (full)` job merges the reports, fails on any +# missing, stale or unfinished one, and applies the threshold once to the +# merged score. With one shard the sweep runs as one job, as it always has. +# Report freshness, merging and scoring live in `.github/scripts`, which the +# jobs check out at this workflow's own commit. # ============================================================================== name: Node Quality Gates @@ -183,20 +187,47 @@ jobs: - name: Install dependencies run: npm ci + - name: Checkout the report scripts + uses: actions/checkout@v7 + with: + repository: ${{ job.workflow_repository }} + ref: ${{ job.workflow_sha }} + path: .mutation-scripts + sparse-checkout: .github/scripts + persist-credentials: false + + # Out of the workspace, so neither the scope script nor the fingerprint sees them. + - name: Move the report scripts aside + run: | + mv .mutation-scripts/.github/scripts "$RUNNER_TEMP/mutation-scripts" + rm -rf .mutation-scripts + echo "MUTATION_REPORTS=$RUNNER_TEMP/mutation-scripts/mutation-reports.mjs" >> "$GITHUB_ENV" + + # The default branch's last sharded full sweep, which pull requests can read. + - name: Restore the sweep timings + uses: actions/cache/restore@v6 + with: + path: ${{ runner.temp }}/mutation-full-history.json + key: stryker-full-history-v1-${{ runner.os }}-${{ github.run_id }}-${{ github.run_attempt }} + restore-keys: | + stryker-full-history-v1-${{ runner.os }}- + - name: Plan the shards id: plan env: BASE_REF: ${{ github.base_ref || 'master' }} SHARDS: ${{ inputs.mutation-shards }} SCOPE_FILE: ${{ runner.temp }}/scope.txt + HISTORY: ${{ runner.temp }}/mutation-full-history.json run: | npm run -s mutation:scope -- --base "origin/${BASE_REF}" > "$SCOPE_FILE" - node - <<'JS' - // Splits the scope into balanced shards and fingerprints what the tests read. - const fs = require('node:fs'); - const crypto = require('node:crypto'); - const path = require('node:path'); - const { execFileSync } = require('node:child_process'); + node --input-type=module - <<'JS' + // Splits the scope into shards balanced by expected time and fingerprints what the tests read. + import fs from 'node:fs'; + import crypto from 'node:crypto'; + import path from 'node:path'; + import { execFileSync } from 'node:child_process'; + const { escape, estimateScope, normalise, planScope } = await import(process.env.MUTATION_REPORTS); const fail = (message) => { console.log(`::error::${message}`); @@ -234,15 +265,13 @@ jobs: fail(`mutation-shards must be an integer from 1 to 256, got '${process.env.SHARDS}'.`); } - const lineCount = (file) => { + const lines = (file) => { try { return fs.readFileSync(file, 'utf8').split('\n').length; } catch { - return 1; + return null; } }; - const normalise = (file) => - path.relative(process.cwd(), path.resolve(file)).split(path.sep).join('/'); let tracked; // Extended globs count too: @(a|b), +(a), !(a), ?(a), *(a) and a|b inside parentheses. const isGlob = (pattern) => /[*?[\]{}]|[@+!]\(|\([^)]*\|/.test(pattern) && !fs.existsSync(pattern); @@ -295,63 +324,56 @@ jobs: if (file.includes(',')) { fail(`Scope entry '${text}' matches '${file}', whose comma --mutate cannot carry.`); } - const weight = range ? end - start + 1 : lineCount(file); + const weight = range ? end - start + 1 : lines(file) ?? 1; const entry = range ? `${file}:${range[2]}` : file; - scoped.set(entry, { path: file, start, text: entry, weight, range: Boolean(range) }); + scoped.set(entry, { path: file, start, end, text: entry, weight, range: Boolean(range) }); } } - const byPath = new Map(); - for (const entry of scoped.values()) { - byPath.set(entry.path, [...(byPath.get(entry.path) ?? []), entry]); - } - - if (byPath.size === 0) { + if (scoped.size === 0) { console.log('No mutable source files changed.'); output('empty', 'true'); output('matrix', JSON.stringify({ include: [] })); process.exit(0); } - const compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0); - const weigh = (entries) => entries.reduce((sum, entry) => sum + entry.weight, 0); - const files = [...byPath.keys()].sort(compare).map((file) => byPath.get(file)); - const total = files.reduce((sum, entries) => sum + weigh(entries), 0); - - // A dominating file with several ranges is split by range; a range is never cut. - const units = files.flatMap((entries) => - weigh(entries) > total / shards && entries.length > 1 && entries.every((entry) => entry.range) - ? entries.map((entry) => ({ key: entry.text, weight: entry.weight, entries: [entry] })) - : [{ key: entries[0].path, weight: weigh(entries), entries }]); - units.sort((a, b) => b.weight - a.weight || compare(a.key, b.key)); - - const count = Math.min(shards, units.length); - const bins = Array.from({ length: count }, () => ({ weight: 0, entries: [] })); - for (const unit of units) { - const bin = bins.reduce((least, other) => (other.weight < least.weight ? other : least)); - bin.weight += unit.weight; - bin.entries.push(...unit.entries); + // Without a sharded full sweep to go by, the scope is balanced by line count, as before. + const entries = [...scoped.values()]; + let history = null; + try { + history = JSON.parse(fs.readFileSync(process.env.HISTORY, 'utf8')); + } catch {} + let costs = null; + try { + costs = estimateScope(entries, history, lines); + } catch (error) { + console.log(`::warning::Could not estimate the shards' cost (${error.message}).`); } + const bins = planScope(entries, costs ?? entries.map(({ weight }) => weight), shards); // Every entry is a real path now, but Stryker matches --mutate entries with minimatch after // turning backslashes into slashes, so each magic character becomes a one-character class. // A leading ! would read as an exclusion, so such a path starts with ./ instead. - const escape = (file) => file.replace(/^!/, './!').replace(/[?*()[\]{}]/g, '[$&]'); - const include = bins.map((bin, index) => { - bin.entries.sort((a, b) => compare(a.path, b.path) || a.start - b.start); - const mutate = bin.entries - .map((entry) => escape(entry.path) + entry.text.slice(entry.path.length)) - .join(','); - return { shard: index + 1, mutate }; - }); + const include = bins.map((bin, index) => ({ + shard: index + 1, + mutate: bin.entries.map((entry) => escape(entry.path) + entry.text.slice(entry.path.length)) + .join(','), + })); output('empty', 'false'); output('matrix', JSON.stringify({ include })); + const basis = costs + ? 'Balanced by the last full sweep\'s timings.' + : 'No full sweep timings to go by, so balanced by line count.'; const rows = bins.map((bin, index) => { const entries = bin.entries.map((entry) => `\`${entry.text}\``).join(' '); - return `| ${index + 1} | ${bin.weight} | ${entries} |`; + const estimate = costs ? (bin.weight / 60).toFixed(1) : bin.weight; + return `| ${index + 1} | ${estimate} | ${entries} |`; }); - const summary = ['| Shard | Weight | Entries |', '| --- | --- | --- |', ...rows].join('\n'); - fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, `### Mutation shards\n\n${summary}\n`); + const heading = `| Shard | ${costs ? 'Estimated minutes' : 'Lines'} | Entries |`; + const summary = [heading, '| --- | --- | --- |', ...rows].join('\n'); + fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, + `### Mutation shards\n\n${basis}\n\n${summary}\n`); + console.log(basis); console.log(summary); JS @@ -1337,7 +1359,7 @@ jobs: fs.writeFileSync('build/mutation/mutation.html', lib.renderHtml(report)); output('merged', 'true'); - const timings = lib.measureFiles(report, rows.map(({ shard, record }) => ({ + const timings = lib.measureSweep(report, rows.map(({ shard, record }) => ({ scope: scopes.get(shard), seconds: record.outcome === 'empty' ? 0 @@ -1346,11 +1368,11 @@ jobs: for (const { shard, record } of rows) { if (record.outcome === 'empty') { scopes.get(shard).forEach((_, file) => { - timings[file] = 0; + timings.files[file] = 0; }); } } - fs.writeFileSync(process.env.HISTORY, JSON.stringify({ version: 1, files: timings })); + fs.writeFileSync(process.env.HISTORY, JSON.stringify({ version: 2, ...timings })); output('history', 'true'); const { score, detected, timedOut, undetected, counted } = await lib.scoreReport(report); From c0172e4ba2101c5a506ebf33868d71f3266eb771 Mon Sep 17 00:00:00 2001 From: Ben Carey Date: Sun, 11 Oct 2026 18:49:38 -0400 Subject: [PATCH 2/2] fix(mutation): drop non-finite timings and keep overlapping ranges together --- .github/scripts/mutation-reports.mjs | 15 ++++++++++----- .github/scripts/mutation-reports.test.mjs | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/.github/scripts/mutation-reports.mjs b/.github/scripts/mutation-reports.mjs index 6ee16e8..d062f08 100644 --- a/.github/scripts/mutation-reports.mjs +++ b/.github/scripts/mutation-reports.mjs @@ -321,7 +321,7 @@ export function measureSweep(report, shards) { const files = {}; const lines = {}; for (const { scope, seconds } of shards) { - const time = seconds > 0 ? seconds : 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 ?? []) { @@ -385,9 +385,13 @@ export function estimateScope(entries, history, lineCount) { } return Math.max(recorded(file, start, end), size * (files[file] / count)); }); - return costs.every(Number.isFinite) ? costs : null; + 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)); @@ -401,8 +405,9 @@ export function pack(units, count) { return bins; } -// Splits scope entries ({ path, text, range, start }) into at most `count` shards by their weights. A file -// heavier than a shard's fair share is split by its ranges; a range is never cut. +// 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) => { @@ -412,7 +417,7 @@ export function planScope(entries, weights, count) { 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 && items.every(({ entry }) => entry.range) + 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) }]; }); diff --git a/.github/scripts/mutation-reports.test.mjs b/.github/scripts/mutation-reports.test.mjs index 93d6c34..0efb330 100644 --- a/.github/scripts/mutation-reports.test.mjs +++ b/.github/scripts/mutation-reports.test.mjs @@ -283,6 +283,13 @@ describe('measureSweep', () => { 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', () => { @@ -318,6 +325,8 @@ describe('estimateScope', () => { 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]); }); @@ -343,6 +352,13 @@ describe('planScope', () => { 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']]);