ktstr/cli/stats_cmds/
dispatch.rs

1//! `stats` subcommand dispatch: thin wrappers over the
2//! [`crate::stats`] surface plus host-context render entry points.
3//!
4//! Holds [`last_run_report`], [`list_runs`], [`list_metrics`],
5//! [`list_values`], [`compare_partitions`], [`show_host`],
6//! [`show_run_host`], [`show_thresholds`] and the per-test /
7//! per-run-key fuzzy-match helpers
8//! ([`suggest_closest_test_name`], [`suggest_closest_run_key`]).
9
10use std::path::Path;
11
12use anyhow::{Result, anyhow, bail};
13
14use crate::stats::{ComparisonPolicy, RowFilter};
15
16/// Read sidecar JSON files and return the gauntlet analysis report
17/// for `cargo ktstr stats last-run`.
18///
19/// Source directory, in precedence order:
20/// 1. `dir` (the `--dir` flag) when `Some` — analyzed verbatim,
21///    mirroring [`crate::test_support::analyze_sidecars`]`(Some(dir))`.
22/// 2. `KTSTR_SIDECAR_DIR` when set non-empty — the same env override
23///    `analyze_sidecars(None)` honors.
24/// 3. `kernel` (the `--kernel` flag) when `Some` — the most recently
25///    modified run dir whose leaf name begins `{kernel}-` (see
26///    `newest_run_dir_for_kernel`).
27/// 4. Otherwise the most recently modified run dir under the cargo
28///    target directory's `ktstr/` ([`crate::test_support::newest_run_dir`]).
29///
30/// `cargo ktstr stats` doesn't itself run a kernel, so it can't
31/// reconstruct the `{kernel}-{project_commit}` key the test process
32/// used; the mtime fallback (and the `--kernel` prefix match) stand in
33/// for "show me the report from my last test run."
34///
35/// Returns `None` with a warning on stderr when no sidecars are found.
36/// This is not an error -- regular test runs that skip gauntlet tests
37/// produce no sidecar files.
38pub fn last_run_report(dir: Option<&Path>, kernel: Option<&str>) -> Option<String> {
39    let resolved: Option<std::path::PathBuf> = if let Some(d) = dir {
40        Some(d.to_path_buf())
41    } else if let Ok(d) = std::env::var(crate::KTSTR_SIDECAR_DIR_ENV)
42        && !d.is_empty()
43    {
44        Some(std::path::PathBuf::from(d))
45    } else if let Some(k) = kernel {
46        newest_run_dir_for_kernel(k)
47    } else {
48        crate::test_support::newest_run_dir()
49    };
50    let report = resolved
51        .as_deref()
52        .map(|d| crate::test_support::analyze_sidecars(Some(d)))
53        .filter(|r| !r.is_empty());
54    if report.is_none() {
55        crate::ktstr_status!("cargo ktstr: no sidecar data found (skipped)");
56    }
57    report
58}
59
60/// The most recently modified run dir under the runs root whose leaf
61/// name begins `{kernel}-`.
62///
63/// A run dir is keyed `{kernel}-{project_commit}`; matching on the
64/// `{kernel}-` prefix picks the newest run for that kernel without the
65/// stats process (which runs no kernel) having to reconstruct the
66/// project-commit half. `{kernel}` here is the run dir's detected
67/// version component (e.g. `7.1.3`), NOT the raw `--kernel` spec
68/// `cargo ktstr test` accepts (a path / cache key resolves to a
69/// different label). Filters through
70/// [`crate::test_support::is_run_directory`] so the `.locks/` sentinel
71/// can't be selected. Returns `None` when no run dir matches.
72fn newest_run_dir_for_kernel(kernel: &str) -> Option<std::path::PathBuf> {
73    let root = crate::test_support::runs_root();
74    let prefix = format!("{kernel}-");
75    std::fs::read_dir(&root)
76        .ok()?
77        .flatten()
78        .filter(crate::test_support::is_run_directory)
79        .filter(|e| {
80            e.file_name()
81                .to_str()
82                .is_some_and(|n| n.starts_with(&prefix))
83        })
84        .max_by_key(|e| e.metadata().and_then(|m| m.modified()).ok())
85        .map(|e| e.path())
86}
87
88/// List test runs under the cargo target directory's `ktstr/` (see
89/// [`crate::test_support::runs_root`]).
90pub fn list_runs() -> Result<()> {
91    crate::stats::list_runs()
92}
93
94/// Render the metric registry for `cargo ktstr stats list-metrics`.
95///
96/// Thin wrapper over `crate::stats::list_metrics` — exposed through
97/// `cli::` to match the `list_runs` / `compare_partitions` / `show_host`
98/// convention where every stats-subcommand dispatch arm lands on a
99/// `cli::*` helper before reaching the private `stats` module. The
100/// returned `String` is printed verbatim by the dispatch site.
101pub fn list_metrics(json: bool) -> Result<String> {
102    crate::stats::list_metrics(json)
103}
104
105/// Render the distinct-value catalogue for the sidecar pool, for
106/// `cargo ktstr stats list-values`.
107///
108/// Thin wrapper over `crate::stats::list_values` — exposed
109/// through `cli::` for the same surface-stability reason as
110/// [`list_metrics`]. The returned `String` is printed verbatim by
111/// the dispatch site.
112pub fn list_values(json: bool, dir: Option<&Path>) -> Result<String> {
113    crate::stats::list_values(json, dir)
114}
115
116/// Compare two filter-defined partitions of the sidecar pool and
117/// report regressions across slicing dimensions. See
118/// `crate::stats::compare_partitions` for the full contract.
119pub fn compare_partitions(
120    filter_a: &RowFilter,
121    filter_b: &RowFilter,
122    filter: Option<&str>,
123    policy: &ComparisonPolicy,
124    dir: Option<&Path>,
125    gate: &crate::stats::GateOptions,
126) -> Result<i32> {
127    crate::stats::compare_partitions(filter_a, filter_b, filter, policy, dir, gate)
128}
129
130/// Noise-adjusted variant of [`compare_partitions`]: keeps every per-run row and
131/// gates a confident regression on the two sides being SEPARATED (a two-sided
132/// Welch t-test, or fully disjoint `[min, max]` bands) AND the mean delta being
133/// MATERIAL (the registry `default_abs` + `default_rel` dual-gate), instead of a
134/// fixed single-run threshold. When the scenarios carry phases it also renders a
135/// per-phase spread + coverage block (render-only, honoring `phase_opts`;
136/// per-phase never affects the exit). See
137/// `crate::stats::compare_partitions_noise` for the full contract.
138pub fn compare_partitions_noise(
139    filter_a: &RowFilter,
140    filter_b: &RowFilter,
141    dir: Option<&Path>,
142    spread_threshold_pct: f64,
143    phase_opts: &crate::stats::PhaseDisplayOptions,
144    gate: &crate::stats::GateOptions,
145) -> Result<i32> {
146    crate::stats::compare_partitions_noise(
147        filter_a,
148        filter_b,
149        dir,
150        spread_threshold_pct,
151        phase_opts,
152        gate,
153    )
154}
155
156/// Collect the current host context via
157/// [`crate::host_context::collect_host_context`] and render it as
158/// a human-readable multi-line report via
159/// [`crate::host_context::HostContext::format_human`]. The output
160/// ends with a newline; callers print it verbatim.
161pub fn show_host() -> String {
162    crate::host_context::collect_host_context().format_human()
163}
164
165/// Return the run-directory leaf name under `root` whose Levenshtein
166/// edit distance from `query` is smallest AND within the closeness
167/// threshold, or `None` if no candidate is close enough (or if
168/// `root` cannot be enumerated).
169///
170/// Threshold is `max(3, query.len() / 3)` — same shape as
171/// [`suggest_closest_test_name`] so the "did you mean?" UX stays
172/// uniform across the test-name and run-key surfaces. The absolute-3 floor lets
173/// short keys (e.g. `6.14`) tolerate small typos while the
174/// proportional `len/3` lets longer keys (e.g.
175/// `6.14-abcdef1-dirty`) tolerate roughly one bit-flip per 3
176/// chars.
177///
178/// Ties resolve to the FIRST name encountered in `read_dir`
179/// iteration order — non-deterministic across filesystems but
180/// consistent within a single invocation. The returned `String`
181/// owns the leaf name (heap allocation per match) because
182/// `read_dir` yields `OsString` filenames that the suggestion
183/// outlives.
184///
185/// `read_dir` failure (root doesn't exist, permission denied)
186/// silently degrades to `None` — the caller's primary diagnostic
187/// is "run not found"; the "did you mean?" hint is best-effort
188/// gravy and must not gate the bail path.
189///
190/// Filters via [`crate::test_support::is_run_directory`] so the
191/// flock sentinel subdirectory (`.locks/`) and any other
192/// dotfile-prefixed entry under `runs_root` cannot surface as
193/// a "did you mean?" suggestion — the same predicate that
194/// `newest_run_dir` and `sorted_run_entries` use, so all three
195/// run-listing surfaces agree on what counts as a run dir.
196pub(super) fn suggest_closest_run_key(query: &str, root: &Path) -> Option<String> {
197    let threshold = std::cmp::max(3, query.len() / 3);
198    let entries = std::fs::read_dir(root).ok()?;
199    let mut best: Option<(usize, String)> = None;
200    for entry in entries.flatten() {
201        if !crate::test_support::is_run_directory(&entry) {
202            continue;
203        }
204        let name = match entry.file_name().to_str() {
205            Some(s) => s.to_string(),
206            None => continue,
207        };
208        let d = strsim::levenshtein(query, &name);
209        if d > threshold {
210            continue;
211        }
212        match best {
213            Some((best_d, _)) if best_d <= d => continue,
214            _ => best = Some((d, name)),
215        }
216    }
217    best.map(|(_, name)| name)
218}
219
220/// Render the archived host context for the named run, resolved
221/// against `dir` (or `test_support::runs_root()` when `dir` is
222/// `None`). Loads sidecars under the run directory and returns the
223/// `HostContext::format_human` of the first sidecar that has a
224/// populated `host` field — every sidecar in a single run captures
225/// the same host, so first-wins is adequate.
226///
227/// Returns `Err` when:
228/// - The run directory does not exist (actionable message names
229///   the expected root),
230/// - The run directory exists but has no sidecar data (matches
231///   the `compare_partitions` error shape),
232/// - Every sidecar carried `host: None` (older pre-enrichment
233///   runs won't have the field).
234pub fn show_run_host(run: &str, dir: Option<&Path>) -> Result<String> {
235    let root: std::path::PathBuf = match dir {
236        Some(d) => d.to_path_buf(),
237        None => crate::test_support::runs_root(),
238    };
239    let run_dir = root.join(run);
240    if !run_dir.exists() {
241        let suggestion = suggest_closest_run_key(run, &root)
242            .map(|name| format!(" Did you mean `{name}`?"))
243            .unwrap_or_default();
244        bail!(
245            "run '{run}' not found under {}.{suggestion} \
246             Run `cargo ktstr stats list` to enumerate available run keys.",
247            root.display(),
248        );
249    }
250    let sidecars = crate::test_support::collect_sidecars(&run_dir);
251    if sidecars.is_empty() {
252        bail!("run '{run}' has no sidecar data");
253    }
254    // First sidecar with a populated host wins. Every sidecar in a
255    // single run captures the same host; pre-enrichment sidecars
256    // may have `host: None`. Scan forward rather than take the
257    // first entry so older data doesn't force a "no host context"
258    // error when newer sidecars in the same run DO have it.
259    let host = sidecars
260        .iter()
261        .find_map(|sc| sc.host.as_ref())
262        .ok_or_else(|| {
263            anyhow!(
264                "run '{run}' has {} sidecar(s) but none carries a populated \
265                 host context; this usually means the run predates host-context \
266                 enrichment. Re-run the test to produce a sidecar with the \
267                 current schema.",
268                sidecars.len(),
269            )
270        })?;
271    Ok(host.format_human())
272}
273
274/// Return the registered test name whose Levenshtein edit distance
275/// from `query` is smallest AND within the closeness threshold, or
276/// `None` if no candidate is close enough.
277pub(super) fn suggest_closest_test_name(query: &str) -> Option<&'static str> {
278    let threshold = std::cmp::max(3, query.len() / 3);
279    let mut best: Option<(usize, &'static str)> = None;
280    for entry in crate::test_support::KTSTR_TESTS.iter() {
281        let d = strsim::levenshtein(query, entry.name);
282        if d > threshold {
283            continue;
284        }
285        match best {
286            Some((best_d, _)) if best_d <= d => continue,
287            _ => best = Some((d, entry.name)),
288        }
289    }
290    best.map(|(_, name)| name)
291}
292
293/// Render the resolved, merged `Assert` thresholds for the named
294/// test — the same merge chain evaluated at run time in
295/// `run_ktstr_test_inner`:
296/// `Assert::default_checks().merge(&entry.scheduler.assert).merge(&entry.assert)`.
297///
298/// Returns `Err` when no registered test matches `test_name`. The
299/// CLI wiring (`cargo ktstr show-thresholds <test>`) surfaces this
300/// to the operator without requiring them to read the source, the
301/// nextest `--list` output, or the Debug impl of `Assert`.
302pub fn show_thresholds(test_name: &str) -> Result<String> {
303    let entry = crate::test_support::find_test(test_name).ok_or_else(|| {
304        let suggestion = suggest_closest_test_name(test_name)
305            .map(|s| format!(" Did you mean `{s}`?"))
306            .unwrap_or_default();
307        anyhow!(
308            "no registered ktstr test named '{test_name}'.{suggestion} \
309             Run `cargo nextest list` to see the available test names \
310             — then pass just the function-name component to \
311             `show-thresholds`, not the `<binary>::` prefix that \
312             nextest prepends to each line."
313        )
314    })?;
315    let merged = crate::assert::Assert::default_checks()
316        .merge(&entry.scheduler.assert)
317        .merge(&entry.assert);
318    let mut out = format!("Test: {}\n", entry.name);
319    out.push_str(&format!("Scheduler: {}\n", entry.scheduler.name,));
320    out.push_str("Resolved assertion thresholds:\n");
321    out.push_str(&merged.format_human());
322    Ok(out)
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328
329    /// `last_run_report(Some(dir), _)` analyzes the explicit directory
330    /// verbatim (mirroring `analyze_sidecars(Some(dir))`) and returns
331    /// the gauntlet-analysis blob — the same output bare `cargo ktstr
332    /// stats` used to auto-print, now gated behind `stats last-run`.
333    /// A one valid sidecar renders the `=== GAUNTLET ANALYSIS ===`
334    /// header; the `--dir` arm bypasses env / newest-run resolution.
335    #[test]
336    fn last_run_report_explicit_dir_renders_blob() {
337        let tmp = tempfile::tempdir().unwrap();
338        let sc = crate::test_support::SidecarResult::test_fixture();
339        let json = serde_json::to_string(&sc).unwrap();
340        std::fs::write(tmp.path().join("t-0000000000000000.ktstr.json"), json).unwrap();
341
342        let out = last_run_report(Some(tmp.path()), None)
343            .expect("a dir with one valid sidecar must render a report");
344        assert!(
345            out.contains("=== GAUNTLET ANALYSIS ==="),
346            "last-run must print the gauntlet analysis header: {out}",
347        );
348    }
349
350    /// `last_run_report(Some(empty_dir), _)` returns `None` — an empty
351    /// run dir has no sidecars, so there is nothing to analyze. The
352    /// caller prints nothing (only the stderr "no sidecar data" note).
353    #[test]
354    fn last_run_report_empty_dir_returns_none() {
355        let tmp = tempfile::tempdir().unwrap();
356        assert!(
357            last_run_report(Some(tmp.path()), None).is_none(),
358            "an empty directory must yield no report",
359        );
360    }
361
362    /// `newest_run_dir_for_kernel` matches run dirs whose leaf begins
363    /// `{kernel}-`. Plants two kernels' run dirs under a
364    /// `KTSTR_RUNS_ROOT`-pinned tree; the exact kernel label resolves
365    /// its own dir, and the `{kernel}-` boundary keeps a shorter query
366    /// (`7.1`) from matching a longer version (`7.1.3-*`) — the
367    /// operator passes the full detected label, not a partial.
368    #[test]
369    fn newest_run_dir_for_kernel_prefix_matches() {
370        use crate::test_support::test_helpers::{EnvVarGuard, lock_env};
371        let _lock = lock_env();
372        let tmp = tempfile::tempdir().unwrap();
373        std::fs::create_dir(tmp.path().join("7.1.3-abc1234")).unwrap();
374        std::fs::create_dir(tmp.path().join("6.14-def5678")).unwrap();
375        // Route runs_root() at the planted tree so the helper reads
376        // these dirs and not a real target/ktstr/.
377        let _root = EnvVarGuard::set(crate::KTSTR_RUNS_ROOT_ENV, tmp.path());
378
379        assert_eq!(
380            newest_run_dir_for_kernel("7.1.3")
381                .expect("the exact label 7.1.3 must resolve its run dir"),
382            tmp.path().join("7.1.3-abc1234"),
383        );
384        assert_eq!(
385            newest_run_dir_for_kernel("6.14")
386                .expect("the exact label 6.14 must resolve its run dir"),
387            tmp.path().join("6.14-def5678"),
388        );
389        assert!(
390            newest_run_dir_for_kernel("7.1").is_none(),
391            "the `{{kernel}}-` boundary must keep `7.1` from matching \
392             `7.1.3-*` — the query is a full label, not a partial",
393        );
394        assert!(
395            newest_run_dir_for_kernel("5.0").is_none(),
396            "no run dir begins `5.0-` — must yield None",
397        );
398    }
399
400    #[test]
401    fn show_host_returns_populated_report() {
402        let out = show_host();
403        assert!(!out.is_empty(), "show_host must return non-empty output");
404        assert!(
405            out.ends_with('\n'),
406            "show_host output must end with a newline for print! use: {out:?}",
407        );
408        assert!(
409            out.contains("kernel_name"),
410            "show_host must surface the kernel_name field: {out}",
411        );
412    }
413
414    /// Error path: the named run directory does not exist.
415    #[test]
416    fn show_run_host_missing_run_returns_error() {
417        let tmp = tempfile::tempdir().unwrap();
418        let err = show_run_host("nonexistent-run", Some(tmp.path())).unwrap_err();
419        let msg = format!("{err:#}");
420        assert!(
421            msg.contains("run 'nonexistent-run' not found"),
422            "missing-run error must name the run: {msg}",
423        );
424        assert!(
425            msg.contains("cargo ktstr stats list"),
426            "missing-run error must name the `stats list` discovery \
427             command so operators can enumerate available run keys \
428             without extra lookups: {msg}",
429        );
430    }
431
432    /// Error path: run dir exists but has no sidecars.
433    #[test]
434    fn show_run_host_empty_run_returns_error() {
435        let tmp = tempfile::tempdir().unwrap();
436        std::fs::create_dir(tmp.path().join("run-empty")).unwrap();
437        let err = show_run_host("run-empty", Some(tmp.path())).unwrap_err();
438        let msg = format!("{err:#}");
439        assert!(
440            msg.contains("no sidecar data"),
441            "empty-run error must name the condition: {msg}",
442        );
443    }
444
445    /// Error path: every sidecar carries `host: None`.
446    #[test]
447    fn show_run_host_all_host_none_returns_error() {
448        let tmp = tempfile::tempdir().unwrap();
449        let run_dir = tmp.path().join("run-no-host");
450        std::fs::create_dir(&run_dir).unwrap();
451        let sc = crate::test_support::SidecarResult::test_fixture();
452        let json = serde_json::to_string(&sc).unwrap();
453        std::fs::write(run_dir.join("t-0000000000000000.ktstr.json"), json).unwrap();
454        let err = show_run_host("run-no-host", Some(tmp.path())).unwrap_err();
455        let msg = format!("{err:#}");
456        assert!(
457            msg.contains("no sidecar with a populated host")
458                || msg.contains("none carries a populated host context"),
459            "all-host-None error must name the pre-enrichment likely cause: {msg}",
460        );
461    }
462
463    /// Happy path: a run with a populated host returns format_human.
464    #[test]
465    fn show_run_host_populated_sidecar_returns_format_human() {
466        let tmp = tempfile::tempdir().unwrap();
467        let run_dir = tmp.path().join("run-with-host");
468        std::fs::create_dir(&run_dir).unwrap();
469        let mut sc = crate::test_support::SidecarResult::test_fixture();
470        sc.host = Some(crate::host_context::HostContext::test_fixture());
471        let json = serde_json::to_string(&sc).unwrap();
472        std::fs::write(run_dir.join("t-0000000000000000.ktstr.json"), json).unwrap();
473
474        let out = show_run_host("run-with-host", Some(tmp.path())).unwrap();
475        assert!(
476            out.contains("kernel_name"),
477            "populated host output must include the kernel_name row: {out}",
478        );
479        assert!(
480            out.ends_with('\n'),
481            "output must end with newline for print!: {out:?}",
482        );
483    }
484
485    /// Happy path forward-scan: first sidecar has host:None, later
486    /// has populated host. `iter().find_map` must skip the first.
487    #[test]
488    fn show_run_host_forward_scans_past_none_sidecars() {
489        let tmp = tempfile::tempdir().unwrap();
490        let run_dir = tmp.path().join("run-mixed");
491        std::fs::create_dir(&run_dir).unwrap();
492        let sc_none = crate::test_support::SidecarResult::test_fixture();
493        std::fs::write(
494            run_dir.join("a-0000000000000000.ktstr.json"),
495            serde_json::to_string(&sc_none).unwrap(),
496        )
497        .unwrap();
498        let mut sc_host = crate::test_support::SidecarResult::test_fixture();
499        sc_host.host = Some(crate::host_context::HostContext::test_fixture());
500        std::fs::write(
501            run_dir.join("b-0000000000000000.ktstr.json"),
502            serde_json::to_string(&sc_host).unwrap(),
503        )
504        .unwrap();
505
506        let out = show_run_host("run-mixed", Some(tmp.path()))
507            .expect("forward scan must find the populated sidecar");
508        assert!(
509            out.contains("kernel_name"),
510            "output from populated sidecar must include kernel_name: {out}",
511        );
512    }
513
514    /// Happy path: a registered test name resolves through the
515    /// merge chain (default → scheduler → entry assert) and renders
516    /// the three-section report (Test:, Scheduler:, Resolved
517    /// assertion thresholds:) with the header preceding the
518    /// threshold dump.
519    #[test]
520    fn show_thresholds_known_test_returns_populated_report() {
521        let Some(entry) = crate::test_support::KTSTR_TESTS.iter().next() else {
522            eprintln!(
523                "ktstr: SKIP: show_thresholds_known_test_returns_populated_report — \
524                 no entries in KTSTR_TESTS",
525            );
526            return;
527        };
528        let out = show_thresholds(entry.name).expect("show_thresholds must resolve known test");
529        assert!(
530            out.contains("Test:"),
531            "output missing `Test:` header: {out}"
532        );
533        assert!(
534            out.contains("Scheduler:"),
535            "output missing `Scheduler:` header: {out}"
536        );
537        assert!(
538            out.contains("Resolved assertion thresholds:"),
539            "output missing thresholds section: {out}",
540        );
541        let test_idx = out.find("Test:").unwrap();
542        let thresholds_idx = out.find("Resolved assertion thresholds:").unwrap();
543        assert!(
544            test_idx < thresholds_idx,
545            "`Test:` header must precede threshold dump",
546        );
547    }
548
549    /// Unknown test name surfaces actionable error: missing-name
550    /// diagnostic + nextest pointer + binary:: prefix caveat.
551    #[test]
552    fn show_thresholds_unknown_test_returns_actionable_error() {
553        let err = show_thresholds("definitely_not_a_registered_test_xyz123").unwrap_err();
554        let msg = format!("{err:#}");
555        assert!(
556            msg.contains("no registered ktstr test named"),
557            "error must name the missing-test condition: {msg}",
558        );
559        assert!(
560            msg.contains("cargo nextest list"),
561            "error must point at the discovery command: {msg}",
562        );
563        assert!(
564            msg.contains("function-name component"),
565            "error must flag the nextest binary:: prefix caveat: {msg}",
566        );
567    }
568
569    /// `suggest_closest_test_name` — positive: distance-1 typo of a
570    /// long registered name returns the registered name.
571    #[test]
572    fn suggest_closest_test_name_finds_near_match() {
573        let Some(entry) = crate::test_support::KTSTR_TESTS.iter().find(|e| {
574            e.name.len() >= 10 && !(e.name.starts_with("__unit_test_") && e.name.ends_with("__"))
575        }) else {
576            skip!(
577                "no registered non-sentinel test with name >= 10 chars \
578                 — cannot construct a positive strsim probe"
579            );
580        };
581        let mut mutated: Vec<u8> = entry.name.bytes().collect();
582        mutated[0] = if mutated[0] == b'z' { b'a' } else { b'z' };
583        let query = std::str::from_utf8(&mutated).expect("ASCII mutation stays UTF-8");
584        let suggestion = suggest_closest_test_name(query)
585            .expect("distance-1 typo on a registered name must yield a suggestion");
586        assert_eq!(
587            suggestion, entry.name,
588            "a single-byte typo must suggest the exact name it was derived from",
589        );
590    }
591
592    /// Negative: 40-char unrelated query returns None.
593    #[test]
594    fn suggest_closest_test_name_returns_none_for_unrelated_query() {
595        let unrelated = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
596        assert_eq!(
597            suggest_closest_test_name(unrelated),
598            None,
599            "a query with no lexical relationship to any registered \
600             test name must yield no suggestion (not an over-reach)",
601        );
602    }
603
604    /// `suggest_closest_run_key` — distance-1 planted dir is found.
605    #[test]
606    fn suggest_closest_run_key_finds_near_match() {
607        let tmp = tempfile::tempdir().unwrap();
608        std::fs::create_dir(tmp.path().join("6.14-abc1234")).expect("plant run dir");
609        let suggestion = suggest_closest_run_key("6.14-abc1235", tmp.path())
610            .expect("distance-1 typo on a planted run dir must yield a suggestion");
611        assert_eq!(suggestion, "6.14-abc1234");
612    }
613
614    /// `suggest_closest_run_key` — distant query returns None.
615    #[test]
616    fn suggest_closest_run_key_returns_none_for_distant_query() {
617        let tmp = tempfile::tempdir().unwrap();
618        std::fs::create_dir(tmp.path().join("6.14-abc1234")).expect("plant run dir");
619        assert_eq!(suggest_closest_run_key("xxxxxxxxxxxxx", tmp.path()), None,);
620    }
621
622    /// `suggest_closest_run_key` — empty root returns None.
623    #[test]
624    fn suggest_closest_run_key_returns_none_for_empty_root() {
625        let tmp = tempfile::tempdir().unwrap();
626        assert_eq!(
627            suggest_closest_run_key("6.14-abc1234", tmp.path()),
628            None,
629            "empty root must yield None — no candidates to match against",
630        );
631    }
632
633    /// `suggest_closest_run_key` — file entries are skipped via the
634    /// `is_run_directory` filter.
635    #[test]
636    fn suggest_closest_run_key_skips_files() {
637        let tmp = tempfile::tempdir().unwrap();
638        std::fs::write(tmp.path().join("6.14-abc1234"), b"not a dir").expect("plant file");
639        std::fs::create_dir(tmp.path().join("6.14-abc1235")).expect("plant dir");
640        let suggestion = suggest_closest_run_key("6.14-abc1234", tmp.path())
641            .expect("the planted directory must yield a suggestion despite the same-name file");
642        assert_eq!(
643            suggestion, "6.14-abc1235",
644            "a regression that drops the is_dir() filter would surface \
645             here as `Some(\"6.14-abc1234\")` (the file at distance 0) \
646             instead of `Some(\"6.14-abc1235\")` (the dir at distance 1)",
647        );
648    }
649}