Module cli

Module cli 

Source
Expand description

CLI support functions shared between ktstr and cargo-ktstr.

Validation, configuration, and kernel/KVM resolution logic used by both binaries.

Structs§

AveragedGroup
Re-export of the comparison-policy types so downstream crates using ktstr::cli as their public surface don’t need to reach into the internal ktstr::stats module (which is pub(crate) — see lib.rs — and therefore not a stable public path). The policy is the only item in stats that a CLI or external consumer constructs directly; every other item is internal plumbing reached via cli::compare_partitions. One aggregated GauntletRow produced by group_and_average_by, plus the pass-bookkeeping needed to render the per-group summary block (N/M passed + the (S skip, I inc, F fail) breakdown).
ComparisonPolicy
Re-export of the comparison-policy types so downstream crates using ktstr::cli as their public surface don’t need to reach into the internal ktstr::stats module (which is pub(crate) — see lib.rs — and therefore not a stable public path). The policy is the only item in stats that a CLI or external consumer constructs directly; every other item is internal plumbing reached via cli::compare_partitions. Per-metric threshold policy driving compare_rows / compare_partitions.
CpuCap
Re-export of the internal vmm::host_topology::CpuCap type so the ktstr and cargo-ktstr CLI binaries (which import this module through the pub mod cli surface) can resolve --cpu-cap N without depending on the pub(crate) vmm module. Keeping the canonical definition in vmm::host_topology (so the acquire_llc_plan internal call site consumes its own type without needing cli) and re-exporting here — versus inverting the dependency — avoids pulling the CLI module into the VMM internals. Parsed --cpu-cap N value. N is a CPU count: the planner reserves exactly N host CPUs by walking whole LLCs in contention- / NUMA-aware order (filtered to the calling process’s allowed cpuset) and partial-taking the last LLC so plan.cpus.len() == N. The flock set is still per-LLC (the last LLC is flocked whole even when only a prefix of its CPUs enters plan.cpus). Bounded to 1..=usize::MAX at the constructor — a cap of 0 is nonsensical (reserving zero CPUs is just “don’t run”) and rejected upstream by the CLI layer, but we enforce the bound in the type system via NonZeroUsize so callers can CpuCap::new(...)? without a follow-up bounds check.
FetchProgress
FetchProgress is the public handle the ktstr / cargo-ktstr binaries construct to render kernel-fetch progress (the parallel resolve_kernel_set and the single-shot kernel build paths). It must be pub (not pub(crate)) because those call sites live in the binary crates and thread &FetchProgress into the library resolvers — the same lib/bin-boundary reason Spinner is pub. The child-bar types (GroupBar, CloneProgress) stay pub(crate): only the in-crate fetch path constructs them. Shared owner of the concurrent fetch progress bars for one resolve operation.
GateOptions
Re-export of the comparison-policy types so downstream crates using ktstr::cli as their public surface don’t need to reach into the internal ktstr::stats module (which is pub(crate) — see lib.rs — and therefore not a stable public path). The policy is the only item in stats that a CLI or external consumer constructs directly; every other item is internal plumbing reached via cli::compare_partitions. Operator-level perf-delta failure gate + render options, layered on top of the per-metric significance policy (which decides WHICH deltas are confident regressions). These decide HOW MANY / WHICH-NAMED confident regressions fail the run, and whether stable/noisy rows render.
KernelBuildResult
Result of the post-acquisition kernel build pipeline.
KernelDirCacheHit
Cache-hit signal returned from resolve_kernel_dir_to_entry when a clean source tree’s cache entry was found and reused without invoking kernel_build_pipeline.
KernelDirOutcome
Result bundle from resolve_kernel_dir_to_entry.
KernelResolvePolicy
Policy controlling resolve_kernel_image behavior across binaries.
PhaseDisplayOptions
Re-export of the comparison-policy types so downstream crates using ktstr::cli as their public surface don’t need to reach into the internal ktstr::stats module (which is pub(crate) — see lib.rs — and therefore not a stable public path). The policy is the only item in stats that a CLI or external consumer constructs directly; every other item is internal plumbing reached via cli::compare_partitions. CLI-controlled rendering of the per-phase spread block in cargo ktstr perf-delta --noise-adjust. Bundled as a struct so the 5-flag clap surface threads through compare_partitions_noise as a single positional rather than five. Default value renders every phase / every metric / every paired row — equivalent to passing no phase flags. All 5 flags require --noise-adjust (per-phase output exists only there).
RowFilter
Re-export of the comparison-policy types so downstream crates using ktstr::cli as their public surface don’t need to reach into the internal ktstr::stats module (which is pub(crate) — see lib.rs — and therefore not a stable public path). The policy is the only item in stats that a CLI or external consumer constructs directly; every other item is internal plumbing reached via cli::compare_partitions. Typed-field filter set for narrowing GauntletRow sets in the cargo ktstr perf-delta pipeline. Every field is None / empty by default; populated fields are AND-combined ACROSS fields, with field-internal OR/AND semantics described per-field below. Applied via apply_row_filters in compare_partitions before the rows reach compare_rows_by.
Spinner
Progress spinner for long-running CLI operations.

