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