Crate ktstr

Crate ktstr 

Source
Expand description

VM-based test framework for Linux kernel subsystems, with a focus on sched_ext.

ktstr boots lightweight KVM virtual machines with controlled CPU topologies, runs scheduler test scenarios inside them, and evaluates results from the host via guest memory introspection. Each test creates cgroups, spawns worker processes, and checks that the scheduler handled the workload correctly. The same scenarios also run under the kernel’s default EEVDF scheduler, so a test can baseline sched_ext behavior against stock scheduling.

§Quick start

Declare cgroups and workloads as data, let the framework handle lifecycle and checking:

use ktstr::prelude::*;

#[ktstr_test(llcs = 1, cores = 2, threads = 1)]
fn my_scheduler_test(ctx: &Ctx) -> Result<AssertResult> {
    execute_defs(ctx, vec![
        CgroupDef::named("cg_0").workers(2),
        CgroupDef::named("cg_1").workers(2),
    ])
}

Requires a kernel image; see find_kernel() for the resolution chain.

For multi-phase scenarios with dynamic topology changes:

use ktstr::prelude::*;

#[ktstr_test(llcs = 1, cores = 2, threads = 1)]
fn my_dynamic_test(ctx: &Ctx) -> Result<AssertResult> {
    let steps = vec![
        Step::with_defs(
            vec![CgroupDef::named("cg_0").workers(4)],
            HoldSpec::frac(0.5),
        ),
        Step::new(
            vec![Op::stop_cgroup("cg_0"), Op::remove_cgroup("cg_0")],
            HoldSpec::frac(0.5),
        ),
    ];
    execute_steps(ctx, steps)
}

§Scheduler definition

Tests work with just topology parameters (as above). When multiple tests share a scheduler, use declare_scheduler! to declare it once with a binary, default topology, and any always-on args. Tests reference the generated const and inherit its configuration:

use ktstr::prelude::*;

declare_scheduler!(MY_SCHED, {
    name = "my_sched",
    binary = "scx_my_sched",
});

#[ktstr_test(scheduler = MY_SCHED)]
fn basic(ctx: &Ctx) -> Result<AssertResult> {
    execute_defs(ctx, vec![
        CgroupDef::named("cg_0").workers(2),
        CgroupDef::named("cg_1").workers(2),
    ])
}

For full control over cgroup setup, worker spawning, and assertion you can use the low-level API directly:

use ktstr::prelude::*;

#[ktstr_test(llcs = 1, cores = 2, threads = 1)]
fn my_low_level_test(ctx: &Ctx) -> Result<AssertResult> {
    let mut group = CgroupGroup::new(ctx.cgroups);
    group.add_cgroup_no_cpuset("workers")?;
    let cpus = ctx.topo.all_cpuset();
    ctx.cgroups.set_cpuset("workers", &cpus)?;

    let cfg = WorkloadConfig {
        num_workers: 2,
        work_type: WorkType::SpinWait,
        ..Default::default()
    };
    let mut handle = WorkloadHandle::spawn(&cfg)?;
    ctx.cgroups.move_tasks("workers", &handle.worker_pids_for_cgroup_procs()?)?;
    handle.start();

    std::thread::sleep(ctx.duration);
    let reports = handle.stop_and_collect();

    let a = Assert::default_checks();
    Ok(a.assert_cgroup(&reports, None))
}

For pointwise assertions against captured stats — the most direct way to express “this counter is at least N”, “this rate is between A and B”, “this metric is finite” — use Verdict + #[derive(Claim)] accessors and the claim! macro:

use ktstr::prelude::*;

// A test author would obtain `cg` and `report` from `ctx`-driven
// execution; the literal here just illustrates the assertion shape.
let cg = CgroupStats {
    num_workers: 2,
    num_cpus: 2,
    max_gap_ms: 50,
    p99_wake_latency_us: 25.0,
    median_wake_latency_us: 10.0,
    total_iterations: 5_000,
    ..Default::default()
};
let work_units = 10_000u64;
let throughput = work_units as f64 / 5.0;