Enums§

Dimension
Re-exports of the dimensional-slicing types used by cargo-ktstr’s BuildCompareFilters::build() plumbing. The stats module is pub(crate) (its tabular reporting types have no stable surface yet), but the cargo-ktstr binary needs Dimension and derive_slicing_dims to unit-test the filter-builder shape (the BuildCompareFilters tests assert which slicing dim a per-side filter pair derives). Same pattern as CpuCap above: keep the canonical definitions in stats (where the comparison plumbing consumes them internally) and re-export the slim slicing surface through cli so the binaries reach them through the public cli module. One of the nine dimensions that compose a GauntletRow’s identity in the comparison pipeline: kernel, scheduler, topology, work-type, project-commit, kernel-commit, run-source, resolve-source, cpu-budget. Each maps to the corresponding RowFilter field and GauntletRow field; the dimension model lets compare_partitions derive its slicing dims and dynamic pairing key without hardcoding the dimension list at every call site. Variant names match the CLI flag suffix (e.g. Dimension::ProjectCommit--project-commit, Dimension::RunSource--run-source, Dimension::CpuBudget--cpu-budget) so a reader can map from operator surface to internal enum without a translation table.
KernelCommand
Shared kernel subcommand tree used by both ktstr and cargo ktstr. The two binaries embed this as ktstr kernel <subcmd> / cargo ktstr kernel <subcmd> and dispatch identically; defining the variants once means a new kernel subcommand (or a flag change) lands in both surfaces by construction.

Constants§

