oxmutate 2.5.0 → 2.6.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/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { defineCommand, defineProgram, ExitCode } from 'burgee';
4
- import { loadOptions } from './config.js';
4
+ import { DEFAULT_IDLE_TIMEOUT_MS, loadOptions } from './config.js';
5
5
  import { InstrumentFault, run } from './coordinator.js';
6
6
  import { frozenOracle } from './frozen.js';
7
7
  import { parseShard } from './lanes.js';
@@ -56,8 +56,15 @@ function staticOverridesFrom(o) {
56
56
  overrides.staticReaders = 'on';
57
57
  return overrides;
58
58
  }
59
+ function workerOverridesFrom(o) {
60
+ const warm = o['coldWorkers'] !== true;
61
+ const idle = typeof o['workerIdleTimeout'] === 'number' && o['workerIdleTimeout'] >= 0 ? Math.floor(o['workerIdleTimeout']) : undefined;
62
+ if (warm && idle === undefined)
63
+ return {};
64
+ return { workers: { warm, idleTimeoutMs: idle ?? DEFAULT_IDLE_TIMEOUT_MS } };
65
+ }
59
66
  function overridesFrom(o, root) {
60
- const overrides = { ...staticOverridesFrom(o) };
67
+ const overrides = { ...staticOverridesFrom(o), ...workerOverridesFrom(o) };
61
68
  if (typeof o['since'] === 'string')
62
69
  overrides.since = o['since'];
63
70
  if (typeof o['frozenOracle'] === 'string')
@@ -104,6 +111,8 @@ const runCommand = defineCommand({
104
111
  ignoreStatic: { type: 'boolean', description: 'skip static mutants (module-level code): faster, and the score leaves them out' },
105
112
  staticGroup: { type: 'number', description: 'arm this many static mutants together in a file that is not their first (default 1; a heuristic, audited)' },
106
113
  staticBudget: { type: 'number', description: 'the most the static phase may take, ms; static mutants still undecided then are left out of the score' },
114
+ coldWorkers: { type: 'boolean', description: 'a fresh Vitest server per unit, closed after it: slower, the least memory held' },
115
+ workerIdleTimeout: { type: 'number', description: 'close a server idle this long, ms (default 30000; 0 keeps them all until the run ends)' },
107
116
  staticReaders: { type: 'boolean', description: 'run each static mutant only in the test files that read its value (a heuristic, audited)' },
108
117
  reportStaticReaders: { type: 'boolean', description: 'one more dry run that reports how many tests static mutants would need if each ran only where its value is read; changes no verdict' },
109
118
  incremental: { type: 'boolean', description: 'reuse verdicts whose source and covering tests did not change' },
package/dist/config.d.ts CHANGED
@@ -6,6 +6,8 @@ export interface Thresholds {
6
6
  /** Fail the run (exit 1) below this score. `null`: never fail on score. */
7
7
  break: number | null;
8
8
  }
9
+ /** By default a server idle this long is closed: past a phase's tail, short of a phase's gaps. */
10
+ export declare const DEFAULT_IDLE_TIMEOUT_MS = 30000;
9
11
  /** Why a static mutant is Ignored when `static.budgetMs` ran out before it was decided; the summary counts them by it. */
10
12
  export declare const STATIC_BUDGET_REASON = "static mutant (static budget spent)";
11
13
  /** Why a static mutant is Ignored under `ignoreStatic`; the summary counts them by it. */
@@ -15,6 +17,16 @@ export interface Options {
15
17
  mutate: string[];
16
18
  vitestConfig?: string | undefined;
17
19
  concurrency: number;
20
+ /**
21
+ * How long Vitest servers live. `resources.warmWorkers: true` (default) keeps each one's Vitest
22
+ * between units; `false` starts one per unit and closes it after: slower, the least memory held.
23
+ * `resources.workerIdleTimeout` (ms, default 30,000): a server with no unit for this long is
24
+ * closed, and a new one starts if work comes later; 0 keeps every server until the run ends.
25
+ */
26
+ workers: {
27
+ warm: boolean;
28
+ idleTimeoutMs: number;
29
+ };
18
30
  timeoutMS: number;
19
31
  timeoutFactor: number;
20
32
  thresholds: Thresholds;
package/dist/config.js CHANGED
@@ -3,6 +3,12 @@ import { availableParallelism } from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import { resolveEsm } from './resolve.js';
6
+ export const DEFAULT_IDLE_TIMEOUT_MS = 30_000;
7
+ function workersOf(resources) {
8
+ const r = (typeof resources === 'object' && resources !== null ? resources : {});
9
+ const ms = Math.floor(Number(r.workerIdleTimeout ?? DEFAULT_IDLE_TIMEOUT_MS));
10
+ return { warm: r.warmWorkers !== false, idleTimeoutMs: ms >= 0 ? ms : DEFAULT_IDLE_TIMEOUT_MS };
11
+ }
6
12
  function staticGroupOf(group) {
7
13
  const asked = Math.floor(Number(group));
8
14
  return asked >= 2 ? asked : 1;
@@ -46,7 +52,7 @@ const DEFAULT_TIMEOUT_FACTOR = 1.5;
46
52
  const DEFAULT_THRESHOLD_HIGH = 80;
47
53
  const DEFAULT_THRESHOLD_LOW = 60;
48
54
  const DEFAULT_DRY_RUN_MINUTES = 5;
49
- const USED = new Set(['mutate', 'vitest', 'concurrency', 'timeoutMS', 'timeoutFactor', 'thresholds', 'ignoreStatic', 'static', 'reporters', 'jsonReporter', 'htmlReporter', 'incremental', 'incrementalFile', '$schema', 'mutator', 'dryRunOnly', 'dryRunTimeoutMinutes', 'buildCommand', 'testRunnerNodeArgs', 'allowEmpty', 'warnings', 'testRunner', 'commandRunner', 'checkers', 'tsconfigFile']);
55
+ const USED = new Set(['mutate', 'vitest', 'concurrency', 'resources', 'timeoutMS', 'timeoutFactor', 'thresholds', 'ignoreStatic', 'static', 'reporters', 'jsonReporter', 'htmlReporter', 'incremental', 'incrementalFile', '$schema', 'mutator', 'dryRunOnly', 'dryRunTimeoutMinutes', 'buildCommand', 'testRunnerNodeArgs', 'allowEmpty', 'warnings', 'testRunner', 'commandRunner', 'checkers', 'tsconfigFile']);
50
56
  async function loadFile(file) {
51
57
  if (file.endsWith('.json')) {
52
58
  return JSON.parse(readFileSync(file, 'utf8'));
@@ -107,6 +113,7 @@ export async function loadOptions(root, overrides = {}, configFile) {
107
113
  mutate,
108
114
  vitestConfig: vitest.configFile ? path.resolve(root, vitest.configFile) : undefined,
109
115
  concurrency: Number(raw['concurrency'] ?? Math.max(1, Math.min(MAX_DEFAULT_CONCURRENCY, availableParallelism() - 1))),
116
+ workers: workersOf(raw['resources']),
110
117
  timeoutMS: Number(raw['timeoutMS'] ?? DEFAULT_TIMEOUT_MS),
111
118
  timeoutFactor: Number(raw['timeoutFactor'] ?? DEFAULT_TIMEOUT_FACTOR),
112
119
  thresholds: { high: thresholds.high ?? DEFAULT_THRESHOLD_HIGH, low: thresholds.low ?? DEFAULT_THRESHOLD_LOW, break: thresholds.break ?? null },
@@ -104,6 +104,8 @@ export interface RunStats {
104
104
  flakyMutants: number;
105
105
  units: number;
106
106
  serversSpawned: number;
107
+ /** Servers closed for sitting idle past `resources.workerIdleTimeout`: memory given back before the run ended. */
108
+ serversReleased: number;
107
109
  /** Mutants whose Timeout their worker called itself, the wait able to end by nothing (quiescence.ts): no watchdog wait, no respawn. */
108
110
  deadlocks: number;
109
111
  }
@@ -98,7 +98,7 @@ export async function run(options) {
98
98
  const work = mkdtempSync(path.join(tmpdir(), 'oxmutate-'));
99
99
  const stats = {
100
100
  files: 0, mutants: 0, instrumentMs: 0, dryRunMs: 0, mutationMs: 0, staticMs: 0, staticRecollections: 0, staticGroupRuns: 0, staticGroupSplits: 0, staticAuditSampled: 0, staticAuditDisagreed: 0, isolatedMs: 0, wallMs: 0, testExecutions: 0, warmUnitMs: 0, warmArmedMs: 0, isolatedByCause: { static: 0, stopped: 0, unfinished: 0, rerun: 0, confirm: 0, flaky: 0 },
101
- watchdogKills: 0, idleStalls: 0, deadlocks: 0, crashes: 0, canaryFiles: 0, pollutionRestarts: 0, diskWrites: 0, diskWritePaths: [], auditSampled: 0, auditDisagreed: 0, survivorsOverturned: 0, timeoutsOverturned: 0, compileErrors: 0, isolatedRuns: 0, reused: 0, flakyTests: 0, flakyMutants: 0, units: 0, serversSpawned: 0,
101
+ watchdogKills: 0, idleStalls: 0, deadlocks: 0, crashes: 0, canaryFiles: 0, pollutionRestarts: 0, diskWrites: 0, diskWritePaths: [], auditSampled: 0, auditDisagreed: 0, survivorsOverturned: 0, timeoutsOverturned: 0, compileErrors: 0, isolatedRuns: 0, reused: 0, flakyTests: 0, flakyMutants: 0, units: 0, serversSpawned: 0, serversReleased: 0,
102
102
  };
103
103
  let unitSeq = 0;
104
104
  const fileFor = (kind, ext) => path.join(work, `${kind}-${String(unitSeq++)}.${ext}`);
@@ -188,7 +188,7 @@ export async function run(options) {
188
188
  traceDirs[oracle.name] = await tracesFor(oracle, root, work);
189
189
  if (options.specOracles.length)
190
190
  env[SPEC_TRACES_ENV] = JSON.stringify(traceDirs);
191
- const dryPool = createPool({ root, vitestConfig: options.vitestConfig, workers: options.concurrency, instrumentedMap: mapFile, nodeArgs: options.testRunnerNodeArgs }, 1, work, 'dry');
191
+ const dryPool = createPool({ root, vitestConfig: options.vitestConfig, workers: options.concurrency, instrumentedMap: mapFile, nodeArgs: options.testRunnerNodeArgs }, 1, { workDir: work, tag: 'dry', lifecycle: options.workers });
192
192
  pools.push(dryPool);
193
193
  const dryRun = async (trackReads = false) => {
194
194
  const unit = { mode: 'dry', files: [], results: fileFor('dry', 'jsonl'), progress: fileFor('dry', 'progress'), ...(trackReads && { trackReads: true }) };
@@ -449,7 +449,7 @@ export async function run(options) {
449
449
  };
450
450
  const runaways = new Set();
451
451
  const crashedIds = new Set();
452
- const pool = createPool({ root, vitestConfig: options.vitestConfig, workers: 1, instrumentedMap: mapFile, nodeArgs: options.testRunnerNodeArgs, inlineDeps: true }, options.concurrency, work, 'mutant');
452
+ const pool = createPool({ root, vitestConfig: options.vitestConfig, workers: 1, instrumentedMap: mapFile, nodeArgs: options.testRunnerNodeArgs, inlineDeps: true }, options.concurrency, { workDir: work, tag: 'mutant', lifecycle: options.workers });
453
453
  pools.push(pool);
454
454
  const killedSoFar = (spec) => new Set([...runaways, ...crashedIds, ...records.filter((r) => r.type === 'mutant' && r.status !== 'Survived' && Boolean(r.spec) === spec).map((r) => r.id ?? '')]);
455
455
  const afterUnit = async (unit, outcome) => {
@@ -904,6 +904,7 @@ export async function run(options) {
904
904
  return summarizeSpec({ oracle, modelledFiles: new Set(matchFiles(root, oracle.files)), traces, mutants: located, testName: (t) => testInfo.get(t)?.name ?? t, specMs: ms });
905
905
  });
906
906
  stats.serversSpawned = pools.reduce((s, p) => s + p.stats.spawned, 0);
907
+ stats.serversReleased = pools.reduce((s, p) => s + p.stats.released, 0);
907
908
  stats.wallMs = performance.now() - wall0;
908
909
  return {
909
910
  root,
@@ -126,7 +126,7 @@ export function takeFloor() {
126
126
  export function confirmStep(o) {
127
127
  if (!o.quiet)
128
128
  return { quietSince: undefined };
129
- const since = o.quietSince ?? o.now - o.span;
129
+ const since = o.quietSince ?? Math.max(o.now - o.span, o.start ?? -Infinity);
130
130
  const open = o.now - since;
131
131
  return open >= o.confirmMs ? { quietSince: since, deadlockMs: open } : { quietSince: since };
132
132
  }
@@ -156,7 +156,7 @@ export function watch() {
156
156
  };
157
157
  if (env['OXMUTATE_DEBUG_QUIET'])
158
158
  stderr.write(`quiet? ${JSON.stringify(reading)} res=${JSON.stringify([...resources()])} floor=${JSON.stringify([...floor])}\n`);
159
- const next = confirmStep({ quietSince, quiet: quiet(reading), now, span, confirmMs: armed.confirmMs });
159
+ const next = confirmStep({ quietSince, quiet: quiet(reading), now, span, confirmMs: armed.confirmMs, start: armed.start });
160
160
  quietSince = next.quietSince;
161
161
  if (next.deadlockMs !== undefined) {
162
162
  const { reject } = armed;
@@ -172,7 +172,7 @@ export function watch() {
172
172
  return pending;
173
173
  const deadlock = new Promise((_, reject) => {
174
174
  quietSince = undefined;
175
- armed = { reject, confirmMs: Math.max(MIN_CONFIRM_MS, confirmMs) };
175
+ armed = { reject, confirmMs: Math.max(MIN_CONFIRM_MS, confirmMs), start: realNow() };
176
176
  });
177
177
  try {
178
178
  return await Promise.race([pending, deadlock]);
package/dist/reports.js CHANGED
@@ -140,6 +140,8 @@ function whereItWent(r) {
140
140
  if (s.warmUnitMs > 0)
141
141
  lines.push(` warm servers ran ${(s.warmUnitMs / MS_PER_S).toFixed(1)} s, ${(s.warmArmedMs / MS_PER_S).toFixed(1)} s of it inside test runs`);
142
142
  lines.push(...staticLine(r));
143
+ if (s.serversReleased > 0)
144
+ lines.push(` servers: ${String(s.serversSpawned)} started, ${String(s.serversReleased)} closed for sitting idle (resources.workerIdleTimeout)`);
143
145
  const sr = s.staticReaders;
144
146
  if (sr && sr.mutants > 0) {
145
147
  const ratio = sr.readerTests > 0 ? `, ${(sr.loaderTests / sr.readerTests).toFixed(1)}x fewer` : '';
package/dist/scheduler.js CHANGED
@@ -107,16 +107,40 @@ class Server {
107
107
  setTimeout(() => this.child.kill('SIGKILL'), CLOSE_GRACE_MS).unref();
108
108
  }
109
109
  }
110
- export function createPool(config, size, workDir, tag) {
110
+ const IDLE_CHECK_MS = 1000;
111
+ export function createPool(config, size, place) {
112
+ const { workDir, tag } = place;
113
+ const lifecycle = place.lifecycle ?? { warm: true, idleTimeoutMs: 0 };
111
114
  const configFile = path.join(workDir, `server-${tag}.json`);
112
115
  writeFileSync(configFile, JSON.stringify(config));
113
- const stats = { spawned: 0, killed: 0, idle: 0, crashed: 0 };
116
+ const stats = { spawned: 0, killed: 0, idle: 0, crashed: 0, released: 0 };
114
117
  const spawn = () => {
115
118
  stats.spawned++;
116
119
  return new Server(configFile, config.root, config.nodeArgs ?? [], workDir);
117
120
  };
118
- const servers = Array.from({ length: size }, spawn);
119
- let spare = spawn();
121
+ const servers = Array.from({ length: size }, () => (lifecycle.warm ? spawn() : undefined));
122
+ let spare = lifecycle.warm ? spawn() : undefined;
123
+ const idleSince = servers.map(() => performance.now());
124
+ let spareSince = performance.now();
125
+ const sweep = lifecycle.idleTimeoutMs > 0
126
+ ? setInterval(() => {
127
+ const now = performance.now();
128
+ for (const [slot, server] of servers.entries()) {
129
+ const since = idleSince[slot];
130
+ if (server && since !== undefined && now - since >= lifecycle.idleTimeoutMs) {
131
+ server.close();
132
+ servers.fill(undefined, slot, slot + 1);
133
+ stats.released++;
134
+ }
135
+ }
136
+ if (spare && now - spareSince >= lifecycle.idleTimeoutMs) {
137
+ spare.close();
138
+ spare = undefined;
139
+ stats.released++;
140
+ }
141
+ }, IDLE_CHECK_MS)
142
+ : undefined;
143
+ sweep?.unref();
120
144
  const tally = (outcome) => {
121
145
  if (outcome.killedFor)
122
146
  stats.killed++;
@@ -127,9 +151,31 @@ export function createPool(config, size, workDir, tag) {
127
151
  };
128
152
  const replacement = () => {
129
153
  const next = spare ?? spawn();
130
- spare = spawn();
154
+ spare = lifecycle.warm ? spawn() : undefined;
155
+ spareSince = performance.now();
131
156
  return next;
132
157
  };
158
+ const serverFor = async (slot) => {
159
+ idleSince.fill(undefined, slot, slot + 1);
160
+ let server = servers[slot] ?? spawn();
161
+ if (!(await server.ready)) {
162
+ server = replacement();
163
+ await server.ready;
164
+ }
165
+ servers.fill(server, slot, slot + 1);
166
+ return server;
167
+ };
168
+ const settle = (slot, server, outcome) => {
169
+ const lost = Boolean(outcome.killedFor ?? outcome.crashed);
170
+ if (!lifecycle.warm) {
171
+ if (!lost)
172
+ server.close();
173
+ servers.fill(undefined, slot, slot + 1);
174
+ }
175
+ else if (lost)
176
+ servers.fill(replacement(), slot, slot + 1);
177
+ idleSince.fill(performance.now(), slot, slot + 1);
178
+ };
133
179
  return {
134
180
  stats,
135
181
  async drain(units, budget, after, prepare) {
@@ -158,17 +204,10 @@ export function createPool(config, size, workDir, tag) {
158
204
  continue;
159
205
  }
160
206
  busy++;
161
- let server = servers[slot];
162
- if (!(await server.ready)) {
163
- server = replacement();
164
- servers[slot] = server;
165
- await server.ready;
166
- }
207
+ const server = await serverFor(slot);
167
208
  const outcome = await server.run(unit, (id) => budget(unit, id));
168
209
  tally(outcome);
169
- if (outcome.killedFor || outcome.crashed) {
170
- servers[slot] = replacement();
171
- }
210
+ settle(slot, server, outcome);
172
211
  const more = await after(unit, outcome);
173
212
  queue.unshift(...more);
174
213
  busy--;
@@ -177,8 +216,10 @@ export function createPool(config, size, workDir, tag) {
177
216
  }));
178
217
  },
179
218
  close() {
219
+ if (sweep)
220
+ clearInterval(sweep);
180
221
  for (const s of servers)
181
- s.close();
222
+ s?.close();
182
223
  spare?.close();
183
224
  spare = undefined;
184
225
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oxmutate",
3
- "version": "2.5.0",
3
+ "version": "2.6.0",
4
4
  "description": "Mutation testing for JavaScript and TypeScript on the oxc engine, run warm inside the project's own Vitest, with CI lanes, SARIF and an agent surface. No dependency outside the burgee family. A Stryker migration path.",
5
5
  "license": "MIT",
6
6
  "author": "Ofri Peretz <ofriperetzdev@gmail.com>",