Skip to main content

fallow_api/runtime/
mutation_replay.rs

1//! [`replay_mutation`]: one export of a source file, called with one input
2//! on the original and on one mutant, through the replay request of the
3//! runner companion (replay contract 1).
4
5use std::path::Path;
6use std::time::{Duration, Instant};
7
8use fallow_engine::mutation::{
9    MutationError, MutationOptions, Operator, SourceKind, export_containing,
10};
11use fallow_output::{
12    MutationReplayCall, MutationReplayInput, MutationReplayInputSource, MutationReplayOutput,
13    MutationReplayVerdict,
14};
15
16use super::mutation::{
17    DEFAULT_RUNNER_TIMEOUT, Planned, ProgrammaticResult, guard_cache_dir, init_options, millis,
18    mutation_error, plan_for, runtime_error,
19};
20use crate::mutation::companion::{COMPANION_FILES, install};
21use crate::mutation::discovery::discover_runtime;
22use crate::mutation::ignore_cache_dir;
23use crate::mutation::manifest::manifest;
24use crate::mutation::protocol::{
25    InitRequest, LinkFault, ReplayRequest, ReplayResult, Request, Response,
26};
27use crate::mutation::recorded_args;
28use crate::mutation::replay::{check_calls, output_outcome, output_side, verdict};
29use crate::mutation::run_dir::{RunFile, write_run_dir};
30use crate::mutation::runner_version::runner_version_help;
31use crate::mutation::transport::{CompanionLink, CompanionSpawner, ProcessSpawner, SpawnFailure};
32use crate::mutation::{
33    MutationReplayOptions, MutationRunOptions, MutationRunScope, RecordArgsMode,
34};
35
36/// The most recorded inputs that one replay runs.
37const MAX_RECORDED_INPUTS: usize = 3;
38/// The calls of each side. Three calls show a value that changes from one
39/// call to the next, for example from a clock that the replay does not fix.
40const CALLS_PER_SIDE: u32 = 3;
41/// The default time limit of one call.
42const DEFAULT_CALL_TIMEOUT: Duration = Duration::from_secs(5);
43/// The longest time limit of one call. The companion refuses a longer one.
44const MAX_CALL_TIMEOUT: Duration = Duration::from_mins(10);
45/// The fixed `Date.now()` of each call: 2026-01-01T00:00:00Z.
46const REPLAY_CLOCK_MS: i64 = 1_767_225_600_000;
47/// The seed of `Math.random` in each call.
48const REPLAY_SEED: i64 = 1;
49/// The time of the worker start, the setup files and the module load of one
50/// replay call, on top of its call timeout.
51const REPLAY_CALL_MARGIN: Duration = Duration::from_secs(20);
52/// The time of the replay request outside the calls. The wall limit of the
53/// whole request is the sum, so a call that blocks its worker cannot stop
54/// the command.
55const REPLAY_REQUEST_MARGIN: Duration = Duration::from_secs(30);
56
57/// The wall limit of one replay request: each call with its margin, and the
58/// margin of the request.
59fn wall_limit(call_timeout: Duration) -> Duration {
60    (call_timeout + REPLAY_CALL_MARGIN) * (2 * CALLS_PER_SIDE) + REPLAY_REQUEST_MARGIN
61}
62
63/// The facts of the mutant that the replay needs.
64struct Target {
65    instrumented: String,
66    export: Result<String, String>,
67}
68
69fn replay_error(message: impl Into<String>) -> crate::ProgrammaticError {
70    mutation_error("FALLOW_MUTATION_REPLAY_FAILED", message).with_context("mutation.replay")
71}
72
73/// The instrumentation options that can give the mutant, in order: its own
74/// operator, then each operator, each over the whole file and then over the
75/// span of the mutant only. A mutant id can depend on the other mutants of
76/// the file: a run of another scope can give the same id to another mutant
77/// with the same text, so the span selects the mutant.
78fn instrument_passes(operator: Option<Operator>, span: (u32, u32)) -> Vec<MutationOptions> {
79    let mut sets = Vec::new();
80    if let Some(operator) = operator {
81        sets.push(vec![operator]);
82    }
83    sets.push(Operator::ALL.to_vec());
84    sets.into_iter()
85        .flat_map(|operators| {
86            [None, Some(vec![span])].map(|ranges| MutationOptions {
87                operators: operators.clone(),
88                ranges,
89                record_exports: false,
90                ..MutationOptions::default()
91            })
92        })
93        .collect()
94}
95
96/// The export of the function of `mutant`, or the reason why none fits.
97fn export_of(
98    source: &str,
99    kind: SourceKind,
100    options: &MutationReplayOptions,
101    function: Option<&fallow_engine::mutation::FunctionRef>,
102) -> Result<String, String> {
103    match (&options.export, function) {
104        (Some(export), _) => Ok(export.clone()),
105        (None, Some(function)) => export_containing(source, kind, function.span).ok_or_else(|| {
106            format!(
107                "no callable export holds the function {}; pass --export to call an export of the file that runs it",
108                function
109                    .name
110                    .as_deref()
111                    .map_or_else(|| "of the mutant".to_owned(), |name| format!("`{name}`"))
112            )
113        }),
114        (None, None) => Err(
115            "the mutant is in top-level code; pass --export to call an export of the file that reads it"
116                .to_owned(),
117        ),
118    }
119}
120
121/// Instruments `source` until a pass gives `mutant_id` at its span, and
122/// finds the export to call.
123fn find_target(
124    source: &str,
125    options: &MutationReplayOptions,
126) -> ProgrammaticResult<Option<Target>> {
127    let file = options.file.as_str();
128    let Some(kind) = SourceKind::from_path(file) else {
129        return Ok(None);
130    };
131    for request in instrument_passes(options.operator, options.span) {
132        let instrumented = match fallow_engine::mutation::instrument_source(source, file, &request)
133        {
134            Some(Ok(instrumented)) => instrumented,
135            Some(Err(MutationError::Parse { messages })) => {
136                return Err(replay_error(format!(
137                    "`{file}` does not parse: {}",
138                    messages.join("; ")
139                )));
140            }
141            Some(Err(error)) => {
142                return Err(replay_error(format!(
143                    "cannot instrument `{file}`: {error:?}"
144                )));
145            }
146            None => return Ok(None),
147        };
148        let Some(mutant) = instrumented
149            .mutants
150            .iter()
151            .find(|mutant| mutant.id.as_str() == options.mutant_id && mutant.span == options.span)
152        else {
153            continue;
154        };
155        let export = export_of(source, kind, options, mutant.enclosing_function.as_ref());
156        return Ok(Some(Target {
157            instrumented: instrumented.code,
158            export,
159        }));
160    }
161    Err(mutation_error(
162        "FALLOW_MUTATION_UNKNOWN_MUTANT",
163        format!(
164            "the current `{file}` gives no mutant `{}` at bytes {}..{}",
165            options.mutant_id, options.span.0, options.span.1
166        ),
167    )
168    .with_context("mutation.mutantId")
169    .with_help(
170        "a mutant id changes when its source changes; run `fallow mutation` again for new ids",
171    ))
172}
173
174/// An output with no call, for a replay that did not run or did not end.
175fn without_calls(
176    input: &MutationReplayInput,
177    export: Option<String>,
178    verdict: MutationReplayVerdict,
179    reason: String,
180    call_timeout: Duration,
181) -> ProgrammaticResult<MutationReplayOutput> {
182    let manifest = manifest()
183        .map_err(|message| mutation_error("FALLOW_MUTATION_PROTOCOL_INVALID", message))?;
184    Ok(MutationReplayOutput {
185        contract_version: manifest.replay.contract_version,
186        verdict,
187        reason: Some(reason),
188        export,
189        input: input.clone(),
190        inputs_checked: 0,
191        calls_per_side: CALLS_PER_SIDE,
192        call_timeout_ms: millis(call_timeout),
193        clock_ms: REPLAY_CLOCK_MS,
194        seed: REPLAY_SEED,
195        calls: Vec::new(),
196        duration_ms: 0,
197    })
198}
199
200/// Sends `init` and checks the runner version and the replay capability.
201fn start(
202    link: &mut Box<dyn CompanionLink>,
203    init: InitRequest,
204    runner_name: &str,
205    timeout: Duration,
206) -> ProgrammaticResult<()> {
207    let manifest = manifest()
208        .map_err(|message| mutation_error("FALLOW_MUTATION_PROTOCOL_INVALID", message))?;
209    let range = manifest.runner(runner_name).ok_or_else(|| {
210        mutation_error(
211            "FALLOW_MUTATION_PROTOCOL_INVALID",
212            format!("the protocol manifest has no `{runner_name}` runner"),
213        )
214    })?;
215    let ready = match link.request(&Request::Init(init), timeout) {
216        Ok(Response::Ready(ready)) => ready,
217        Ok(_) => return Err(replay_error("the companion answered init with no ready")),
218        Err(fault) => return Err(link_error("init", &fault)),
219    };
220    if !range.contains(&ready.runner_version) {
221        return Err(mutation_error(
222            "FALLOW_MUTATION_RUNNER_UNSUPPORTED",
223            format!(
224                "{} {} is not supported; the supported range is >={} <{}",
225                range.package, ready.runner_version, range.min_version, range.max_version_exclusive
226            ),
227        )
228        .with_help(runner_version_help(range)));
229    }
230    if !ready.capabilities.replay {
231        return Err(mutation_error(
232            "FALLOW_MUTATION_REPLAY_UNSUPPORTED",
233            format!("the {runner_name} runner has no replay"),
234        )
235        .with_context("mutation.replay")
236        .with_help("replay supports the Vitest and node:test runners"));
237    }
238    Ok(())
239}
240
241fn link_error(stage: &str, fault: &LinkFault) -> crate::ProgrammaticError {
242    let error = replay_error(format!("the replay companion failed at {stage}: {fault}"));
243    match fault.stderr_tail() {
244        Some(tail) => error.with_help(format!("companion stderr:\n{}", tail.trim_end())),
245        None => error,
246    }
247}
248
249/// The source of the file of the mutant, without a byte order mark.
250fn read_source(root: &Path, file: &str) -> ProgrammaticResult<String> {
251    let bytes = std::fs::read(root.join(file))
252        .map_err(|error| replay_error(format!("cannot read `{file}`: {error}")))?;
253    let text = String::from_utf8(bytes)
254        .map_err(|_| replay_error(format!("`{file}` is not UTF-8 text")))?;
255    Ok(text
256        .strip_prefix('\u{feff}')
257        .map_or_else(|| text.clone(), str::to_owned))
258}
259
260/// Writes the run directory with the instrumented file, starts the
261/// companion, and sends `init`.
262fn start_companion(
263    planned: &Planned,
264    options: &MutationReplayOptions,
265    instrumented: &str,
266) -> ProgrammaticResult<Box<dyn CompanionLink>> {
267    let manifest = manifest()
268        .map_err(|message| mutation_error("FALLOW_MUTATION_PROTOCOL_INVALID", message))?;
269    let runner = planned.runner;
270    let runtime = discover_runtime(options.runtime.as_deref(), runner.runtimes())
271        .map_err(|message| runtime_error(runner, message))?;
272    let cache_error =
273        |message: String| mutation_error("FALLOW_MUTATION_CACHE_WRITE_FAILED", message);
274    ignore_cache_dir(&planned.cache_dir).map_err(|error| cache_error(error.to_string()))?;
275    let mutation_cache = planned.cache_dir.join("mutation");
276    let companion = install(&mutation_cache, COMPANION_FILES)
277        .map_err(|message| mutation_error("FALLOW_MUTATION_COMPANION_INTEGRITY", message))?;
278    let files = [RunFile {
279        path: &options.file,
280        code: instrumented,
281    }];
282    let run_dir = write_run_dir(&mutation_cache, &files, Some(&companion)).map_err(cache_error)?;
283    let root = planned.resolved.root().to_path_buf();
284    let init = InitRequest {
285        root: root.to_string_lossy().into_owned(),
286        runner: runner.name().to_owned(),
287        config_path: planned.runner_config.clone(),
288        run_dir: run_dir.dir.to_string_lossy().into_owned(),
289        path_map: run_dir.path_map,
290        options: init_options(
291            runner,
292            &root,
293            &planned.plan.test_files,
294            &planned.runner_projects,
295        ),
296    };
297    let spawner = ProcessSpawner {
298        runtime: runtime.path,
299        companion,
300        root,
301        wire_version: manifest.wire_protocol_version,
302        session_token_env: manifest.session_token_env.clone(),
303    };
304    let mut link = spawner.spawn().map_err(|failure| match failure {
305        SpawnFailure::Integrity(message) => {
306            mutation_error("FALLOW_MUTATION_COMPANION_INTEGRITY", message)
307        }
308        SpawnFailure::Fault(fault) => link_error("start", &fault),
309    })?;
310    let runner_timeout = options.runner_timeout.unwrap_or(DEFAULT_RUNNER_TIMEOUT);
311    if let Err(error) = start(&mut link, init, runner.name(), runner_timeout) {
312        link.shutdown();
313        return Err(error);
314    }
315    Ok(link)
316}
317
318/// The reason of a verdict that needs one.
319fn verdict_reason(verdict: MutationReplayVerdict, export: &str) -> Option<String> {
320    match verdict {
321        MutationReplayVerdict::NotCallable => Some(format!("the export `{export}` is not a function")),
322        MutationReplayVerdict::Timeout => {
323            Some("a call did not end before the call timeout".to_owned())
324        }
325        MutationReplayVerdict::Unstable => Some(
326            "the calls of one side gave different results; a value that the replay does not fix (for example crypto random values or the network) can cause this".to_owned(),
327        ),
328        _ => None,
329    }
330}
331
332/// The output of a replay result that keeps the contract.
333fn completed(
334    input: &MutationReplayInput,
335    export: String,
336    result: ReplayResult,
337    call_timeout: Duration,
338) -> ProgrammaticResult<MutationReplayOutput> {
339    check_calls(&result.calls, CALLS_PER_SIDE).map_err(replay_error)?;
340    let verdict = verdict(&result.calls);
341    let mut output = without_calls(input, Some(export), verdict, String::new(), call_timeout)?;
342    output.reason = verdict_reason(verdict, output.export.as_deref().unwrap_or_default());
343    output.duration_ms = result.duration_ms;
344    output.calls = result
345        .calls
346        .into_iter()
347        .map(|call| MutationReplayCall {
348            side: output_side(call.side),
349            index: call.index,
350            outcome: output_outcome(call.outcome),
351            value: call.value,
352            text: call.text,
353        })
354        .collect();
355    Ok(output)
356}
357
358/// Calls one export of a source file with one input on the original and on
359/// one mutant, three times each, in turns, and gives the verdict. It runs
360/// project code: the module of the file and each module that it imports.
361///
362/// Each call runs in its own worker with a fresh module instance, a clock
363/// that starts at a fixed time and a fixed seed of `Math.random`. The whole
364/// request has a wall limit. The
365/// verdict is never `equivalent`: equal results give `no_witness_found`.
366///
367/// # Errors
368///
369/// Returns an error when the file does not give the mutant, the runtime or
370/// the runner is missing, the runner has no replay, or the companion fails.
371pub fn replay_mutation(
372    options: &MutationReplayOptions,
373) -> ProgrammaticResult<MutationReplayOutput> {
374    let call_timeout = options.call_timeout.unwrap_or(DEFAULT_CALL_TIMEOUT);
375    if call_timeout > MAX_CALL_TIMEOUT || call_timeout < Duration::from_millis(1) {
376        return Err(mutation_error(
377            "FALLOW_INVALID_MUTATION_OPTIONS",
378            "the replay call timeout must be from 1ms to 10m",
379        )
380        .with_context("mutation.replay.callTimeout"));
381    }
382    let run_options = MutationRunOptions {
383        analysis: options.analysis.clone(),
384        scope: MutationRunScope::Paths(vec![options.file.clone().into()]),
385        runtime: options.runtime.clone(),
386        runner_config: options.runner_config.clone(),
387        runner_projects: options.runner_projects.clone(),
388        allow_dirty: true,
389        ..MutationRunOptions::default()
390    };
391    let planned = plan_for(&run_options, guard_cache_dir)?;
392    let source = read_source(planned.resolved.root(), &options.file)?;
393    let unknown = MutationReplayInput {
394        source: if options.args.is_some() {
395            MutationReplayInputSource::Argument
396        } else {
397            MutationReplayInputSource::Recorded
398        },
399        input_id: None,
400        args: options.args.clone().unwrap_or_default(),
401    };
402    let not_replayable = |export: Option<String>, reason: String| {
403        without_calls(
404            &unknown,
405            export,
406            MutationReplayVerdict::NotReplayable,
407            reason,
408            call_timeout,
409        )
410    };
411    let Some(target) = find_target(&source, options)? else {
412        return not_replayable(
413            None,
414            "a component file has no module exports to call".to_owned(),
415        );
416    };
417    let export = match target.export {
418        Ok(export) => export,
419        Err(reason) => return not_replayable(None, reason),
420    };
421    let inputs = match input_list(&planned.cache_dir, options, &export) {
422        Ok(inputs) => inputs,
423        Err(reason) => return not_replayable(Some(export), reason),
424    };
425    let mut link = start_companion(&planned, options, &target.instrumented)?;
426    let replay_target = ReplayTarget {
427        file: &options.file,
428        mutant_id: &options.mutant_id,
429        export: &export,
430    };
431    let output = replay_inputs(&mut link, &replay_target, &inputs, call_timeout, None);
432    link.shutdown();
433    output
434}
435
436/// Replays `inputs` on an open companion, up to the first input that ends
437/// the search or the deadline, and gives the result with `inputs_checked`
438/// and the rule 3 reason of "no witness found".
439pub(super) fn replay_inputs(
440    link: &mut Box<dyn CompanionLink>,
441    target: &ReplayTarget<'_>,
442    inputs: &[MutationReplayInput],
443    call_timeout: Duration,
444    deadline: Option<Instant>,
445) -> ProgrammaticResult<MutationReplayOutput> {
446    let mut outputs = Vec::new();
447    for input in inputs {
448        // The first input always runs, so the result is never empty.
449        if !outputs.is_empty() && deadline.is_some_and(|deadline| Instant::now() >= deadline) {
450            break;
451        }
452        let output = replay_one(link, target, input, call_timeout)?;
453        let stop = ends_search(output.verdict);
454        outputs.push(output);
455        if stop {
456            break;
457        }
458    }
459    let checked = u32::try_from(outputs.len()).unwrap_or(u32::MAX);
460    let mut output = pick_output(outputs).ok_or_else(|| replay_error("the replay has no input"))?;
461    output.inputs_checked = checked;
462    if output.verdict == MutationReplayVerdict::NoWitnessFound {
463        output.reason = Some(no_witness_reason(&output));
464    }
465    Ok(output)
466}
467
468/// True when the replay of the next input cannot change the result: a
469/// witness, a call that hangs (the companion is gone), or an export that is
470/// no function. An unstable input says nothing about the next input.
471const fn ends_search(verdict: MutationReplayVerdict) -> bool {
472    matches!(
473        verdict,
474        MutationReplayVerdict::Witness
475            | MutationReplayVerdict::Timeout
476            | MutationReplayVerdict::NotCallable
477    )
478}
479
480/// The output of a replay of several inputs: the last one, unless it shows
481/// no witness and an earlier input was unstable. An unstable input is then
482/// the result, because it can hide a difference.
483fn pick_output(outputs: Vec<MutationReplayOutput>) -> Option<MutationReplayOutput> {
484    let unstable = outputs
485        .iter()
486        .position(|output| output.verdict == MutationReplayVerdict::Unstable);
487    let last_is_plain = outputs
488        .last()
489        .is_some_and(|output| output.verdict == MutationReplayVerdict::NoWitnessFound);
490    match (unstable, last_is_plain) {
491        (Some(index), true) => outputs.into_iter().nth(index),
492        _ => outputs.into_iter().last(),
493    }
494}
495
496/// The wording of rule 3: the inputs, where they come from, and the calls.
497fn no_witness_reason(output: &MutationReplayOutput) -> String {
498    let inputs = output.inputs_checked;
499    let noun = if inputs == 1 { "input" } else { "inputs" };
500    let source = match output.input.source {
501        MutationReplayInputSource::Argument => "--args",
502        MutationReplayInputSource::Recorded => "recorded",
503    };
504    format!(
505        "no witness found ({inputs} {noun}, {source}, {} calls of each side)",
506        output.calls_per_side
507    )
508}
509
510/// The inputs of the replay: the `--args` value, or the first recorded
511/// inputs of the export. The error is the reason why none can run.
512fn input_list(
513    cache_dir: &Path,
514    options: &MutationReplayOptions,
515    export: &str,
516) -> Result<Vec<MutationReplayInput>, String> {
517    if let Some(args) = &options.args {
518        return Ok(vec![MutationReplayInput {
519            source: MutationReplayInputSource::Argument,
520            input_id: None,
521            args: args.clone(),
522        }]);
523    }
524    recorded_inputs(cache_dir, &options.file, export)
525}
526
527/// Up to [`MAX_RECORDED_INPUTS`] recorded inputs of `file#export` with their
528/// values. The error is the reason why none can run.
529pub(super) fn recorded_inputs(
530    cache_dir: &Path,
531    file: &str,
532    export: &str,
533) -> Result<Vec<MutationReplayInput>, String> {
534    let key = format!("{file}#{export}");
535    let hint = "run `fallow mutation --record-args values` for this code, or pass --args";
536    let Some(stored) = recorded_args::load(cache_dir, &key, recorded_args::now_secs()) else {
537        return Err(format!(
538            "no recorded input of `{export}` in the last 7 days; {hint}"
539        ));
540    };
541    if stored.mode != RecordArgsMode::Values {
542        return Err(format!(
543            "the recording of `{export}` keeps argument types only; {hint}"
544        ));
545    }
546    let inputs: Vec<MutationReplayInput> = stored
547        .inputs
548        .into_iter()
549        .filter_map(|input| {
550            Some(MutationReplayInput {
551                source: MutationReplayInputSource::Recorded,
552                input_id: Some(input.input_id),
553                args: input.args?,
554            })
555        })
556        .take(MAX_RECORDED_INPUTS)
557        .collect();
558    if inputs.is_empty() {
559        let reasons: Vec<String> = stored
560            .not_replayable
561            .iter()
562            .map(|refusal| format!("{} ({})", refusal.reason, refusal.count))
563            .collect();
564        let detail = if reasons.is_empty() {
565            "no call of the dry run reached it".to_owned()
566        } else {
567            format!("the calls were not replayable: {}", reasons.join(", "))
568        };
569        return Err(format!(
570            "no recorded input of `{export}` can run: {detail}; {hint}"
571        ));
572    }
573    Ok(inputs)
574}
575
576/// The mutant and the export of one replay.
577pub(super) struct ReplayTarget<'a> {
578    pub file: &'a str,
579    pub mutant_id: &'a str,
580    pub export: &'a str,
581}
582
583/// Replays one input on an open companion. A wall-limit timeout gives the
584/// verdict `timeout`, and the companion is then gone.
585fn replay_one(
586    link: &mut Box<dyn CompanionLink>,
587    target: &ReplayTarget<'_>,
588    input: &MutationReplayInput,
589    call_timeout: Duration,
590) -> ProgrammaticResult<MutationReplayOutput> {
591    let export = target.export;
592    let request = ReplayRequest {
593        file: target.file.to_owned(),
594        export: export.to_owned(),
595        mutant_id: target.mutant_id.to_owned(),
596        args: input.args.clone(),
597        calls: CALLS_PER_SIDE,
598        call_timeout_ms: millis(call_timeout),
599        clock_ms: REPLAY_CLOCK_MS,
600        seed: REPLAY_SEED,
601    };
602    let wall_limit = wall_limit(call_timeout);
603    let started = Instant::now();
604    match link.request(&Request::Replay(request), wall_limit) {
605        Ok(Response::Replay(result)) => completed(input, export.to_owned(), result, call_timeout),
606        Ok(_) => Err(replay_error(
607            "the companion answered replay with another response",
608        )),
609        Err(LinkFault::Timeout) => {
610            let mut output = without_calls(
611                input,
612                Some(export.to_owned()),
613                MutationReplayVerdict::Timeout,
614                format!(
615                    "the replay did not end in its wall limit of {}s; the module load, the original or the mutant can block the worker, and a longer --call-timeout gives more time",
616                    wall_limit.as_secs()
617                ),
618                call_timeout,
619            )?;
620            output.duration_ms = millis(started.elapsed());
621            Ok(output)
622        }
623        Err(fault) => Err(link_error("replay", &fault)),
624    }
625}
626
627#[cfg(test)]
628#[expect(clippy::expect_used, reason = "tests expect to keep the setup short")]
629mod tests {
630    use super::*;
631
632    const TWINS: &str =
633        "export const first = (a, b) => a + b;\nexport const second = (a, b) => a + b;\n";
634
635    fn span_of_nth(source: &str, needle: &str, nth: usize) -> (u32, u32) {
636        let start = source.match_indices(needle).nth(nth).expect("needle").0;
637        let start = u32::try_from(start).expect("small");
638        (start, start + u32::try_from(needle.len()).expect("small"))
639    }
640
641    /// The id that a run scoped to `span` gives the mutant of that span.
642    fn scoped_id(span: (u32, u32)) -> String {
643        let options = MutationOptions {
644            operators: Operator::ALL.to_vec(),
645            ranges: Some(vec![span]),
646            record_exports: false,
647            ..MutationOptions::default()
648        };
649        let instrumented = fallow_engine::mutation::instrument_source(TWINS, "src/a.js", &options)
650            .expect("layout")
651            .expect("instrumented");
652        instrumented
653            .mutants
654            .iter()
655            .find(|mutant| mutant.span == span)
656            .expect("the scoped mutant")
657            .id
658            .to_string()
659    }
660
661    #[test]
662    fn a_mutant_id_that_a_twin_shares_replays_the_mutant_at_its_own_span() {
663        let second = span_of_nth(TWINS, "a + b", 1);
664        let options = MutationReplayOptions {
665            file: "src/a.js".to_owned(),
666            mutant_id: scoped_id(second),
667            span: second,
668            ..MutationReplayOptions::default()
669        };
670        let target = find_target(TWINS, &options)
671            .expect("no error")
672            .expect("a target");
673        assert_eq!(target.export.as_deref(), Ok("second"));
674        assert!(target.instrumented.contains(&options.mutant_id));
675    }
676
677    #[test]
678    fn the_wall_limit_leaves_room_for_the_per_call_limits_of_the_companion() {
679        // The Vitest adapter gives each call its call timeout and 10 seconds
680        // as the test timeout, and node:test gives it 5 seconds more. Each
681        // call also starts a worker before its test timeout runs.
682        const COMPANION_CALL_MARGIN: Duration = Duration::from_secs(10);
683        for call_timeout in [
684            Duration::from_millis(1),
685            DEFAULT_CALL_TIMEOUT,
686            MAX_CALL_TIMEOUT,
687        ] {
688            let calls = (call_timeout + COMPANION_CALL_MARGIN) * (2 * CALLS_PER_SIDE);
689            assert!(wall_limit(call_timeout) >= calls + Duration::from_secs(60));
690        }
691    }
692
693    fn output(verdict: MutationReplayVerdict, id: &str) -> MutationReplayOutput {
694        let input = MutationReplayInput {
695            source: MutationReplayInputSource::Recorded,
696            input_id: Some(id.to_owned()),
697            args: Vec::new(),
698        };
699        without_calls(
700            &input,
701            Some("f".to_owned()),
702            verdict,
703            String::new(),
704            DEFAULT_CALL_TIMEOUT,
705        )
706        .expect("output")
707    }
708
709    #[test]
710    fn an_unstable_input_does_not_end_the_search_and_stays_the_result_without_a_witness() {
711        use MutationReplayVerdict::{NoWitnessFound, Unstable, Witness};
712        assert!(!ends_search(Unstable));
713        assert!(!ends_search(NoWitnessFound));
714        assert!(ends_search(Witness));
715        let picked = pick_output(vec![output(Unstable, "a"), output(Witness, "b")]).expect("one");
716        assert_eq!(picked.verdict, Witness);
717        let picked =
718            pick_output(vec![output(Unstable, "a"), output(NoWitnessFound, "b")]).expect("one");
719        assert_eq!(picked.verdict, Unstable);
720        assert_eq!(picked.input.input_id.as_deref(), Some("a"));
721    }
722
723    #[test]
724    fn an_id_at_another_span_is_an_unknown_mutant() {
725        let second = span_of_nth(TWINS, "a + b", 1);
726        let options = MutationReplayOptions {
727            file: "src/a.js".to_owned(),
728            mutant_id: scoped_id(second),
729            span: (0, 1),
730            ..MutationReplayOptions::default()
731        };
732        let error = find_target(TWINS, &options).err().expect("an error");
733        assert_eq!(
734            error.code.as_deref(),
735            Some("FALLOW_MUTATION_UNKNOWN_MUTANT")
736        );
737    }
738}