CPU_CAP_HELP
Help text for the --cpu-cap N flag. Shared across ktstr kernel build, cargo ktstr kernel build, and ktstr shell so the operator-facing wording is identical regardless of entry point.
DIRTY_TREE_CACHE_SKIP_HINT
Emitted by kernel build when a local source tree has uncommitted index/worktree changes. Caching would key the built artifact on a git hash that does not describe the actual tree, so the build completes but the result is not archived. The hint names the two remediation paths (commit or stash) so an operator re-running the build after cleaning the tree benefits from the cache. Extracted from the call site so a wording drift between what’s printed and what’s documented elsewhere is impossible by construction; pinned by dirty_tree_cache_skip_hint_shape below.
DISK_HELP
Help text for the --disk <SIZE> shell flag, shared between cargo ktstr shell (src/bin/cargo_ktstr/cli.rs) and ktstr shell (src/bin/ktstr.rs) so a future tweak lands in one place. Mirrors the super::CPU_CAP_HELP pattern.
EMBEDDED_KCONFIG
ktstr.kconfig embedded at compile time.
EOL_EXPLANATION
Explanation of the (EOL) tag, shared between the text-output legend printed after kernel list and the kernel list --help long description (via KERNEL_LIST_LONG_ABOUT, which embeds this exact byte sequence at its head through the shared eol_explanation_literal! macro). One literal → one source of truth, so a wording drift cannot put the two surfaces out of sync. pub matches the visibility of the sibling KERNEL_HELP_* constants so downstream consumers (e.g. documentation generators) can reference the exact text the CLI prints.
EXTRA_KCONFIG_HELP
Short clap-help for --extra-kconfig. Mirrors the CPU_CAP_HELP pattern: terse first sentence on the clap surface, full rustdoc on the KernelCommand::Build variant for --help long-about.
INCLUDE_EOL_HELP
Help text for the --include-eol flag, shared by every command that expands a START..END kernel range (cargo ktstr test, coverage, llvm-cov, verifier, kernel list, and kernel build when the --kernel value is a range). One const so the wording stays identical across every surface the flag appears on.
KERNEL_HELP_BUILD
Help text for --kernel on kernel build (ktstr and cargo ktstr). Unlike KERNEL_HELP_NO_RAW, this surface builds a kernel rather than resolving one for a test run: it is NOT repeatable (one kernel or one range per invocation), and a cache key is rejected (a cache key names an already-built entry, so there is nothing to build). A source-directory path auto-builds; a version / range auto-downloads; a git source is fetched and built. Omitting --kernel builds the latest stable release.
KERNEL_HELP_NO_RAW
Help text for --kernel in contexts that reject raw image files: cargo ktstr test, cargo ktstr coverage, cargo ktstr llvm-cov, and ktstr shell. Matches KernelResolvePolicy { accept_raw_image: false, .. }.
KERNEL_HELP_RAW_OK
Help text for --kernel in contexts that accept raw image files: cargo ktstr shell. Matches KernelResolvePolicy { accept_raw_image: true, .. }. See KERNEL_HELP_NO_RAW for the converse and the rationale for the asymmetry.
KERNEL_LIST_LONG_ABOUT
long_about for kernel list --help. Embeds EOL_EXPLANATION verbatim (via eol_explanation_literal!) so the tag legend cannot drift between the post-table output and the help copy, then appends a plain-text rendering of the --json output schema so scripted consumers can discover the contract from the terminal without running cargo doc. The schema wording mirrors the Rust-doc schema on super::kernel_list; keeping both surfaces terse makes a drift obvious on review. A plain-text (not JSON/markdown) rendering is used because clap applies no JSON/markdown formatting pass, so the schema reads as plain text. Clap does apply terminal-width wrapping, so the embedded EOL sentence re-flows to the width of the host terminal; the schema block’s explicit \n line breaks survive wrapping and preserve the column-aligned field table.
NON_GIT_TREE_CACHE_SKIP_HINT
Hint shown in place of DIRTY_TREE_CACHE_SKIP_HINT when the source tree is not a git repository at all. commit / stash are not actionable remediations in that case — the operator’s only path to caching is to put the source under git (or use a kernel-source fetch mode that produces a git-tracked tree). Pinned by non_git_tree_cache_skip_hint_shape below so a wording drift is caught in unit tests.
STALE_KCONFIG_EXPLANATION
Explanation of the (stale kconfig) tag. Mirrors UNTRACKED_KCONFIG_EXPLANATION so the kconfig tag pair shares one shape — every kconfig-status legend in the informational trio (EOL / UNTRACKED / STALE) is now a const surfaced via a *_legend_if_any helper. Verbatim wording preserved from the prior inline eprintln! in kernel_list so existing operators see no behavioural change.
UNTRACKED_KCONFIG_EXPLANATION
Explanation of the (untracked kconfig) tag. Consumer-facing wording mirrors EOL_EXPLANATION’s “one-const, one-surface” pattern so a doc-drift between the tag word and the legend cannot silently slip. Mirrors STALE_KCONFIG_EXPLANATION so the kconfig tag pair shares one shape.

Functions§