let mut v = Assert::default_checks().verdict();
cg.claim_max_gap_ms(&mut v).at_most(100);          // typed CgroupStats accessor
cg.claim_p99_wake_latency_us(&mut v).at_most(50.0);
cg.claim_total_iterations(&mut v).at_least(1_000);
claim!(v, work_units).at_least(5_000);             // local-binding label
claim!(v, throughput).is_finite();                  // expression label
claim!(v, cg.wake_latency_tail_ratio()).between(1.0, 5.0);
let r = v.into_result();
assert!(r.is_pass());

Every claim is labeled by stringify! on either a struct field name (via the derive) or an identifier/expression (via the macro), so a rename or refactor updates the failure-message label automatically and a stale call site fails to compile. There is no manual-string escape hatch — by design, every label is source-text-grounded.

Run with cargo nextest run (requires /dev/kvm).

See the prelude module for the full set of re-exports.

§Library usage

Default install (full feature set — includes the installed ktstr / cargo-ktstr bins’ deps):

[dev-dependencies]
ktstr = "0.23.0"

Lean dev-dep (drops the host-tooling crates: tikv-jemallocator, clap_complete, tree-sitter, tree-sitter-c, base64):

[dev-dependencies]
ktstr = { version = "0.23.0", default-features = false }

§Feature flags

  • cli-bins (default) — umbrella for deps used only by the four src/bin/*.rs entry points and the matching test-binary dispatch hooks. Pulls in tikv-jemallocator, clap_complete, tree-sitter, tree-sitter-c, and the export feature.
  • export (pulled in by cli-bins) — gates export and the cargo ktstr export dispatch path in the test binary. Drops base64 from the manifest when off.
  • wprof — embed the wprof BPF tracer in shell-mode VMs. First build clones github.com/anakryiko/wprof (requires git, make, gcc, clang, elfutils-devel, zlib-devel).
  • pretty-labels — grex-based regex synthesis for ctprof_compare display labels. With the feature off, labels fall back to the deterministic join key.
  • remote-cache — GitHub Actions cache backend for blob storage. CI-only; off-by-default. Pulls in opendal + minimal tokio runtime.
  • integration — gates resolve_func_ip visibility for integration tests.

§Crate organization

  • cache – kernel image cache (XDG directories, metadata, atomic writes)
  • cgroup – cgroup v2 filesystem operations
  • cli – shared helpers backing the ktstr and cargo-ktstr binaries
  • fetch – kernel tarball and git source acquisition
  • flock – advisory file-locking primitives used by cache + LLC reservations
  • kernel_path – kernel ID parsing and filesystem image discovery
  • remote_cache – GitHub Actions cache integration
  • scenario – declarative ops API (CgroupDef, Step, Op, Backdrop, execute_defs, execute_steps, execute_scenario)
  • scenario::scenarios – curated canned scenarios for common patterns
  • assert – pass/fail assertions (starvation, isolation, fairness)
  • test_support#[ktstr_test] runtime and registration
  • topology – CPU topology abstraction (LLCs, NUMA nodes)
  • verifier – BPF verifier log parsing, cycle detection, and output formatting
  • worker_ready / worker_ready_wait – pid-scoped ready-marker the alloc/test worker writes once it is work-ready, polled (worker_ready_wait) before the probe is launched against it
  • workload – worker process types and telemetry collection

§ctprof subsystem

Per-thread + per-process runtime profile, captured via ktstr ctprof capture and compared via ktstr ctprof compare:

  • host_context – one-shot host snapshot (kernel, CPU, memory, tunables)
  • host_heap – jemalloc global heap counters (mallctl)
  • ctprof – per-thread procfs walk + cumulative scheduling, I/O, page-fault, jemalloc TSD counters
  • ctprof_compare – two-snapshot diff engine (group-by + delta tables)

host_thread_probe (the ELF/DWARF + ptrace + process_vm_readv engine that pulls per-thread jemalloc TSD counters) is pub(crate)-only and consumed exclusively by ctprof plus the source-shared standalone ktstr-jemalloc-probe binary. Direct probe access from downstream is intentionally not part of the surface — scheduler authors get the captured counters through ctprof::ThreadState.

Internal modules (not re-exported): host_thread_probe reads per-thread jemalloc TSD counters via ptrace, monitor reads live guest state, probe attaches BPF probes to traced functions, and vmm owns the KVM VM lifecycle.

timeline is a public module (its StimulusEvent appears in assert::build_phase_buckets_with_stimulus’s signature and is re-exported in the prelude); it correlates stimulus events with monitor samples for phase-aligned reporting.

Re-exports§

pub use test_support::runtime::bypass_llc_locks_active;
pub use ::linkme;

Modules§

assert
Pass/fail evaluation of scenario results.
cache
Kernel image cache for ktstr.
cgroup
Cgroup v2 filesystem operations for test cgroup management.
cli
CLI support functions shared between ktstr and cargo-ktstr.
cpu_util
CPU-affinity utilities shared across the crate.
ctprof
Per-thread ctprof (cgroup/thread profiler) data model + capture layer.
ctprof_compare
Group, aggregate, and render the comparison between two CtprofSnapshots.
export
cargo ktstr export — package a registered test as a self-extracting .run file that reproduces the scenario on bare metal without a VM.
fetch
Kernel source acquisition: tarball download, GitHub codeload snapshot, git clone, local tree.
flock
Advisory flock(2) primitives shared across every ktstr lock file.
fun
Fun mode — deterministically rename a JSON dump’s non-metric values to playful adjective-animal names (and hashed numeric IDs). Every non-metric value is funified by default: strings and integers under non-metric keys become a deterministic fun name, while values under metric-allowlisted keys (counts, rates, ratios, byte/duration units, structural enums) pass through unchanged. Structure and relationships are preserved — which keys nest where, which values co-refer — so agile-otter migrated from CPU 3 to CPU 7 reads the same, just with fun names. Deterministic per seed; a funify is a one-way rename.
gauntlet
Gauntlet topology presets.
host_context
Host runtime state captured at sidecar-write time.
host_heap
Heap-state snapshot for the running ktstr binary.
kernel_path
live_host
Public surface for the live-host introspection pipeline.
metric_types
Type-safe wrappers for per-thread metric values.
prelude
Re-exports for writing #[ktstr_test] functions.
remote_cache
Remote cache backend for GHA runners via opendal.
scenario
Scenario definitions and test execution.
test_support
Runtime support for #[ktstr_test] integration tests.
timeline
Stimulus/phase correlation for scenario execution.
topology
CPU topology abstraction.
verifier
BPF verifier log parsing, cycle detection, and output formatting.
worker_ready
Shared ready-marker path format for the ktstr-jemalloc-alloc-worker binary and the integration tests that drive it.
worker_ready_wait
Test-side poll helper for the worker ready marker. Separated from crate::worker_ready because this helper references crate::scenario::payload_run::PayloadHandle; the bin crate ktstr-jemalloc-alloc-worker pulls worker_ready.rs in via #[path] and must stay dependency-free (see that module’s doc for why). This module is library-only.
workload
Worker process management and telemetry.

Macros§

claim
Open a Verdict claim from a local binding or expression. The label is stringify!(<expr-tokens>) so a regression that renames the binding or alters the expression updates the rendered failure message in lock-step.
claim_present
Presence-checked sibling of claim! for a possibly-absent metric.
declare_scheduler
Function-style macro that registers a Scheduler const.
json
Convert JSON-like Rust tokens into a &'static str at compile time.

Constants§

EMBEDDED_KCONFIG
Contents of ktstr.kconfig (the kernel-config fragment that enables sched_ext, BPF, kprobes, cgroups, and the other options ktstr requires) baked into the binary at build time via include_str!. Consumed by the kernel build pipeline to olddefconfig a kernel source tree, and used to derive the cache key suffix so a kconfig change produces a fresh cache entry.
KTSTR_BUDGET_SECS_ENV
Name of the environment variable that overrides the per-test budget in seconds for VM-boot dispatch. Empty / unset falls back to the dispatcher’s default. Parsed as f64 seconds at crate::test_support::dispatch (accepts fractional values like 2.5); invalid or non-positive values surface a warn and the default applies.
KTSTR_BUSYBOX_PATH_ENV
Name of the environment variable that points at the busybox blob on-disk. Exported by cargo-ktstr’s startup install_env (see bin/cargo_ktstr/blobs.rs) which extracts the embedded BUSYBOX_BYTES to a tempfile and sets this var to the absolute path; read by crate::vmm::blobs::load_busybox_bytes. Both unset and set-but-empty surface a hard error, BUT the diagnostic differs: unset hits the Err(_) arm and surfaces the “blob is provided by cargo-ktstr at startup” install-env hint; empty hits the Ok("") arm and falls through to a generic fs::read("") ENOENT — less actionable. Operators invoking cargo ktstr <SUB> see neither case; raw cargo nextest run reliably triggers the unset diagnostic. Busybox is load-bearing for shell-mode VMs + disk-template builds.
KTSTR_BYPASS_LLC_LOCKS_ENV
Name of the environment variable that bypasses LLC resource locks at scenario setup (test_support::dispatch / cargo-ktstr shell). Set by the --bypass-llc-locks CLI flag.
KTSTR_CACHE_DIR_ENV
Name of the environment variable that overrides ktstr’s cache root directory (kernel-build cache, btf-anchor cache, blob cache, etc.). Empty / unset falls back to the per-user default (typically $HOME/.cache/ktstr). Heavy test usage — crate::test_support::test_helpers::IsolatedCacheDir sets it to a temp dir per-test so cache reads don’t leak host state into the test, and post-test the original value is restored via crate::test_support::test_helpers::EnvVarGuard.
KTSTR_CARGO_TEST_MODE_ENV
Name of the environment variable that signals ktstr is running in “cargo test” mode (raw test binary launched by cargo’s test harness, no orchestrator). Distinct from KTSTR_ORCHESTRATED_ENV which marks cargo-ktstr orchestration; KTSTR_CARGO_TEST_MODE is for narrower cases like in-process VMM tests that adapt their resource budgets when run via cargo test / cargo nextest. Read via crate::cargo_test_mode::cargo_test_mode_active: treats unset and empty as disabled; ANY non-empty value enables — no trim, no special-case strings ("0" and "false" ENABLE because they’re non-empty).
KTSTR_CGROUP_WALK_ROOT_ENV
Name of the environment variable that overrides the cgroup-fs root crate::cgroup::CgroupManager::setup walks down from when enabling controllers in every ancestor’s cgroup.subtree_control. Empty / unset falls back to /sys/fs/cgroup (the canonical cgroup-v2 mount). Non-empty value must be a prefix of KTSTR_HOST_CGROUP_PARENT_ENV’s configured parent so the walk stays inside the directory the operator owns; values that do not satisfy the prefix invariant are rejected upfront by crate::cgroup::CgroupManager::with_walk_root.
KTSTR_CONTENTION_BYPASS_ENV
Name of the environment variable that bypasses the contention guard at scenario setup. Strict v == "1" semantics (only the literal "1" enables; everything else disables). Used by tests that need to provoke contention scenarios without the production guard kicking in.
KTSTR_CPU_CAP_ENV
Name of the environment variable that caps the host CPU count the scenario engine sees, for testing scaling logic without a real CPU narrowing. Read at crate::vmm::host_topology and set by the --cpu-cap CLI flag in the bin entry points. Empty falls back to the host’s actual CPU count; non-empty numeric value caps the observed count.
KTSTR_GHA_CACHE_ENV
Name of the environment variable that enables the GitHub Actions remote-cache backend in crate::remote_cache. Read at cache- init time; value-typed — only the exact string "1" enables; unset / empty / any other value (including "true", "yes", "0", "false") is disabled. Set explicitly by GitHub Actions workflows when the runner has cache-API credentials; absent in dev environments where local-only caching is the right default.
KTSTR_GUEST_INIT_ENV
Name of the environment variable cargo-ktstr’s spawn-pipeline sets to “1” inside the guest-side init binary so the binary detects it’s running as the guest init. Presence check via var_os(...).is_none() at crate::workload::spawn — absent in host-side dispatch.
KTSTR_HOST_CGROUP_PARENT_ENV
Name of the environment variable that overrides the default host-mode cgroup parent (where host_only tests’ workload cgroups land). Empty / unset falls back to the canonical default; a non-empty value must be rooted under /sys/fs/cgroup and name a non-root subdirectory.
KTSTR_JEMALLOC_ALLOC_WORKER_BINARY_ENV
Name of the environment variable that points at a worker binary for jemalloc allocation-probe runs. Empty / unset leaves the worker binary unwired — same shape as KTSTR_JEMALLOC_PROBE_BINARY_ENV; the crate::test_support::runtime builder-wiring site calls .jemalloc_alloc_worker_binary() only on set+non-empty, no which-based fallback. Set alongside the probe via #[ctor] in tests/jemalloc_probe_tests.rs.
KTSTR_JEMALLOC_PROBE_BINARY_ENV
Name of the environment variable that points at a probe binary for jemalloc-feature detection. Empty / unset leaves the probe binary unwired (the crate::test_support::runtime builder-wiring site calls .jemalloc_probe_binary() only on set+non-empty — there is no which-based fallback). Tests that need the probe set this var via #[ctor] before the harness runs (see tests/jemalloc_probe_tests.rs).
KTSTR_KERNEL_COMMIT_ENV
Name of the environment variable cargo-ktstr sets to a dir=commit;dir=commit;... map of each resolved SOURCE kernel’s short commit hash (with a -dirty suffix when the tree is dirty), keyed by the same directory string exported in KTSTR_KERNEL_ENV / KTSTR_KERNEL_LIST_ENV.
KTSTR_KERNEL_ENV
KTSTR_* env-var empty-string contract
KTSTR_KERNEL_HINT
Shared skip / error hint for call sites that cannot proceed without a resolvable kernel. Phrased so the user sees the same wording regardless of which layer surfaced the failure — tests, CLI, monitor probes, and sidecar writers all point the operator at the same remediation. Referenced by the non-VM-boot skip paths in cache.rs, probe/btf.rs, monitor/mod.rs, test_support/eval/mod.rs, and test_support/mod.rs.
KTSTR_KERNEL_LIST_ENV
Name of the environment variable that carries the multi-kernel fan-out list across the cargo ktstrcargo nextest → test- binary boundary. Format: label1=path1;label2=path2;… (semicolon entry separator, = separates label from absolute kernel-dir path). Empty / unset means “single-kernel mode” — the test binary honours KTSTR_KERNEL_ENV directly.
KTSTR_KERNEL_PARALLELISM_ENV
Name of the environment variable that overrides the rayon pool width used by cargo ktstr’s resolve_kernel_set to fan out per-spec kernel resolves (download / git-clone / build) in parallel. Default cap is available_parallelism() — the host’s logical CPU count — chosen so download streams do not outnumber threads the host can drive without thrashing a contended local network (kernel.org CDN per-IP throttle, developer ISP, CI shared NIC).
KTSTR_LOCK_DIR_ENV
Name of the environment variable that overrides ktstr’s flock directory for inter-process resource locking (cpuset / LLC reservation locks). Empty / unset falls back to the hardcoded /tmp default at crate::cache::resolve::resolve_lock_dir (the literal string, not std::env::temp_dir() / TMPDIR resolution — historical default kept for stability). Used by tests + CI environments that need isolated lock-dirs.
KTSTR_LOG_PASSES_ENV
Name of the environment variable that opts into per-assertion PASS logging in the verdict pipeline. Read once per call at crate::assert::claim::Verdict::new via the log_passes_default helper in src/assert/claim.rs: the reader is !(v.is_empty() || v == "0"), so empty and the literal "0" disable; any other value ("1", "true", "yes", even "false" because it isn’t "0") enables. Unset → disabled. Default-off keeps the PASS path unallocated under normal runs.
KTSTR_NO_PERF_MODE_ENV
Name of the environment variable that forces ktstr to skip the perf_event_open access check + the perf_event_paranoid-relaxation gate. Read at scenario-engine startup (crate::test_support::runtime) and by the cargo ktstr shell / verifier dispatch sites that disable perf collection when the operator passes --no-perf-mode.
KTSTR_NO_SKIP_MODE_ENV
Name of the environment variable cargo-ktstr’s test dispatcher sets to disable the skip-on-contention test behavior. Presence check via var_os(...).is_some() — set to “1” by cargo ktstr test --no-skip-mode, absent otherwise.
KTSTR_ORCHESTRATED_ENV
Name of the environment variable cargo-ktstr sets to signal “this test process was launched by a cargo-ktstr orchestration path, not raw cargo nextest”. cargo-ktstr’s test and verifier subcommands set it to "1" before spawning the nextest child; the value content does not matter, only the presence — std::env::var(KTSTR_ORCHESTRATED_ENV).is_ok().
KTSTR_PERF_ONLY_ENV
Name of the environment variable that restricts a run to ONLY performance_mode tests: when set to a non-empty value, every test whose entry does not have performance_mode is skipped (skip sidecar recorded, libtest sees pass) before any VM boot. The mergebase perf-delta subcommand sets this so a regression run measures only the tests configured for clean performance numbers; an explicit nextest -E filter narrows further within the perf-mode set.
KTSTR_PROJECT_COMMIT_ENV
Name of the environment variable cargo-ktstr’s perf-delta sets to the PROJECT tree’s short commit hash (with a -dirty suffix when the tree is dirty) that the child’s sidecars must record as their project_commit. Unlike KTSTR_KERNEL_COMMIT_ENV this is a single value, not a dir=commit map — a child has exactly one project tree.
KTSTR_RUNS_ROOT_ENV
Name of the environment variable that pins the sidecar runs-root to an ABSOLUTE path, overriding the CWD-relative {CARGO_TARGET_DIR or "target"}/ktstr default of test_support::runs_root.
KTSTR_RUN_EPOCH_ENV
Name of the environment variable carrying the cargo ktstr test SESSION EPOCH: nanoseconds since the Unix epoch, stamped ONCE by the orchestrator (cargo_ktstr::run_cargo) before it spawns nextest, inherited by every per-test child process.
KTSTR_SCHEDULER_ALLOW_STALE_FALLBACK_ENV
Name of the presence-only opt-out env var that re-enables the pre-built-binary fallback after a FAILED orchestrated scheduler build. When set to a NON-EMPTY value, a failed cargo build -p <sched> in the non-cargo-test Discover path falls back to a sibling / target/{debug,release}/ binary AS-IS instead of failing the test. Default (unset / empty) REFUSES the stale fallback so a build that fails for a new reason cannot silently validate the test against an old scheduler. Empty-string rejection mirrors KTSTR_CARGO_TEST_MODE (cargo_test_mode_active) — NOT the presence-only KTSTR_ORCHESTRATED_ENV, which activates on an empty value — so a stray KTSTR_SCHEDULER_ALLOW_STALE_FALLBACK= cannot re-enable the hazard.
KTSTR_SCHEDULER_ENV
Name of the environment variable that overrides the scheduler binary path test_support::eval uses for in-process scheduler dispatch. Read at crate::test_support::eval. This is the COARSE (global) override: it applies to EVERY SchedulerSpec::Discover scheduler regardless of name, so a test declaring multiple distinct schedulers can’t point them at different binaries through it — use the per-name variant (per_name_scheduler_env) for that.
KTSTR_SCHEDULER_PROFILE_ENV
Name of the environment variable selecting the cargo build profile for a SchedulerSpec::Discover scheduler built on demand by build_and_find_binary. Holds a cargo profile NAME; unset / empty means the RELEASE default (see build_and_find_binary — a debug sched_ext scheduler is never the intended thing to test). Set by cargo ktstr <cmd> --profile <NAME> (on test / coverage / verifier / perf-delta / replay), or exported directly to pick a non-default profile. This is INDEPENDENT of the harness --release (--cargo-profile release to nextest), which selects the harness/test binary’s compile profile and does NOT touch this var — DECOUPLING the scheduler-under-test’s profile from the harness profile: the scheduler runs optimized by default while the harness keeps its dev-profile assertion thresholds and catch_unwind behavior unless its own build profile is set separately.
KTSTR_SIDECAR_DIR_ENV
Name of the environment variable that overrides the sidecar output directory (the per-test *.ktstr.json write target). Empty / unset falls back to the per-test target/ktstr/<run-id> location. Read at crate::test_support::sidecar + crate::cli::stats_cmds::dispatch (the stats reader).
KTSTR_STALL_POLL_MS_ENV
Name of the environment variable that overrides the poll cadence (in milliseconds) of the host-mode stall monitor in crate::scenario::host_stall.
KTSTR_TEST_KERNEL_ENV
Name of the environment variable that overrides the kernel path the eval dispatch reads (orthogonal to KTSTR_KERNEL_ENV which the main entry points use). Read at crate::test_support::eval::resolve_test_kernel: a set-but-empty KTSTR_TEST_KERNEL= surfaces a KTSTR_TEST_KERNEL not found: hard error (typo-loud per reader comment); ONLY the unset / Err(NotPresent) case falls through to crate::find_kernel() (cache + sysroot probes), which themselves fall through to a KernelUnavailable error hinting at both KTSTR_TEST_KERNEL and KTSTR_KERNEL.
KTSTR_VERBOSE_ENV
Name of the environment variable that triggers verbose logging in the VMM setup phase. Strict v == "1" semantics (only the literal "1" enables; unset / empty / any other value — including "true", "yes", "0" — is disabled). Read in crate::vmm::setup at the two cmdline-assembly sites (one per arch: x86_64 and aarch64); both readers identical.
KTSTR_VERIFIER_RAW_ENV
Name of the environment variable that switches the cargo ktstr verifier per-cell handler from the cycle-collapsed default rendering to a raw scheduler-log dump. Set to any value (the presence of the variable is what matters; the value is ignored) by the dispatcher in src/bin/cargo_ktstr/verifier.rs when the operator passes --raw, and read by crate::test_support::dispatch::run_verifier_cell before formatting via crate::verifier::format_verifier_output.
KTSTR_VERIFIER_RESULT_DIR_ENV
Name of the environment variable carrying the directory that each cargo ktstr verifier cell writes its per-cell PASS/FAIL record to. The cargo ktstr verifier dispatcher creates the dir, exports this var (inherited by the spawned cargo nextest run and thus by every cell process), and after nextest returns reads the records back to render the per-(topology × scheduler) summary grid. Unset when a verifier cell runs outside the dispatcher (a hand-driven --exact verifier/...): the cell then simply skips the record write. Single source of truth so the name is not spelled by hand at the writer (cell) and reader (dispatcher) ends.
KTSTR_VERIFIER_SCHEDULER_ENV
Name of the environment variable carrying the operator’s cargo ktstr verifier --scheduler <NAME> filter. Set by the dispatcher in src/bin/cargo_ktstr/verifier.rs; read by crate::test_support::dispatch’s verifier cell emission, which skips every declared scheduler whose name does not equal the value so the sweep runs one scheduler across topologies instead of the full declared-scheduler matrix. Unset, every declared scheduler is swept. Single source of truth so the writer (dispatcher) and reader (emission) do not spell the name by hand.
KTSTR_WPROF_PATH_ENV
WPROF_MIN_MEMORY_MIB
Minimum guest memory (MiB) for test entries that enable wprof.

Functions§

apply_wprof_memory_floor
Apply the wprof memory floor to a raw memory size.
build_and_find_binary
Build a cargo binary package and return its output path.
cache_key_suffix
Cache key suffix derived from the embedded kconfig fragment. Used in kernel cache keys so a kconfig change produces a distinct cache entry. The kernel binary is independent of ktstr userspace source, so no ktstr or consumer build identity feeds this suffix.
cache_key_suffix_with_extra
Two-segment cache key suffix accounting for an optional --extra-kconfig fragment.
extra_kconfig_hash
CRC32 hash (8 hex chars) of a user-supplied --extra-kconfig fragment, hashed verbatim.
find_kernel
Find a bootable kernel image on the host.
kconfig_hash
CRC32 hash of the embedded kconfig fragment (8 hex chars).
ktstr_kernel_env
Read KTSTR_KERNEL_ENV once, normalizing the raw value: missing / empty / whitespace-only reads collapse to None, and a surrounding-whitespace trim is applied so a shell-quoted KTSTR_KERNEL=" ../linux" behaves the same as the unquoted form. Every caller that reads the env var should route through this helper so the normalization rules live in one place; a future change to the rules (e.g. accepting a trailing slash) propagates to every site automatically.
merge_kconfig_fragments
Merge the user-supplied --extra-kconfig fragment on top of EMBEDDED_KCONFIG for the configure pass. Returns a std::borrow::Cow so the no-extras branch borrows baked without allocating; only the Some branch heaps the merged String.
per_name_scheduler_env
Per-scheduler-NAME override environment variable for a SchedulerSpec::Discover(name) scheduler: KTSTR_SCHEDULER_BIN_<NAME>, where <NAME> is the discover name uppercased with every non-alphanumeric character replaced by _ (e.g. scx_layered -> KTSTR_SCHEDULER_BIN_SCX_LAYERED, scx-ktstr -> KTSTR_SCHEDULER_BIN_SCX_KTSTR).
precompute_cast_analysis
Pre-populate the on-disk cast analysis cache for a scheduler binary.
read_kmsg
Read the kernel ring buffer (equivalent to dmesg --notime). Exposed as pub so scenario tests that need to assert on kernel-log content (e.g. the sched_ext stall duration emitted by scx_exit(SCX_EXIT_ERROR_STALL) in kernel/sched/ext.c) can read the same buffer the framework captures into AssertResult::details on scheduler-died failures.
resolve_func_ip
Resolve a kernel function name to its address via /proc/kallsyms.
run_shell
Boot a KVM VM in interactive shell mode.
scheduler_profile_name
The cargo build profile NAME for the scheduler-under-test: KTSTR_SCHEDULER_PROFILE_ENV when set non-empty, else the "release" default. Single source of the default so build_and_find_binary (which builds it) and the Discover fallback probe (which locates a pre-built one) never disagree on which target/<dir>/ the scheduler lands in.
send_kmsg
Forward the guest’s /dev/kmsg ring buffer to the host over the bulk port, so a host-side post_vm callback can read it via VmResult::guest_kmsg. Mirrors read_kmsg: that reads the ring buffer in the guest process; this forwards the bytes (typically read_kmsg().as_bytes()) to the host. The scx_exit SCX_EXIT_ERROR_STALL printk lands in /dev/kmsg but is suppressed from the COM1 console at the default loglevel=0, so it never reaches VmResult::stderr; this forward is the only host-visible path to it.

Attribute Macros§

distributed_slice
linkme::distributed_slice re-exported as part of ktstr’s public surface. Combined with crate::linkme for the #[linkme(crate = ...)] annotation, this lets a downstream crate register entries into KTSTR_TESTS or KTSTR_SCHEDULERS without adding linkme as a direct Cargo dependency:
ktstr_test
Attribute macro that registers a function as a ktstr integration test.

Derive Macros§

Claim
Generate per-field claim accessors on a stats struct.
Payload
Derive macro that generates a Payload const from an annotated struct for a userspace binary workload (stress-ng, fio, and similar tools test authors compose under a scheduler).