Expand description
Runtime support for #[ktstr_test] integration tests.
Provides the registration type, distributed slice, VM launcher, and result evaluation. Includes guest-side profraw flush for coverage-instrumented builds.
The entry point for test authors is the crate::ktstr_test
attribute macro; see the user-facing Writing Tests guide shipped
with the crate’s mdbook for end-to-end examples and the full
attribute grammar.
§Consumer API
Test authors interact primarily with the #[ktstr_test] proc
macro; programmatic test generation can instead populate
KtstrTestEntry values into the KTSTR_TESTS
linkme distributed slice. The remaining items in this module
are runtime glue invoked by the macro-generated code and the
ktstr / cargo-ktstr binaries.
§Module layout
Implementation is split across 19 production submodules
re-exported at test_support::* for a flat public API: args
(CLI argument extraction), dispatch (ktstr / cargo-ktstr CLI
entry points), entry (scheduler + test-entry types),
entry_validate (KtstrTestEntry::validate + phase helpers split
out of entry.rs), eval
(host-side VM result evaluation), host_class (shared
host-insufficiency error classification), metrics (payload stdout →
Metric list), output
(guest-output and console parsing), payload (Payload /
MetricCheck / Metric / Polarity), probe (auto-repro and
BPF probe pipeline), probe_metrics (host-side BPF map
introspection), profraw (coverage flush), runtime (pub mod
— neutral home for verbose/shm-size/config-file-parts shared by
eval and probe so they don’t circularly depend on each other),
shell_descriptor (wire-format struct shared between the test
binary’s --ktstr-shell-test=<NAME> producer and cargo-ktstr’s
shell-mode consumer), wprof (#[cfg(feature = "wprof")] —
Perfetto-trace wire constants + .wprof.pb shape assertions),
sidecar (per-run JSON records), staged
(pub(crate) mod — staged-payload writer), timefmt (ISO-8601
- run-id helpers), and
topo(topology override parsing).
A #[cfg(test)] pub(crate) mod test_helpers exists for cross-file
test wiring; it is not part of the production surface.
Re-exports§
pub use wprof::PERFETTO_TRACE_PACKETS_TAG;pub use wprof::WPROF_PB_MIN_BYTES;pub use wprof::assert_wprof_pb_shape;pub use entry::KTSTR_SCHEDULERS;pub use entry::KTSTR_TESTS;
Modules§
- runtime
- Runtime configuration primitives shared by
evalandprobe. - wprof
- Public wire-format constants + assertion helpers for the wprof
Perfetto-trace artifacts produced by
#[ktstr_test(wprof, ...)]tests.
Structs§
- BpfMap
Write - Host-side BPF map write performed during VM execution.
- Cgroup
Path - Validated cgroup parent path.
- Kernel
Unavailable - Marker error for “the test harness can’t find a kernel image to
boot the VM against”. Wraps the actionable diagnostic that
resolve_test_kernelemits when neitherKTSTR_TEST_KERNELnor any standard cache / sysroot location produced a bootable image. - Ktstr
Test Entry - Registration entry for an
#[ktstr_test]-annotated function. - MemSide
Cache - Re-exports of topology types for use in
KtstrTestEntrystatics generated by the#[ktstr_test]macro. HMAT Type 2 memory-side cache descriptor. - Metric
- A single extracted metric from a payload’s output.
- Metric
Hint - Payload-author metric declaration: polarity + display unit.
- Numa
Distance - Re-exports of topology types for use in
KtstrTestEntrystatics generated by the#[ktstr_test]macro. NxN inter-NUMA-node distance matrix. - Numa
Node - Re-exports of topology types for use in
KtstrTestEntrystatics generated by the#[ktstr_test]macro. Per-NUMA-node configuration. - Payload
- A test payload — either a scheduler or a userspace binary to run inside the guest VM.
- Payload
Metrics - All metrics extracted from a single payload run plus the process exit code.
- Perf
Delta Assertion - A per-test performance-regression assertion that
cargo ktstr perf-delta --noise-adjustenforces when this test is compared across two commits — and that a normalcargo ktstr testrun IGNORES. - Perf
Delta Assertion Record - Owned, serialized mirror of
crate::test_support::PerfDeltaAssertion. The public declaration type uses&'static str(so it stays const/E0493-safe on the entry) and therefore cannotDeserializeinto an owned value; thisString-backed record is the sidecar carrier the perf-delta compare reads.pubbecause it is a field of thepubSidecarResult(constructed across the workspace, including by thecargo-ktstrbinary crate); the author-facing declaration type iscrate::test_support::PerfDeltaAssertion. - Scheduler
- Definition of a scheduler for the test framework.
- Scheduler
Json - JSON shape projected from a registered
Scheduler. Each entry carries scheduler name, aBinaryKindJson-tagged binary specification (Discover / Path / Eevdf / KernelBuiltin), per-scheduler defaultTopologyJson, always-on scheduler args, declared kernel set, and gauntlet constraints. Internal fields (assertion overrides, sysctls, kargs, cgroup parent, config-file plumbing) are intentionally omitted. - Scheduler
List Entry - A
SchedulerJsonplus the number of#[ktstr_test]s declared against it. Emitted (as a JSON array) by the--ktstr-list-schedulersprobe socargo ktstr affectedcan enumerate declared schedulers AND skip those with zero tests when producing its CI matrix, in one probe. - Scheduler
Test Json - A single
#[ktstr_test]paired with its declared scheduler’s name. Emitted (as a JSON array) by the--ktstr-list-scheduler-testsprobe so--relevantcan map each test to its scheduler and select the tests whose scheduler a diff affects. - Shell
Test Descriptor - Wire-format descriptor exchanged between a test binary and
cargo ktstr shell --test <NAME>to let the shell VM mirror the named#[ktstr_test]’s topology, scheduler, wprof config, and performance mode. - Sidecar
Result - Test result sidecar written to KTSTR_SIDECAR_DIR for post-run analysis.
- Sysctl
- A
key=valuesysctl applied to the guest before the scheduler starts, injected into the guest kernel cmdline assysctl.<key>=<value>. - Topology
- Re-exports of topology types for use in
KtstrTestEntrystatics generated by the#[ktstr_test]macro. CPU topology specification with NUMA memory topology. - Topology
Constraints - Gauntlet topology filtering constraints.
- Topology
Constraints Json - JSON-friendly mirror of
TopologyConstraints— the host-sideOption<u32>fields serialize asnull(default serde behavior; noskip_serializing_if) rather than theSome(N)/None-tagged shapes serde uses forOptioninside larger struct graphs. Field semantics matchTopologyConstraintsverbatim; see that type for per-field documentation. - Topology
Json - JSON-friendly mirror of
Topologyfor the verifier wire format. Captures the four-tuple shape (numa nodes × LLCs × cores × threads) the per-scheduler baseline topology was declared with. The verifier uses this when computing the sweep matrix — the baseline anchors the default cell when no gauntlet preset matches the scheduler’s constraints. - Watch
BpfMap - Host-side, observer-effect-free read of a NAMED scheduler BPF-map field, surfaced as an assertable run-level metric.
Enums§
- Binary
Kind Json - JSON-friendly form of
SchedulerSpectagged so the verifier dispatch can exhaustivelymatchon the variant.DiscoverandPathboth carry a string identifier;EevdfandKernelBuiltinboth signal “no BPF to verify”. - BpfMap
Agg - Aggregation for a
WatchBpfMaptarget. - Host
Class - Outcome of classifying a test-body error against the host-insufficiency taxonomy.
- Metric
Check - Assertion check evaluated against an extracted
PayloadMetrics(or the exit code forMetricCheck::ExitCodeEq). - Metric
Stream - Which of the payload’s output streams a
Metricwas extracted from. - Output
Format - How the framework extracts metrics from a payload’s output.
- Payload
Kind - How a payload is launched inside the guest.
- Polarity
- Regression direction for a metric.
- Resolve
Source - Provenance of a scheduler binary returned by
resolve_scheduler. - Scheduler
Kind - Discriminator for the test’s scheduler-spec shape on the
--ktstr-shell-test=<NAME>wire format. Wire-byte-compatible with the prior stringly-typed"eevdf" | "discover" | "path" | "kernel_builtin"values via#[serde(rename_all = "snake_case")]; the typed enum replaces the stringly-typed boundary so a rename on either side (producer indispatch::maybe_dispatch_shell_test, consumer incargo_ktstr::misc::shell) is a compile error instead of a silent banner-emit-gate regression. - Scheduler
Spec - How to specify the scheduler for an
#[ktstr_test]. - Thread
Lookup - Outcome of scanning the flat metric list for a tid-keyed thread
entry. Distinguishes “tid not present” from “tid present but
allocated_bytesmissing” AND from “probe emitted more thanMAX_SCAN_INDEXcontiguous threads without the caller’s tid appearing in the prefix” — so a caller can issue a precise diagnostic instead of a blanket “not found”.
Constants§
- DEFAULT_
HOST_ CGROUP_ PARENT - Default cgroup parent path for
host_onlytests whenKTSTR_HOST_CGROUP_PARENTis unset. Suitable for both root (writable directly) and non-root (operator pre-creates/sys/fs/cgroup/ktstrwith appropriate ownership, OR overrides viaKTSTR_HOST_CGROUP_PARENTto point at a path inside a delegated subtree) invocations. Seeresolve_host_cgroup_parentfor the env-override path andbuild_host_cgroup_managerfor the cgroup-v2 Mode B/C delegation wire-up. - EXIT_
FAIL - Process exit code for a Fail verdict (or any expect_err satisfaction failure).
- EXIT_
INCONCLUSIVE - Process exit code for an Inconclusive verdict (a zero-denominator ratio gate that could not evaluate).
- EXIT_
PASS - Process exit code for a Pass verdict (and for the Skip path, which degenerates to Pass because the test never ran).
- MAX_
SCAN_ INDEX - Safety bound on the
snapshots.*.threads.N.tidscan inlookup_thread,snapshot_worker_allocated,thread_count, andsnapshot_count. Realistic probe runs see at most a few dozen threads in a single-allocator worker process; hitting this cap indicates either an unexpectedly wide target or a flat-metric schema change that broke the terminator convention. - MAX_
WALK_ DEPTH - Hard cap on recursion depth in
walk. Object and array children past this depth are skipped and a single [tracing::warn!] fires. Serde_json’s default parser recursion limit is 128, so this caps us well below that; a hand-builtserde_json::Valuethat bypasses the parser can still reach arbitrary depth, so an explicit walker guard is the last line of defence against a stack overflow. - WALK_
TRUNCATION_ SENTINEL_ NAME - Sentinel metric name emitted when
walkhitsMAX_WALK_DEPTHand skips a subtree. Callers ofwalk_json_leaves/extract_metricsthat want to distinguish “no deep metrics present” from “deep metrics dropped by the depth cap” scan the returnedVec<Metric>for a metric whosenameequals this constant — itsvalueis the depth at which truncation occurred, so nested failures at different subtrees produce one sentinel per trigger.
Statics§
- KTSTR_
SCHEDULERS - Distributed slice collecting all
declare_scheduler!registrations via linkme. Each entry is a&'static Schedulerpointing at a const emitted by the macro. The verifier discovers schedulers by spawning the test binary with--ktstr-list-schedulers; a per-binary ctor walks this slice and serializes each entry to JSON. - KTSTR_
TESTS - Distributed slice collecting all
#[ktstr_test]entries via linkme.
Functions§
- analyze_
sidecars - Collect sidecar JSON files and return the full gauntlet analysis.
- classify_
host_ error - Classify a test-body error against the host-insufficiency taxonomy.
- collect_
pool - Pool every sidecar JSON under every run directory at
root. - count_
indexed_ metrics - Walk
0..capapplyingkey_fn(i)to form a metric name and count how many consecutive indices yield a present metric. Stops at the first miss — the probe’swalk_json_leavesflattening yields indices 0..N contiguously, so the first gap is the array terminator. Returns the count, which may becapif every index below the bound is present (inconclusive — the caller should treatcapas “saturated scan, real count may be larger”). - default_
post_ vm_ periodic_ fired - Default
post_vmcallback emitted by#[ktstr_test]when the attribute omitspost_vm = .... Asserts that at least one periodic snapshot produced REAL BPF state during the workload window WHEN periodic was configured (num_snapshots > 0); when periodic was disabled (num_snapshots == 0), the helper is a no-op and returnsOk. - extract_
metrics - Extract metrics from a payload’s captured output per its declared
OutputFormat. - find_
metric - Find a metric by exact name. Returns
Noneif absent. - find_
metric_ u64 - Fetch a metric by exact name and return its numeric value as a
u64. ReturnsNoneif the metric is absent. Thin wrapper aroundfind_metric+value as u64for the common numeric-lookup shape. - find_
scheduler - Look up a registered scheduler by its
Scheduler::namefield (thename = "..."value supplied todeclare_scheduler!, not the SCREAMING_SNAKE_CASE const identifier the macro emits). ReturnsNoneif no registered scheduler matches. - find_
test - Look up a registered test function by name.
- flat_
metrics_ dump - Flatten the full
(name, value)pair list for diagnostic rendering inside error messages. Returned as an ownedVec<(&str, f64)>so call sites spell the diagnostic as a single{:?}formatter argument instead of re-typing the.iter().map(...).collect()chain at every site. - format_
run_ artifact_ footer - Render the
cargo ktstr testpost-run footer: for each run directory written at or aftersince, name every FAILED test and the concrete path to each of its artifacts (failure dump, auto-repro dump, stats sidecar, wprof trace), plus a per-dir count of stats sidecars and wprof traces. - has_
metric - Does the flat metric list contain a metric with this exact name?
Thin wrapper around
find_metricfor the common existence check — avoids forcing every call site to spell.is_some(). - host_
capacity - Host capacity triple
(cpus, llcs, max_cpus_per_llc)used to filter gauntlet topology presets against what the host can actually schedule. Bothdispatch::list_tests_*(gauntlet variant filter) anddispatch::list_verifier_cells_all(verifier sweep filter) share this single source of truth so the two filters never drift. Readsavailable_parallelism()for CPU count +HostTopology::from_sysfs()for LLC layout; falls back to single-LLC + single-cpu-per-llc when sysfs is unavailable. - is_
truncation_ sentinel_ name - Predicate for “this metric name / map key is the walk-truncation sentinel.” Centralises the literal-equality check so every consumer stays in sync when the sentinel name changes, and so future sentinel variants (e.g. a parser-rejection sentinel) can be threaded through one predicate instead of scattered string literals.
- ktstr_
main - Nextest protocol handler.
- lookup_
thread - Extract the
allocated_bytes/deallocated_bytesvalues forworker_tidfrom snapshot 0 in the flat metric list produced bywalk_json_leavesover the probe’s JSON output. - newest_
run_ dir - Find the most recently modified run directory under
runs_root. - post_
vm_ skip - Request a test SKIP from a
post_vm/post_vm_unconditionalcallback:return Err(post_vm_skip(reason))when the run is INCONCLUSIVE — the VM could not produce the artifact the assertion needs (e.g. a load-starved VM whose BPF probe never attached, leaving a placeholder failure dump), as distinct from a real regression. The framework detects the attachedHostSkipRequestmarker and converts the run tocrate::assert::AssertResult::skipinstead of a failure. - profraw_
target_ dir - Resolve the llvm-cov-target directory for profraw output.
- resolve_
host_ cgroup_ parent - Resolve the cgroup parent path for
host_onlytests. - resolve_
scheduler - Resolve a scheduler binary from a
SchedulerSpec. - resolve_
test_ kernel - Find a kernel image for running tests.
- run_
ktstr_ test - Host-side entry point: build a VM, boot it with
--ktstr-test-fn=NAME, extract profraw from SHM, and return the test result. - runs_
root - Resolve the parent directory that holds all test-run subdirectories.
- sanitize_
kernel_ label - Sanitise a kernel label (the producer-side identity emitted by
cargo ktstr’s resolver) into a nextest-safe identifier of the shapekernel_[a-z0-9_]+. - sidecar_
dir - Resolve the sidecar output directory for the current test process.
- snapshot_
count - Count the number of
snapshots.N.timestamp_unix_secentries in the flat metric list, capped atMAX_SCAN_INDEX. - snapshot_
worker_ allocated - Extract
snapshots.{snap_idx}.threads[*].allocated_bytesfor the thread whose tid matchesworker_tid. ReturnsThreadLookupso callers distinguish “tid absent” from “cap hit before tid seen” from “allocated_bytes sibling missing” — parallel tolookup_thread, which covers the single-snapshot path. - thread_
count - Count the number of
snapshots.0.threads.N.{Ok,Err}.tidentries in the flat metric list, capped atMAX_SCAN_INDEX. Each index carries exactly one variant wrapper (OkorErr); the count terminates at the first index where neither exists. - walk_
json_ leaves - Walk numeric leaves of a JSON value, emitting
Metrics keyed by dotted paths.
Type Aliases§
- Post
VmCallback - Shared callback signature for the
KtstrTestEntry::post_vmandKtstrTestEntry::post_vm_unconditionalhost-side hooks. Both fields wrap this same shape inOption<_>; the alias collapses the open-codedfn(&crate::vmm::VmResult) -> anyhow::Result<()>repetition at the field declarations and at the matchingwith_post_vm{,_unconditional}builder parameters. Future post-VM hooks (e.g. anexpect_auto_reproartifact-existence checker) plug into the same shape without triplicating the signature.