append_extra_kconfig_suffix
Append the -xkc{extra_hash} segment to a cache key built around the bare baked-in suffix (...-kc{baked_hash}), bringing it to the two-segment shape produced by crate::cache_key_suffix_with_extra.
auto_download_kernel
Auto-download, build, and cache the latest stable kernel.
cache_lookup
Look up a cache key, checking local first, then remote (if enabled).
check_kvm
Pre-flight check for /dev/kvm availability and permissions.
check_tools
Pre-flight check: verify that all required external tools are present in $PATH before starting work. Collects every missing tool into a single error so the user sees the full list at once.
compare_partitions
Compare two filter-defined partitions of the sidecar pool and report regressions across slicing dimensions. See crate::stats::compare_partitions for the full contract.
compare_partitions_noise
Noise-adjusted variant of compare_partitions: keeps every per-run row and gates a confident regression on the two sides being SEPARATED (a two-sided Welch t-test, or fully disjoint [min, max] bands) AND the mean delta being MATERIAL (the registry default_abs + default_rel dual-gate), instead of a fixed single-run threshold. When the scenarios carry phases it also renders a per-phase spread + coverage block (render-only, honoring phase_opts; per-phase never affects the exit). See crate::stats::compare_partitions_noise for the full contract.
derive_slicing_dims
Re-exports of the dimensional-slicing types used by cargo-ktstr’s BuildCompareFilters::build() plumbing. The stats module is pub(crate) (its tabular reporting types have no stable surface yet), but the cargo-ktstr binary needs Dimension and derive_slicing_dims to unit-test the filter-builder shape (the BuildCompareFilters tests assert which slicing dim a per-side filter pair derives). Same pattern as CpuCap above: keep the canonical definitions in stats (where the comparison plumbing consumes them internally) and re-export the slim slicing surface through cli so the binaries reach them through the public cli module. Derive the set of dimensions on which filter_a and filter_b differ. These are the SLICING dimensions — dimensions on which the two sides select disjoint cohorts and therefore form the A/B contrast. The complement (every other dimension) is the PAIRING-key dimension set used by compare_rows to join A-side rows against B-side rows.
download_and_cache_version
Download a specific kernel version, build it, and store in the cache. Returns the cache entry directory path (NOT the image path).
embedded_kconfig_hash
Compute CRC32 of the embedded ktstr.kconfig fragment.
expand_kernel_range
Expand a kernel-version range to the list of stable / longterm releases that fall inside [start, end] inclusive.
explain_sidecar
Diagnose Option-field absences for a run’s sidecars. Mirrors show_run_host’s shape (--run + optional --dir, printable string return). See the original rustdoc on the public surface for the full JSON / text contract and exit-code policy.
format_entry_row
Format a human-readable table row for a cache entry.
is_render_suppressed_component
Re-export of the comparison-policy types so downstream crates using ktstr::cli as their public surface don’t need to reach into the internal ktstr::stats module (which is pub(crate) — see lib.rs — and therefore not a stable public path). The policy is the only item in stats that a CLI or external consumer constructs directly; every other item is internal plumbing reached via cli::compare_partitions. True when name is a Rate component suppressed from compare output (see the private RENDER_SUPPRESSED_COMPONENTS list).
kernel_build_pipeline
Post-acquisition kernel build pipeline.
kernel_clean
Remove cached kernels with optional keep-N and confirmation prompt.
kernel_list
List cached kernel images.
kernel_list_range_preview
Range-preview variant of kernel_list.
list_locks
ktstr locks entry point. See module-level doc block above.
list_metrics
Render the metric registry for cargo ktstr stats list-metrics.
list_runs
List test runs under {CARGO_TARGET_DIR or "target"}/ktstr/.
list_values
Render the distinct-value catalogue for the sidecar pool, for cargo ktstr stats list-values.
make_kernel_with_output
Build the kernel with output piped through the progress group.
metric_def
Re-export of the comparison-policy types so downstream crates using ktstr::cli as their public surface don’t need to reach into the internal ktstr::stats module (which is pub(crate) — see lib.rs — and therefore not a stable public path). The policy is the only item in stats that a CLI or external consumer constructs directly; every other item is internal plumbing reached via cli::compare_partitions. Look up a metric definition by name.
new_table
Build a borderless comfy-table with styling gated on stdout_color. When stdout is not a TTY (CI, piped-to-file), force_no_tty suppresses cell color escapes so a log or grep capture does not land raw \x1b[... sequences. The NOTHING preset skips box-drawing characters and keeps whitespace-padded columns, matching the previous hand-rolled format!("{:<30}…") look while auto-measuring each column from actual cell contents.
new_wrapped_table
Variant of new_table that opts into comfy-table’s terminal-width-aware [comfy_table::ContentArrangement::Dynamic] layout. Cells too wide for the available terminal width wrap inside the cell rather than pushing later columns past the edge, at the cost of taller rows. Used by ctprof compare / ctprof show under the --wrap flag; the existing fixed-column new_table stays the default for every other caller (locks, verifier, stats) so their output stays byte-stable for shell-pipeline consumers.
parse_disk_arg
Parse the --disk <SIZE> CLI argument into an Option<crate::vmm::disk_config::DiskConfig>. None input returns Ok(None) (no disk attached); a Some(s) input runs s through parse_disk_size_mib and wraps the result in a DiskConfig whose remaining fields fall through to crate::vmm::disk_config::DiskConfig::default (raw filesystem, no throttle, read-write). Shared between cargo ktstr shell and ktstr shell so both bins parse identically; a malformed size surfaces here at CLI-argument time, never mid-VM-setup.
parse_disk_size_mib
Parse a human-readable size string (e.g. "256mib", "10gib", "1gib") into a count of mebibytes (MiB), rounded down. Returns Err when the suffix is unrecognized, the numeric portion fails to parse, the value is not a positive integer multiple of one MiB, or the result exceeds u32::MAX MiB (the crate::vmm::disk_config::DiskConfig::capacity_mib capacity).
parse_topology_string
Parse a comma-separated topology string into its four dimensions: (numa_nodes, llcs, cores, threads). The canonical format is "numa_nodes,llcs,cores,threads" — the same shape accepted by the ktstr shell --topology and cargo ktstr shell --topology flags.
print_stats_report
Read sidecar JSON files and return the gauntlet analysis report.
read_extra_kconfig
Read a --extra-kconfig PATH file. Returns Ok(content) on success or Err(message) with an actionable diagnostic naming --extra-kconfig and the user’s literal input path verbatim so a typo names the exact string they passed.
resolve_cached_kernel
Resolve a Version or CacheKey identifier to a cache entry directory.
resolve_git_kernel
Resolve a git+URL#tag=/#branch=/#sha= kernel spec to a cache-entry directory.
resolve_include_files
Resolve --include-files arguments into (archive_path, host_path) pairs.
resolve_kernel_dir
Resolve a kernel directory: auto-build from source tree.
resolve_kernel_dir_to_entry
Resolve a source-tree path through the local-kernel cache, returning a KernelDirOutcome that carries the boot-image directory, the cache-hit signal, and the dirty-tree flag.
resolve_kernel_image
Resolve a kernel identifier to a bootable image path.
resolve_kernel_parallelism
Resolve the rayon pool width for cargo ktstr’s resolve_kernel_set per-spec fan-out.
restore_sigpipe_default
Restore SIGPIPE to its default action (terminate the process) so piping a ktstr binary’s output to a reader that closes early (e.g. ... | head) does not panic inside print! / println!. Rust’s startup code sets SIGPIPE to SIG_IGN, which turns the broken-pipe write into an io::Error that print! escalates to a panic. Setting SIG_DFL restores the POSIX “process terminates on SIGPIPE” convention that Unix CLI tools rely on.
run_make
Run make in a kernel directory under a wall-clock timeout, with the parent’s stdout/stderr inherited.
run_make_with_output
Run make with merged stdout+stderr piped through the progress group.
show_host
Collect the current host context via crate::host_context::collect_host_context and render it as a human-readable multi-line report via crate::host_context::HostContext::format_human. The output ends with a newline; callers print it verbatim.
show_run_host
Render the archived host context for the named run, resolved against dir (or test_support::runs_root() when dir is None). Loads sidecars under the run directory and returns the HostContext::format_human of the first sidecar that has a populated host field — every sidecar in a single run captures the same host, so first-wins is adequate.
show_thresholds
Render the resolved, merged Assert thresholds for the named test — the same merge chain evaluated at run time in run_ktstr_test_inner: Assert::default_checks().merge(&entry.scheduler.assert).merge(&entry.assert).
stderr_color
Whether stderr supports color (cached per process).
stdout_color
Whether stdout supports color (cached per process). Distinct from stderr_color because cargo ktstr perf-delta > report.txt pipes stdout to a file while leaving stderr on the TTY — gating stdout tables on the stderr TTY state would leave ANSI escapes in the file. Table-rendering code paths gate on this reading; diagnostic/status prints use stderr_color.
validate_kernel_config
Validate the output .config for critical options that the kconfig fragment requested but the kernel build system may have silently disabled (e.g. CONFIG_DEBUG_INFO_BTF requires pahole).