ktstr/test_support/entry.rs
1//! `#[ktstr_test]` entry registration and scheduler configuration.
2//!
3//! Every `#[ktstr_test]` proc-macro expansion writes a static
4//! [`KtstrTestEntry`] into [`KTSTR_TESTS`] via `linkme`; programmatic
5//! callers can do the same by pushing their own `KtstrTestEntry` values
6//! into the slice. [`find_test`] is the name-to-entry lookup used by
7//! host-side dispatch.
8//!
9//! Each entry points at a [`Scheduler`] definition — a `&'static` value
10//! that captures the scheduler binary ([`SchedulerSpec`]), guest
11//! [`Sysctl`]s, kernel args, [`CgroupPath`] parent, topology and
12//! [`TopologyConstraints`], and monitor assertions. [`BpfMapWrite`]
13//! describes a host-side map write the runtime performs mid-run.
14
15use anyhow::Result;
16use linkme::distributed_slice;
17use std::time::Duration;
18
19use crate::assert::AssertResult;
20use crate::scenario::Ctx;
21
22/// Re-exports of topology types for use in [`KtstrTestEntry`] statics
23/// generated by the `#[ktstr_test]` macro.
24pub use crate::vmm::topology::{MemSideCache, NumaDistance, NumaNode, Topology};
25
26/// How to specify the scheduler for an `#[ktstr_test]`.
27///
28/// The four variants form a semantic taxonomy, not a syntactic one:
29/// [`Eevdf`](Self::Eevdf) is the no-scx control ("kernel default,
30/// don't launch anything"); [`Discover`](Self::Discover) and
31/// [`Path`](Self::Path) both locate a userspace scheduler binary, by
32/// name-lookup vs. explicit filesystem path respectively; and
33/// [`KernelBuiltin`](Self::KernelBuiltin) activates an in-kernel
34/// scheduling policy via shell commands rather than any binary.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub enum SchedulerSpec {
37 /// No userspace scheduler — run under the kernel's default
38 /// scheduler. On current kernels that's EEVDF; the variant
39 /// name is fixed so the assertion isn't coupled to the kernel
40 /// version's default.
41 Eevdf,
42 /// Auto-discover the scheduler binary by name (the
43 /// `KTSTR_SCHEDULER` env override, then in cargo-test mode a
44 /// `$PATH` lookup, otherwise `cargo build -p <name>` in the
45 /// declaring crate's workspace).
46 Discover(&'static str),
47 /// Explicit filesystem path to a scheduler binary. The file must
48 /// already exist; `resolve_scheduler` does not auto-build this
49 /// variant.
50 Path(&'static str),
51 /// Kernel-built scheduler (e.g. BPF-less sched_ext or
52 /// debugfs-tuned). Activated/deactivated via shell commands
53 /// rather than a userspace binary.
54 KernelBuiltin {
55 /// Shell commands invoked before the scenario runs to switch
56 /// the kernel into this scheduling policy (e.g. write to
57 /// `/sys/kernel/debug/sched/...`).
58 enable: &'static [&'static str],
59 /// Shell commands invoked after the scenario finishes to
60 /// restore the kernel's baseline scheduling policy.
61 disable: &'static [&'static str],
62 },
63}
64
65impl SchedulerSpec {
66 /// Whether this spec represents an active scheduling policy
67 /// (anything other than the kernel default EEVDF).
68 ///
69 /// Returns `true` for every variant except [`Self::Eevdf`] —
70 /// including [`Self::KernelBuiltin`], which runs an in-kernel
71 /// non-default policy via shell enable/disable commands but
72 /// has no userspace BPF binary. Callers that need "the test
73 /// runs SOMETHING other than EEVDF" — e.g. enabling
74 /// repro-section render, switching verbose-output mode on,
75 /// gating non-default-only logic — want this method.
76 ///
77 /// Callers that need "the test runs a userspace BPF
78 /// scheduler binary with verifier-stats / struct_ops slab
79 /// activity" — e.g. wiring monitor thresholds, surfacing
80 /// `verifier_stats` warnings, gating the auto-repro probe —
81 /// want the narrower [`Self::has_bpf_scheduler`] instead.
82 /// `has_active_scheduling` returns `true` for `KernelBuiltin`,
83 /// which is the wrong gate for any code path that assumes a
84 /// BPF binary is attached.
85 ///
86 /// Quick gate-picker: use `has_active_scheduling` when the
87 /// predicate is "non-default scheduling policy"; use
88 /// [`Self::has_bpf_scheduler`] when the predicate is
89 /// "userspace BPF binary attached".
90 pub const fn has_active_scheduling(&self) -> bool {
91 !matches!(self, SchedulerSpec::Eevdf)
92 }
93
94 /// Whether this spec drives a userspace BPF scheduler binary
95 /// (i.e. attaches a `struct sched_ext_ops` to the kernel).
96 ///
97 /// Returns `true` for [`Self::Discover`] and [`Self::Path`] —
98 /// both variants point at a userspace BPF binary that
99 /// `resolve_scheduler` locates and launches. Returns `false`
100 /// for [`Self::Eevdf`] (no scheduler) and [`Self::KernelBuiltin`]
101 /// (in-kernel policy switched via shell commands, no userspace
102 /// binary, no BPF verifier output, no struct_ops slab activity).
103 ///
104 /// Distinct from [`Self::has_active_scheduling`]: that returns
105 /// `true` for `KernelBuiltin` too (because the kernel IS running
106 /// a non-default scheduling policy), which is the wrong gate
107 /// for code paths that read `verifier_stats`, wire BPF-attach
108 /// monitor thresholds, or probe for the userspace scheduler
109 /// binary's auto-repro hooks. Use this method whenever the
110 /// downstream consumer assumes "BPF binary is loaded and
111 /// running" rather than "the kernel is on a non-EEVDF policy".
112 pub const fn has_bpf_scheduler(&self) -> bool {
113 matches!(self, SchedulerSpec::Discover(_) | SchedulerSpec::Path(_))
114 }
115
116 /// Short, human-readable name for logging and sidecar output.
117 ///
118 /// Maps `Eevdf` → `"eevdf"`, `Discover(n)` → `n`, `Path(p)` → `p`,
119 /// `KernelBuiltin { .. }` → `"kernel"`. Single source of truth
120 /// for "what do we call this scheduler when telling the user" —
121 /// sidecar serialization and failure-header formatting both use
122 /// this, and any future consumer gets identical naming for free.
123 pub const fn display_name(&self) -> &'static str {
124 match self {
125 SchedulerSpec::Eevdf => "eevdf",
126 SchedulerSpec::Discover(n) => n,
127 SchedulerSpec::Path(p) => p,
128 SchedulerSpec::KernelBuiltin { .. } => "kernel",
129 }
130 }
131
132 /// Best-effort git commit of the scheduler binary used for this
133 /// run, or `None` when the commit cannot be determined honestly.
134 ///
135 /// Currently ALWAYS returns `None`. The field is reserved on the
136 /// sidecar schema so stats tooling can enrich it once a reliable
137 /// source exists, but no variant today has one:
138 ///
139 /// - `Eevdf` — no userspace scheduler binary at all. Kernel
140 /// default; the running kernel's identity belongs in
141 /// `host.kernel_release`, not here.
142 /// - `Discover(_)` — `resolve_scheduler` resolves via three
143 /// steps (`KTSTR_SCHEDULER` env override → cargo-test-mode
144 /// `$PATH` lookup → `cargo build -p <name>`). Only the build
145 /// path guarantees the resulting binary was built from the
146 /// current tree; the env-override and `$PATH` paths can point
147 /// at a binary whose commit is unknown to this process.
148 /// Synthesizing a commit would be a lie in 2 of 3 cases and
149 /// would silently attribute regressions to the wrong commit.
150 /// A future
151 /// enhancement can probe the binary itself (e.g.
152 /// `--version` output, an ELF note) and return `Some(..)`
153 /// ONLY when the actual commit is introspected; until then,
154 /// `None` is the only honest answer.
155 /// - `Path(p)` — arbitrary externally-built binary. No
156 /// reliable introspection path (no shared ABI, no required
157 /// `--version` format).
158 /// - `KernelBuiltin` — in-kernel scheduler, no userspace
159 /// binary commit to record.
160 ///
161 /// Returning `None` rather than `Some("unknown")` keeps the
162 /// sidecar schema's nullable semantics honest: `perf-delta`
163 /// distinguishes "unset" from "set to a sentinel" without a
164 /// magic string, and a future enhancement that learns to
165 /// introspect a scheduler binary can flip a single arm to
166 /// `Some(..)` without retrofitting consumers to strip a
167 /// sentinel.
168 pub const fn scheduler_commit(&self) -> Option<&'static str> {
169 match self {
170 SchedulerSpec::Eevdf
171 | SchedulerSpec::Discover(_)
172 | SchedulerSpec::Path(_)
173 | SchedulerSpec::KernelBuiltin { .. } => None,
174 }
175 }
176}
177
178/// A `key=value` sysctl applied to the guest before the scheduler
179/// starts, injected into the guest kernel cmdline as
180/// `sysctl.<key>=<value>`.
181///
182/// Use the **dot-separated** form for `key` (e.g. `"kernel.foo"`, not
183/// `"kernel/foo"`). Duplicate keys in a scheduler's sysctls slice are
184/// applied in order; the last write wins.
185///
186/// Construct with [`Sysctl::new`], which const-asserts the key format
187/// at compile time. Direct struct-literal construction is rejected
188/// (fields are crate-private) to ensure every constructed `Sysctl`
189/// passed through the format gate.
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191pub struct Sysctl {
192 key: &'static str,
193 value: &'static str,
194}
195
196impl Sysctl {
197 /// Const constructor for use in `static`/`const` context.
198 ///
199 /// # Panics
200 ///
201 /// Panics at compile time (or const-eval time) when:
202 /// - `key` is empty
203 /// - `key` contains `/` (common typo from sysctl conf-file paths —
204 /// sysctl-write uses the dotted form, not the slash form)
205 /// - `key` contains whitespace, `=`, or any control byte
206 /// (would corrupt the `sysctl.<key>=<value>` cmdline form)
207 /// - `key` does not contain at least one `.` (sysctls are
208 /// namespaced like `kernel.foo` / `net.core.bar`; a bare
209 /// single-segment name is almost certainly a typo)
210 /// - `key` starts or ends with `.`
211 /// - `key` contains an empty segment (`..` — kernel sysctl
212 /// parser rejects)
213 /// - `value` is empty
214 /// - `value` contains a newline / carriage return / `=`
215 /// (would corrupt the `sysctl.<key>=<value>` cmdline form)
216 pub const fn new(key: &'static str, value: &'static str) -> Self {
217 let key_bytes = key.as_bytes();
218 assert!(!key_bytes.is_empty(), "Sysctl key must not be empty");
219 assert!(
220 key_bytes[0] != b'.' && key_bytes[key_bytes.len() - 1] != b'.',
221 "Sysctl key must not start or end with `.`",
222 );
223 let mut i = 0;
224 let mut has_dot = false;
225 let mut prev = 0u8;
226 while i < key_bytes.len() {
227 let b = key_bytes[i];
228 assert!(
229 b != b'/',
230 "Sysctl key must use the dotted form (e.g. `kernel.foo`), not the slash form (`kernel/foo`)",
231 );
232 assert!(
233 b != b' ' && b != b'\t' && b != b'\n' && b != b'\r',
234 "Sysctl key must not contain whitespace (would corrupt cmdline form)",
235 );
236 assert!(
237 b != b'=',
238 "Sysctl key must not contain `=` (would corrupt `sysctl.<key>=<value>` cmdline split)",
239 );
240 assert!(
241 b >= 0x20 && b < 0x7f,
242 "Sysctl key must be printable ASCII only (no control bytes / high-bit chars)",
243 );
244 if b == b'.' {
245 has_dot = true;
246 assert!(
247 i == 0 || prev != b'.',
248 "Sysctl key must not contain `..` (empty segment — kernel sysctl parser rejects)",
249 );
250 }
251 prev = b;
252 i += 1;
253 }
254 assert!(
255 has_dot,
256 "Sysctl key must be namespaced (contain at least one `.`, e.g. `kernel.foo`)",
257 );
258 let value_bytes = value.as_bytes();
259 assert!(!value_bytes.is_empty(), "Sysctl value must not be empty");
260 let mut j = 0;
261 while j < value_bytes.len() {
262 let b = value_bytes[j];
263 assert!(
264 b != b'\n',
265 "Sysctl value must not contain a newline (would corrupt cmdline form)",
266 );
267 assert!(
268 b != b'\r',
269 "Sysctl value must not contain a carriage return (would corrupt cmdline form)",
270 );
271 assert!(
272 b != b'=',
273 "Sysctl value must not contain `=` (would corrupt `sysctl.<key>=<value>` cmdline form)",
274 );
275 j += 1;
276 }
277 Self { key, value }
278 }
279
280 /// The validated dotted sysctl key (e.g. `"kernel.sched_cfs_bandwidth_slice_us"`).
281 pub const fn key(&self) -> &'static str {
282 self.key
283 }
284
285 /// The validated sysctl value, written as a string.
286 pub const fn value(&self) -> &'static str {
287 self.value
288 }
289}
290
291/// Validated cgroup parent path.
292///
293/// Wraps a `&'static str` that is guaranteed to start with `/` and not
294/// be `"/"` alone. Construct via [`CgroupPath::new`] (which const-panics
295/// on invalid input) or the [`Scheduler::cgroup_parent`] builder.
296#[derive(Debug, Clone, Copy, PartialEq, Eq)]
297pub struct CgroupPath(&'static str);
298
299impl CgroupPath {
300 /// Const constructor. Mirrors the runtime gate in
301 /// `test_support::args::cell_parent_path_is_valid` byte-for-byte.
302 /// `Path::components` and `Components` are not yet const-fn
303 /// reachable, so the walk iterates bytes directly via a stable
304 /// `while` loop.
305 ///
306 /// So `cgroup_parent = "/foo/.."` panics at const-eval just as
307 /// `--cell-parent-cgroup=/foo/..` panics at test setup; the two
308 /// share validation contract, and the asymmetry that would
309 /// otherwise exist (const-fn rejecting `/foo/./bar` while the
310 /// runtime accepts it) is eliminated by the auto-strip rule.
311 ///
312 /// # Panics
313 ///
314 /// Panics at compile time (or const-eval time) when `path` would
315 /// normalize back to (or escape) the host cgroup root once
316 /// concatenated with `/sys/fs/cgroup` and canonicalized by the
317 /// kernel:
318 ///
319 /// - must start with `/`
320 /// - must not contain any `..` (ParentDir) segments
321 /// - must contain at least one non-`.`, non-empty segment
322 /// - empty segments (consecutive `/`) and `.` (CurDir) segments
323 /// are auto-stripped, matching `Path::components` semantics
324 /// used by the runtime validator
325 pub const fn new(path: &'static str) -> Self {
326 assert!(
327 !path.is_empty() && path.as_bytes()[0] == b'/',
328 "CgroupPath must begin with '/' (e.g. \"/ktstr\")"
329 );
330 assert!(
331 path.len() > 1,
332 "CgroupPath must not be \"/\" alone (that is the cgroup root)"
333 );
334 let bytes = path.as_bytes();
335 let mut seg_start: usize = 1; // skip leading `/`
336 let mut i: usize = 1;
337 let mut has_normal = false;
338 while i <= bytes.len() {
339 let at_end = i == bytes.len();
340 if at_end || bytes[i] == b'/' {
341 let seg_len = i - seg_start;
342 let is_dotdot =
343 seg_len == 2 && bytes[seg_start] == b'.' && bytes[seg_start + 1] == b'.';
344 assert!(
345 !is_dotdot,
346 "CgroupPath must not contain `..` segments \
347 (they escape `/sys/fs/cgroup` once the kernel \
348 canonicalizes the resolved path)"
349 );
350 let is_empty_or_dot = seg_len == 0 || (seg_len == 1 && bytes[seg_start] == b'.');
351 if !is_empty_or_dot {
352 has_normal = true;
353 }
354 seg_start = i + 1;
355 }
356 i += 1;
357 }
358 assert!(
359 has_normal,
360 "CgroupPath must contain at least one non-`.`/non-empty segment \
361 (paths like `/`, `///`, or `/.` normalize back to `/sys/fs/cgroup`)"
362 );
363 Self(path)
364 }
365
366 /// The raw path string (e.g. `"/ktstr"`).
367 pub const fn as_str(&self) -> &'static str {
368 self.0
369 }
370
371 /// The full sysfs cgroup directory (e.g. `"/sys/fs/cgroup/ktstr"`).
372 pub fn sysfs_path(&self) -> String {
373 format!("/sys/fs/cgroup{}", self.0)
374 }
375}
376
377impl std::ops::Deref for CgroupPath {
378 type Target = str;
379 fn deref(&self) -> &str {
380 self.0
381 }
382}
383
384impl std::fmt::Display for CgroupPath {
385 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
386 f.write_str(self.0)
387 }
388}
389
390/// Host-side BPF map write performed during VM execution.
391///
392/// Applied by the host thread `freeze_coord::start_bpf_map_write` in three
393/// phases: build the guest-memory BPF-map accessor, resolve the `field`
394/// NAME to a byte offset via the target map's program BTF, then write.
395/// After the writes the host pushes `SIGNAL_BPF_WRITE_DONE` through
396/// virtio-console (`host_comms::request_bpf_map_write_done`) so a guest
397/// scenario gated on `Ctx::wait_for_map_write` unblocks.
398///
399/// Construct with [`BpfMapWrite::new`], which const-asserts the
400/// `map_name_suffix` format at compile time. Direct struct-literal
401/// construction is rejected (fields are crate-private) so every
402/// constructed `BpfMapWrite` passes through the format gate.
403#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
404pub struct BpfMapWrite {
405 map_name_suffix: &'static str,
406 field: &'static str,
407 value: u32,
408}
409
410impl BpfMapWrite {
411 /// Const constructor for use in `static`/`const` context.
412 ///
413 /// # Panics
414 ///
415 /// Panics at compile time (or const-eval time) when:
416 /// - `map_name_suffix` is empty
417 /// - `map_name_suffix` does not start with `.` (BPF map names
418 /// are derived from ELF section names like `.bss`, `.data`,
419 /// `.rodata`; a suffix without the leading `.` would never
420 /// match any loaded map and is almost certainly a typo)
421 /// - `map_name_suffix` is a bare `.` or starts with `..`
422 /// (no real BPF section name has that shape)
423 /// - `map_name_suffix` contains whitespace, `/`, `\`, or any
424 /// non-printable / control byte (no real BPF map name carries
425 /// those characters; NULL would truncate libbpf C-string
426 /// comparison)
427 /// - `field` is empty (it names the VAR to write — a bare `.bss`/`.data`
428 /// global like `"crash"`, or a dot-path into the value struct; the
429 /// byte offset is resolved from the map's BTF value type at write
430 /// time, so a raw offset can never land in struct padding)
431 /// - `field` starts or ends with `.`, or contains `..` (an empty
432 /// path segment the BTF resolver could never match)
433 /// - `field` contains whitespace, `/`, `\`, or any non-printable /
434 /// control byte (no real BTF VAR name carries those characters)
435 pub const fn new(map_name_suffix: &'static str, field: &'static str, value: u32) -> Self {
436 let bytes = map_name_suffix.as_bytes();
437 assert!(
438 !bytes.is_empty(),
439 "BpfMapWrite map_name_suffix must not be empty"
440 );
441 assert!(
442 bytes[0] == b'.',
443 "BpfMapWrite map_name_suffix must start with `.` (BPF map suffixes match ELF section names like `.bss`, `.data`, `.rodata`)",
444 );
445 assert!(
446 bytes.len() >= 2,
447 "BpfMapWrite map_name_suffix must be longer than a bare `.` (no real BPF section name is just `.`)",
448 );
449 assert!(
450 bytes[1] != b'.',
451 "BpfMapWrite map_name_suffix must not start with `..` (no real BPF section name has that shape)",
452 );
453 let mut i = 0;
454 while i < bytes.len() {
455 let b = bytes[i];
456 assert!(
457 b != b' ' && b != b'\t' && b != b'\n' && b != b'\r',
458 "BpfMapWrite map_name_suffix must not contain whitespace",
459 );
460 assert!(
461 b != b'/' && b != b'\\',
462 "BpfMapWrite map_name_suffix must not contain path separators",
463 );
464 assert!(
465 b >= 0x20 && b < 0x7f,
466 "BpfMapWrite map_name_suffix must be printable ASCII only (no control bytes / NULL / high-bit chars)",
467 );
468 i += 1;
469 }
470 // `field` names a VAR in the map's BTF value type — a bare global
471 // like `crash`, or a dot-path into the value struct
472 // (`sys_stat.avg_lat_cri`); the write-time resolver
473 // (`resolve_map_field_offset_width`) maps it to a byte offset. Mirror
474 // the WatchBpfMap::field gate (both feed the same resolver): non-empty,
475 // printable ASCII, no whitespace, no path separators. `.` IS allowed
476 // but must separate non-empty segments, so reject a leading / trailing
477 // / doubled `.` — an empty segment the resolver could never match. No
478 // leading-`.` section rule here (a VAR path is not a section name).
479 let fb = field.as_bytes();
480 assert!(!fb.is_empty(), "BpfMapWrite field must not be empty");
481 assert!(
482 fb[0] != b'.' && fb[fb.len() - 1] != b'.',
483 "BpfMapWrite field must not start or end with `.` (empty path segment)",
484 );
485 let mut j = 0;
486 while j < fb.len() {
487 let b = fb[j];
488 assert!(
489 b != b' ' && b != b'\t' && b != b'\n' && b != b'\r',
490 "BpfMapWrite field must not contain whitespace",
491 );
492 assert!(
493 b != b'/' && b != b'\\',
494 "BpfMapWrite field must not contain path separators",
495 );
496 assert!(
497 !(b == b'.' && j > 0 && fb[j - 1] == b'.'),
498 "BpfMapWrite field must not contain `..` (empty path segment)",
499 );
500 assert!(
501 b >= 0x20 && b < 0x7f,
502 "BpfMapWrite field must be printable ASCII only (no control bytes / NULL / high-bit chars)",
503 );
504 j += 1;
505 }
506 Self {
507 map_name_suffix,
508 field,
509 value,
510 }
511 }
512
513 /// The validated map-name suffix to match against loaded BPF maps
514 /// (e.g. `".bss"`).
515 pub const fn map_name_suffix(&self) -> &'static str {
516 self.map_name_suffix
517 }
518
519 /// The field to write within the matched map's value region: a bare
520 /// BTF VAR name (e.g. `"crash"`) or a dot-path into the value struct
521 /// (e.g. `"sys_stat.avg_lat_cri"`). The byte offset is resolved from
522 /// the map's BTF value type at write time.
523 pub const fn field(&self) -> &'static str {
524 self.field
525 }
526
527 /// u32 value to write into `field` inside the matched map.
528 pub const fn value(&self) -> u32 {
529 self.value
530 }
531}
532
533/// Aggregation for a [`WatchBpfMap`] target.
534///
535/// Picks how a watched field's per-tick reads collapse into run-level
536/// metric key(s). Choose by the field's semantic class: a GAUGE (a current
537/// level — fold as the mean) vs a monotonic COUNTER (an accumulating total —
538/// fold as the final value).
539#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
540pub enum BpfMapAgg {
541 /// A single scalar GAUGE field (e.g. a `.bss` global struct member like
542 /// `sys_stat.avg_lat_cri` — a current level such as latency-criticality
543 /// or headroom). Emits ONE metric key (`<prefix>_<label>`), folded as the
544 /// mean over the run's reporting samples. For a monotonic counter use
545 /// [`BpfMapAgg::ScalarCounter`] instead — a rising counter mean-folded
546 /// here reports a window-average below its final total.
547 Scalar,
548 /// A single scalar monotonic COUNTER field (e.g. a `.bss` global like
549 /// `ktstr_alloc_count` bumped via `__sync_fetch_and_add`). Emits ONE
550 /// metric key (`<prefix>_<label>`), folded as the value at the LAST
551 /// reporting sample — the accumulated total at the end of the monitoring
552 /// window, which is the meaningful count (not the mean of a rising
553 /// series).
554 ScalarCounter,
555 /// A per-CPU array field (a `BPF_MAP_TYPE_PERCPU_ARRAY` value member,
556 /// e.g. `cpu_ctx_stor.lat_headroom`). Emits TWO metric keys: the
557 /// cross-CPU mean (`<prefix>_<label>_avg`) and the cross-CPU spatial
558 /// max (`<prefix>_<label>_max`), each folded over the run's reporting
559 /// samples. The divisor is the count of CPUs that reported a value,
560 /// never the topology CPU count.
561 PerCpu,
562 /// A per-CPU array field that is a monotonic COUNTER (each CPU's slot
563 /// rises independently, e.g. a `BPF_MAP_TYPE_PERCPU_ARRAY` per-CPU event
564 /// tally). Emits ONE metric key (`<prefix>_<label>`), folded as the
565 /// CROSS-CPU SUM at the LAST reporting sample — the accumulated total
566 /// across all (reporting) CPUs at the end of the monitoring window, and
567 /// SUM-folded across runs like [`BpfMapAgg::ScalarCounter`]. Watch at u64
568 /// width: a too-narrow width truncates each per-CPU slot before the sum.
569 /// An offline CPU's accumulated count is excluded (only CPUs whose per-CPU
570 /// page is readable contribute). Use this for a rising per-CPU counter;
571 /// [`BpfMapAgg::PerCpu`] mean/max-folds (a gauge) and
572 /// [`BpfMapAgg::ScalarCounter`] is for a single scalar, not a per-CPU array.
573 PerCpuCounter,
574}
575
576/// Host-side, observer-effect-free read of a NAMED scheduler BPF-map field,
577/// surfaced as an assertable run-level metric.
578///
579/// The free-running host monitor resolves the field once (lazily, after the
580/// scheduler attaches and its maps appear) via BTF, then reads it each
581/// monitor tick WITHOUT freezing the guest — turning "the scheduler computed
582/// X" into an assertable metric. Read via
583/// [`crate::vmm::result::VmResult::run_metric`] under the key
584/// `<scheduler-obj>_<label>` (scalar, scalar-counter, or per-CPU-counter) or
585/// `<scheduler-obj>_<label>_{avg,max}` (per-CPU gauge), e.g.
586/// `scx_lavd_avg_lat_cri`, `scx_lavd_lat_headroom_avg`.
587/// `<scheduler-obj>` is libbpf's object name for the active scheduler, which
588/// can differ from its source / ops name (e.g. scx-ktstr's object is
589/// `bpf_bpf`). Each target's `label` must be unique within a test: duplicate
590/// labels resolve to one metric key and are rejected at VM build time.
591///
592/// Construct with [`WatchBpfMap::new`], which const-asserts the field
593/// formats at compile time. Direct struct-literal construction is rejected
594/// (fields are crate-private) so every constructed value passes the gate.
595#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
596pub struct WatchBpfMap {
597 map_name_suffix: &'static str,
598 field: &'static str,
599 agg: BpfMapAgg,
600 label: &'static str,
601}
602
603impl WatchBpfMap {
604 /// Const constructor for use in `static`/`const` context.
605 ///
606 /// `map_name_suffix` matches a loaded BPF map by `ends_with` (kernel map
607 /// names truncate to 15 bytes). Unlike [`BpfMapWrite::new`] it does NOT
608 /// require a leading `.`: a watched map may be a section map (`.bss`)
609 /// OR a named map (`cpu_ctx_stor`). `field` is a dot-path into the map's
610 /// value type (`sys_stat.avg_lat_cri`, or a bare `lat_headroom`).
611 /// `label` is the metric-key leaf appended to the scheduler-obj prefix.
612 ///
613 /// # Panics
614 ///
615 /// Panics at compile time when any of `map_name_suffix` / `field` /
616 /// `label` is empty or carries whitespace, a path separator (`/`, `\`),
617 /// or a non-printable / control / high-bit byte. Additionally `field`
618 /// may not have a leading/trailing `.` or a doubled `..` (an empty path
619 /// segment the resolver could never match), and `label` may not contain
620 /// `.` at all (it is a single metric-key leaf, not a path).
621 pub const fn new(
622 map_name_suffix: &'static str,
623 field: &'static str,
624 agg: BpfMapAgg,
625 label: &'static str,
626 ) -> Self {
627 // map_name_suffix: non-empty, printable, no whitespace / separators.
628 // No leading-`.` requirement (matches both `.bss` and `cpu_ctx_stor`).
629 let s = map_name_suffix.as_bytes();
630 assert!(
631 !s.is_empty(),
632 "WatchBpfMap map_name_suffix must not be empty"
633 );
634 let mut i = 0;
635 while i < s.len() {
636 let b = s[i];
637 assert!(
638 b != b' ' && b != b'\t' && b != b'\n' && b != b'\r',
639 "WatchBpfMap map_name_suffix must not contain whitespace",
640 );
641 assert!(
642 b != b'/' && b != b'\\',
643 "WatchBpfMap map_name_suffix must not contain path separators",
644 );
645 assert!(
646 b >= 0x20 && b < 0x7f,
647 "WatchBpfMap map_name_suffix must be printable ASCII only",
648 );
649 i += 1;
650 }
651 // field: non-empty, printable, no whitespace / separators. `.` IS
652 // allowed (dot-path into the value struct) but must separate non-empty
653 // segments — a leading / trailing / doubled `.` is an empty segment
654 // the resolver could never match, so reject it at compile time.
655 let f = field.as_bytes();
656 assert!(!f.is_empty(), "WatchBpfMap field must not be empty");
657 assert!(
658 f[0] != b'.' && f[f.len() - 1] != b'.',
659 "WatchBpfMap field must not start or end with `.` (empty path segment)",
660 );
661 let mut i = 0;
662 while i < f.len() {
663 let b = f[i];
664 assert!(
665 b != b' ' && b != b'\t' && b != b'\n' && b != b'\r',
666 "WatchBpfMap field must not contain whitespace",
667 );
668 assert!(
669 b != b'/' && b != b'\\',
670 "WatchBpfMap field must not contain path separators",
671 );
672 assert!(
673 !(b == b'.' && i > 0 && f[i - 1] == b'.'),
674 "WatchBpfMap field must not contain `..` (empty path segment)",
675 );
676 assert!(
677 b >= 0x20 && b < 0x7f,
678 "WatchBpfMap field must be printable ASCII only",
679 );
680 i += 1;
681 }
682 // label: non-empty, printable, no whitespace / separators / dots
683 // (it is a single metric-key leaf).
684 let l = label.as_bytes();
685 assert!(!l.is_empty(), "WatchBpfMap label must not be empty");
686 let mut i = 0;
687 while i < l.len() {
688 let b = l[i];
689 assert!(
690 b != b' ' && b != b'\t' && b != b'\n' && b != b'\r',
691 "WatchBpfMap label must not contain whitespace",
692 );
693 assert!(
694 b != b'/' && b != b'\\',
695 "WatchBpfMap label must not contain path separators",
696 );
697 assert!(
698 b != b'.',
699 "WatchBpfMap label is a single metric-key leaf and must not contain `.`",
700 );
701 assert!(
702 b >= 0x20 && b < 0x7f,
703 "WatchBpfMap label must be printable ASCII only",
704 );
705 i += 1;
706 }
707 Self {
708 map_name_suffix,
709 field,
710 agg,
711 label,
712 }
713 }
714
715 /// The validated map-name suffix to match (via `ends_with`) against
716 /// loaded BPF maps (e.g. `".bss"`, `"cpu_ctx_stor"`).
717 pub const fn map_name_suffix(&self) -> &'static str {
718 self.map_name_suffix
719 }
720
721 /// The dot-path into the map's value type
722 /// (e.g. `"sys_stat.avg_lat_cri"` or `"lat_headroom"`).
723 pub const fn field(&self) -> &'static str {
724 self.field
725 }
726
727 /// How the per-tick reads aggregate into run-level metric key(s).
728 pub const fn agg(&self) -> BpfMapAgg {
729 self.agg
730 }
731
732 /// The metric-key leaf appended to the scheduler-obj prefix.
733 pub const fn label(&self) -> &'static str {
734 self.label
735 }
736}
737
738/// A per-test performance-regression assertion that
739/// `cargo ktstr perf-delta --noise-adjust` enforces when this test is compared
740/// across two commits — and that a normal `cargo ktstr test` run IGNORES.
741///
742/// Enforced ONLY under `--noise-adjust`. A declared gate is a CI-gating perf
743/// assertion; gating on a single-run scalar comparison would flip CI on noise,
744/// so the multi-run `--noise-adjust` path (Welch + disjoint-band separation) is
745/// the only statistically sound basis. Plain `perf-delta` (scalar) does NOT
746/// evaluate declared gates — it warns that they were skipped. Declaring a gate
747/// also REQUIRES `performance_mode` (validated at compile time by the macro and
748/// at discovery time by [`KtstrTestEntry::validate`]) so the compared data is
749/// pinned.
750///
751/// Inert-as-a-test / active-under-perf-delta is by CONSTRUCTION, not a runtime
752/// flag: the in-VM verdict path consults only [`crate::assert::Assert`], never a
753/// `PerfDeltaAssertion`, so declaring one changes no normal-run verdict or exit
754/// code. It becomes active only because `perf-delta` serializes the declaration
755/// into the sidecar and consults it in the host-side `--noise-adjust` compare.
756///
757/// A declaration names a registry metric and OVERRIDES, for this test, the gate
758/// that decides a confident regression on it: a tighter relative threshold, an
759/// absolute floor, a pinned direction, and/or a phase scope. It LAYERS ON TOP of
760/// the `--noise-adjust` default all-metrics regression net (which still runs, to
761/// catch unknown-unknown regressions) — it is an explicit contract check, not a
762/// whitelist that narrows the net.
763///
764/// Declare by binding each gate to a `const` and listing it on the macro:
765/// `const RPS_GATE: PerfDeltaAssertion =
766/// PerfDeltaAssertion::new("rps_p50").with_max_regression_pct(5.0);` then
767/// `#[ktstr_test(performance_mode = true, perf_delta_assertions = [RPS_GATE])]`.
768/// Or directly on a programmatically-built [`KtstrTestEntry`]:
769/// `perf_delta_assertions: &[&RPS_GATE]` — bind the const first; a chained inline
770/// `&PerfDeltaAssertion::new(..).with_*(..)` does NOT rvalue-promote to `'static`
771/// in a non-const `KtstrTestEntry { .. }` literal (E0716). Construct via
772/// [`PerfDeltaAssertion::new`] + the `const fn` `with_*` builders; fields are
773/// crate-private so every value passes the compile-time format gate. The type is
774/// `Copy` over a `&'static str` metric (no `Drop`, E0493-safe); the owned form
775/// the sidecar serializes is a separate internal mirror,
776/// [`crate::test_support::PerfDeltaAssertionRecord`].
777#[derive(Debug, Clone, Copy, PartialEq)]
778pub struct PerfDeltaAssertion {
779 metric: &'static str,
780 direction: Option<crate::test_support::Polarity>,
781 max_regression_pct: Option<f64>,
782 min_abs: Option<f64>,
783 phase: Option<u16>,
784}
785
786impl PerfDeltaAssertion {
787 /// Const constructor for use in `static`/`const` context. `metric` is a
788 /// registry metric name (see `cargo ktstr stats list-metrics`); the
789 /// remaining knobs default to the registry values and are set via the
790 /// builders below.
791 ///
792 /// # Panics
793 ///
794 /// Panics at compile time when `metric` is empty, contains whitespace or a
795 /// path separator (`/`, `\`), or a non-printable / high-bit byte. That the
796 /// name RESOLVES in the metric registry is checked at run time by
797 /// [`KtstrTestEntry::validate`] (the registry is not const-accessible).
798 pub const fn new(metric: &'static str) -> Self {
799 let m = metric.as_bytes();
800 assert!(!m.is_empty(), "PerfDeltaAssertion metric must not be empty");
801 let mut i = 0;
802 while i < m.len() {
803 let b = m[i];
804 assert!(
805 b != b' ' && b != b'\t' && b != b'\n' && b != b'\r',
806 "PerfDeltaAssertion metric must not contain whitespace",
807 );
808 assert!(
809 b != b'/' && b != b'\\',
810 "PerfDeltaAssertion metric must not contain path separators",
811 );
812 assert!(
813 b >= 0x20 && b < 0x7f,
814 "PerfDeltaAssertion metric must be printable ASCII only",
815 );
816 i += 1;
817 }
818 Self {
819 metric,
820 direction: None,
821 max_regression_pct: None,
822 min_abs: None,
823 phase: None,
824 }
825 }
826
827 /// Override the relative-regression gate (percent) for this metric: a
828 /// worsening move larger than `pct`% of the baseline gates. `None` (unset)
829 /// inherits the registry `default_rel`. `pct` must be finite and `>= 0`
830 /// (enforced at discovery time by [`KtstrTestEntry::validate`]).
831 pub const fn with_max_regression_pct(mut self, pct: f64) -> Self {
832 self.max_regression_pct = Some(pct);
833 self
834 }
835
836 /// Override the absolute-materiality floor for this metric: a move smaller
837 /// than `min` in absolute units never gates, regardless of the relative
838 /// threshold. `None` (unset) inherits the registry `default_abs`. `min` must
839 /// be finite and `>= 0` (enforced at discovery time by
840 /// [`KtstrTestEntry::validate`]).
841 pub const fn with_min_abs(mut self, min: f64) -> Self {
842 self.min_abs = Some(min);
843 self
844 }
845
846 /// Pin the regression DIRECTION for this metric instead of inheriting the
847 /// registry polarity (e.g. assert a metric the registry treats as
848 /// `Informational` as `LowerBetter` for this test).
849 ///
850 /// # Panics
851 ///
852 /// Panics at compile time on [`crate::test_support::Polarity::TargetValue`]:
853 /// symmetric target-distance gating is not implemented, and the compare
854 /// polarity path would silently treat it as increase-is-worse. Use
855 /// `HigherBetter`, `LowerBetter`, or `Informational`.
856 pub const fn with_direction(mut self, polarity: crate::test_support::Polarity) -> Self {
857 assert!(
858 !matches!(polarity, crate::test_support::Polarity::TargetValue(_)),
859 "PerfDeltaAssertion::with_direction does not support Polarity::TargetValue \
860 (symmetric target-distance gating is unimplemented); use HigherBetter, \
861 LowerBetter, or Informational",
862 );
863 self.direction = Some(polarity);
864 self
865 }
866
867 /// Scope the assertion to a single phase (`step_index`: `0` = BASELINE,
868 /// `1..=N` = scenario `Step` ordinals). `None` (unset) gates the aggregate
869 /// (whole-run) value. Unlike the render-only per-phase spread tables, a
870 /// phase-scoped assertion DOES contribute to the `perf-delta --noise-adjust`
871 /// exit code (the scalar `perf-delta` path warns and skips all declared
872 /// gates, phase-scoped included).
873 pub const fn with_phase(mut self, step_index: u16) -> Self {
874 self.phase = Some(step_index);
875 self
876 }
877
878 /// The registry metric name this assertion gates.
879 pub const fn metric(&self) -> &'static str {
880 self.metric
881 }
882
883 /// The pinned regression direction, or `None` to inherit the registry
884 /// polarity.
885 pub const fn direction(&self) -> Option<crate::test_support::Polarity> {
886 self.direction
887 }
888
889 /// The relative-regression override (percent), or `None` for the registry
890 /// `default_rel`.
891 pub const fn max_regression_pct(&self) -> Option<f64> {
892 self.max_regression_pct
893 }
894
895 /// The absolute-materiality override, or `None` for the registry
896 /// `default_abs`.
897 pub const fn min_abs(&self) -> Option<f64> {
898 self.min_abs
899 }
900
901 /// The phase scope (`step_index`), or `None` to gate the aggregate value.
902 pub const fn phase(&self) -> Option<u16> {
903 self.phase
904 }
905}
906
907/// Gauntlet topology filtering constraints.
908///
909/// Controls which gauntlet presets are eligible for a test entry.
910/// Presets that don't meet all constraints are skipped.
911#[derive(Debug, Clone, Copy, PartialEq, Eq)]
912pub struct TopologyConstraints {
913 /// Minimum number of NUMA nodes.
914 pub min_numa_nodes: u32,
915 /// Maximum number of NUMA nodes.
916 pub max_numa_nodes: Option<u32>,
917 /// Minimum number of LLCs.
918 pub min_llcs: u32,
919 /// Maximum number of LLCs.
920 pub max_llcs: Option<u32>,
921 /// Whether the test requires SMT (threads_per_core > 1).
922 pub requires_smt: bool,
923 /// Minimum total CPU count.
924 pub min_cpus: u32,
925 /// Maximum total CPU count.
926 pub max_cpus: Option<u32>,
927}
928
929impl TopologyConstraints {
930 /// Conservative default constraints: single NUMA node, 1-12 LLCs,
931 /// no SMT requirement, 1-192 CPUs. Accepts most single-node
932 /// gauntlet presets ktstr ships while rejecting multi-NUMA presets
933 /// (`2numa-*`, `4numa-*`) and the scale-boundary single-node presets
934 /// that exceed the CPU/LLC caps (`240cpu-15llc-{smt,nosmt}`,
935 /// `252cpu-14llc-{smt,nosmt}`, and related variants). Test authors
936 /// that want broader coverage must
937 /// raise `max_numa_nodes`, `max_llcs`, or `max_cpus` explicitly.
938 ///
939 /// The canonical const handle — use directly when you need an
940 /// explicit const binding (`pub const X: TopologyConstraints =
941 /// TopologyConstraints::DEFAULT;`). For struct-literal spread in
942 /// a `static` / `const` initializer, either form works (modern
943 /// Rust promotes the trivially-Copy temporary returned by the
944 /// const-fn constructor):
945 ///
946 /// ```ignore
947 /// pub static A: TopologyConstraints = TopologyConstraints {
948 /// min_llcs: 4,
949 /// ..TopologyConstraints::DEFAULT // const path
950 /// };
951 /// pub static B: TopologyConstraints = TopologyConstraints {
952 /// min_llcs: 4,
953 /// ..TopologyConstraints::new() // const-fn constructor
954 /// };
955 /// ```
956 ///
957 /// [`Self::new()`] and `Default::default()` delegate to this const
958 /// for the `const fn` / trait-impl entry points.
959 pub const DEFAULT: Self = Self {
960 min_numa_nodes: 1,
961 max_numa_nodes: Some(1),
962 min_llcs: 1,
963 max_llcs: Some(12),
964 requires_smt: false,
965 min_cpus: 1,
966 max_cpus: Some(192),
967 };
968
969 /// Build the default constraints. Equivalent to [`Self::DEFAULT`].
970 /// Either form works for struct-literal spread in `static` /
971 /// `const`: `..Self::DEFAULT` (const path) or `..Self::new()`
972 /// (const-fn constructor — modern Rust promotes the trivially-Copy
973 /// temporary). `Default::default()` is the trait-impl entry point
974 /// for non-const contexts.
975 pub const fn new() -> Self {
976 Self::DEFAULT
977 }
978}
979
980impl Default for TopologyConstraints {
981 fn default() -> Self {
982 Self::new()
983 }
984}
985
986impl TopologyConstraints {
987 /// Whether a topology preset is eligible under these constraints
988 /// and the host's physical limits.
989 pub fn accepts(
990 &self,
991 topo: &Topology,
992 host_cpus: u32,
993 host_llcs: u32,
994 host_max_cpus_per_llc: u32,
995 ) -> bool {
996 topo.num_numa_nodes() >= self.min_numa_nodes
997 && self
998 .max_numa_nodes
999 .is_none_or(|max| topo.num_numa_nodes() <= max)
1000 && topo.num_llcs() >= self.min_llcs
1001 && self.max_llcs.is_none_or(|max| topo.num_llcs() <= max)
1002 && (!self.requires_smt || topo.threads_per_core >= 2)
1003 && topo.total_cpus() >= self.min_cpus
1004 && self.max_cpus.is_none_or(|max| topo.total_cpus() <= max)
1005 && topo.total_cpus() <= host_cpus
1006 && topo.num_llcs() <= host_llcs
1007 && topo.cores_per_llc * topo.threads_per_core <= host_max_cpus_per_llc
1008 }
1009
1010 /// No-perf-mode variant of [`Self::accepts`]. The VM topology is
1011 /// emulated via KVM (vCPUs, ACPI SRAT/SLIT, CPUID), not pinned to
1012 /// host hardware, so the host's NUMA-node count, LLC count, and
1013 /// per-LLC CPU width do not constrain it. Only the total-CPU
1014 /// inequality survives — the guest needs `topo.total_cpus()` host
1015 /// CPUs to schedule its vCPU threads, regardless of how those
1016 /// vCPUs are grouped into virtual LLCs and nodes.
1017 ///
1018 /// The entry's `min_numa_nodes` / `min_llcs` / `min_cpus` /
1019 /// `requires_smt` / `max_*` fields still gate which gauntlet
1020 /// presets the test author wants to exercise — those are
1021 /// expressing test scope, not host capability — so they keep
1022 /// firing here. The host-side checks (`<= host_cpus`,
1023 /// `<= host_llcs`, `<= host_max_cpus_per_llc`) collapse to the
1024 /// single CPU-budget check.
1025 pub fn accepts_no_perf_mode(&self, topo: &Topology, host_cpus: u32) -> bool {
1026 topo.num_numa_nodes() >= self.min_numa_nodes
1027 && self
1028 .max_numa_nodes
1029 .is_none_or(|max| topo.num_numa_nodes() <= max)
1030 && topo.num_llcs() >= self.min_llcs
1031 && self.max_llcs.is_none_or(|max| topo.num_llcs() <= max)
1032 && (!self.requires_smt || topo.threads_per_core >= 2)
1033 && topo.total_cpus() >= self.min_cpus
1034 && self.max_cpus.is_none_or(|max| topo.total_cpus() <= max)
1035 && topo.total_cpus() <= host_cpus
1036 }
1037
1038 /// Verifier-battery variant of [`Self::accepts_no_perf_mode`].
1039 ///
1040 /// The verifier sweep is correctness-only — boot, attach, verify,
1041 /// exit — with NO timing or perf assertions, so it tolerates a
1042 /// battery far wider than perf-mode gauntlet cells. Two departures
1043 /// from `accepts_no_perf_mode`:
1044 ///
1045 /// 1. **DEFAULT caps carry no opinion.** For each of `max_numa_nodes`,
1046 /// `max_llcs`, `max_cpus`, a value equal to the corresponding
1047 /// [`Self::DEFAULT`] field is read as `None` (unbounded). The
1048 /// default caps are the *conservative gauntlet* ceiling, chosen to
1049 /// keep perf-mode cells within host capacity — a scheduler that
1050 /// never touched them expressed no verifier-scope opinion, and the
1051 /// verifier should not inherit that ceiling and silently shrink the
1052 /// battery. An explicitly declared NON-default cap IS respected (a
1053 /// deliberate scope statement). NOTE the indistinguishability: a
1054 /// scheduler that explicitly writes the default value (e.g.
1055 /// `max_cpus: Some(192)`) is byte-identical to one that left it at
1056 /// default, so both read as "no cap" — there is no way to
1057 /// explicitly re-assert the default as a hard verifier ceiling. The
1058 /// `min_*` floors and `requires_smt` are ALWAYS honored: they
1059 /// express test SCOPE (the smallest / SMT shape the author wants
1060 /// exercised), not a conservative ceiling.
1061 ///
1062 /// 2. **No host-size bound at all.** Unlike `accepts` /
1063 /// `accepts_no_perf_mode` (strict `<= host_cpus`), verifier preset
1064 /// selection drops the total-CPU-vs-host check ENTIRELY — no
1065 /// multiple, no ceiling. A battery shape lists on any host. The
1066 /// rationale: verifier cells are correctness-only; vCPU overcommit
1067 /// at any ratio is the storm-validated supported regime (measured
1068 /// to ~36x sustained on this branch), the progress-watchdog's
1069 /// Tier-3 deadman scales with vCPU count so a slow oversubscribed
1070 /// boot is progress-protected rather than deadline-raced, and the
1071 /// forced-budget presets (see
1072 /// [`crate::gauntlet::TopoPreset::forced_cpu_budget`]) make deep
1073 /// overcommit the deliberately-exercised path. `host_cpus` is
1074 /// therefore unused here. Gauntlet / test selection keeps its
1075 /// strict host gates untouched.
1076 pub fn accepts_verifier(&self, topo: &Topology) -> bool {
1077 // Left-at-default cap == no opinion. `DEFAULT` fields are the
1078 // canonical const, so equality here means "the author did not
1079 // deviate" (or wrote the default verbatim — indistinguishable).
1080 let max_numa_nodes = if self.max_numa_nodes == Self::DEFAULT.max_numa_nodes {
1081 None
1082 } else {
1083 self.max_numa_nodes
1084 };
1085 let max_llcs = if self.max_llcs == Self::DEFAULT.max_llcs {
1086 None
1087 } else {
1088 self.max_llcs
1089 };
1090 let max_cpus = if self.max_cpus == Self::DEFAULT.max_cpus {
1091 None
1092 } else {
1093 self.max_cpus
1094 };
1095 topo.num_numa_nodes() >= self.min_numa_nodes
1096 && max_numa_nodes.is_none_or(|max| topo.num_numa_nodes() <= max)
1097 && topo.num_llcs() >= self.min_llcs
1098 && max_llcs.is_none_or(|max| topo.num_llcs() <= max)
1099 && (!self.requires_smt || topo.threads_per_core >= 2)
1100 && topo.total_cpus() >= self.min_cpus
1101 && max_cpus.is_none_or(|max| topo.total_cpus() <= max)
1102 }
1103
1104 /// Reject inverted ranges (any `max_*` strictly less than the
1105 /// matching `min_*`). An inverted range cannot match ANY topology
1106 /// — [`Self::accepts`] / [`Self::accepts_no_perf_mode`] would
1107 /// silently return `false` for every preset and the test would
1108 /// be skipped without diagnostic.
1109 ///
1110 /// Wired into [`KtstrTestEntry::validate`], which fires at the
1111 /// start of `run_ktstr_test` (before any VM boot or preset
1112 /// enumeration). A struct-literal like `TopologyConstraints {
1113 /// min_numa_nodes: 5, max_numa_nodes: Some(2), ..DEFAULT }`
1114 /// surfaces a loud error within seconds of test dispatch instead
1115 /// of as a silently-empty gauntlet sweep at runtime. NOTE: this
1116 /// only covers the BASE test invocation path — nextest's
1117 /// `--list` output for gauntlet variant lines still elides
1118 /// presets that don't satisfy `accepts()`, so an inverted entry
1119 /// produces zero gauntlet variant lines in `--list` output
1120 /// without a per-variant diagnostic. The base-test invocation
1121 /// surfaces the error definitively; the listing-time silent
1122 /// elision of gauntlet variants is a separate concern.
1123 pub fn validate(&self) -> anyhow::Result<()> {
1124 if let Some(max) = self.max_numa_nodes
1125 && max < self.min_numa_nodes
1126 {
1127 anyhow::bail!(
1128 "TopologyConstraints inverted: max_numa_nodes={} < \
1129 min_numa_nodes={}. No topology can satisfy both bounds, \
1130 so every gauntlet preset would silently skip.",
1131 max,
1132 self.min_numa_nodes,
1133 );
1134 }
1135 if let Some(max) = self.max_llcs
1136 && max < self.min_llcs
1137 {
1138 anyhow::bail!(
1139 "TopologyConstraints inverted: max_llcs={} < min_llcs={}. \
1140 No topology can satisfy both bounds.",
1141 max,
1142 self.min_llcs,
1143 );
1144 }
1145 if let Some(max) = self.max_cpus
1146 && max < self.min_cpus
1147 {
1148 anyhow::bail!(
1149 "TopologyConstraints inverted: max_cpus={} < min_cpus={}. \
1150 No topology can satisfy both bounds.",
1151 max,
1152 self.min_cpus,
1153 );
1154 }
1155 Ok(())
1156 }
1157}
1158
1159impl TopologyConstraints {
1160 /// Override `min_numa_nodes`.
1161 #[must_use = "builder methods consume self; bind the result"]
1162 pub const fn with_min_numa_nodes(mut self, min_numa_nodes: u32) -> Self {
1163 self.min_numa_nodes = min_numa_nodes;
1164 self
1165 }
1166
1167 /// Override `max_numa_nodes`.
1168 #[must_use = "builder methods consume self; bind the result"]
1169 pub const fn with_max_numa_nodes(mut self, max_numa_nodes: u32) -> Self {
1170 self.max_numa_nodes = Some(max_numa_nodes);
1171 self
1172 }
1173
1174 /// Clear `max_numa_nodes` (lift the upper bound).
1175 #[must_use = "builder methods consume self; bind the result"]
1176 pub const fn without_max_numa_nodes(mut self) -> Self {
1177 self.max_numa_nodes = None;
1178 self
1179 }
1180
1181 /// Override `min_llcs`.
1182 #[must_use = "builder methods consume self; bind the result"]
1183 pub const fn with_min_llcs(mut self, min_llcs: u32) -> Self {
1184 self.min_llcs = min_llcs;
1185 self
1186 }
1187
1188 /// Override `max_llcs`.
1189 #[must_use = "builder methods consume self; bind the result"]
1190 pub const fn with_max_llcs(mut self, max_llcs: u32) -> Self {
1191 self.max_llcs = Some(max_llcs);
1192 self
1193 }
1194
1195 /// Clear `max_llcs` (lift the upper bound).
1196 #[must_use = "builder methods consume self; bind the result"]
1197 pub const fn without_max_llcs(mut self) -> Self {
1198 self.max_llcs = None;
1199 self
1200 }
1201
1202 /// Override `requires_smt`.
1203 #[must_use = "builder methods consume self; bind the result"]
1204 pub const fn with_requires_smt(mut self, requires_smt: bool) -> Self {
1205 self.requires_smt = requires_smt;
1206 self
1207 }
1208
1209 /// Override `min_cpus`.
1210 #[must_use = "builder methods consume self; bind the result"]
1211 pub const fn with_min_cpus(mut self, min_cpus: u32) -> Self {
1212 self.min_cpus = min_cpus;
1213 self
1214 }
1215
1216 /// Override `max_cpus`.
1217 #[must_use = "builder methods consume self; bind the result"]
1218 pub const fn with_max_cpus(mut self, max_cpus: u32) -> Self {
1219 self.max_cpus = Some(max_cpus);
1220 self
1221 }
1222
1223 /// Clear `max_cpus` (lift the upper bound).
1224 #[must_use = "builder methods consume self; bind the result"]
1225 pub const fn without_max_cpus(mut self) -> Self {
1226 self.max_cpus = None;
1227 self
1228 }
1229}
1230
1231/// Definition of a scheduler for the test framework.
1232///
1233/// Captures everything the framework needs to know about a scheduler:
1234/// its name, binary spec, sysctls, kernel args, scheduler args,
1235/// cgroup parent, default topology, gauntlet topology constraints,
1236/// config-file plumbing, kernel sweep set, and assertion overrides.
1237///
1238/// Construct via the `declare_scheduler!` macro (the production
1239/// path) or the [`Scheduler::named`] const builder chain. Test bodies
1240/// reference declared schedulers via the `scheduler = MY_SCHED`
1241/// attribute on `#[ktstr_test]`.
1242#[derive(Debug)]
1243pub struct Scheduler {
1244 /// Short human name for the scheduler, used in logs and sidecar
1245 /// metadata.
1246 pub name: &'static str,
1247 /// Source of the scheduler: a built-in spec variant (`Eevdf`,
1248 /// `Discover`, `Path`, or `KernelBuiltin`).
1249 ///
1250 /// The `declare_scheduler!` macro exposes three pseudo-keys that
1251 /// each map to one [`SchedulerSpec`] variant — the macro never
1252 /// accepts an enum literal, so authors must pick the matching
1253 /// key:
1254 /// - `binary = "scx_name"` → [`SchedulerSpec::Discover("scx_name")`](SchedulerSpec::Discover) (PATH lookup in the guest).
1255 /// - `binary_path = "/abs/path"` → [`SchedulerSpec::Path("/abs/path")`](SchedulerSpec::Path) (explicit absolute path).
1256 /// - `kernel_builtin_enable = "…", kernel_builtin_disable = "…"` (paired) → [`SchedulerSpec::KernelBuiltin`].
1257 ///
1258 /// Code that constructs a [`Scheduler`] outside the macro
1259 /// (manual `..Scheduler::EEVDF` spread, programmatic builders)
1260 /// uses the typed [`SchedulerSpec`] enum directly — see the
1261 /// chainable [`Scheduler::binary_discover`] sugar for the
1262 /// `Discover` common case.
1263 pub binary: SchedulerSpec,
1264 /// Guest sysctls applied before the scheduler starts (injected
1265 /// into the guest kernel cmdline as `sysctl.<key>=<value>`).
1266 /// Applied in order; duplicate keys last-write-wins.
1267 pub sysctls: &'static [Sysctl],
1268 /// Extra guest kernel command-line arguments appended when booting
1269 /// the VM. This is the GUEST KERNEL cmdline, not the scheduler
1270 /// binary's CLI — use [`sched_args`](field@Self::sched_args) for that.
1271 ///
1272 /// Do not override the kargs ktstr injects itself (`console=`,
1273 /// `loglevel=`, `init=`): those break guest-side init
1274 /// and leave the VM unable to run tests.
1275 pub kargs: &'static [&'static str],
1276 /// Scheduler-wide assertion overrides merged on top of
1277 /// `Assert::default_checks()` and below each per-entry `assert`.
1278 ///
1279 /// Construct via [`crate::assert::Assert::NO_OVERRIDES`] (the
1280 /// zero-overrides baseline) chained through the `Assert` builder
1281 /// methods. The `Assert` builder surface (every overridable
1282 /// threshold + scheduler-tunable knob) is documented at the
1283 /// [Checking](https://ktstr.dev/guide/concepts/checking.html)
1284 /// guide chapter; see [`crate::assert::Assert`] for the full
1285 /// per-method threshold list.
1286 pub assert: crate::assert::Assert,
1287 /// Cgroup parent path. Must begin with `/` and must not be `"/"`
1288 /// alone (that is the cgroup root). Example: `"/ktstr"`.
1289 /// When set, the init creates the sysfs directory before starting
1290 /// the scheduler, and `--cell-parent-cgroup {path}` is injected
1291 /// into scheduler args.
1292 pub cgroup_parent: Option<CgroupPath>,
1293 /// Scheduler CLI args, prepended before per-test `extra_sched_args`.
1294 pub sched_args: &'static [&'static str],
1295 /// Default VM topology for tests using this scheduler. Tests inherit
1296 /// this topology unless they override `numa_nodes`, `llcs`, `cores`,
1297 /// or `threads` explicitly in `#[ktstr_test]`.
1298 pub topology: Topology,
1299 /// Gauntlet topology constraints. Tests inherit these unless they
1300 /// override specific fields in `#[ktstr_test]`.
1301 pub constraints: TopologyConstraints,
1302 /// Host-side path to an opaque config file passed to the scheduler
1303 /// binary inside the VM. The file is included in the initramfs at
1304 /// `/include-files/{filename}` and `--config /include-files/{filename}`
1305 /// is prepended to `sched_args`.
1306 pub config_file: Option<&'static str>,
1307 /// Declares how an inline config is passed to the scheduler.
1308 /// First element: CLI arg template with `{file}` placeholder
1309 /// (e.g. `"f:{file}"`, `"--config {file}"`). Second element:
1310 /// guest filesystem path where the JSON is written
1311 /// (e.g. `"/include-files/layered.json"`). The framework
1312 /// `mkdir -p`s the parent and writes the config content there.
1313 pub config_file_def: Option<(&'static str, &'static str)>,
1314 /// Per-scheduler filter on the verifier sweep matrix.
1315 ///
1316 /// Each entry is a string consumed by [`KernelId::parse`](crate::kernel_path::KernelId::parse)
1317 /// at verifier runtime — same parser as the
1318 /// `cargo ktstr verifier --kernel <SPEC>` CLI flag. Accepts exact
1319 /// versions (`"6.14"`), closed ranges spelled either `..` or `..=`
1320 /// (`"6.14..7.0"` or `"6.14..=7.0"` — both inclusive on both
1321 /// endpoints), git refs (`"git+URL#tag=NAME"`), paths, and cache keys.
1322 ///
1323 /// The verifier sweep matrix is driven by the operator's
1324 /// `cargo ktstr verifier --kernel <SPEC>` set (which the
1325 /// dispatcher always populates into `KTSTR_KERNEL_LIST` — even
1326 /// the no-`--kernel` case synthesizes a single auto-discovered
1327 /// entry). For each scheduler,
1328 /// `list_verifier_cells_all` in `test_support::dispatch`
1329 /// emits a cell per (kernel-list entry that passes this filter ×
1330 /// accepted gauntlet topology preset).
1331 ///
1332 /// Match semantics per spec variant:
1333 /// - `Version`: raw-label string equality OR sanitized-label
1334 /// match against the kernel-list entry.
1335 /// - `Range`: range-membership check via
1336 /// `decompose_version_for_compare` on the entry's raw version
1337 /// string. Lets a scheduler declaring
1338 /// `kernels = ["6.14..6.16"]` match any operator-supplied
1339 /// kernel whose version falls in `[6.14, 6.16]` inclusive.
1340 /// - `Path` / `CacheKey` / `Git`: sanitized-label equality.
1341 ///
1342 /// Empty (`&[]`) means no filter — the scheduler verifies
1343 /// against every entry in `KTSTR_KERNEL_LIST`.
1344 pub kernels: &'static [&'static str],
1345 /// Gauntlet preset names omitted from this scheduler's verifier
1346 /// matrix.
1347 ///
1348 /// This is a named exception layer applied after
1349 /// [`Self::constraints`]. It is intended for cases where a topology
1350 /// is valid in general but irrelevant or unsupported for this
1351 /// scheduler, and a structural min/max constraint would exclude
1352 /// additional useful presets. It affects only `cargo ktstr
1353 /// verifier`; ordinary tests and gauntlet variants are unchanged.
1354 ///
1355 /// `declare_scheduler!` exposes this as
1356 /// `verifier_exclude_topologies = ["preset-name", ...]`.
1357 /// Empty means no named exclusions.
1358 pub verifier_exclude_topologies: &'static [&'static str],
1359 /// Manifest directory of the crate that DECLARED this scheduler —
1360 /// the `CARGO_MANIFEST_DIR` captured at the `declare_scheduler!`
1361 /// call site. A [`SchedulerSpec::Discover`] scheduler is built with
1362 /// `cargo build -p <pkg>` run FROM this directory, so cargo walks up
1363 /// to the declaring crate's own workspace root: lockfile, feature
1364 /// unification, and target dir all come from that workspace, and
1365 /// verifier-cell emission checks package membership of that same
1366 /// workspace.
1367 ///
1368 /// `declare_scheduler!` fills this automatically with the invoking
1369 /// crate's `CARGO_MANIFEST_DIR`. Direct [`Scheduler::named`] /
1370 /// [`Scheduler::EEVDF`] construction leaves the empty sentinel,
1371 /// which [`Self::effective_manifest_dir`] resolves at runtime from
1372 /// the CONSUMING process (its `CARGO_MANIFEST_DIR`, then the current
1373 /// directory) — a compile-time `env!` here in the ktstr library
1374 /// would bake ktstr's own package dir (the registry checkout for a
1375 /// downstream user), a workspace the consumer's scheduler is not a
1376 /// member of. Read through [`Self::effective_manifest_dir`], not
1377 /// this field; override for non-cargo launch contexts via
1378 /// [`Self::manifest_dir`] with `env!("CARGO_MANIFEST_DIR")`.
1379 pub manifest_dir: &'static str,
1380}
1381
1382/// Runtime resolution for the empty [`Scheduler::manifest_dir`] sentinel:
1383/// the orchestrator-pinned fallback when present
1384/// ([`crate::KTSTR_MANIFEST_DIR_FALLBACK_ENV`], exported by `cargo ktstr`
1385/// so its ELF-stamp requirements and every descendant resolve to one exact
1386/// string), else the consuming process's own `CARGO_MANIFEST_DIR`, else
1387/// the current directory. Resolved once per process.
1388#[doc(hidden)]
1389pub fn runtime_manifest_dir() -> &'static str {
1390 static RUNTIME_DIR: std::sync::OnceLock<String> = std::sync::OnceLock::new();
1391 RUNTIME_DIR
1392 .get_or_init(|| {
1393 std::env::var(crate::KTSTR_MANIFEST_DIR_FALLBACK_ENV)
1394 .ok()
1395 .filter(|dir| !dir.is_empty())
1396 .or_else(|| {
1397 std::env::var("CARGO_MANIFEST_DIR")
1398 .ok()
1399 .filter(|dir| !dir.is_empty())
1400 })
1401 .unwrap_or_else(|| {
1402 std::env::current_dir()
1403 .map(|dir| dir.display().to_string())
1404 .unwrap_or_else(|_| ".".to_string())
1405 })
1406 })
1407 .as_str()
1408}
1409
1410impl Scheduler {
1411 /// Placeholder scheduler representing "no scx scheduler." Tests
1412 /// that use `Scheduler::EEVDF` run under the kernel's default
1413 /// scheduler (EEVDF on current kernels), with no scheduler binary
1414 /// launched. Useful as a baseline and for tests that exercise
1415 /// framework behavior independent of any scx scheduler.
1416 ///
1417 /// The `.name` is the compile-time-fixed string `"eevdf"` — NOT
1418 /// runtime-derived from the live kernel. A sidecar written on a
1419 /// kernel whose default is a successor scheduling class still
1420 /// records `"eevdf"` here as long as the test attributes this
1421 /// `Scheduler` to a run. The sidecar reads
1422 /// `self.name` directly via the `scheduler` field
1423 /// projection.
1424 ///
1425 /// The sidecar itself does not carry the mapping from kernel
1426 /// version to scheduling class: the `host.kernel_release`
1427 /// field records the live kernel's release string (`6.6.12`,
1428 /// `6.14.2`, …) and nothing else. Consumers that need to answer
1429 /// "did this run actually use EEVDF?" must combine
1430 /// `host.kernel_release` with version-to-class knowledge
1431 /// maintained OUTSIDE the sidecar — e.g. an external lookup
1432 /// table that records the default scheduling class per upstream
1433 /// kernel release. A sidecar alone cannot distinguish a true
1434 /// EEVDF run from a run on a successor-class kernel that
1435 /// reused the same `"eevdf"` label via
1436 /// [`Scheduler::EEVDF`]'s compile-time-fixed `.name`.
1437 pub const EEVDF: Scheduler = Scheduler {
1438 name: "eevdf",
1439 binary: SchedulerSpec::Eevdf,
1440 sysctls: &[],
1441 kargs: &[],
1442 assert: crate::assert::Assert::NO_OVERRIDES,
1443 cgroup_parent: None,
1444 sched_args: &[],
1445 topology: Topology {
1446 llcs: 1,
1447 cores_per_llc: 2,
1448 threads_per_core: 1,
1449 numa_nodes: 1,
1450 nodes: None,
1451 distances: None,
1452 llc_cores: None,
1453 },
1454 constraints: TopologyConstraints::DEFAULT,
1455 config_file: None,
1456 config_file_def: None,
1457 kernels: &[],
1458 verifier_exclude_topologies: &[],
1459 manifest_dir: "",
1460 };
1461
1462 /// Const constructor for defining schedulers in static context.
1463 /// Caller chains [`Self::binary`] (or
1464 /// [`Self::binary_discover`]) plus any of the other const-fn
1465 /// builders to override the per-field defaults; the unset
1466 /// fields stay at the values below.
1467 ///
1468 /// **Defaults** (intentional — these compose with the
1469 /// per-test `#[ktstr_test]` attributes via merge, so every
1470 /// field has a no-op identity that lets per-test overrides
1471 /// take precedence):
1472 /// - `binary`: [`SchedulerSpec::Eevdf`] — kernel default
1473 /// scheduling class, no scheduler binary launched.
1474 /// Override via [`Self::binary`] / [`Self::binary_discover`].
1475 /// - `sysctls` / `kargs` / `sched_args`: empty slices — no
1476 /// guest sysctls applied, no extra kernel cmdline args, no
1477 /// extra scheduler CLI args.
1478 /// - `assert`: [`crate::assert::Assert::NO_OVERRIDES`] — no
1479 /// threshold overrides on top of
1480 /// [`crate::assert::Assert::default_checks`].
1481 /// - `cgroup_parent`: `None` — no `--cell-parent-cgroup`
1482 /// injection.
1483 /// - `topology`: `1 numa × 1 llc × 2 cores × 1 thread` —
1484 /// smallest meaningful topology for a quick smoke
1485 /// scheduler. Override via [`Self::topology`].
1486 /// - `constraints`: [`TopologyConstraints::DEFAULT`] — no
1487 /// gauntlet limits.
1488 /// - `config_file` / `config_file_def`: `None` — no config
1489 /// file plumbing. Setting both at construction is rejected
1490 /// at validation time.
1491 /// - `kernels`: empty slice — verifies against every kernel
1492 /// in the operator's `--kernel` set (no per-scheduler
1493 /// filter).
1494 /// - `verifier_exclude_topologies`: empty slice — no named
1495 /// verifier-only topology exclusions.
1496 /// - `manifest_dir`: the empty sentinel — resolved at runtime by
1497 /// [`Self::effective_manifest_dir`] from the consuming process
1498 /// (`CARGO_MANIFEST_DIR`, then the current directory), which
1499 /// under cargo test / nextest is the consumer package's own dir.
1500 /// `declare_scheduler!` captures the invoking crate's dir at
1501 /// compile time instead; override explicitly via
1502 /// [`Self::manifest_dir`] for non-cargo launch contexts.
1503 pub const fn named(name: &'static str) -> Scheduler {
1504 Scheduler {
1505 name,
1506 binary: SchedulerSpec::Eevdf,
1507 sysctls: &[],
1508 kargs: &[],
1509 assert: crate::assert::Assert::NO_OVERRIDES,
1510 cgroup_parent: None,
1511 sched_args: &[],
1512 topology: Topology {
1513 llcs: 1,
1514 cores_per_llc: 2,
1515 threads_per_core: 1,
1516 numa_nodes: 1,
1517 nodes: None,
1518 distances: None,
1519 llc_cores: None,
1520 },
1521 constraints: TopologyConstraints::DEFAULT,
1522 config_file: None,
1523 config_file_def: None,
1524 kernels: &[],
1525 verifier_exclude_topologies: &[],
1526 manifest_dir: "",
1527 }
1528 }
1529
1530 /// The scheduler's build/resolution workspace: [`Self::manifest_dir`]
1531 /// when the declaration carried one (`declare_scheduler!`, explicit
1532 /// [`Self::manifest_dir`] builder), otherwise resolved ONCE at
1533 /// runtime from the consuming process — `CARGO_MANIFEST_DIR` (cargo
1534 /// test / nextest set it to the running test target's package dir,
1535 /// exactly the workspace whose `cargo build -p <pkg>` can see the
1536 /// consumer's scheduler package), falling back to the current
1537 /// directory for non-cargo launches. Mirrors the sidecar's
1538 /// runtime-over-`env!` project resolution
1539 /// (`sidecar::detect_project_commit`): a compile-time `env!` in this
1540 /// library bakes ktstr's OWN package dir, which downstream is the
1541 /// read-only cargo registry checkout.
1542 pub fn effective_manifest_dir(&self) -> &'static str {
1543 if !self.manifest_dir.is_empty() {
1544 return self.manifest_dir;
1545 }
1546 runtime_manifest_dir()
1547 }
1548
1549 /// Set the binary spec. Returns self for const chaining.
1550 pub const fn binary(mut self, binary: SchedulerSpec) -> Self {
1551 self.binary = binary;
1552 self
1553 }
1554
1555 /// Set the declaring crate's manifest directory — the workspace a
1556 /// [`SchedulerSpec::Discover`] scheduler is built in. Returns self
1557 /// for const chaining.
1558 ///
1559 /// `declare_scheduler!` passes the call-site
1560 /// `CARGO_MANIFEST_DIR` automatically; direct builder users outside
1561 /// the ktstr tree should pass their own `env!("CARGO_MANIFEST_DIR")`
1562 /// so cargo builds the scheduler in ITS workspace rather than
1563 /// ktstr's. See the [field doc](field@Self::manifest_dir).
1564 pub const fn manifest_dir(mut self, dir: &'static str) -> Self {
1565 self.manifest_dir = dir;
1566 self
1567 }
1568
1569 /// Sugar for `.binary(SchedulerSpec::Discover(name))` — the
1570 /// dominant Scheduler construction path. Use when the scheduler
1571 /// binary is on `PATH` under the named filename (e.g.
1572 /// `.binary_discover("scx_rusty")`) and the framework should
1573 /// resolve it at guest-init time via `which`-style lookup.
1574 /// Equivalent to:
1575 ///
1576 /// ```ignore
1577 /// Scheduler::named("rusty").binary(SchedulerSpec::Discover("scx_rusty"))
1578 /// // is equivalent to
1579 /// Scheduler::named("rusty").binary_discover("scx_rusty")
1580 /// ```
1581 ///
1582 /// For an explicit absolute path (no `PATH` lookup), call
1583 /// `.binary(SchedulerSpec::Path("/absolute/path"))` directly —
1584 /// the path variant has no chainable sugar because absolute
1585 /// paths are the rare case (cross-compiled trees, ad-hoc
1586 /// installs) and a path-typed setter would obscure the intent.
1587 pub const fn binary_discover(self, name: &'static str) -> Self {
1588 self.binary(SchedulerSpec::Discover(name))
1589 }
1590
1591 /// Set sysctls. Returns self for const chaining.
1592 pub const fn sysctls(mut self, sysctls: &'static [Sysctl]) -> Self {
1593 self.sysctls = sysctls;
1594 self
1595 }
1596
1597 /// Set kernel args. Returns self for const chaining.
1598 pub const fn kargs(mut self, kargs: &'static [&'static str]) -> Self {
1599 self.kargs = kargs;
1600 self
1601 }
1602
1603 /// Set assertion config. Returns self for const chaining.
1604 pub const fn assert(mut self, assert: crate::assert::Assert) -> Self {
1605 self.assert = assert;
1606 self
1607 }
1608
1609 /// Set cgroup parent path. See the [`cgroup_parent`](field@Self::cgroup_parent)
1610 /// field for path format requirements (must begin with `/`, must
1611 /// not be `"/"` alone).
1612 pub const fn cgroup_parent(mut self, path: &'static str) -> Self {
1613 self.cgroup_parent = Some(CgroupPath::new(path));
1614 self
1615 }
1616
1617 /// Set scheduler CLI args prepended before per-test
1618 /// `extra_sched_args`.
1619 pub const fn sched_args(mut self, args: &'static [&'static str]) -> Self {
1620 self.sched_args = args;
1621 self
1622 }
1623
1624 /// Set the default VM topology for tests using this scheduler.
1625 /// Tests inherit this unless they override individual dimensions
1626 /// explicitly in `#[ktstr_test]`.
1627 pub const fn topology(mut self, numa_nodes: u32, llcs: u32, cores: u32, threads: u32) -> Self {
1628 self.topology = Topology {
1629 llcs,
1630 cores_per_llc: cores,
1631 threads_per_core: threads,
1632 numa_nodes,
1633 nodes: None,
1634 distances: None,
1635 llc_cores: None,
1636 };
1637 self
1638 }
1639
1640 /// Set gauntlet topology constraints. Tests inherit these unless
1641 /// they override specific fields in `#[ktstr_test]`.
1642 pub const fn constraints(mut self, constraints: TopologyConstraints) -> Self {
1643 self.constraints = constraints;
1644 self
1645 }
1646
1647 /// Set minimum number of NUMA nodes.
1648 pub const fn min_numa_nodes(mut self, n: u32) -> Self {
1649 self.constraints.min_numa_nodes = n;
1650 self
1651 }
1652
1653 /// Set maximum number of NUMA nodes.
1654 pub const fn max_numa_nodes(mut self, n: u32) -> Self {
1655 self.constraints.max_numa_nodes = Some(n);
1656 self
1657 }
1658
1659 /// Set minimum number of LLCs.
1660 pub const fn min_llcs(mut self, n: u32) -> Self {
1661 self.constraints.min_llcs = n;
1662 self
1663 }
1664
1665 /// Set maximum number of LLCs.
1666 pub const fn max_llcs(mut self, n: u32) -> Self {
1667 self.constraints.max_llcs = Some(n);
1668 self
1669 }
1670
1671 /// Set whether the scheduler requires SMT.
1672 pub const fn requires_smt(mut self, v: bool) -> Self {
1673 self.constraints.requires_smt = v;
1674 self
1675 }
1676
1677 /// Set minimum total CPU count.
1678 pub const fn min_cpus(mut self, n: u32) -> Self {
1679 self.constraints.min_cpus = n;
1680 self
1681 }
1682
1683 /// Set maximum total CPU count.
1684 pub const fn max_cpus(mut self, n: u32) -> Self {
1685 self.constraints.max_cpus = Some(n);
1686 self
1687 }
1688
1689 /// Set a host-side config file path. The file is included in the
1690 /// guest initramfs and `--config` is injected into scheduler args.
1691 pub const fn config_file(mut self, path: &'static str) -> Self {
1692 self.config_file = Some(path);
1693 self
1694 }
1695
1696 /// Declare how inline config content is passed to the scheduler.
1697 /// `arg_template`: CLI arg with `{file}` placeholder for the
1698 /// guest path (e.g. `"f:{file}"`, `"--config {file}"`).
1699 /// `guest_path`: where the JSON is written in the guest
1700 /// (e.g. `"/include-files/layered.json"`).
1701 pub const fn config_file_def(
1702 mut self,
1703 arg_template: &'static str,
1704 guest_path: &'static str,
1705 ) -> Self {
1706 self.config_file_def = Some((arg_template, guest_path));
1707 self
1708 }
1709
1710 /// Set the kernel specs the verifier should exercise this scheduler
1711 /// against. See [`Self::kernels`](field@Self::kernels) for the
1712 /// accepted string shapes.
1713 pub const fn kernels(mut self, kernels: &'static [&'static str]) -> Self {
1714 self.kernels = kernels;
1715 self
1716 }
1717
1718 /// Exclude named gauntlet topology presets from this scheduler's
1719 /// verifier matrix without changing ordinary gauntlet selection.
1720 pub const fn verifier_exclude_topologies(mut self, presets: &'static [&'static str]) -> Self {
1721 self.verifier_exclude_topologies = presets;
1722 self
1723 }
1724
1725 /// Whether this scheduler runs an active scheduling policy
1726 /// (anything other than the kernel default EEVDF). Forwards to
1727 /// [`SchedulerSpec::has_active_scheduling`].
1728 ///
1729 /// Kept (unlike the trivial `name` / `binary` accessors that were
1730 /// dropped) because the 11+ call sites in `crate::test_support::eval` / `probe.rs`
1731 /// would otherwise spell `entry.scheduler.binary.has_active_scheduling()`
1732 /// at every dispatch decision — the `.binary.` indirection
1733 /// repeats noise without adding meaning. The forwarder is one
1734 /// line of glue for a recurring readability win.
1735 ///
1736 /// Returns `true` for `KernelBuiltin` schedulers. See
1737 /// [`Self::has_bpf_scheduler`] for the narrower gate that
1738 /// excludes them (the right gate when callers assume a
1739 /// userspace BPF binary is attached).
1740 pub const fn has_active_scheduling(&self) -> bool {
1741 self.binary.has_active_scheduling()
1742 }
1743
1744 /// Whether this scheduler attaches a userspace BPF binary.
1745 /// Forwards to [`SchedulerSpec::has_bpf_scheduler`].
1746 ///
1747 /// Same `.binary.` elision rationale as
1748 /// [`Self::has_active_scheduling`] — saves
1749 /// `entry.scheduler.binary.has_bpf_scheduler()` ceremony at
1750 /// every BPF-attach-intent dispatch site.
1751 ///
1752 /// Returns `false` for `KernelBuiltin` (no userspace binary)
1753 /// AND `Eevdf` (no scheduler). Use this whenever the caller
1754 /// would react to BPF artifacts — `verifier_stats` wiring,
1755 /// monitor thresholds, auto-repro probe gating.
1756 pub const fn has_bpf_scheduler(&self) -> bool {
1757 self.binary.has_bpf_scheduler()
1758 }
1759}
1760
1761/// Registration entry for an `#[ktstr_test]`-annotated function.
1762///
1763/// Construct via the [`#[ktstr_test]`] macro (the production path)
1764/// or struct-literal with `..KtstrTestEntry::DEFAULT` (the
1765/// integration-test / gauntlet rewriter path). The macro emits the
1766/// `linkme` distributed-slice registration; programmatic callers
1767/// register via [`KTSTR_TESTS`].
1768#[derive(Debug)]
1769pub struct KtstrTestEntry {
1770 /// Bare registered test name. Discovery prefixes VM entries with
1771 /// `ktstr/`, host-only entries with `host/`, and generated topology
1772 /// variants with `gauntlet/`.
1773 pub name: &'static str,
1774 /// Entry point invoked once per replica, inside the guest VM when
1775 /// `host_only` is false and on the host when it is true.
1776 pub func: fn(&Ctx) -> Result<AssertResult>,
1777 /// Base virtual topology; gauntlet expansion produces additional
1778 /// variants layered on top of this baseline.
1779 pub topology: Topology,
1780 /// Host-topology constraints (CPU and LLC bounds) that gate
1781 /// whether this entry is eligible on the current machine.
1782 pub constraints: TopologyConstraints,
1783 /// Guest-memory floor in MiB. Deferred sizing can raise the final
1784 /// allocation to fit the prepared initramfs. Values are binary
1785 /// mebibytes; conversion at VM launch is `value << 20` bytes, not
1786 /// `value * 1_000_000`.
1787 pub memory_mib: u32,
1788 /// Host-CPU budget for the no-perf vCPU mask — the number of host
1789 /// CPUs the VM's vCPU threads share. `None` auto-sizes from the vCPU
1790 /// count plus one service CPU, capped by the allowed host cpuset (so
1791 /// a wide VM's parallel AP bringup isn't needlessly throttled);
1792 /// `Some(n)` with `n` < vCPU count forces CPU overcommit for
1793 /// contention testing. `Some(0)` is rejected (a zero budget cannot
1794 /// run a VM). Requires `no_perf_mode`: the budget sizes only the
1795 /// no-perf vCPU-thread mask, so setting it without `no_perf_mode` is
1796 /// rejected (by the `#[ktstr_test]` macro and by `validate`) rather
1797 /// than silently ignored. An explicit `--cpu-cap` / `KTSTR_CPU_CAP`
1798 /// overrides it. Set by `#[ktstr_test(cpu_budget = N)]`.
1799 pub cpu_budget: Option<u32>,
1800 /// Primary scheduler that drives the test. Defaults to
1801 /// [`Scheduler::EEVDF`] (the no-scx-scheduler placeholder; tests
1802 /// then run under the kernel's default scheduling class).
1803 ///
1804 /// Reference to a static [`Scheduler`] — typically the const
1805 /// emitted by [`declare_scheduler!`](crate::declare_scheduler).
1806 /// Pure-binary-workload tests use `Scheduler::EEVDF` here and
1807 /// supply their binary via the `payload` field below.
1808 pub scheduler: &'static crate::test_support::Scheduler,
1809 /// Additional schedulers staged into the guest initramfs alongside
1810 /// [`Self::scheduler`] so the scheduler-lifecycle ops
1811 /// ([`Op::ReplaceScheduler`](crate::scenario::ops::Op::ReplaceScheduler)
1812 /// and siblings) can swap to a different scheduler mid-experiment
1813 /// without a VM reboot. The boot-time scheduler is always
1814 /// [`Self::scheduler`] — entries here are the candidate set the
1815 /// test will swap TO via `Op::AttachScheduler` /
1816 /// `Op::ReplaceScheduler`.
1817 ///
1818 /// Each staged scheduler must have a `Scheduler::name` that is
1819 /// unique within the set AND distinct from a small reserved-name
1820 /// list (currently `scheduler`, `sched_args`, `init`, `args`,
1821 /// `exec_cmd`, `sched_enable`, `sched_disable`) that the
1822 /// framework uses for boot-time initramfs entries. Name
1823 /// collisions OR reserved-name collisions bail at
1824 /// [`Self::validate`] time with an actionable diagnostic naming
1825 /// the offending entries.
1826 ///
1827 /// The boot-time [`Self::scheduler`] is NOT auto-included in this
1828 /// set AND cannot be repeated here — [`Self::validate`] rejects
1829 /// any staged entry whose `name` matches the boot scheduler's
1830 /// `name`. Keep the boot scheduler in [`Self::scheduler`] and
1831 /// stage only the additional candidates the test wants to swap
1832 /// to. Tests that don't use scheduler-lifecycle ops leave this
1833 /// field at its `&[]` default and pay no initramfs cost for the
1834 /// staging machinery.
1835 ///
1836 /// Staged binary content is hashed into the initramfs cache key
1837 /// (see `BaseKey` in `crate::vmm::initramfs_cache`) — rebuilding a
1838 /// staged scheduler between test runs invalidates the cache
1839 /// automatically; no manual cache clean is needed.
1840 pub staged_schedulers: &'static [&'static crate::test_support::Scheduler],
1841 /// Optional binary payload to run as the primary workload. When
1842 /// `Some`, the test runs the referenced [`Payload`](crate::test_support::Payload)
1843 /// (which must be [`PayloadKind::Binary`](crate::test_support::PayloadKind::Binary))
1844 /// alongside the configured scheduler. When `None`, the test runs
1845 /// a scheduler-only scenario.
1846 ///
1847 /// Populated by `#[ktstr_test(payload = SOME_BIN)]`; direct
1848 /// programmatic callers may also set this.
1849 pub payload: Option<&'static crate::test_support::Payload>,
1850 /// Additional binary payloads composed with the primary. Each
1851 /// entry is launched via [`Ctx::payload`](crate::scenario::Ctx)
1852 /// in the test body.
1853 ///
1854 /// Populated by `#[ktstr_test(workloads = [A, B])]`.
1855 pub workloads: &'static [&'static crate::test_support::Payload],
1856 /// When true, a crash triggers an auto-repro run with BPF probes
1857 /// attached to the crash call chain.
1858 pub auto_repro: bool,
1859 /// When the downstream eval-layer wiring is in place AND this
1860 /// field is set to `true`, the test ASSERTS that the auto-repro
1861 /// path fired during the run — the intended end-state is a
1862 /// verdict inversion converting fail-with-repro-artifact into
1863 /// PASS. The canonical pattern: a test deliberately triggers a
1864 /// scheduler stall, the auto-repro path captures the repro
1865 /// artifact, and the test PASSES because the expected behavior
1866 /// (auto-repro firing) happened.
1867 ///
1868 /// Distinct from [`Self::auto_repro`]:
1869 /// - `auto_repro = true` enables the auto-repro capability —
1870 /// the path fires when the primary run fails.
1871 /// - `expect_auto_repro = true` asserts the path FIRED.
1872 ///
1873 /// Current wiring state (HEAD): macro-parser support is in
1874 /// place (`#[ktstr_test(expect_auto_repro)]` /
1875 /// `#[ktstr_test(expect_auto_repro = true)]` both parse and
1876 /// set this field), cross-attribute validation rejects
1877 /// structurally-nonsensical combinations at macro-parse
1878 /// time (`auto_repro = false`, `expect_err = true`,
1879 /// `host_only = true`, `wprof = false`, missing
1880 /// `scheduler`), AND the eval-layer inversion that makes
1881 /// the assertion observable is wired:
1882 /// `crate::test_support::eval::apply_expect_auto_repro_inversion`
1883 /// runs after `evaluate_vm_result`, probes the auto-repro
1884 /// `.repro.wprof.pb` artifact via the shape validator, and
1885 /// (when satisfied) wraps the failure `Err` with the
1886 /// `ExpectAutoReproSatisfied` marker; the dispatch arm at
1887 /// `crate::test_support::dispatch::result_to_exit_code`
1888 /// downcasts the marker and routes the verdict to
1889 /// `EXIT_PASS`. Default `false` matches prior behavior
1890 /// (no inversion, original verdict stands).
1891 pub expect_auto_repro: bool,
1892 /// Requires the `wprof` cargo feature; without it, the
1893 /// `#[ktstr_test(wprof)]` attribute fails at macro expansion.
1894 /// When true, the VM spawns `/bin/wprof` concurrently with the
1895 /// workload and ships the Perfetto `.pb` trace to the host.
1896 pub wprof: bool,
1897 /// Custom wprof CLI args (requires the `wprof` cargo feature).
1898 /// Overrides `WprofConfig::default_args` when [`Self::wprof`]
1899 /// is true. Populated by `#[ktstr_test(wprof_args = "...")]`.
1900 pub wprof_args: Option<&'static str>,
1901 /// Per-entry assertion overrides merged on top of
1902 /// `Assert::default_checks()` and the scheduler's `assert`.
1903 pub assert: crate::assert::Assert,
1904 /// Extra CLI arguments appended to the scheduler invocation.
1905 pub extra_sched_args: &'static [&'static str],
1906 /// `scx_sched.watchdog_timeout` override applied to the guest kernel.
1907 pub watchdog_timeout: Duration,
1908 /// Host-side BPF map writes to perform during VM execution.
1909 ///
1910 /// Empty slice (the default) means "no writes." The host thread
1911 /// (`freeze_coord::start_bpf_map_write`) runs three phases: (1) build
1912 /// the guest-memory BPF-map accessor once the kernel page tables are
1913 /// up; (2) resolve every entry's `field` NAME to a byte offset + width
1914 /// from the target map's program BTF; (3) write each resolved entry.
1915 /// A phase-1/2 failure (accessor init, or a field that never resolves
1916 /// within the deadline) aborts before phase 3 without signalling the
1917 /// guest, which self-unblocks on its own `wait_for_map_write` timeout.
1918 /// In phase 3 every resolved entry is attempted — a field whose width
1919 /// is not the 4 bytes the `u32` value stores is skipped (logged), and
1920 /// a failed write is logged — then `SIGNAL_BPF_WRITE_DONE` is pushed
1921 /// to the guest UNCONDITIONALLY after the loop, so a skipped or failed
1922 /// entry still unblocks the guest rather than leaving it to time out.
1923 pub bpf_map_write: &'static [&'static BpfMapWrite],
1924 /// Named scheduler BPF-map fields to read observer-effect-free into
1925 /// assertable run-level metrics. The free-running host monitor resolves
1926 /// each [`WatchBpfMap`] lazily (after the scheduler attaches and its maps
1927 /// appear) and reads it each tick without freezing the guest; the value
1928 /// is folded run-level and exposed via
1929 /// [`crate::vmm::result::VmResult::run_metric`] under
1930 /// `<scheduler-obj>_<label>` (scalar/scalar-counter/per-CPU-counter) or
1931 /// `_<label>_{avg,max}` (per-CPU gauge).
1932 pub watch_bpf_maps: &'static [&'static WatchBpfMap],
1933 /// Pin vCPU threads to host cores matching the virtual topology's LLC
1934 /// structure, use 2MB hugepages for guest memory, NUMA mbind guest
1935 /// memory to pinned vCPU nodes, and promote vCPU threads to
1936 /// SCHED_FIFO. Validates that the host has enough CPUs and LLCs to
1937 /// satisfy the request without oversubscription.
1938 ///
1939 /// On x86_64, additionally: set KVM_HINTS_REALTIME CPUID hint
1940 /// (disables PV spinlocks, PV TLB flush, PV sched_yield; enables
1941 /// haltpoll cpuidle), disable PAUSE and HLT VM exits via
1942 /// KVM_CAP_X86_DISABLE_EXITS (HLT falls back to PAUSE-only when
1943 /// mitigate_smt_rsb is active), skip KVM_CAP_HALT_POLL (guest
1944 /// haltpoll cpuidle disables host halt polling via
1945 /// MSR_KVM_POLL_CONTROL), and check TSC stability.
1946 ///
1947 /// On aarch64, KVM exit suppression and CPUID hints are not
1948 /// available. The four host-side optimizations (vCPU pinning,
1949 /// hugepages, NUMA mbind, RT scheduling) apply.
1950 pub performance_mode: bool,
1951 /// Per-test performance-regression assertions enforced ONLY by
1952 /// `cargo ktstr perf-delta --noise-adjust` (inert under a normal
1953 /// `cargo ktstr test` run — the in-VM verdict never consults them — and
1954 /// skipped-with-a-warning under a scalar `perf-delta` without
1955 /// `--noise-adjust`, since single-run gating would flip CI on noise). Each
1956 /// [`PerfDeltaAssertion`] names a registry metric and overrides the
1957 /// confident-regression gate for it (relative / absolute threshold,
1958 /// direction, phase scope), LAYERED ON TOP of the `--noise-adjust` default
1959 /// all-metrics net. Serialized into the sidecar so the host-side compare can
1960 /// read the declaration. `&[]` = no per-test assertions. Requires
1961 /// `performance_mode` (checked by [`Self::validate`] and the macro) — a
1962 /// declaration on a non-perf test would compare unpinned, noisy data.
1963 pub perf_delta_assertions: &'static [&'static PerfDeltaAssertion],
1964 /// Enable the virtio-PCI transport: a host bridge at `00:00.0`
1965 /// plus the PCI0 ECAM/CAM config-access windows. When `false`, no
1966 /// PCI host bridge is exposed and the guest cmdline carries
1967 /// `pci=off`. Surfaced by `#[ktstr_test(pci)]`; named to match the
1968 /// attribute and the bare-bool-field convention (`host_only`,
1969 /// `auto_repro`).
1970 pub pci: bool,
1971 /// Decouple virtual topology from host hardware. When set:
1972 ///
1973 /// - The VM's virtual topology (`numa_nodes`, `llcs`, `cores`,
1974 /// `threads`) is built as declared — the guest sees the full
1975 /// requested topology via KVM vCPU layout, ACPI SRAT/SLIT
1976 /// tables, etc.
1977 /// - Host-side cpuset/LLC locking still applies (the no-perf
1978 /// `LlcPlan` path), so concurrent perf-mode peers are still
1979 /// serialised against this VM.
1980 /// - Host-side performance_mode optimisations are skipped:
1981 /// no vCPU-to-host-core pinning, no 2 MB hugepages, no NUMA
1982 /// mbind, no `SCHED_FIFO` promotion, no `KVM_HINTS_REALTIME`
1983 /// CPUID hint, no `KVM_CAP_X86_DISABLE_EXITS`.
1984 /// - Host topology constraints are relaxed during gauntlet
1985 /// preset filtering — the entry's `min_numa_nodes` /
1986 /// `min_llcs` / `requires_smt` / per-LLC CPU limits are not
1987 /// compared against host hardware. The only host check that
1988 /// stays is "total host CPUs >= total vCPUs", so a test
1989 /// declaring `numa_nodes = 3` runs on a 1-NUMA-node host.
1990 ///
1991 /// Equivalent to setting `KTSTR_NO_PERF_MODE=1` per-test —
1992 /// either source forces the no-perf path. Mutually exclusive
1993 /// with `performance_mode = true`; [`KtstrTestEntry::validate`]
1994 /// rejects the combination because "I want pinning" and "I
1995 /// explicitly don't want pinning" are contradictory.
1996 pub no_perf_mode: bool,
1997 /// Workload duration.
1998 pub duration: Duration,
1999 /// When true, the test expects run_ktstr_test to return Err.
2000 /// Disables auto_repro (no point probing a deliberately failing test).
2001 pub expect_err: bool,
2002 /// When true, assert the scx scheduler SURVIVES the run — it must NOT
2003 /// die or get ejected during any hold. The positive inverse of
2004 /// [`Self::expect_err`].
2005 ///
2006 /// Survival is otherwise IMPLICIT: a scheduler that dies during a hold
2007 /// records a `DetailKind::Scheduler*` fail via the scenario liveness
2008 /// probe (`crate::scenario::ops` `build_sched_died_*`), which already
2009 /// fails the run through the failure→Err→EXIT_FAIL path. Setting this
2010 /// flag makes the intent explicit in source and attaches a survival-
2011 /// specific failure explainer that names the asserted intent. It is
2012 /// enforced for EVERY scenario: those driven through
2013 /// `execute_defs`/`execute_steps`/`execute_scenario` re-check liveness
2014 /// between steps and inside every hold, and a guest-side post-function
2015 /// probe (`enforce_survives_storm_liveness`) re-checks once more after the
2016 /// test function returns — so even a scenario that hand-rolls `Op`
2017 /// dispatch without an `execute_*` driver actively fails if the scheduler
2018 /// died or went down (scx state `disabling`/`disabled`) during the run.
2019 ///
2020 /// Mutually exclusive with both [`Self::expect_err`] (one demands
2021 /// failure, the other survival) and [`Self::expect_auto_repro`] (both
2022 /// invert the scheduler-death-fail signal — survives_storm forces it to
2023 /// EXIT_FAIL, expect_auto_repro inverts a crash-with-repro fail to
2024 /// PASS), and requires an active scheduler
2025 /// ([`SchedulerSpec::has_active_scheduling`]); all three are rejected by
2026 /// `validate`.
2027 pub survives_storm: bool,
2028 /// When true, a terminal Inconclusive verdict (e.g. zero-denominator
2029 /// ratio gate that couldn't evaluate) routes to EXIT_PASS instead
2030 /// of EXIT_INCONCLUSIVE at the dispatch layer. The test process
2031 /// exits 0 and CI gates keying off the per-test exit code see no
2032 /// failure. Use only when the test author has reason to accept an
2033 /// Inconclusive arm as not-a-failure for this specific test —
2034 /// e.g. an exploratory benchmark whose ratio gate may legitimately
2035 /// see no signal under certain host topologies. Inconclusive is
2036 /// still recorded in the sidecar so stats tooling can surface it,
2037 /// and the operator-facing failure dump still renders the
2038 /// Inconclusive diagnostic. This flag changes only the dispatch
2039 /// exit-code projection.
2040 ///
2041 /// Mutually orthogonal with [`Self::expect_err`]: when both are
2042 /// true and the result is Inconclusive, expect_err still wins
2043 /// (expect_err demands a real Fail; Inconclusive doesn't satisfy
2044 /// that and routes to EXIT_FAIL with the expect_err unsatisfied
2045 /// explainer).
2046 ///
2047 /// Populated by `#[ktstr_test(allow_inconclusive)]` /
2048 /// `#[ktstr_test(allow_inconclusive = true)]` or by direct entry
2049 /// construction.
2050 pub allow_inconclusive: bool,
2051 /// When true, the test runs directly on the host instead of
2052 /// booting a VM. Used for tests that need host tools (cargo,
2053 /// nested VMs) unavailable in the guest initramfs.
2054 pub host_only: bool,
2055 /// Whether the base test is ignored by default and runs only when the
2056 /// harness is invoked with `--run-ignored`. Populated by
2057 /// `#[ktstr_test(ignore)]` / `#[ktstr_test(ignore = true)]`.
2058 ///
2059 /// This lives on the registered entry in addition to the generated
2060 /// libtest wrapper's `#[ignore]`: cargo-ktstr discovers generated
2061 /// `ktstr/<name>` VM cases and `host/<name>` host-only cases from
2062 /// [`KTSTR_TESTS`], so the custom listing path must carry the same bit or
2063 /// it would run an ignored fixture by default.
2064 pub ignored: bool,
2065 /// Extra host-side file specs beyond what the entry's
2066 /// [`scheduler`](Self::scheduler) / [`payload`](Self::payload) /
2067 /// [`workloads`](Self::workloads) declare. Unions with those
2068 /// per-payload specs at `run_ktstr_test` time; see
2069 /// [`all_include_files`](Self::all_include_files) for the
2070 /// aggregation contract. Use this slot for test-level
2071 /// dependencies that don't belong on a specific Payload —
2072 /// auxiliary data files, per-test helper scripts, fixtures.
2073 pub extra_include_files: &'static [&'static str],
2074 /// Maximum acceptable wall-clock duration of host-side VM teardown
2075 /// (BSP exit through SHM drain). Compared against
2076 /// [`VmResult::cleanup_duration`](crate::vmm::VmResult::cleanup_duration)
2077 /// in `evaluate_vm_result`; when the budget is exceeded the test's
2078 /// `AssertResult` is folded with a failing
2079 /// [`AssertDetail`](crate::assert::AssertDetail). Catches
2080 /// sub-watchdog cleanup regressions (e.g. a 30s teardown that the
2081 /// 60s host watchdog would silently absorb) at the test that
2082 /// declares the budget rather than at gross-timeout failure.
2083 /// `None` (the default) disables the check, leaving the watchdog
2084 /// as the only guard. Populated by
2085 /// `#[ktstr_test(cleanup_budget_ms = N)]` or by direct entry
2086 /// construction.
2087 pub cleanup_budget: Option<Duration>,
2088 /// Inline config content (JSON string) written to the guest path
2089 /// declared by the scheduler's `config_file_def`. The framework
2090 /// writes this string to a temp file, packs it into the initramfs,
2091 /// and passes the scheduler's arg template with `{file}` replaced.
2092 ///
2093 /// Populated by `#[ktstr_test(config = EXPR)]` (literal or path to
2094 /// a `const &'static str`) or by direct entry construction.
2095 ///
2096 /// Pairing gate: `config_content` and the scheduler's
2097 /// `config_file_def` must both be `Some(_)` or both be `None`.
2098 /// [`KtstrTestEntry::validate`] enforces this at runtime so direct
2099 /// programmatic-entry callers see the misconfiguration before VM
2100 /// boot, and the `#[ktstr_test]` macro emits a `const _: () = {
2101 /// assert!(...) };` block that catches the same mismatch at
2102 /// compile time for attribute-built entries. A `Some` here without
2103 /// a scheduler `config_file_def` would be silently dropped at
2104 /// dispatch (no `--config` flag derives from it); a `None` here
2105 /// against a scheduler that declares `config_file_def` would
2106 /// launch the scheduler binary without `--config`. Both are
2107 /// rejected.
2108 pub config_content: Option<&'static str>,
2109 /// Optional virtio-blk disk attached to the VM at `/dev/vda`.
2110 /// `None` (the default) boots without a disk; `Some(cfg)` calls
2111 /// `crate::vmm::KtstrVmBuilder::disk` in
2112 /// `crate::test_support::runtime::build_vm_builder_base` so the
2113 /// guest sees a raw block device sized per `cfg.capacity_mib`.
2114 /// Surfaced by `#[ktstr_test(disk = PATH)]`, `with_disk`, or direct
2115 /// construction via `..KtstrTestEntry::DEFAULT`. Mutually exclusive
2116 /// with `host_only`: `validate` rejects the combination because
2117 /// `host_only` skips the VM boot that owns the disk lifecycle.
2118 pub disk: Option<crate::vmm::disk_config::DiskConfig>,
2119 /// virtio-net devices attached to the VM (in-VMM loopback backend),
2120 /// one per element. Empty (the default) boots without a NIC; each
2121 /// element calls `crate::vmm::KtstrVmBuilder::network` in
2122 /// `crate::test_support::runtime::build_vm_builder_base`. On x86_64
2123 /// every element gets its own virtio-pci function (PCI slots 1..=N,
2124 /// one INTx GSI apiece); aarch64 takes a single virtio-MMIO NIC (build()
2125 /// errors on more than one). Surfaced by `#[ktstr_test(networks = [PATH, ...])]`,
2126 /// `with_networks`, or direct construction. Mutually exclusive with
2127 /// `host_only`: `validate` rejects a non-empty list because `host_only`
2128 /// skips the VM boot that owns the virtio-net devices.
2129 pub networks: &'static [crate::vmm::net_config::NetConfig],
2130 /// Host-side callback invoked after `vm.run()` returns, with
2131 /// access to the full `VmResult`. Runs on the HOST, not inside
2132 /// the guest. Use for assertions that need host-side state
2133 /// (e.g., `VmResult.snapshot_bridge` content after a snapshot
2134 /// capture pipeline fires inside the VM).
2135 ///
2136 /// `None` (the default) skips the callback. When `Some`, the
2137 /// closure receives `&VmResult` and returns `Result<()>` — an
2138 /// `Err` fails the test with the returned message.
2139 ///
2140 /// Skipped when the guest already reported a failed
2141 /// `AssertResult` — the existing guest-side fail diagnostic
2142 /// is more useful than a derivative post_vm `Err` that
2143 /// asserts on workload-derived state the crashed guest
2144 /// never produced. Tests that need the host-side check to
2145 /// run even on guest-fail should use
2146 /// [`post_vm_unconditional`](Self::post_vm_unconditional)
2147 /// instead.
2148 pub post_vm: Option<super::PostVmCallback>,
2149 /// Host-side callback invoked after `vm.run()` returns —
2150 /// like [`post_vm`](Self::post_vm) — but **UNCONDITIONAL**:
2151 /// runs even when the guest already reported a failed
2152 /// `AssertResult`.
2153 ///
2154 /// Use this when the callback must observe host-side state
2155 /// regardless of guest-side outcome — e.g. verifying that
2156 /// an artifact landed in the sidecar directory even on a
2157 /// deliberately-failing fault-injection test.
2158 ///
2159 /// Setting `post_vm_unconditional` does NOT invert the test
2160 /// verdict — a guest-reported fail still fails the test
2161 /// even when the unconditional callback returns Ok. The
2162 /// primitive lets the callback OBSERVE host-side state
2163 /// despite the fail; flipping a forced-fail test to PASS
2164 /// requires a separate framework primitive (e.g. an
2165 /// `expect_auto_repro = true` attribute that converts
2166 /// fail-plus-artifacts-present to PASS) which is intentionally
2167 /// out of scope here.
2168 ///
2169 /// Canonical callback shape (mirrors the framework's
2170 /// `default_post_vm_periodic_fired` self-guard):
2171 ///
2172 /// ```ignore
2173 /// fn my_unconditional_check(result: &VmResult) -> anyhow::Result<()> {
2174 /// // Skip when the VM run itself crashed (scheduler
2175 /// // died, watchdog fired, KVM exit during boot) — the
2176 /// // underlying failure already drives the test
2177 /// // diagnostic; layering a "missing state" error on
2178 /// // top obscures the cause.
2179 /// if !result.success {
2180 /// return Ok(());
2181 /// }
2182 /// // Now assert on whatever host-side artifact must
2183 /// // exist when the workload ran to completion.
2184 /// // ...
2185 /// Ok(())
2186 /// }
2187 /// ```
2188 ///
2189 /// Two suppression layers to be aware of:
2190 ///
2191 /// 1. FRAMEWORK level: `post_vm` is skipped entirely when
2192 /// the guest already reported a failed `AssertResult`
2193 /// (see the `guest_already_failed` gate in
2194 /// `src/test_support/eval/mod.rs::run_ktstr_test_inner_impl`'s
2195 /// post_vm dispatch site). `post_vm_unconditional`
2196 /// bypasses that suppression and always runs.
2197 /// 2. CALLBACK level: the conventional `post_vm` callback
2198 /// body short-circuits via `if !result.success { return
2199 /// Ok(()); }` to silence on crash/watchdog/KVM-boot-exit
2200 /// cases where the guest never produced an AssertResult
2201 /// for the framework gate to fire on; the framework's
2202 /// [`default_post_vm_periodic_fired`] is the canonical
2203 /// example. An unconditional callback that asserts on
2204 /// workload-derived state without an equivalent
2205 /// callback-side guard will surface a misleading
2206 /// "missing state" error on scheduler crashes.
2207 ///
2208 /// `None` (the default) skips the unconditional callback.
2209 /// Both [`post_vm`](Self::post_vm) and `post_vm_unconditional`
2210 /// may be set on the same entry — `post_vm` is suppressed on
2211 /// guest-fail per its existing contract, `post_vm_unconditional`
2212 /// always runs. If both callbacks set on the same entry both
2213 /// return `Err`, the framework surfaces both via
2214 /// `combine_post_vm_errs` chained as
2215 /// `post_vm: <conditional_err>; post_vm_unconditional: <unconditional_err>`
2216 /// so a debugging operator sees both regressions on the
2217 /// first pass rather than discovering the second one only
2218 /// after fixing the first.
2219 ///
2220 /// Setting the SAME callback fn pointer on BOTH slots will
2221 /// invoke it twice on the guest-success path (conditional +
2222 /// unconditional) and once on the guest-fail path
2223 /// (unconditional only); idempotent callbacks (read-only
2224 /// assertions) tolerate this fine, but a side-effecting
2225 /// callback (counter increment, file open) should pick exactly
2226 /// one slot.
2227 pub post_vm_unconditional: Option<super::PostVmCallback>,
2228 /// Gate boot-time scheduler launch on full probe-counter dump
2229 /// readiness.
2230 ///
2231 /// When true, the primary runtime adds
2232 /// `KTSTR_AWAIT_PROBE_DUMP_READY=1` to the guest cmdline. Guest
2233 /// args also request the minimal diagnostic probe needed to
2234 /// materialize the counter map. Guest init then waits before
2235 /// spawning the scheduler until the host
2236 /// freeze coordinator has used the real failure-dump decoder to
2237 /// discover `probe_bp.bss`, parse its split BTF, resolve the
2238 /// `ktstr_pcpu_counters` offset, and read the complete per-CPU
2239 /// counter slab. This is stronger than
2240 /// [`crate::scenario::ops::await_accessor_ready`], which only
2241 /// proves accessor adoption and runs after scheduler launch.
2242 ///
2243 /// Auto-repro does not inherit this primary-only gate: stall
2244 /// auto-repro deliberately skips probe attachment and therefore
2245 /// cannot satisfy it.
2246 ///
2247 /// The gate is intended for diagnostic tests whose scheduler
2248 /// arguments trigger a failure relative to process startup (for
2249 /// example `--stall-after=1`). `false` (the default) adds no host
2250 /// decode work and no guest wait.
2251 pub probe_dump_ready_gate: bool,
2252 /// Periodic snapshot count: when non-zero, the freeze
2253 /// coordinator divides the 10 %–90 % slice of the capturable
2254 /// window into `num_snapshots + 1` equal intervals and fires a
2255 /// host-side
2256 /// `freeze_and_dispatch(FreezeMode::Capture { gate_on_exit_kind: false })`
2257 /// at each of the
2258 /// `num_snapshots` interior boundaries — e.g. `N = 1` lands a
2259 /// single capture at the window midpoint; `N = 3` lands at
2260 /// 0.3 / 0.5 / 0.7 of the window. No boundary lands at exactly
2261 /// the 0.1 / 0.9 edges — the buffers reserve those for workload
2262 /// ramp-up / ramp-down. Each boundary is stored under
2263 /// `"periodic_NNN"` (zero-padded 3-digit index) on the host's
2264 /// [`crate::scenario::snapshot::SnapshotBridge`]. The window is
2265 /// `[max(scenario_start, prereqs_ready), scenario_start +
2266 /// duration]`: the start floats to the prereq-ready moment
2267 /// (kaslr + BPF-accessor attach) so cold-boot latency cannot
2268 /// strand boundaries pre-ready, and the end is CLAMPED to the
2269 /// workload end so captures never spill into post-workload
2270 /// idle. On a WARM boot the start equals `scenario_start`, so
2271 /// the window is the full `[start, start + d]` and the fractions
2272 /// above apply as documented (`start + 0.3·d` etc., modulo
2273 /// integer-ns truncation); on a COLD boot the
2274 /// window starts later and is shorter, so the landings shift —
2275 /// cross-run compares of the window-averaged keys
2276 /// `avg_cpu_util_comp_scale` / `avg_task_lat_cri` should use
2277 /// `--noise-adjust`. Boot + verifier time before ScenarioStart
2278 /// does not eat the budget. Pauses observed via
2279 /// `MSG_TYPE_SCENARIO_PAUSE` / `MSG_TYPE_SCENARIO_RESUME` shift
2280 /// every un-fired boundary by the cumulative pause duration —
2281 /// the boundary clock is workload-time, not wall-clock, so a
2282 /// guest that pauses for `P` ns delays each remaining boundary
2283 /// by `P` ns. `0` (the default) disables periodic capture
2284 /// entirely; the coordinator's run-loop never even computes
2285 /// boundary timestamps.
2286 ///
2287 /// **Capture cost.** Each periodic boundary fires the same
2288 /// host-side
2289 /// `freeze_and_dispatch(FreezeMode::Capture { gate_on_exit_kind: false })`
2290 /// path that
2291 /// [`crate::scenario::ops::Op::CaptureSnapshot`] dispatches: every
2292 /// vCPU is parked under `FREEZE_RENDEZVOUS_TIMEOUT` (30 s
2293 /// hard ceiling), BPF maps are walked, the dump is serialised
2294 /// to JSON, and the report is stored on the
2295 /// [`crate::scenario::snapshot::SnapshotBridge`]. On a healthy
2296 /// guest with a typical scheduler-state map size the freeze
2297 /// is tens of milliseconds (10–100 ms is the steady-state
2298 /// observation; cold-cache and large guest-memory walks can
2299 /// push higher). The host-side watchdog deadline is extended
2300 /// by the freeze duration after each fire, so periodic
2301 /// captures do not eat into the workload's wall-clock budget.
2302 ///
2303 /// **Best-effort delivery.** Up to `N` captures fire; an early
2304 /// VM exit (kill flag, BSP done, rendezvous timeout, watchdog
2305 /// deadline) can cut the periodic sequence short, and the
2306 /// run-loop stops servicing periodic boundaries the moment the
2307 /// kill flag fires. Tests should assert `>= some_lower_bound`
2308 /// rather than `== num_snapshots`. `Op::CaptureSnapshot` captures
2309 /// composed by the test author land on the same bridge
2310 /// alongside the `periodic_NNN` tags; total bridge occupancy
2311 /// is `num_snapshots + user_captures` and the bridge
2312 /// FIFO-evicts past
2313 /// [`crate::scenario::snapshot::MAX_STORED_SNAPSHOTS`].
2314 /// Additionally, the run-loop abandons the remaining sequence
2315 /// after 2 consecutive rendezvous timeouts and emits a
2316 /// `tracing::warn` naming the consecutive-timeout count.
2317 ///
2318 /// **Minimum spacing.** Each capture freezes every vCPU for
2319 /// tens of milliseconds at minimum (see "Capture cost" above),
2320 /// so boundaries scheduled closer than ~100 ms apart would
2321 /// fire back-to-back without any workload progress in between.
2322 /// `validate()` rejects entries where
2323 /// `0.8 · duration / (N + 1) < 100 ms` — choose `N` and
2324 /// `duration` so the resulting interval clears that floor.
2325 ///
2326 /// **Ordering.** Periodic captures are stored in order
2327 /// (`periodic_000` first, `periodic_NNN` last). Tests that
2328 /// need to walk them in time order should call
2329 /// [`crate::scenario::snapshot::SnapshotBridge::drain_ordered`]
2330 /// rather than [`crate::scenario::snapshot::SnapshotBridge::drain`]
2331 /// — the latter returns a `HashMap` and loses ordering.
2332 ///
2333 /// `validate()` rejects `num_snapshots >
2334 /// crate::scenario::snapshot::MAX_STORED_SNAPSHOTS` (= 64
2335 /// today): the bridge enforces FIFO eviction at that cap, so a
2336 /// higher count would silently drop the earliest periodic
2337 /// samples once `store()` started evicting. Refusing the
2338 /// configuration is more honest than half-delivering it. The
2339 /// 64 cap also ensures the 3-digit `:03` width on
2340 /// `periodic_NNN` is always sufficient.
2341 pub num_snapshots: u32,
2342 /// Cgroup directory that the framework creates BEFORE the
2343 /// scheduler starts and uses as the parent for every workload
2344 /// cgroup the test author declares via [`Ctx::cgroup_def`]
2345 /// (`ctx.cgroup_def("cg_0")` etc.). When `Some(path)`, the
2346 /// guest mkdir's `/sys/fs/cgroup{path}` and the per-test
2347 /// CgroupManager places its children there
2348 /// (`/sys/fs/cgroup{path}/cg_0` etc.); when `None`, the
2349 /// framework falls back to the legacy resolution
2350 /// (`crate::test_support::args::resolve_cgroup_root` —
2351 /// `--cell-parent-cgroup` in `sched_args` overrides; default
2352 /// `/sys/fs/cgroup/ktstr`).
2353 ///
2354 /// Distinct from [`crate::test_support::Scheduler::cgroup_parent`]:
2355 /// `cgroup_parent` is a scheduler-only knob that controls the
2356 /// scheduler argv (`--cell-parent-cgroup` flag, only when the
2357 /// scheduler declaration explicitly carries it in `sched_args`);
2358 /// `workload_root_cgroup` is a framework knob for the workload
2359 /// side and never reaches the scheduler argv. A test can set
2360 /// `workload_root_cgroup` without affecting the scheduler's
2361 /// cgroup placement, and a scheduler can set `cgroup_parent`
2362 /// without affecting where workloads land.
2363 pub workload_root_cgroup: Option<CgroupPath>,
2364 /// Whether KASLR is enabled in the guest kernel for this test.
2365 /// `true` (the default) lets the guest randomize kernel virt + direct-map
2366 /// addresses (CONFIG_RANDOMIZE_BASE=y + CONFIG_RANDOMIZE_MEMORY=y in
2367 /// `ktstr.kconfig`); `false` appends `nokaslr` to the guest cmdline so
2368 /// the kernel-image slide and the `page_offset_base` direct-map randomization
2369 /// both stay at compile-time defaults. KASLR-off is the determinism escape
2370 /// for tests that depend on fixed kernel addresses or that need to reproduce
2371 /// bugs masked by randomization; the default-on case exercises ktstr's
2372 /// host-side derivation chain (MSR_LSTAR readback, KERN_ADDRS guest channel,
2373 /// /proc/kallsyms `page_offset_base` lookup) end-to-end. The
2374 /// `kaslr_*_e2e` regression tests guard the derivation; the
2375 /// `kaslr_disabled_via_macro_attribute` regression guards this opt-out.
2376 /// Operator-level alternative: `kargs = ["nokaslr"]` on the scheduler decl
2377 /// — same effect, declared once for every test that uses the scheduler.
2378 /// Combining `kaslr = false` with `kargs = ["nokaslr"]` is redundant
2379 /// but harmless — `nokaslr` appearing twice on the cmdline is a no-op
2380 /// (kernel parses it as a bool flag, not a value).
2381 pub kaslr: bool,
2382}
2383
2384/// Placeholder function for [`KtstrTestEntry::DEFAULT`].
2385///
2386/// Returns `Err` — NOT a panic — so a programmatic caller that
2387/// accidentally uses `KtstrTestEntry::DEFAULT` without overriding
2388/// `func` gets an immediate actionable failure inside the test-run
2389/// loop rather than taking down the whole dispatch process. The
2390/// `..KtstrTestEntry::DEFAULT` struct-update spread only populates
2391/// unfilled fields; if the caller spread the default without
2392/// setting `func`, this stub runs and bails with a message pointing
2393/// at the mistake.
2394fn default_test_func(_ctx: &Ctx) -> Result<AssertResult> {
2395 anyhow::bail!("KtstrTestEntry::DEFAULT func called — override func before use")
2396}
2397
2398impl KtstrTestEntry {
2399 /// Sensible defaults for all fields. Override `name`, `func`, and
2400 /// `scheduler` (at minimum) via struct update syntax. Manual
2401 /// consumers should also set `auto_repro` explicitly: the default
2402 /// `true` boots a second VM with BPF probes attached on failure,
2403 /// which roughly doubles a failing test's wall-clock time.
2404 ///
2405 /// [`Self::DEFAULT`] is the source of truth (struct-literal
2406 /// const); [`Self::new()`] is a delegating alias for method-style
2407 /// use and `Default::default()` is the trait-shim — both
2408 /// equivalent in non-const contexts. For `static` / `const`
2409 /// initializer spread sites (e.g. `#[distributed_slice(KTSTR_TESTS)]`
2410 /// macro expansions), `..Self::DEFAULT` is the canonical shape —
2411 /// it spreads the struct-literal const directly without taking a
2412 /// detour through a const-fn return.
2413 ///
2414 /// ```
2415 /// use ktstr::prelude::*;
2416 ///
2417 /// fn my_test_fn(_ctx: &Ctx) -> Result<AssertResult> {
2418 /// Ok(AssertResult::pass())
2419 /// }
2420 ///
2421 /// #[distributed_slice(KTSTR_TESTS)]
2422 /// #[linkme(crate = ktstr::linkme)]
2423 /// static ENTRY: KtstrTestEntry = KtstrTestEntry {
2424 /// name: "my_test",
2425 /// func: my_test_fn,
2426 /// scheduler: &Scheduler::EEVDF,
2427 /// ..KtstrTestEntry::DEFAULT
2428 /// };
2429 /// ```
2430 ///
2431 /// The `#[linkme(crate = ktstr::linkme)]` annotation is required
2432 /// when the downstream crate does not depend on `linkme` directly
2433 /// — see [`crate::distributed_slice`] for the full rationale.
2434 pub const DEFAULT: Self = Self {
2435 name: "",
2436 func: default_test_func,
2437 topology: Topology {
2438 llcs: 1,
2439 cores_per_llc: 2,
2440 threads_per_core: 1,
2441 numa_nodes: 1,
2442 nodes: None,
2443 distances: None,
2444 llc_cores: None,
2445 },
2446 constraints: TopologyConstraints::DEFAULT,
2447 memory_mib: 256,
2448 cpu_budget: None,
2449 scheduler: &crate::test_support::Scheduler::EEVDF,
2450 staged_schedulers: &[],
2451 payload: None,
2452 workloads: &[],
2453 auto_repro: true,
2454 expect_auto_repro: false,
2455 wprof: false,
2456 wprof_args: None,
2457 assert: crate::assert::Assert::NO_OVERRIDES,
2458 extra_sched_args: &[],
2459 watchdog_timeout: Duration::from_secs(5),
2460 bpf_map_write: &[],
2461 watch_bpf_maps: &[],
2462 performance_mode: false,
2463 perf_delta_assertions: &[],
2464 pci: false,
2465 no_perf_mode: false,
2466 duration: Duration::from_secs(12),
2467 expect_err: false,
2468 survives_storm: false,
2469 allow_inconclusive: false,
2470 host_only: false,
2471 ignored: false,
2472 extra_include_files: &[],
2473 cleanup_budget: None,
2474 config_content: None,
2475 disk: None,
2476 networks: &[],
2477 post_vm: None,
2478 post_vm_unconditional: None,
2479 probe_dump_ready_gate: false,
2480 num_snapshots: 0,
2481 workload_root_cgroup: None,
2482 kaslr: true,
2483 };
2484
2485 /// Build the default entry. Equivalent to [`Self::DEFAULT`].
2486 /// Either `..Self::DEFAULT` or `..Self::new()` works in
2487 /// `static` / `const` initializer spread sites since `new()`
2488 /// is `const fn` and KtstrTestEntry has no Drop-bearing
2489 /// fields. `Default::default()` is the trait-shim equivalent
2490 /// for non-const contexts.
2491 pub const fn new() -> Self {
2492 Self::DEFAULT
2493 }
2494
2495 /// Aggregate every declared include-file spec: the entry's
2496 /// primary [`payload`](Self::payload) (if present) contributes
2497 /// its [`Payload::include_files`](crate::test_support::Payload::include_files),
2498 /// each entry in [`workloads`](Self::workloads) contributes its
2499 /// own, and [`extra_include_files`](Self::extra_include_files)
2500 /// contributes test-level extras. Pre-dedupe aggregation order:
2501 /// payload → workloads (in declaration order) → extras. The
2502 /// scheduler tier does not contribute — `Scheduler` has no
2503 /// `include_files` field, and the scheduler binary path is
2504 /// resolved separately at run time. Duplicate spec strings at
2505 /// this layer are NOT deduped — the framework's include-file
2506 /// pipeline at `run_ktstr_test` resolves each entry to a
2507 /// `(archive_path, host_path)` pair and dedupes on identical
2508 /// pairs while erroring on archive_path collisions with
2509 /// conflicting host_paths. This aggregation order does NOT
2510 /// survive downstream: the final resolved list is sorted
2511 /// alphabetically by archive_path after deduplication.
2512 /// Alphabetical ordering ensures deterministic initramfs layout
2513 /// regardless of declaration order.
2514 pub fn all_include_files(&self) -> Vec<&'static str> {
2515 let mut out: Vec<&'static str> = Vec::new();
2516 if let Some(p) = self.payload {
2517 out.extend(p.include_files.iter().copied());
2518 }
2519 for w in self.workloads {
2520 out.extend(w.include_files.iter().copied());
2521 }
2522 out.extend(self.extra_include_files.iter().copied());
2523 out
2524 }
2525}
2526
2527/// Programmatic builder methods. Use at runtime (let bindings, fn
2528/// returns). For `static` / `const` initializers and
2529/// `#[distributed_slice(KTSTR_TESTS)]` registration, prefer the
2530/// struct-literal `..KtstrTestEntry::DEFAULT` spread — chained
2531/// `with_X` calls fail in `const` context with E0015 ("cannot call
2532/// non-const fn in constants") because these setters are declared
2533/// `pub fn`, not `pub const fn`. See [`Self::DEFAULT`] for the
2534/// worked struct-literal example.
2535impl KtstrTestEntry {
2536 /// Override `name`.
2537 #[must_use = "builder methods consume self; bind the result"]
2538 pub fn with_name(mut self, name: &'static str) -> Self {
2539 self.name = name;
2540 self
2541 }
2542
2543 /// Override `func`.
2544 #[must_use = "builder methods consume self; bind the result"]
2545 pub fn with_func(mut self, func: fn(&Ctx) -> Result<AssertResult>) -> Self {
2546 self.func = func;
2547 self
2548 }
2549
2550 /// Override `topology`.
2551 #[must_use = "builder methods consume self; bind the result"]
2552 pub fn with_topology(mut self, topology: Topology) -> Self {
2553 self.topology = topology;
2554 self
2555 }
2556
2557 /// Override `constraints`.
2558 #[must_use = "builder methods consume self; bind the result"]
2559 pub fn with_constraints(mut self, constraints: TopologyConstraints) -> Self {
2560 self.constraints = constraints;
2561 self
2562 }
2563
2564 /// Override `memory_mib`.
2565 #[must_use = "builder methods consume self; bind the result"]
2566 pub fn with_memory_mib(mut self, memory_mib: u32) -> Self {
2567 self.memory_mib = memory_mib;
2568 self
2569 }
2570
2571 /// Override `cpu_budget` (the no-perf host-CPU budget; `n` below the
2572 /// vCPU count forces overcommit). Sets `Some(n)`; the default is
2573 /// `None` (auto-size to the vCPU count plus one service CPU, clamped
2574 /// to the allowed cpuset). `validate` rejects `Some(0)` and rejects a
2575 /// budget set without `no_perf_mode`.
2576 #[must_use = "builder methods consume self; bind the result"]
2577 pub fn with_cpu_budget(mut self, cpu_budget: u32) -> Self {
2578 self.cpu_budget = Some(cpu_budget);
2579 self
2580 }
2581
2582 /// Clear `cpu_budget` (auto-size the no-perf vCPU mask to the vCPU
2583 /// count plus one service CPU, clamped to the allowed cpuset).
2584 #[must_use = "builder methods consume self; bind the result"]
2585 pub fn without_cpu_budget(mut self) -> Self {
2586 self.cpu_budget = None;
2587 self
2588 }
2589
2590 /// Override `scheduler`.
2591 #[must_use = "builder methods consume self; bind the result"]
2592 pub fn with_scheduler(mut self, scheduler: &'static crate::test_support::Scheduler) -> Self {
2593 self.scheduler = scheduler;
2594 self
2595 }
2596
2597 /// Override `staged_schedulers` — the candidate set the test can
2598 /// swap to mid-experiment via the scheduler-lifecycle ops
2599 /// ([`Op::AttachScheduler`](crate::scenario::ops::Op::AttachScheduler) /
2600 /// [`Op::ReplaceScheduler`](crate::scenario::ops::Op::ReplaceScheduler)).
2601 /// See the field doc on [`Self::staged_schedulers`] for the
2602 /// per-scheduler-name uniqueness + reserved-name validation
2603 /// contract.
2604 #[must_use = "builder methods consume self; bind the result"]
2605 pub fn with_staged_schedulers(
2606 mut self,
2607 staged: &'static [&'static crate::test_support::Scheduler],
2608 ) -> Self {
2609 self.staged_schedulers = staged;
2610 self
2611 }
2612
2613 /// Override `payload`.
2614 #[must_use = "builder methods consume self; bind the result"]
2615 pub fn with_payload(mut self, payload: &'static crate::test_support::Payload) -> Self {
2616 self.payload = Some(payload);
2617 self
2618 }
2619
2620 /// Clear `payload` (run a scheduler-only scenario with no primary
2621 /// binary).
2622 #[must_use = "builder methods consume self; bind the result"]
2623 pub fn without_payload(mut self) -> Self {
2624 self.payload = None;
2625 self
2626 }
2627
2628 /// Override `workloads`.
2629 #[must_use = "builder methods consume self; bind the result"]
2630 pub fn with_workloads(
2631 mut self,
2632 workloads: &'static [&'static crate::test_support::Payload],
2633 ) -> Self {
2634 self.workloads = workloads;
2635 self
2636 }
2637
2638 /// Override `auto_repro`.
2639 #[must_use = "builder methods consume self; bind the result"]
2640 pub fn with_auto_repro(mut self, auto_repro: bool) -> Self {
2641 self.auto_repro = auto_repro;
2642 self
2643 }
2644
2645 /// Override `expect_auto_repro`.
2646 #[must_use = "builder methods consume self; bind the result"]
2647 pub fn with_expect_auto_repro(mut self, expect_auto_repro: bool) -> Self {
2648 self.expect_auto_repro = expect_auto_repro;
2649 self
2650 }
2651
2652 /// Override `assert`.
2653 ///
2654 /// Replaces the entry's per-test overrides wholesale; the assertion
2655 /// resolution at run time still layers `Assert::default_checks()`
2656 /// and the scheduler-level `assert` underneath.
2657 #[must_use = "builder methods consume self; bind the result"]
2658 pub fn with_assert(mut self, assert: crate::assert::Assert) -> Self {
2659 self.assert = assert;
2660 self
2661 }
2662
2663 /// Override `extra_sched_args`.
2664 #[must_use = "builder methods consume self; bind the result"]
2665 pub fn with_extra_sched_args(mut self, extra_sched_args: &'static [&'static str]) -> Self {
2666 self.extra_sched_args = extra_sched_args;
2667 self
2668 }
2669
2670 /// Override `watchdog_timeout`.
2671 #[must_use = "builder methods consume self; bind the result"]
2672 pub fn with_watchdog_timeout(mut self, watchdog_timeout: Duration) -> Self {
2673 self.watchdog_timeout = watchdog_timeout;
2674 self
2675 }
2676
2677 /// Override `bpf_map_write`.
2678 #[must_use = "builder methods consume self; bind the result"]
2679 pub fn with_bpf_map_write(mut self, bpf_map_write: &'static [&'static BpfMapWrite]) -> Self {
2680 self.bpf_map_write = bpf_map_write;
2681 self
2682 }
2683
2684 /// Override `watch_bpf_maps`.
2685 #[must_use = "builder methods consume self; bind the result"]
2686 pub fn with_watch_bpf_maps(mut self, watch_bpf_maps: &'static [&'static WatchBpfMap]) -> Self {
2687 self.watch_bpf_maps = watch_bpf_maps;
2688 self
2689 }
2690
2691 /// Override `performance_mode`.
2692 #[must_use = "builder methods consume self; bind the result"]
2693 pub fn with_performance_mode(mut self, performance_mode: bool) -> Self {
2694 self.performance_mode = performance_mode;
2695 self
2696 }
2697
2698 /// Override `no_perf_mode`.
2699 #[must_use = "builder methods consume self; bind the result"]
2700 pub fn with_no_perf_mode(mut self, no_perf_mode: bool) -> Self {
2701 self.no_perf_mode = no_perf_mode;
2702 self
2703 }
2704
2705 /// Override `duration`.
2706 #[must_use = "builder methods consume self; bind the result"]
2707 pub fn with_duration(mut self, duration: Duration) -> Self {
2708 self.duration = duration;
2709 self
2710 }
2711
2712 /// Override `expect_err`.
2713 #[must_use = "builder methods consume self; bind the result"]
2714 pub fn with_expect_err(mut self, expect_err: bool) -> Self {
2715 self.expect_err = expect_err;
2716 self
2717 }
2718
2719 /// Override [`Self::survives_storm`].
2720 #[must_use = "builder methods consume self; bind the result"]
2721 pub fn with_survives_storm(mut self, survives_storm: bool) -> Self {
2722 self.survives_storm = survives_storm;
2723 self
2724 }
2725
2726 /// Override [`Self::allow_inconclusive`]. When true, an
2727 /// Inconclusive terminal verdict routes to EXIT_PASS instead
2728 /// of EXIT_INCONCLUSIVE at the dispatch layer.
2729 #[must_use = "builder methods consume self; bind the result"]
2730 pub fn with_allow_inconclusive(mut self, allow_inconclusive: bool) -> Self {
2731 self.allow_inconclusive = allow_inconclusive;
2732 self
2733 }
2734
2735 /// Override `host_only`.
2736 #[must_use = "builder methods consume self; bind the result"]
2737 pub fn with_host_only(mut self, host_only: bool) -> Self {
2738 self.host_only = host_only;
2739 self
2740 }
2741
2742 /// Override [`Self::ignored`].
2743 #[must_use = "builder methods consume self; bind the result"]
2744 pub fn with_ignored(mut self, ignored: bool) -> Self {
2745 self.ignored = ignored;
2746 self
2747 }
2748
2749 /// Override `extra_include_files`.
2750 #[must_use = "builder methods consume self; bind the result"]
2751 pub fn with_extra_include_files(
2752 mut self,
2753 extra_include_files: &'static [&'static str],
2754 ) -> Self {
2755 self.extra_include_files = extra_include_files;
2756 self
2757 }
2758
2759 /// Override `cleanup_budget`.
2760 #[must_use = "builder methods consume self; bind the result"]
2761 pub fn with_cleanup_budget(mut self, cleanup_budget: Duration) -> Self {
2762 self.cleanup_budget = Some(cleanup_budget);
2763 self
2764 }
2765
2766 /// Clear `cleanup_budget` (leave the host watchdog as the only
2767 /// guard).
2768 #[must_use = "builder methods consume self; bind the result"]
2769 pub fn without_cleanup_budget(mut self) -> Self {
2770 self.cleanup_budget = None;
2771 self
2772 }
2773
2774 /// Override `config_content`.
2775 #[must_use = "builder methods consume self; bind the result"]
2776 pub fn with_config_content(mut self, config_content: &'static str) -> Self {
2777 self.config_content = Some(config_content);
2778 self
2779 }
2780
2781 /// Clear `config_content`.
2782 #[must_use = "builder methods consume self; bind the result"]
2783 pub fn without_config_content(mut self) -> Self {
2784 self.config_content = None;
2785 self
2786 }
2787
2788 /// Override `disk`.
2789 ///
2790 /// Pairs with the `host_only = false` requirement enforced by
2791 /// [`Self::validate`] — `host_only = true` with a `Some(..)` disk
2792 /// is rejected because host-only skips the VM boot that owns the
2793 /// virtio-blk lifecycle.
2794 #[must_use = "builder methods consume self; bind the result"]
2795 pub fn with_disk(mut self, disk: crate::vmm::disk_config::DiskConfig) -> Self {
2796 self.disk = Some(disk);
2797 self
2798 }
2799
2800 /// Override `networks` (one virtio-net device per element).
2801 ///
2802 /// Pairs with the `host_only = false` requirement enforced by
2803 /// [`Self::validate`] — `host_only = true` with a non-empty list
2804 /// is rejected because host-only skips the VM boot that owns the
2805 /// virtio-net devices.
2806 #[must_use = "builder methods consume self; bind the result"]
2807 pub fn with_networks(mut self, networks: &'static [crate::vmm::net_config::NetConfig]) -> Self {
2808 self.networks = networks;
2809 self
2810 }
2811
2812 /// Clear `networks` (boot without a virtio-net device).
2813 #[must_use = "builder methods consume self; bind the result"]
2814 pub fn without_networks(mut self) -> Self {
2815 self.networks = &[];
2816 self
2817 }
2818
2819 /// Clear `disk` (boot without a virtio-blk device).
2820 #[must_use = "builder methods consume self; bind the result"]
2821 pub fn without_disk(mut self) -> Self {
2822 self.disk = None;
2823 self
2824 }
2825
2826 /// Override `post_vm`.
2827 ///
2828 /// The closure runs on the host after `vm.run()` returns with
2829 /// access to the full `VmResult`; an `Err` from the closure fails
2830 /// the test with the returned message. Skipped when the guest
2831 /// already reported a failed `AssertResult` — see
2832 /// [`Self::post_vm`] for the suppression contract; use
2833 /// [`Self::with_post_vm_unconditional`] when the host-side
2834 /// check must run even on guest-fail.
2835 #[must_use = "builder methods consume self; bind the result"]
2836 pub fn with_post_vm(mut self, post_vm: super::PostVmCallback) -> Self {
2837 self.post_vm = Some(post_vm);
2838 self
2839 }
2840
2841 /// Clear `post_vm` (skip the host-side callback).
2842 #[must_use = "builder methods consume self; bind the result"]
2843 pub fn without_post_vm(mut self) -> Self {
2844 self.post_vm = None;
2845 self
2846 }
2847
2848 /// Override `post_vm_unconditional`.
2849 ///
2850 /// The closure runs on the host after `vm.run()` returns —
2851 /// like [`Self::with_post_vm`] — but bypasses the guest-fail
2852 /// suppression that gates the conditional [`Self::with_post_vm`]
2853 /// callback. An `Err` from the closure fails the test with the
2854 /// returned message.
2855 #[must_use = "builder methods consume self; bind the result"]
2856 pub fn with_post_vm_unconditional(
2857 mut self,
2858 post_vm_unconditional: super::PostVmCallback,
2859 ) -> Self {
2860 self.post_vm_unconditional = Some(post_vm_unconditional);
2861 self
2862 }
2863
2864 /// Clear `post_vm_unconditional` (skip the unconditional host-side
2865 /// callback). Does not affect the conditional [`Self::with_post_vm`]
2866 /// callback if one is set.
2867 #[must_use = "builder methods consume self; bind the result"]
2868 pub fn without_post_vm_unconditional(mut self) -> Self {
2869 self.post_vm_unconditional = None;
2870 self
2871 }
2872
2873 /// Override `num_snapshots`.
2874 #[must_use = "builder methods consume self; bind the result"]
2875 pub fn with_num_snapshots(mut self, num_snapshots: u32) -> Self {
2876 self.num_snapshots = num_snapshots;
2877 self
2878 }
2879
2880 /// Override `workload_root_cgroup` with a validated path.
2881 /// `path` must satisfy [`CgroupPath::new`]'s requirements
2882 /// (starts with `/`, not bare `/`, no `..` components); the
2883 /// const-eval gate panics on invalid input so programmatic
2884 /// callers see the same validation as the macro path.
2885 #[must_use = "builder methods consume self; bind the result"]
2886 pub const fn with_workload_root_cgroup(mut self, path: &'static str) -> Self {
2887 self.workload_root_cgroup = Some(CgroupPath::new(path));
2888 self
2889 }
2890}
2891
2892impl Default for KtstrTestEntry {
2893 fn default() -> Self {
2894 Self::new()
2895 }
2896}
2897
2898/// Distributed slice collecting all `#[ktstr_test]` entries via linkme.
2899#[distributed_slice]
2900pub static KTSTR_TESTS: [KtstrTestEntry];
2901
2902/// Distributed slice collecting all `declare_scheduler!` registrations
2903/// via linkme. Each entry is a `&'static Scheduler` pointing at a
2904/// const emitted by the macro. Runtime lookup and retained private probe
2905/// commands walk this slice; `cargo ktstr` discovery reads the parallel
2906/// versioned ELF-stamp registry without starting the binary.
2907#[distributed_slice]
2908pub static KTSTR_SCHEDULERS: [&'static Scheduler];
2909
2910/// Look up a registered test function by name.
2911pub fn find_test(name: &str) -> Option<&'static KtstrTestEntry> {
2912 KTSTR_TESTS.iter().find(|e| e.name == name)
2913}
2914
2915/// Look up a registered scheduler by its [`Scheduler::name`] field
2916/// (the `name = "..."` value supplied to
2917/// [`declare_scheduler!`](crate::declare_scheduler), not the
2918/// SCREAMING_SNAKE_CASE const identifier the macro emits). Returns
2919/// `None` if no registered scheduler matches.
2920///
2921/// Two `declare_scheduler!` invocations that share a `name = "..."`
2922/// value (under distinct const idents) both register in
2923/// [`KTSTR_SCHEDULERS`]; a linear scan returns the first match and
2924/// the second is unreachable. This function panics on the first call
2925/// when any duplicate exists so the misconfiguration surfaces
2926/// loudly instead of silently dropping a registration. The scan and
2927/// map construction happen once per process via a `LazyLock`.
2928pub fn find_scheduler(name: &str) -> Option<&'static Scheduler> {
2929 scheduler_index().get(name).copied()
2930}
2931
2932/// Process-wide index from [`Scheduler::name`] to the registered
2933/// `&'static Scheduler`. Built once on first lookup. Detects
2934/// duplicate names and panics with both colliding consts' addresses
2935/// so the test author can identify the two declarations.
2936fn scheduler_index() -> &'static std::collections::HashMap<&'static str, &'static Scheduler> {
2937 static INDEX: std::sync::LazyLock<std::collections::HashMap<&'static str, &'static Scheduler>> =
2938 std::sync::LazyLock::new(|| {
2939 build_scheduler_index_or_panic(KTSTR_SCHEDULERS.iter().copied())
2940 });
2941 &INDEX
2942}
2943
2944/// Build a name → scheduler map from an iterator of registered
2945/// schedulers, panicking on the first duplicate name. Factored out
2946/// so `tests` can exercise the duplicate-detection branch against a
2947/// mock slice — the real [`KTSTR_SCHEDULERS`] is the union of every
2948/// `declare_scheduler!` invocation in the linked binary and so
2949/// cannot host an intentional duplicate without poisoning every
2950/// other test.
2951fn build_scheduler_index_or_panic<I>(
2952 schedulers: I,
2953) -> std::collections::HashMap<&'static str, &'static Scheduler>
2954where
2955 I: IntoIterator<Item = &'static Scheduler>,
2956{
2957 let mut map: std::collections::HashMap<&'static str, &'static Scheduler> =
2958 std::collections::HashMap::new();
2959 for sched in schedulers {
2960 if let Some(prev) = map.insert(sched.name, sched)
2961 && !std::ptr::eq(prev, sched)
2962 {
2963 // `{:p}` prints the pointer in the standard `0x…` form
2964 // so a user diff'ing two declarations can tell at a
2965 // glance whether they're literally the same static
2966 // (re-export of the same const, harmless) or two
2967 // distinct consts with the same `name = "..."` (the
2968 // collision this guard exists for).
2969 panic!(
2970 "ktstr: duplicate scheduler name `{name}` registered \
2971 in KTSTR_SCHEDULERS:\n \
2972 first: {prev:p}\n \
2973 second: {sched:p}\n\
2974 Two `declare_scheduler!` invocations declared the \
2975 same `name = \"{name}\"`. The first registration \
2976 wins under linear scan and the second is unreachable. \
2977 Rename one of the declarations or remove the \
2978 duplicate.",
2979 name = sched.name,
2980 );
2981 }
2982 }
2983 map
2984}
2985
2986/// Ordered JSON representation of one [`Sysctl`].
2987///
2988/// A scheduler may declare the same key more than once and the last write
2989/// wins, so [`SchedulerJson::sysctls`] uses a sequence of these records rather
2990/// than a JSON object. That preserves declaration order and duplicate keys as
2991/// part of the scheduler's execution identity.
2992#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
2993pub struct SysctlJson {
2994 /// Dotted sysctl key (for example, `"kernel.sched_rr_timeslice_ms"`).
2995 pub key: String,
2996 /// Value written to the sysctl.
2997 pub value: String,
2998}
2999
3000/// JSON shape projected from a registered [`Scheduler`]. Each entry
3001/// carries the complete execution identity needed to compare declarations:
3002/// scheduler name, a [`BinaryKindJson`]-tagged binary specification
3003/// (Discover / Path / Eevdf / KernelBuiltin), guest setup, static scheduler
3004/// configuration, per-scheduler default [`TopologyJson`], always-on scheduler
3005/// args, declared kernel set, and gauntlet constraints. Assertion overrides
3006/// and inline per-test config-file content are intentionally omitted.
3007#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
3008pub struct SchedulerJson {
3009 /// Scheduler name — the `name = "..."` value supplied to
3010 /// [`declare_scheduler!`](crate::declare_scheduler) or
3011 /// [`Scheduler::named`].
3012 pub name: String,
3013 /// Manifest directory of the crate that declared this scheduler.
3014 ///
3015 /// `Discover` resolution is workspace-relative: cargo walks upward from
3016 /// this directory to find the declaring workspace. The verifier parent
3017 /// carries it through scheduler discovery so it can prebuild the exact
3018 /// package once and key the immutable artifact manifest identically to
3019 /// the child cell. The serde default keeps probes from older linked test
3020 /// binaries readable during a rolling upgrade.
3021 #[serde(default)]
3022 pub manifest_dir: String,
3023 /// Binary specification: distinguishes Discover (build via cargo
3024 /// `[[bin]]` name), Path (use absolute path verbatim), Eevdf
3025 /// (kernel default scheduler, no binary), and KernelBuiltin
3026 /// (built into the kernel, enable/disable via guest commands).
3027 /// The variant tag lets the verifier dispatch exhaustively `match`
3028 /// on the binary type without parsing the string.
3029 pub binary_kind: BinaryKindJson,
3030 /// Default VM topology for tests using this scheduler. The
3031 /// verifier sweep's per-cell topology comes from gauntlet presets
3032 /// filtered through `constraints`; this field carries the
3033 /// per-scheduler baseline that test-entry plumbing inherits when
3034 /// a test does not override `numa_nodes`/`llcs`/`cores`/`threads`
3035 /// in its `#[ktstr_test]` attributes. Mirror of
3036 /// [`Scheduler::topology`].
3037 pub topology: TopologyJson,
3038 /// Always-on scheduler CLI args.
3039 pub sched_args: Vec<String>,
3040 /// Guest sysctls applied before scheduler startup, in declaration order.
3041 ///
3042 /// This remains a sequence instead of a map because duplicate keys are
3043 /// meaningful: the last declared value wins.
3044 #[serde(default)]
3045 pub sysctls: Vec<SysctlJson>,
3046 /// Extra guest kernel command-line arguments.
3047 #[serde(default)]
3048 pub kargs: Vec<String>,
3049 /// Optional scheduler cgroup parent path.
3050 #[serde(default)]
3051 pub cgroup_parent: Option<String>,
3052 /// Optional host-side static scheduler config-file path.
3053 #[serde(default)]
3054 pub config_file: Option<String>,
3055 /// Kernel specs (consumed by `cargo_ktstr::kernel::resolve_kernel_set`).
3056 pub kernels: Vec<String>,
3057 /// Named topology presets excluded only from the verifier matrix.
3058 #[serde(default)]
3059 pub verifier_exclude_topologies: Vec<String>,
3060 /// Gauntlet preset constraints (filter the verifier's topology sweep).
3061 pub constraints: TopologyConstraintsJson,
3062}
3063
3064/// A [`SchedulerJson`] plus the number of `#[ktstr_test]`s which use it as
3065/// either their primary or a staged scheduler. Emitted (as a JSON array) by
3066/// the `--ktstr-list-schedulers` probe so `cargo ktstr affected` can enumerate
3067/// declared schedulers AND skip those with zero test uses when producing its
3068/// CI matrix, in one probe.
3069#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
3070pub struct SchedulerListEntry {
3071 /// The projected scheduler.
3072 pub scheduler: SchedulerJson,
3073 /// Count of registered [`KtstrTestEntry`]s whose primary or staged
3074 /// scheduler is this one.
3075 pub test_count: usize,
3076}
3077
3078/// One exact scheduler executable requirement reported by a warmed test
3079/// binary.
3080///
3081/// The artifact identity is `(binary_kind, manifest_dir)`. Repeated primary
3082/// and staged uses collapse into one entry, while `use_count` records how many
3083/// registry edges require it and `schedulers` retains every declared name
3084/// sharing the executable.
3085#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
3086pub struct SchedulerArtifactRequirement {
3087 /// `Discover(package)` or `Path(path)`. Kernel-only schedulers are omitted.
3088 pub binary_kind: BinaryKindJson,
3089 /// Exact declaring `CARGO_MANIFEST_DIR`.
3090 pub manifest_dir: String,
3091 /// Sorted, unique scheduler names using the executable.
3092 pub schedulers: Vec<String>,
3093 /// Number of primary plus staged references across [`KTSTR_TESTS`].
3094 pub use_count: usize,
3095}
3096
3097/// Complete scheduler metadata projected from one test binary.
3098///
3099/// `cargo ktstr` reconstructs this object from the binary's versioned ELF
3100/// stamp without executing it. The private
3101/// `--ktstr-list-scheduler-manifest` runtime projection remains available to
3102/// internal callers and as an exact parity oracle.
3103#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
3104pub struct SchedulerManifestProbe {
3105 /// Every scheduler declaration linked into this test binary.
3106 pub declarations: Vec<SchedulerListEntry>,
3107 /// Every userspace scheduler executable referenced by its test registry.
3108 pub artifact_requirements: Vec<SchedulerArtifactRequirement>,
3109 /// Every registered test paired once with each primary and staged
3110 /// scheduler it exercises.
3111 pub tests: Vec<SchedulerTestJson>,
3112}
3113
3114/// Private CLI discriminator for the combined scheduler-manifest probe.
3115#[doc(hidden)]
3116pub const SCHEDULER_MANIFEST_PROBE_ARG: &str = "--ktstr-list-scheduler-manifest";
3117
3118/// A single `#[ktstr_test]` paired with one scheduler it exercises. A test
3119/// contributes one entry for its primary scheduler and one for every staged
3120/// scheduler. Included in [`SchedulerManifestProbe::tests`] and also emitted
3121/// as the legacy JSON array for `--ktstr-list-scheduler-tests`.
3122#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
3123pub struct SchedulerTestJson {
3124 /// The `#[ktstr_test]` function name, as registered.
3125 pub test: String,
3126 /// The declared scheduler's name (the `SchedulerJson::name` field).
3127 pub scheduler: String,
3128}
3129
3130/// JSON-friendly form of [`SchedulerSpec`] tagged so the verifier
3131/// dispatch can exhaustively `match` on the variant. `Discover` and
3132/// `Path` both carry a string identifier; `Eevdf` and
3133/// `KernelBuiltin` both signal "no BPF to verify".
3134#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
3135#[serde(rename_all = "snake_case", tag = "kind", content = "value")]
3136pub enum BinaryKindJson {
3137 /// Cargo `[[bin]]` name. Verifier resolves via `build_and_find_binary`.
3138 Discover(String),
3139 /// Absolute filesystem path. Verifier checks `path.exists()` and uses verbatim.
3140 Path(String),
3141 /// Kernel default scheduler (EEVDF on current kernels). No BPF, no binary.
3142 Eevdf,
3143 /// Built into the kernel (e.g. `scx_simple` enabled via sysfs). No userspace binary.
3144 KernelBuiltin,
3145}
3146
3147fn collect_scheduler_artifact_requirements<'a>(
3148 schedulers: impl IntoIterator<Item = &'a Scheduler>,
3149) -> Vec<SchedulerArtifactRequirement> {
3150 struct Accumulator {
3151 binary_kind: BinaryKindJson,
3152 manifest_dir: String,
3153 schedulers: std::collections::BTreeSet<String>,
3154 use_count: usize,
3155 }
3156
3157 let mut requirements: std::collections::BTreeMap<(u8, String, String), Accumulator> =
3158 std::collections::BTreeMap::new();
3159 for scheduler in schedulers {
3160 let (kind_order, value, binary_kind) = match scheduler.binary {
3161 SchedulerSpec::Discover(package) => (
3162 0,
3163 package.to_string(),
3164 BinaryKindJson::Discover(package.to_string()),
3165 ),
3166 SchedulerSpec::Path(path) => {
3167 (1, path.to_string(), BinaryKindJson::Path(path.to_string()))
3168 }
3169 SchedulerSpec::Eevdf | SchedulerSpec::KernelBuiltin { .. } => continue,
3170 };
3171 // Keep the empty runtime sentinel VERBATIM in requirement identities:
3172 // probe output can be persisted into the machine-shared artifact
3173 // cache, and an eagerly resolved absolute path would poison it for
3174 // every other checkout. The orchestrator resolves at per-run
3175 // consumption (`prepare_scheduler_artifacts_from_requirements`).
3176 let manifest_dir = scheduler.manifest_dir.to_string();
3177 let accumulator = requirements
3178 .entry((kind_order, value, manifest_dir.clone()))
3179 .or_insert_with(|| Accumulator {
3180 binary_kind,
3181 manifest_dir,
3182 schedulers: std::collections::BTreeSet::new(),
3183 use_count: 0,
3184 });
3185 accumulator.schedulers.insert(scheduler.name.to_string());
3186 accumulator.use_count += 1;
3187 }
3188 requirements
3189 .into_values()
3190 .map(|requirement| SchedulerArtifactRequirement {
3191 binary_kind: requirement.binary_kind,
3192 manifest_dir: requirement.manifest_dir,
3193 schedulers: requirement.schedulers.into_iter().collect(),
3194 use_count: requirement.use_count,
3195 })
3196 .collect()
3197}
3198
3199fn test_schedulers<'a>(
3200 primary: &'a Scheduler,
3201 staged: &'a [&'a Scheduler],
3202) -> impl Iterator<Item = &'a Scheduler> + 'a {
3203 std::iter::once(primary).chain(staged.iter().copied())
3204}
3205
3206fn collect_scheduler_list_entries_from<'a>(
3207 schedulers: impl IntoIterator<Item = &'a Scheduler>,
3208 tests: impl IntoIterator<Item = (&'a Scheduler, &'a [&'a Scheduler])>,
3209) -> Vec<SchedulerListEntry> {
3210 let mut test_counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
3211 for (primary, staged) in tests {
3212 for scheduler in test_schedulers(primary, staged) {
3213 *test_counts.entry(scheduler.name).or_insert(0) += 1;
3214 }
3215 }
3216 schedulers
3217 .into_iter()
3218 .map(|scheduler| SchedulerListEntry {
3219 scheduler: SchedulerJson::from_scheduler(scheduler),
3220 test_count: test_counts.get(scheduler.name).copied().unwrap_or(0),
3221 })
3222 .collect()
3223}
3224
3225fn collect_scheduler_list_entries() -> Vec<SchedulerListEntry> {
3226 collect_scheduler_list_entries_from(
3227 KTSTR_SCHEDULERS.iter().copied(),
3228 KTSTR_TESTS
3229 .iter()
3230 .map(|test| (test.scheduler, test.staged_schedulers)),
3231 )
3232}
3233
3234fn collect_registered_scheduler_artifact_requirements() -> Vec<SchedulerArtifactRequirement> {
3235 let schedulers = KTSTR_TESTS.iter().flat_map(|entry| {
3236 std::iter::once(entry.scheduler).chain(entry.staged_schedulers.iter().copied())
3237 });
3238 collect_scheduler_artifact_requirements(schedulers)
3239}
3240
3241fn collect_scheduler_tests_from<'a>(
3242 tests: impl IntoIterator<Item = (&'a str, &'a Scheduler, &'a [&'a Scheduler])>,
3243) -> Vec<SchedulerTestJson> {
3244 tests
3245 .into_iter()
3246 .flat_map(|(test, primary, staged)| {
3247 test_schedulers(primary, staged).map(move |scheduler| SchedulerTestJson {
3248 test: test.to_string(),
3249 scheduler: scheduler.name.to_string(),
3250 })
3251 })
3252 .collect()
3253}
3254
3255fn collect_scheduler_tests() -> Vec<SchedulerTestJson> {
3256 collect_scheduler_tests_from(
3257 KTSTR_TESTS
3258 .iter()
3259 .map(|test| (test.name, test.scheduler, test.staged_schedulers)),
3260 )
3261}
3262
3263fn collect_scheduler_manifest_probe() -> SchedulerManifestProbe {
3264 SchedulerManifestProbe {
3265 declarations: collect_scheduler_list_entries(),
3266 artifact_requirements: collect_registered_scheduler_artifact_requirements(),
3267 tests: collect_scheduler_tests(),
3268 }
3269}
3270
3271/// JSON-friendly mirror of `Topology` for the verifier wire format.
3272/// Captures the four-tuple shape (numa nodes × LLCs × cores × threads)
3273/// the per-scheduler baseline topology was declared with. The verifier
3274/// uses this when computing the sweep matrix — the baseline anchors
3275/// the default cell when no gauntlet preset matches the
3276/// scheduler's constraints.
3277#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
3278pub struct TopologyJson {
3279 /// NUMA node count. Maps to [`Topology::num_numa_nodes`].
3280 pub num_numa_nodes: u32,
3281 /// Last-level cache (LLC) count, equivalent to "sockets" on
3282 /// pre-CCX/CCD x86. Maps to [`Topology::num_llcs`].
3283 pub num_llcs: u32,
3284 /// Physical cores per LLC. Mirrors `Topology::cores_per_llc`.
3285 pub cores_per_llc: u32,
3286 /// Hardware threads per physical core. `1` for non-SMT; `2`
3287 /// for x86 hyperthreading. Mirrors `Topology::threads_per_core`.
3288 pub threads_per_core: u32,
3289}
3290
3291impl TopologyJson {
3292 /// Single-CPU baseline: 1 NUMA node × 1 LLC × 1 core × 1 thread.
3293 /// Used by `cargo ktstr verifier` and verifier-pipeline tests as
3294 /// the no-scheduling-workload default.
3295 pub const SINGLE_CPU: Self = Self {
3296 num_numa_nodes: 1,
3297 num_llcs: 1,
3298 cores_per_llc: 1,
3299 threads_per_core: 1,
3300 };
3301}
3302
3303/// Result-based validation for wire-format topology values. Lets the
3304/// verifier dispatch surface a per-cell "topology rejected" diagnostic
3305/// instead of taking the [`Topology::new`] panic surface in the builder.
3306/// Mirrors [`Topology::validate`] — any field == 0, overflow in total
3307/// CPU count, or `llcs` not divisible by `numa_nodes` returns `Err`.
3308/// The result is a uniform-distribution [`Topology`] (`nodes = None`,
3309/// `distances = None`); explicit per-node config and distance matrices
3310/// require constructing [`Topology`] directly.
3311impl TryFrom<TopologyJson> for Topology {
3312 type Error = String;
3313
3314 fn try_from(value: TopologyJson) -> Result<Self, Self::Error> {
3315 let topo = Self {
3316 llcs: value.num_llcs,
3317 cores_per_llc: value.cores_per_llc,
3318 threads_per_core: value.threads_per_core,
3319 numa_nodes: value.num_numa_nodes,
3320 nodes: None,
3321 distances: None,
3322 llc_cores: None,
3323 };
3324 topo.validate()?;
3325 Ok(topo)
3326 }
3327}
3328
3329/// Project a [`Topology`] into its wire-format mirror. Drops the
3330/// `nodes` and `distances` fields (uniform-distribution shape only);
3331/// callers that need to preserve explicit per-node config or distance
3332/// matrices must not use this conversion. Takes [`Topology`] by value
3333/// (it derives [`Copy`]) to match the by-value shape of
3334/// [`From<TopologyConstraintsJson> for TopologyConstraints`].
3335impl From<Topology> for TopologyJson {
3336 fn from(t: Topology) -> Self {
3337 Self {
3338 num_numa_nodes: t.numa_nodes,
3339 num_llcs: t.llcs,
3340 cores_per_llc: t.cores_per_llc,
3341 threads_per_core: t.threads_per_core,
3342 }
3343 }
3344}
3345
3346/// JSON-friendly mirror of [`TopologyConstraints`] — the host-side
3347/// `Option<u32>` fields serialize as `null` (default serde behavior;
3348/// no `skip_serializing_if`) rather than the `Some(N)`/`None`-tagged
3349/// shapes serde uses for `Option` inside larger struct graphs.
3350/// Field semantics match [`TopologyConstraints`] verbatim; see that
3351/// type for per-field documentation.
3352#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
3353pub struct TopologyConstraintsJson {
3354 pub min_numa_nodes: u32,
3355 pub max_numa_nodes: Option<u32>,
3356 pub min_llcs: u32,
3357 pub max_llcs: Option<u32>,
3358 pub requires_smt: bool,
3359 pub min_cpus: u32,
3360 pub max_cpus: Option<u32>,
3361}
3362
3363/// Infallible shape conversion — every field maps 1:1 to
3364/// [`TopologyConstraints`], so the verifier sweep dispatch can reuse
3365/// the same `accepts` / `accepts_no_perf_mode` filters that gauntlet
3366/// dispatch uses.
3367impl From<TopologyConstraintsJson> for TopologyConstraints {
3368 fn from(j: TopologyConstraintsJson) -> Self {
3369 Self {
3370 min_numa_nodes: j.min_numa_nodes,
3371 max_numa_nodes: j.max_numa_nodes,
3372 min_llcs: j.min_llcs,
3373 max_llcs: j.max_llcs,
3374 requires_smt: j.requires_smt,
3375 min_cpus: j.min_cpus,
3376 max_cpus: j.max_cpus,
3377 }
3378 }
3379}
3380
3381fn verifier_kernel_entry_matches_spec(label: &str, sanitized: &str, spec: &str) -> bool {
3382 use crate::kernel_path::{KernelId, decompose_version_for_compare};
3383
3384 match KernelId::parse(spec) {
3385 KernelId::Version(spec_ver) => {
3386 label == spec_ver || sanitized == super::sanitize_kernel_label(&spec_ver)
3387 }
3388 KernelId::Range { start, end, .. } => {
3389 let Some(entry_t) = decompose_version_for_compare(label) else {
3390 return false;
3391 };
3392 let Some(start_t) = decompose_version_for_compare(&start) else {
3393 return false;
3394 };
3395 let Some(end_t) = decompose_version_for_compare(&end) else {
3396 return false;
3397 };
3398 entry_t >= start_t && entry_t <= end_t
3399 }
3400 KernelId::CacheKey(_)
3401 | KernelId::Path(_)
3402 | KernelId::Git { .. }
3403 | KernelId::Package { .. }
3404 | KernelId::Distro { .. } => sanitized == super::sanitize_kernel_label(spec),
3405 }
3406}
3407
3408pub(super) fn verifier_kernel_specs_accept<'a>(
3409 declared: impl IntoIterator<Item = &'a str>,
3410 label: &str,
3411 sanitized: &str,
3412) -> bool {
3413 let mut declared_any = false;
3414 for spec in declared {
3415 declared_any = true;
3416 if verifier_kernel_entry_matches_spec(label, sanitized, spec) {
3417 return true;
3418 }
3419 }
3420 !declared_any
3421}
3422
3423impl SchedulerJson {
3424 /// Whether one resolved kernel entry survives this scheduler's declared
3425 /// kernel filter. Shared by test-binary cell emission and the
3426 /// `cargo ktstr verifier` parent prebuild planner so both sides classify
3427 /// the same raw/sanitized label pair identically.
3428 pub fn accepts_verifier_kernel(&self, label: &str, sanitized: &str) -> bool {
3429 verifier_kernel_specs_accept(self.kernels.iter().map(String::as_str), label, sanitized)
3430 }
3431
3432 /// Whether one canned topology preset survives this scheduler's verifier
3433 /// constraints and named verifier-only exclusions.
3434 pub fn accepts_verifier_preset(&self, preset: &crate::gauntlet::TopoPreset) -> bool {
3435 TopologyConstraints::from(self.constraints).accepts_verifier(&preset.topology)
3436 && !self
3437 .verifier_exclude_topologies
3438 .iter()
3439 .any(|excluded| excluded == preset.name)
3440 }
3441
3442 /// Whether the resolved kernel × canned-preset matrix contains at least
3443 /// one cell this scheduler can emit. Binary-kind, path-existence,
3444 /// workspace-membership, and scheduler-name checks are intentionally
3445 /// handled by the callers because they require registry or filesystem
3446 /// context; the matrix policy itself stays pure and shared.
3447 pub fn has_accepted_verifier_cell<'a>(
3448 &self,
3449 kernels: impl IntoIterator<Item = (&'a str, &'a str)>,
3450 presets: &[crate::gauntlet::TopoPreset],
3451 ) -> bool {
3452 kernels
3453 .into_iter()
3454 .any(|(label, sanitized)| self.accepts_verifier_kernel(label, sanitized))
3455 && presets
3456 .iter()
3457 .any(|preset| self.accepts_verifier_preset(preset))
3458 }
3459
3460 /// Project a `Scheduler` static into its JSON shape.
3461 pub fn from_scheduler(s: &Scheduler) -> Self {
3462 let binary_kind = match s.binary {
3463 SchedulerSpec::Discover(n) => BinaryKindJson::Discover(n.to_string()),
3464 SchedulerSpec::Path(p) => BinaryKindJson::Path(p.to_string()),
3465 SchedulerSpec::Eevdf => BinaryKindJson::Eevdf,
3466 SchedulerSpec::KernelBuiltin { .. } => BinaryKindJson::KernelBuiltin,
3467 };
3468 Self {
3469 name: s.name.to_string(),
3470 // The effective (never-empty) dir: wire consumers
3471 // (`scheduler_artifact`, the verifier planner) reject an
3472 // empty manifest_dir, so the runtime sentinel must not
3473 // escape the process.
3474 manifest_dir: s.effective_manifest_dir().to_string(),
3475 binary_kind,
3476 topology: TopologyJson {
3477 num_numa_nodes: s.topology.num_numa_nodes(),
3478 num_llcs: s.topology.num_llcs(),
3479 cores_per_llc: s.topology.cores_per_llc,
3480 threads_per_core: s.topology.threads_per_core,
3481 },
3482 sched_args: s.sched_args.iter().map(|a| a.to_string()).collect(),
3483 sysctls: s
3484 .sysctls
3485 .iter()
3486 .map(|sysctl| SysctlJson {
3487 key: sysctl.key().to_string(),
3488 value: sysctl.value().to_string(),
3489 })
3490 .collect(),
3491 kargs: s.kargs.iter().map(|arg| arg.to_string()).collect(),
3492 cgroup_parent: s.cgroup_parent.map(|parent| parent.as_str().to_string()),
3493 config_file: s.config_file.map(str::to_string),
3494 kernels: s.kernels.iter().map(|k| k.to_string()).collect(),
3495 verifier_exclude_topologies: s
3496 .verifier_exclude_topologies
3497 .iter()
3498 .map(|p| p.to_string())
3499 .collect(),
3500 constraints: TopologyConstraintsJson {
3501 min_numa_nodes: s.constraints.min_numa_nodes,
3502 max_numa_nodes: s.constraints.max_numa_nodes,
3503 min_llcs: s.constraints.min_llcs,
3504 max_llcs: s.constraints.max_llcs,
3505 requires_smt: s.constraints.requires_smt,
3506 min_cpus: s.constraints.min_cpus,
3507 max_cpus: s.constraints.max_cpus,
3508 },
3509 }
3510 }
3511}
3512
3513::ctor::declarative::ctor! {
3514/// Ctor that intercepts `--ktstr-list-schedulers` before `main()` runs.
3515/// Walks [`KTSTR_SCHEDULERS`], emits a [`SchedulerListEntry`] per scheduler
3516/// (its [`SchedulerJson`] projection plus the count of primary and staged
3517/// uses across [`KTSTR_TESTS`]) as a single JSON array on stdout, and exits
3518/// with status 0.
3519///
3520/// One ctor per binary, regardless of how many schedulers the binary
3521/// registers — walks the slices once and emits a single JSON array. The
3522/// `test_count` is what lets `cargo ktstr affected` drop zero-test schedulers
3523/// from its CI matrix without a second probe.
3524///
3525/// Uses ctor's declarative `ctor::declarative::ctor! { ... }` form;
3526/// the proc-macro `#[ctor::ctor(...)]` form is re-exported at
3527/// `crate::__private::ctor::ctor` for downstream consumers.
3528#[ctor(unsafe)]
3529fn __ktstr_list_schedulers() {
3530 if !std::env::args().any(|a| a == "--ktstr-list-schedulers") {
3531 return;
3532 }
3533 let entries = collect_scheduler_list_entries();
3534 let json = ::serde_json::to_string(&entries).expect("serialize schedulers");
3535 println!("{json}");
3536 std::process::exit(0);
3537}
3538}
3539
3540::ctor::declarative::ctor! {
3541/// Ctor that emits declarations, artifact requirements, and per-test scheduler
3542/// mappings for one test binary in a single process startup.
3543#[ctor(unsafe)]
3544fn __ktstr_list_scheduler_manifest() {
3545 if !std::env::args().any(|argument| {
3546 argument == SCHEDULER_MANIFEST_PROBE_ARG
3547 }) {
3548 return;
3549 }
3550 let manifest = collect_scheduler_manifest_probe();
3551 let json = ::serde_json::to_string(&manifest).expect("serialize scheduler manifest probe");
3552 println!("{json}");
3553 std::process::exit(0);
3554}
3555}
3556
3557::ctor::declarative::ctor! {
3558/// Ctor that reports every scheduler executable referenced by this binary's
3559/// [`KTSTR_TESTS`] registry.
3560///
3561/// Both each test's primary scheduler and every `staged_schedulers` entry are
3562/// included. `Path` and `Discover` requirements are deduplicated by exact
3563/// binary specification plus declaring manifest directory; kernel-only
3564/// schedulers are omitted. The `cargo ktstr` parent uses this probe to make
3565/// one strict artifact manifest complete before any nextest child starts.
3566#[ctor(unsafe)]
3567fn __ktstr_list_scheduler_artifact_requirements() {
3568 if !std::env::args().any(|argument| {
3569 argument == "--ktstr-list-scheduler-artifact-requirements"
3570 }) {
3571 return;
3572 }
3573 let requirements = collect_registered_scheduler_artifact_requirements();
3574 let json =
3575 ::serde_json::to_string(&requirements).expect("serialize scheduler artifact requirements");
3576 println!("{json}");
3577 std::process::exit(0);
3578}
3579}
3580
3581::ctor::declarative::ctor! {
3582/// Ctor that intercepts `--ktstr-list-scheduler-tests` before `main()` runs.
3583/// Walks [`KTSTR_TESTS`], emits a [`SchedulerTestJson`] for each test's primary
3584/// and staged scheduler as a single JSON array on stdout, and exits 0.
3585/// Distinct from `--ktstr-list-schedulers`: this is test-NAME level, retained
3586/// as the legacy mapping probe.
3587#[ctor(unsafe)]
3588fn __ktstr_list_scheduler_tests() {
3589 if !std::env::args().any(|a| a == "--ktstr-list-scheduler-tests") {
3590 return;
3591 }
3592 let entries = collect_scheduler_tests();
3593 let json = ::serde_json::to_string(&entries).expect("serialize scheduler tests");
3594 println!("{json}");
3595 std::process::exit(0);
3596}
3597}
3598
3599/// Default `post_vm` callback emitted by `#[ktstr_test]` when the
3600/// attribute omits `post_vm = ...`. Asserts that at least one
3601/// periodic snapshot produced REAL BPF state during the workload
3602/// window WHEN periodic was configured (`num_snapshots > 0`); when
3603/// periodic was disabled (`num_snapshots == 0`), the helper is a
3604/// no-op and returns `Ok`.
3605///
3606/// This is the smoke-floor for any periodic-configured test:
3607/// "the test produced meaningful data." Importantly, the floor
3608/// reads
3609/// [`SnapshotBridge::periodic_real_count`](crate::scenario::snapshot::SnapshotBridge::periodic_real_count) —
3610/// NOT [`VmResult::periodic_fired`](crate::vmm::VmResult::periodic_fired).
3611/// The latter counts every periodic boundary the coordinator
3612/// attempted, INCLUDING placeholder rows from rendezvous timeouts;
3613/// a scheduler that attaches but produces nothing but placeholders
3614/// would pass the `periodic_fired >= 1` floor and obscure the
3615/// broken-scheduler diagnosis. The real-count floor catches that
3616/// case (placeholder-only fills surface as zero) while tolerating
3617/// the realistic single-snapshot timeout flake (one real capture
3618/// among N is enough to pass the floor).
3619///
3620/// Tests that need stronger assertions (per-snapshot field reads,
3621/// per-phase ratios, etc.) supply their own `post_vm = my_checker`
3622/// instead.
3623///
3624/// The macro routes this fn pointer into [`KtstrTestEntry::post_vm`]
3625/// so the runner's existing dispatch path applies it identically
3626/// to an author-supplied callback.
3627pub fn default_post_vm_periodic_fired(result: &crate::vmm::VmResult) -> anyhow::Result<()> {
3628 // Short-circuit when the VM run already failed: the underlying
3629 // crash/timeout already drives the test failure with its own
3630 // diagnostic. Emitting a periodic-floor Err on top obscures the
3631 // real cause (e.g., a scheduler that exited before any periodic
3632 // boundary fired would surface as "0 real captures" here
3633 // instead of the scheduler-log message that explains the
3634 // exit). The runner's own success path renders the crash; let
3635 // it.
3636 if !result.success {
3637 return Ok(());
3638 }
3639 if result.periodic_target == 0 {
3640 return Ok(());
3641 }
3642 let real = result.snapshot_bridge.periodic_real_count();
3643 if real >= 1 {
3644 return Ok(());
3645 }
3646 // Witnessed starvation: the readiness-gated capture chain can
3647 // legitimately produce zero real captures when the host was
3648 // saturated enough that accessor-init / the KASLR publish outlasted
3649 // the workload window (see `capture_starvation_witness`). SKIP —
3650 // an environmental non-verdict — rather than fail; a quiet-host
3651 // miss still fails below, which is the regression this floor
3652 // exists to catch.
3653 crate::test_support::eval::periodic_starvation_gate(result, 1)?;
3654 anyhow::bail!(
3655 "no periodic snapshot produced real BPF state \
3656 (periodic_real_count=0, periodic_fired={}, target={}) — \
3657 scheduler attached but every snapshot was a placeholder \
3658 (typical cause: scheduler stalled during the workload and \
3659 the freeze rendezvous timed out fetching state; less \
3660 commonly: gate suppression rejected every capture); the \
3661 contention witness shows no host starvation to blame",
3662 result.periodic_fired,
3663 result.periodic_target,
3664 );
3665}
3666
3667#[cfg(test)]
3668mod tests {
3669 use super::*;
3670 use crate::scenario::Ctx;
3671
3672 /// Minimal Ctx for invoking `default_test_func` without booting a
3673 /// real workload. The func signature only requires `&Ctx`; the
3674 /// stub returns Err unconditionally so no field on Ctx is read.
3675 fn dummy_ctx() -> (crate::cgroup::CgroupManager, crate::topology::TestTopology) {
3676 let cgroups = crate::cgroup::CgroupManager::new("/sys/fs/cgroup/ktstr-dummy");
3677 let topo = crate::topology::TestTopology::from_vm_topology(&Topology {
3678 llcs: 1,
3679 cores_per_llc: 1,
3680 threads_per_core: 1,
3681 numa_nodes: 1,
3682 nodes: None,
3683 distances: None,
3684 llc_cores: None,
3685 });
3686 (cgroups, topo)
3687 }
3688
3689 /// `WatchBpfMap::new` accepts the `PerCpuCounter` agg (pub-API surface); the
3690 /// const-fn validates map/field/label format, not the agg, so the variant
3691 /// is stored verbatim.
3692 #[test]
3693 fn watch_bpf_map_new_accepts_per_cpu_counter() {
3694 let w = WatchBpfMap::new(
3695 "cpu_ctx_stor",
3696 "evt_count",
3697 BpfMapAgg::PerCpuCounter,
3698 "evt_count",
3699 );
3700 assert_eq!(w.agg, BpfMapAgg::PerCpuCounter);
3701 }
3702
3703 #[test]
3704 fn ktstr_test_entry_default_fields() {
3705 let d = KtstrTestEntry::DEFAULT;
3706 assert_eq!(d.name, "");
3707 // func is the stub — verified separately in
3708 // default_test_func_returns_err.
3709 assert_eq!(d.topology.llcs, 1);
3710 assert_eq!(d.topology.cores_per_llc, 2);
3711 assert_eq!(d.topology.threads_per_core, 1);
3712 assert_eq!(d.topology.numa_nodes, 1);
3713 assert!(d.topology.nodes.is_none());
3714 assert!(d.topology.distances.is_none());
3715 assert_eq!(d.constraints, TopologyConstraints::DEFAULT);
3716 assert_eq!(d.memory_mib, 256);
3717 // scheduler defaults to `&Scheduler::EEVDF`, whose
3718 // compile-time-fixed `.name = "eevdf"`. Read directly via
3719 // field access — no kind dispatch.
3720 assert_eq!(d.scheduler.name, "eevdf");
3721 assert!(!d.scheduler.has_active_scheduling());
3722 assert!(d.auto_repro);
3723 assert!(d.extra_sched_args.is_empty());
3724 assert_eq!(d.watchdog_timeout, Duration::from_secs(5));
3725 assert!(d.bpf_map_write.is_empty());
3726 assert!(d.watch_bpf_maps.is_empty());
3727 assert!(!d.performance_mode);
3728 assert!(!d.no_perf_mode);
3729 assert_eq!(d.duration, Duration::from_secs(12));
3730 assert!(!d.expect_err);
3731 assert!(!d.survives_storm);
3732 assert!(!d.host_only);
3733 // Payload slot defaults to None (scheduler-only entry); workloads
3734 // slice defaults to empty. Macro emits these as explicit None/&[]
3735 // so struct-update spreaders also get the right values.
3736 assert!(d.payload.is_none());
3737 assert!(d.workloads.is_empty());
3738 // post_vm_unconditional defaults to None — the unconditional
3739 // dispatch arm in `run_post_vm_callbacks` is a no-op for the default entry,
3740 // matching the macro's omit-when-unset codegen.
3741 assert!(d.post_vm_unconditional.is_none());
3742 }
3743
3744 /// Empirical pin: `..Self::new()` works in a `static` spread.
3745 /// KtstrTestEntry has no Drop-bearing transitive fields (every
3746 /// type in the struct is Copy or holds only `&'static`/`Option`/
3747 /// primitives), so `Self::new()` returning a const Self literal
3748 /// is const-evaluable AND the temporary it produces needs no
3749 /// destructor. Both DEFAULT and new() are valid in const-spread.
3750 #[allow(dead_code)]
3751 static ENTRY_VIA_NEW: KtstrTestEntry = KtstrTestEntry {
3752 name: "via_new",
3753 ..KtstrTestEntry::new()
3754 };
3755
3756 #[allow(dead_code)]
3757 static ENTRY_VIA_DEFAULT: KtstrTestEntry = KtstrTestEntry {
3758 name: "via_default",
3759 ..KtstrTestEntry::DEFAULT
3760 };
3761
3762 #[test]
3763 fn ktstr_test_entry_const_spread_works_via_both_new_and_default() {
3764 assert_eq!(ENTRY_VIA_NEW.name, "via_new");
3765 assert_eq!(ENTRY_VIA_DEFAULT.name, "via_default");
3766 // Both spread forms produce identical non-name fields.
3767 assert_eq!(ENTRY_VIA_NEW.memory_mib, ENTRY_VIA_DEFAULT.memory_mib);
3768 assert_eq!(ENTRY_VIA_NEW.duration, ENTRY_VIA_DEFAULT.duration);
3769 }
3770
3771 #[test]
3772 fn ktstr_test_entry_with_chain_overrides_target_fields() {
3773 let entry = KtstrTestEntry::DEFAULT
3774 .with_name("chain_test")
3775 .with_memory_mib(4096)
3776 .with_duration(Duration::from_secs(30))
3777 .with_auto_repro(false)
3778 .with_performance_mode(true)
3779 .with_num_snapshots(2);
3780 assert_eq!(entry.name, "chain_test");
3781 assert_eq!(entry.memory_mib, 4096);
3782 assert_eq!(entry.duration, Duration::from_secs(30));
3783 assert!(!entry.auto_repro);
3784 assert!(entry.performance_mode);
3785 assert_eq!(entry.num_snapshots, 2);
3786 // Untouched defaults survive.
3787 assert_eq!(entry.scheduler.name, "eevdf");
3788 assert!(!entry.host_only);
3789 // Validate succeeds — the chain produced a usable entry.
3790 entry.validate().expect("chained entry must validate");
3791 }
3792
3793 /// `with_cpu_budget` chains and produces a validating overcommit
3794 /// entry. cpu_budget requires no_perf_mode (it sizes the no-perf
3795 /// vCPU mask), so the two are set together — pinning the setter pair
3796 /// against the validate gate. (cpu_budget is kept out of the
3797 /// performance_mode chain above because the two are contradictory.)
3798 #[test]
3799 fn ktstr_test_entry_with_cpu_budget_chains_with_no_perf_mode() {
3800 let entry = KtstrTestEntry::DEFAULT
3801 .with_name("cpu_budget_chain")
3802 .with_cpu_budget(16)
3803 .with_no_perf_mode(true);
3804 assert_eq!(entry.cpu_budget, Some(16));
3805 assert!(entry.no_perf_mode);
3806 entry
3807 .validate()
3808 .expect("cpu_budget + no_perf_mode chain must validate");
3809 }
3810
3811 /// `without_<field>` returns the original Option<T> field to
3812 /// `None`. The chain symmetry pin: `with_X(v).without_X() ==
3813 /// DEFAULT-state for that field`.
3814 #[test]
3815 fn ktstr_test_entry_without_chain_clears_option_fields() {
3816 use crate::test_support::{OutputFormat, Payload, PayloadKind};
3817 const FIO: Payload = Payload {
3818 name: "fio",
3819 kind: PayloadKind::Binary("fio"),
3820 output: OutputFormat::Json,
3821 default_args: &[],
3822 default_checks: &[],
3823 metrics: &[],
3824 include_files: &[],
3825 uses_parent_pgrp: false,
3826 known_flags: None,
3827 };
3828 let entry = KtstrTestEntry::DEFAULT
3829 .with_name("clear_test")
3830 .with_payload(&FIO)
3831 .with_cleanup_budget(Duration::from_secs(10))
3832 .with_cpu_budget(8)
3833 .without_payload()
3834 .without_cleanup_budget()
3835 .without_cpu_budget();
3836 assert!(entry.payload.is_none());
3837 assert!(entry.cleanup_budget.is_none());
3838 assert!(entry.cpu_budget.is_none());
3839 }
3840
3841 #[test]
3842 fn ktstr_test_entry_payload_slot_can_be_populated() {
3843 use crate::test_support::{OutputFormat, Payload, PayloadKind};
3844 const FIO: Payload = Payload {
3845 name: "fio",
3846 kind: PayloadKind::Binary("fio"),
3847 output: OutputFormat::Json,
3848 default_args: &[],
3849 default_checks: &[],
3850 metrics: &[],
3851 include_files: &[],
3852 uses_parent_pgrp: false,
3853 known_flags: None,
3854 };
3855 let entry = KtstrTestEntry {
3856 name: "payload_entry",
3857 payload: Some(&FIO),
3858 ..KtstrTestEntry::DEFAULT
3859 };
3860 let p = entry.payload.expect("payload set");
3861 assert_eq!(p.name, "fio");
3862 assert!(!p.is_scheduler());
3863 }
3864
3865 #[test]
3866 fn ktstr_test_entry_workloads_slot_accepts_multiple_payloads() {
3867 use crate::test_support::{OutputFormat, Payload, PayloadKind};
3868 const FIO: Payload = Payload {
3869 name: "fio",
3870 kind: PayloadKind::Binary("fio"),
3871 output: OutputFormat::Json,
3872 default_args: &[],
3873 default_checks: &[],
3874 metrics: &[],
3875 include_files: &[],
3876 uses_parent_pgrp: false,
3877 known_flags: None,
3878 };
3879 // stress-ng emits progress / metrics / summaries to stderr; stdout
3880 // is blank. `OutputFormat::Json` yields zero metrics — stdout has
3881 // nothing JSON-shaped to parse, and the stderr fallback sees prose
3882 // rather than JSON so the extraction pipeline returns empty.
3883 const STRESS_NG: Payload = Payload {
3884 name: "stress-ng",
3885 kind: PayloadKind::Binary("stress-ng"),
3886 output: OutputFormat::ExitCode,
3887 default_args: &[],
3888 default_checks: &[],
3889 metrics: &[],
3890 include_files: &[],
3891 uses_parent_pgrp: false,
3892 known_flags: None,
3893 };
3894 let entry = KtstrTestEntry {
3895 name: "multi_workload",
3896 workloads: &[&FIO, &STRESS_NG],
3897 ..KtstrTestEntry::DEFAULT
3898 };
3899 assert_eq!(entry.workloads.len(), 2);
3900 assert_eq!(entry.workloads[0].name, "fio");
3901 assert_eq!(entry.workloads[1].name, "stress-ng");
3902 }
3903
3904 /// `validate()` rejects any `workloads[i]` that is a
3905 /// Scheduler-kind Payload — symmetric with the existing
3906 /// `payload`-slot rejection. Catches the typo where a test
3907 /// author writes `workloads = [Payload::KERNEL_DEFAULT]` instead of a
3908 /// binary payload.
3909 #[test]
3910 fn validate_rejects_scheduler_kind_in_workloads() {
3911 use crate::test_support::{OutputFormat, Payload, PayloadKind};
3912 const GOOD: Payload = Payload {
3913 name: "fio",
3914 kind: PayloadKind::Binary("fio"),
3915 output: OutputFormat::Json,
3916 default_args: &[],
3917 default_checks: &[],
3918 metrics: &[],
3919 include_files: &[],
3920 uses_parent_pgrp: false,
3921 known_flags: None,
3922 };
3923 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
3924 Ok(AssertResult::pass())
3925 }
3926 let entry = KtstrTestEntry {
3927 name: "mixed_kinds",
3928 func: good_test_func,
3929 // Second workload is scheduler-kind → must bail.
3930 workloads: &[&GOOD, &Payload::KERNEL_DEFAULT],
3931 ..KtstrTestEntry::DEFAULT
3932 };
3933 let err = entry.validate().unwrap_err();
3934 let msg = format!("{err}");
3935 assert!(
3936 msg.contains("workloads[1]") && msg.contains("Scheduler-kind"),
3937 "expected workloads[1] Scheduler-kind bail, got: {msg}"
3938 );
3939 assert!(
3940 msg.contains("kernel_default"),
3941 "error must name the offending workload entry, got: {msg}"
3942 );
3943 }
3944
3945 /// Binary-only workloads slip past `validate()` cleanly — the
3946 /// Scheduler-kind check does not over-reject. Pins the happy
3947 /// path against the rejection path so future edits to the
3948 /// workloads loop don't flip polarity.
3949 #[test]
3950 fn validate_accepts_binary_only_workloads() {
3951 use crate::test_support::{OutputFormat, Payload, PayloadKind};
3952 const FIO: Payload = Payload {
3953 name: "fio",
3954 kind: PayloadKind::Binary("fio"),
3955 output: OutputFormat::Json,
3956 default_args: &[],
3957 default_checks: &[],
3958 metrics: &[],
3959 include_files: &[],
3960 uses_parent_pgrp: false,
3961 known_flags: None,
3962 };
3963 // stress-ng emits progress / metrics / summaries to stderr; stdout
3964 // is blank. `OutputFormat::Json` yields zero metrics — stdout has
3965 // nothing JSON-shaped to parse, and the stderr fallback sees prose
3966 // rather than JSON so the extraction pipeline returns empty.
3967 const STRESS_NG: Payload = Payload {
3968 name: "stress-ng",
3969 kind: PayloadKind::Binary("stress-ng"),
3970 output: OutputFormat::ExitCode,
3971 default_args: &[],
3972 default_checks: &[],
3973 metrics: &[],
3974 include_files: &[],
3975 uses_parent_pgrp: false,
3976 known_flags: None,
3977 };
3978 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
3979 Ok(AssertResult::pass())
3980 }
3981 let entry = KtstrTestEntry {
3982 name: "all_binary",
3983 func: good_test_func,
3984 workloads: &[&FIO, &STRESS_NG],
3985 ..KtstrTestEntry::DEFAULT
3986 };
3987 entry.validate().expect("binary-only workloads must pass");
3988 }
3989
3990 // -- staged_schedulers validation tests --
3991 //
3992 // KtstrTestEntry::validate (in entry_validate.rs, via
3993 // validate_basics_and_staging) walks staged_schedulers and
3994 // enforces (a) per-name shape rules via the delegated
3995 // validate_staged_scheduler_name + (b) within-set uniqueness
3996 // via the BTreeSet insert. Both are silent-data-loss classes
3997 // if they regress — invalid names
3998 // would land at corrupt guest staging paths; duplicate names
3999 // would silently overwrite at the same guest path. The
4000 // delegated shape rules are independently tested at
4001 // src/test_support/staged.rs; the smoke test below proves
4002 // the delegation is wired (catches a future refactor that
4003 // inlines dup-check and forgets the shape-check).
4004
4005 /// Empty `staged_schedulers` slice — the default for every
4006 /// test that doesn't use scheduler-lifecycle ops — must validate.
4007 #[test]
4008 fn validate_accepts_empty_staged_schedulers() {
4009 let entry = KtstrTestEntry {
4010 name: "no_staged",
4011 staged_schedulers: &[],
4012 ..KtstrTestEntry::DEFAULT
4013 };
4014 entry.validate().expect("empty staged_schedulers must pass");
4015 }
4016
4017 /// Two distinct well-formed staged schedulers — both pass shape
4018 /// check, names differ. Pins the happy path for the
4019 /// mid-experiment swap use case (mitosis args A → mitosis args
4020 /// B declared as two distinct schedulers).
4021 #[test]
4022 fn validate_accepts_well_formed_unique_staged_schedulers() {
4023 static SCX_MITOSIS_A: Scheduler =
4024 Scheduler::named("scx_mitosis_a").binary_discover("scx_mitosis");
4025 static SCX_MITOSIS_B: Scheduler =
4026 Scheduler::named("scx_mitosis_b").binary_discover("scx_mitosis");
4027 // Slice itself must be `static` so the &'static [...] field
4028 // can borrow it; binding the slice literal to a static at the
4029 // call site moves the const-promotion responsibility off the
4030 // struct-literal expression where lifetime inference can't
4031 // see the longer-lived destination.
4032 static SCHEDS: &[&Scheduler] = &[&SCX_MITOSIS_A, &SCX_MITOSIS_B];
4033 let entry = KtstrTestEntry {
4034 name: "staged_two",
4035 staged_schedulers: SCHEDS,
4036 ..KtstrTestEntry::DEFAULT
4037 };
4038 entry
4039 .validate()
4040 .expect("two distinct well-formed staged schedulers must pass");
4041 }
4042
4043 /// Two staged schedulers with the SAME name collide at the
4044 /// guest-side staging path (`/staging/schedulers/<name>/`). The
4045 /// validate-time dedup catches this before any VM boot; without
4046 /// the pin, a regression that drops the BTreeSet insert check
4047 /// would silently produce a guest layout where the second
4048 /// scheduler overwrites the first.
4049 #[test]
4050 fn validate_rejects_duplicate_staged_scheduler_names() {
4051 static DUPE_A: Scheduler = Scheduler::named("scx_dupe").binary_discover("scx_first");
4052 static DUPE_B: Scheduler = Scheduler::named("scx_dupe").binary_discover("scx_second");
4053 static SCHEDS: &[&Scheduler] = &[&DUPE_A, &DUPE_B];
4054 let entry = KtstrTestEntry {
4055 name: "staged_dupe",
4056 staged_schedulers: SCHEDS,
4057 ..KtstrTestEntry::DEFAULT
4058 };
4059 let err = entry
4060 .validate()
4061 .expect_err("duplicate staged Scheduler.name must reject");
4062 let msg = err.to_string();
4063 assert!(
4064 msg.contains("duplicate"),
4065 "error must name the duplicate-name violation, got: {msg}"
4066 );
4067 assert!(
4068 msg.contains("scx_dupe"),
4069 "error must name the colliding scheduler name, got: {msg}"
4070 );
4071 assert!(
4072 msg.contains("staged_schedulers"),
4073 "error must name the field, got: {msg}"
4074 );
4075 }
4076
4077 /// A staged scheduler with a shape-violating name (path
4078 /// separator) must reject — proves the validate gate delegates
4079 /// to validate_staged_scheduler_name. The exhaustive shape
4080 /// rejections (empty, NUL, leading dot, reserved names) are
4081 /// covered by the `validate_staged_scheduler_name_*` tests in
4082 /// `test_support::staged`; this smoke test
4083 /// pins the delegation site against a future refactor that
4084 /// inlines the dup-check and forgets the shape-check.
4085 #[test]
4086 fn validate_rejects_shape_violating_staged_scheduler_name() {
4087 static BAD_SLASH: Scheduler = Scheduler::named("scx/path").binary_discover("scx_x");
4088 static SCHEDS: &[&Scheduler] = &[&BAD_SLASH];
4089 let entry = KtstrTestEntry {
4090 name: "staged_bad_shape",
4091 staged_schedulers: SCHEDS,
4092 ..KtstrTestEntry::DEFAULT
4093 };
4094 let err = entry
4095 .validate()
4096 .expect_err("path-separator Scheduler.name must reject");
4097 let msg = err.to_string();
4098 assert!(
4099 msg.contains("staged_schedulers"),
4100 "error must name the field — proves the `who` context propagated \
4101 through the delegate call, got: {msg}"
4102 );
4103 // The exact shape-message ("path separators") is the
4104 // validate_staged_scheduler_name contract pinned by
4105 // `validate_staged_scheduler_name_rejects_path_separators` in
4106 // `test_support::staged`, not duplicated here.
4107 }
4108
4109 /// A staged scheduler whose `name` matches the boot
4110 /// [`KtstrTestEntry::scheduler`]'s name must reject — the boot
4111 /// slot already provides that scheduler, and adding it to the
4112 /// staged set produces a guest layout where the boot scheduler
4113 /// is shadowed by the same binary under
4114 /// `/staging/schedulers/<name>/scheduler`. Catches the
4115 /// "stage all the schedulers I might use"
4116 /// misuse pattern at validate time.
4117 #[test]
4118 fn validate_rejects_staged_scheduler_duplicating_boot_scheduler() {
4119 static BOOT: Scheduler = Scheduler::named("scx_mitosis").binary_discover("scx_mitosis");
4120 static STAGED_COPY: Scheduler =
4121 Scheduler::named("scx_mitosis").binary_discover("scx_mitosis");
4122 static SCHEDS: &[&Scheduler] = &[&STAGED_COPY];
4123 let entry = KtstrTestEntry {
4124 name: "staged_dup_of_boot",
4125 scheduler: &BOOT,
4126 staged_schedulers: SCHEDS,
4127 ..KtstrTestEntry::DEFAULT
4128 };
4129 let err = entry
4130 .validate()
4131 .expect_err("staged scheduler duplicating boot scheduler must reject");
4132 let msg = err.to_string();
4133 assert!(
4134 msg.contains("boot scheduler"),
4135 "error must name the boot-scheduler violation, got: {msg}"
4136 );
4137 assert!(
4138 msg.contains("scx_mitosis"),
4139 "error must name the colliding scheduler, got: {msg}"
4140 );
4141 assert!(
4142 msg.contains("Op::AttachScheduler") || msg.contains("Op::ReplaceScheduler"),
4143 "error must point to the lifecycle Ops that USE the staged set, got: {msg}"
4144 );
4145 }
4146
4147 /// `validate()` rejects `host_only=true` paired with a
4148 /// `Some(DiskConfig)`. The combination is unsatisfiable today:
4149 /// `host_only` skips the VM boot that owns the virtio-blk device
4150 /// lifecycle, so the disk never attaches. Catching it at validate
4151 /// time surfaces the misconfiguration during nextest discovery
4152 /// instead of after a confusing host-only run that silently
4153 /// ignored the disk request.
4154 #[test]
4155 fn validate_rejects_host_only_with_disk() {
4156 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4157 Ok(AssertResult::pass())
4158 }
4159 let entry = KtstrTestEntry {
4160 name: "host_only_with_disk",
4161 func: good_test_func,
4162 host_only: true,
4163 disk: Some(crate::vmm::disk_config::DiskConfig::default()),
4164 ..KtstrTestEntry::DEFAULT
4165 };
4166 let err = entry
4167 .validate()
4168 .expect_err("host_only=true + disk=Some must be rejected");
4169 let msg = format!("{err}");
4170 assert!(
4171 msg.contains("host_only=true") && msg.contains("disk"),
4172 "expected host_only+disk diagnostic, got: {msg}",
4173 );
4174 assert!(
4175 msg.contains("host_only_with_disk"),
4176 "error must name the offending entry, got: {msg}",
4177 );
4178 }
4179
4180 /// `host_only=true` with `disk=None` is the legitimate host-side
4181 /// shape: a host-only test running without any VM device. Pins
4182 /// the happy path against the rejection path so future edits
4183 /// to the host_only/disk gate don't flip polarity (rejecting a
4184 /// legitimate combination would silently break every host-only
4185 /// test author).
4186 #[test]
4187 fn validate_accepts_host_only_without_disk() {
4188 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4189 Ok(AssertResult::pass())
4190 }
4191 let entry = KtstrTestEntry {
4192 name: "host_only_no_disk",
4193 func: good_test_func,
4194 host_only: true,
4195 disk: None,
4196 ..KtstrTestEntry::DEFAULT
4197 };
4198 entry
4199 .validate()
4200 .expect("host_only=true + disk=None must validate");
4201 }
4202
4203 /// `host_only=false` (the default) with `disk=Some(..)` is the
4204 /// canonical disk-attached VM test. Pins that the gate fires
4205 /// only on the actual conflict (host_only=true) and not on any
4206 /// `disk=Some(..)` entry — a future tightening that rejected
4207 /// every Some(DiskConfig) would break the entire disk
4208 /// integration test surface.
4209 #[test]
4210 fn validate_accepts_vm_with_disk() {
4211 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4212 Ok(AssertResult::pass())
4213 }
4214 let entry = KtstrTestEntry {
4215 name: "vm_with_disk",
4216 func: good_test_func,
4217 host_only: false,
4218 disk: Some(crate::vmm::disk_config::DiskConfig::default()),
4219 ..KtstrTestEntry::DEFAULT
4220 };
4221 entry
4222 .validate()
4223 .expect("host_only=false + disk=Some must validate");
4224 }
4225
4226 /// `host_only=true` with a non-empty `networks` is rejected for the same
4227 /// reason as disk: host_only skips the VM boot that owns the virtio-net
4228 /// device lifecycle, so the NICs would never attach. Mirrors the disk
4229 /// gate so the macro-surfaced `networks =` attribute can't silently
4230 /// pair with `host_only`.
4231 #[test]
4232 fn validate_rejects_host_only_with_network() {
4233 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4234 Ok(AssertResult::pass())
4235 }
4236 let entry = KtstrTestEntry {
4237 name: "host_only_with_network",
4238 func: good_test_func,
4239 host_only: true,
4240 networks: &[crate::vmm::net_config::NetConfig::DEFAULT],
4241 ..KtstrTestEntry::DEFAULT
4242 };
4243 let err = entry
4244 .validate()
4245 .expect_err("host_only=true + non-empty networks must be rejected");
4246 let msg = format!("{err}");
4247 assert!(
4248 msg.contains("host_only=true") && msg.contains("networks"),
4249 "expected host_only+networks diagnostic, got: {msg}",
4250 );
4251 assert!(
4252 msg.contains("host_only_with_network"),
4253 "error must name the offending entry, got: {msg}",
4254 );
4255 }
4256
4257 /// `host_only=true` with an empty `networks` is the legitimate host-side
4258 /// shape (no NIC). Pins the happy path so a future edit to the gate
4259 /// doesn't flip polarity and reject legitimate host-only tests.
4260 #[test]
4261 fn validate_accepts_host_only_without_network() {
4262 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4263 Ok(AssertResult::pass())
4264 }
4265 let entry = KtstrTestEntry {
4266 name: "host_only_no_network",
4267 func: good_test_func,
4268 host_only: true,
4269 networks: &[],
4270 ..KtstrTestEntry::DEFAULT
4271 };
4272 entry
4273 .validate()
4274 .expect("host_only=true + empty networks must validate");
4275 }
4276
4277 /// `host_only=false` (the default) with a non-empty `networks` is the
4278 /// canonical NIC-attached VM test. Pins that the gate fires only on
4279 /// the host_only conflict, not on every NIC-bearing entry.
4280 #[test]
4281 fn validate_accepts_vm_with_network() {
4282 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4283 Ok(AssertResult::pass())
4284 }
4285 let entry = KtstrTestEntry {
4286 name: "vm_with_network",
4287 func: good_test_func,
4288 host_only: false,
4289 networks: &[crate::vmm::net_config::NetConfig::DEFAULT],
4290 ..KtstrTestEntry::DEFAULT
4291 };
4292 entry
4293 .validate()
4294 .expect("host_only=false + non-empty networks must validate");
4295 }
4296
4297 /// `validate()` rejects `cpu_budget = Some(0)` — a zero host-CPU
4298 /// budget cannot run a VM (the builder would otherwise silently
4299 /// clamp it to 1). Pins the programmatic-construction guard that
4300 /// mirrors the macro's compile-time zero-reject.
4301 #[test]
4302 fn validate_rejects_cpu_budget_zero() {
4303 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4304 Ok(AssertResult::pass())
4305 }
4306 let entry = KtstrTestEntry {
4307 name: "cpu_budget_zero",
4308 func: good_test_func,
4309 cpu_budget: Some(0),
4310 no_perf_mode: true,
4311 ..KtstrTestEntry::DEFAULT
4312 };
4313 let err = entry
4314 .validate()
4315 .expect_err("cpu_budget=Some(0) must be rejected");
4316 let msg = format!("{err}");
4317 assert!(
4318 msg.contains("cpu_budget") && msg.contains("cpu_budget_zero"),
4319 "expected cpu_budget zero diagnostic naming the entry, got: {msg}",
4320 );
4321 }
4322
4323 /// `validate()` rejects `cpu_budget` set without `no_perf_mode` —
4324 /// the budget sizes only the no-perf vCPU mask, so it would be a
4325 /// silent no-op under performance/default mode. Pins the
4326 /// programmatic-construction guard mirroring the macro's gate.
4327 #[test]
4328 fn validate_rejects_cpu_budget_without_no_perf_mode() {
4329 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4330 Ok(AssertResult::pass())
4331 }
4332 let entry = KtstrTestEntry {
4333 name: "cpu_budget_no_no_perf",
4334 func: good_test_func,
4335 cpu_budget: Some(4),
4336 no_perf_mode: false,
4337 ..KtstrTestEntry::DEFAULT
4338 };
4339 let err = entry
4340 .validate()
4341 .expect_err("cpu_budget without no_perf_mode must be rejected");
4342 let msg = format!("{err}");
4343 assert!(
4344 msg.contains("cpu_budget") && msg.contains("no_perf_mode"),
4345 "expected cpu_budget/no_perf_mode diagnostic, got: {msg}",
4346 );
4347 }
4348
4349 /// `cpu_budget` with `no_perf_mode = true` is the legitimate
4350 /// overcommit shape — pins the happy path against the two rejection
4351 /// paths so a future edit can't flip polarity and reject every
4352 /// valid overcommit test.
4353 #[test]
4354 fn validate_accepts_cpu_budget_with_no_perf_mode() {
4355 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4356 Ok(AssertResult::pass())
4357 }
4358 let entry = KtstrTestEntry {
4359 name: "cpu_budget_with_no_perf",
4360 func: good_test_func,
4361 cpu_budget: Some(4),
4362 no_perf_mode: true,
4363 ..KtstrTestEntry::DEFAULT
4364 };
4365 entry
4366 .validate()
4367 .expect("cpu_budget + no_perf_mode must validate");
4368 }
4369
4370 /// `validate()` rejects `perf_delta_assertions` without
4371 /// `performance_mode` — a declared regression gate is only meaningful on
4372 /// a pinned run (mirrors the macro's compile-time reject). Guards the
4373 /// programmatic-construction path.
4374 #[test]
4375 fn validate_rejects_perf_delta_assertions_without_performance_mode() {
4376 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4377 Ok(AssertResult::pass())
4378 }
4379 const GATE: PerfDeltaAssertion = PerfDeltaAssertion::new("worst_spread");
4380 let entry = KtstrTestEntry {
4381 name: "gate_no_perf_mode",
4382 func: good_test_func,
4383 perf_delta_assertions: &[&GATE],
4384 performance_mode: false,
4385 ..KtstrTestEntry::DEFAULT
4386 };
4387 let err = entry
4388 .validate()
4389 .expect_err("perf_delta_assertions without performance_mode must be rejected");
4390 let msg = format!("{err}");
4391 assert!(
4392 msg.contains("perf_delta_assertions") && msg.contains("performance_mode"),
4393 "expected perf_delta_assertions/performance_mode diagnostic, got: {msg}",
4394 );
4395 }
4396
4397 /// `validate()` rejects a `perf_delta_assertions` metric that does not
4398 /// resolve in the registry — `PerfDeltaAssertion::new` validates only the
4399 /// NAME FORMAT at compile time (the registry is not const-accessible), so a
4400 /// typo'd-but-well-formed metric name is caught here at run time. Without it
4401 /// the gate would silently never match a captured field.
4402 #[test]
4403 fn validate_rejects_perf_delta_assertions_unknown_metric() {
4404 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4405 Ok(AssertResult::pass())
4406 }
4407 const GATE: PerfDeltaAssertion = PerfDeltaAssertion::new("totally_made_up_metric");
4408 let entry = KtstrTestEntry {
4409 name: "gate_unknown_metric",
4410 func: good_test_func,
4411 perf_delta_assertions: &[&GATE],
4412 performance_mode: true,
4413 ..KtstrTestEntry::DEFAULT
4414 };
4415 let err = entry
4416 .validate()
4417 .expect_err("an unregistered metric must be rejected");
4418 let msg = format!("{err}");
4419 assert!(
4420 msg.contains("totally_made_up_metric") && msg.contains("unknown metric"),
4421 "expected unknown-metric diagnostic, got: {msg}",
4422 );
4423 }
4424
4425 /// A well-formed, registry-resolving gate under `performance_mode` is the
4426 /// legitimate shape — pins the happy path against the two rejection paths so
4427 /// a future edit can't flip polarity and reject every valid declared gate.
4428 #[test]
4429 fn validate_accepts_perf_delta_assertions_with_performance_mode_and_known_metric() {
4430 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4431 Ok(AssertResult::pass())
4432 }
4433 const GATE: PerfDeltaAssertion = PerfDeltaAssertion::new("worst_spread")
4434 .with_max_regression_pct(5.0)
4435 .with_min_abs(0.5);
4436 let entry = KtstrTestEntry {
4437 name: "gate_ok",
4438 func: good_test_func,
4439 perf_delta_assertions: &[&GATE],
4440 performance_mode: true,
4441 ..KtstrTestEntry::DEFAULT
4442 };
4443 entry
4444 .validate()
4445 .expect("a known metric under performance_mode must validate");
4446 }
4447
4448 /// `validate()` rejects a gate on a render-suppressed rate COMPONENT: it
4449 /// resolves in the registry (so the unknown-metric check passes) but never
4450 /// surfaces a compare finding, so the gate could never fire.
4451 #[test]
4452 fn validate_rejects_perf_delta_assertions_render_suppressed_component() {
4453 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4454 Ok(AssertResult::pass())
4455 }
4456 const GATE: PerfDeltaAssertion = PerfDeltaAssertion::new("total_iterations_pooled");
4457 let entry = KtstrTestEntry {
4458 name: "gate_suppressed_component",
4459 func: good_test_func,
4460 perf_delta_assertions: &[&GATE],
4461 performance_mode: true,
4462 ..KtstrTestEntry::DEFAULT
4463 };
4464 let err = entry
4465 .validate()
4466 .expect_err("a render-suppressed component gate must be rejected");
4467 let msg = format!("{err}");
4468 assert!(
4469 msg.contains("total_iterations_pooled") && msg.contains("render-suppressed"),
4470 "expected render-suppressed-component diagnostic, got: {msg}",
4471 );
4472 }
4473
4474 /// `validate()` rejects a negative or NaN threshold override — either would
4475 /// silently disable or invert the gate in classify_noise.
4476 #[test]
4477 fn validate_rejects_perf_delta_assertions_negative_or_nan_threshold() {
4478 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4479 Ok(AssertResult::pass())
4480 }
4481 const NEG: PerfDeltaAssertion =
4482 PerfDeltaAssertion::new("worst_spread").with_max_regression_pct(-1.0);
4483 let e1 = KtstrTestEntry {
4484 name: "gate_neg_pct",
4485 func: good_test_func,
4486 perf_delta_assertions: &[&NEG],
4487 performance_mode: true,
4488 ..KtstrTestEntry::DEFAULT
4489 };
4490 assert!(
4491 format!("{}", e1.validate().unwrap_err()).contains("max_regression_pct"),
4492 "a negative relative threshold must be rejected",
4493 );
4494 const NAN_ABS: PerfDeltaAssertion =
4495 PerfDeltaAssertion::new("worst_spread").with_min_abs(f64::NAN);
4496 let e2 = KtstrTestEntry {
4497 name: "gate_nan_abs",
4498 func: good_test_func,
4499 perf_delta_assertions: &[&NAN_ABS],
4500 performance_mode: true,
4501 ..KtstrTestEntry::DEFAULT
4502 };
4503 assert!(
4504 format!("{}", e2.validate().unwrap_err()).contains("min_abs"),
4505 "a NaN absolute floor must be rejected",
4506 );
4507 }
4508
4509 /// `validate()` rejects two gates on the same (metric, phase): the compare
4510 /// applies only the first via `.find()` and silently drops the rest.
4511 #[test]
4512 fn validate_rejects_perf_delta_assertions_duplicate_metric_phase() {
4513 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4514 Ok(AssertResult::pass())
4515 }
4516 const A: PerfDeltaAssertion =
4517 PerfDeltaAssertion::new("worst_spread").with_max_regression_pct(5.0);
4518 const B: PerfDeltaAssertion = PerfDeltaAssertion::new("worst_spread").with_min_abs(1.0);
4519 let entry = KtstrTestEntry {
4520 name: "gate_dup",
4521 func: good_test_func,
4522 perf_delta_assertions: &[&A, &B],
4523 performance_mode: true,
4524 ..KtstrTestEntry::DEFAULT
4525 };
4526 let err = entry
4527 .validate()
4528 .expect_err("duplicate (metric, phase) gates must be rejected");
4529 let msg = format!("{err}");
4530 assert!(
4531 msg.contains("more than one gate") && msg.contains("worst_spread"),
4532 "expected duplicate-gate diagnostic, got: {msg}",
4533 );
4534 }
4535
4536 /// `PerfDeltaAssertion::with_direction` panics on `Polarity::TargetValue`:
4537 /// symmetric target-distance gating is unimplemented and the compare would
4538 /// misclassify it as increase-is-worse.
4539 #[test]
4540 #[should_panic(expected = "TargetValue")]
4541 fn with_direction_rejects_target_value() {
4542 let _ = PerfDeltaAssertion::new("worst_spread")
4543 .with_direction(crate::test_support::Polarity::TargetValue(5.0));
4544 }
4545
4546 /// `validate()` rejects `num_snapshots` greater than the bridge
4547 /// cap (`MAX_STORED_SNAPSHOTS == 64`). Without the gate the
4548 /// periodic loop would publish all `N` boundary captures but the
4549 /// bridge's FIFO eviction at `store()` would silently drop the
4550 /// earliest samples — a periodic run with `N == 128` would only
4551 /// retain `periodic_064..periodic_127`. Refusing the entry is
4552 /// more honest than half-delivering it.
4553 #[test]
4554 fn validate_rejects_num_snapshots_above_max_stored() {
4555 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4556 Ok(AssertResult::pass())
4557 }
4558 let cap = crate::scenario::snapshot::MAX_STORED_SNAPSHOTS as u32;
4559 let entry = KtstrTestEntry {
4560 name: "too_many_snapshots",
4561 func: good_test_func,
4562 num_snapshots: cap + 1,
4563 ..KtstrTestEntry::DEFAULT
4564 };
4565 let err = entry
4566 .validate()
4567 .expect_err("num_snapshots > MAX_STORED_SNAPSHOTS must reject");
4568 let msg = format!("{err}");
4569 assert!(
4570 msg.contains("num_snapshots") && msg.contains("MAX_STORED_SNAPSHOTS"),
4571 "expected num_snapshots/MAX_STORED_SNAPSHOTS diagnostic, got: {msg}",
4572 );
4573 assert!(
4574 msg.contains("too_many_snapshots"),
4575 "error must name the offending entry, got: {msg}",
4576 );
4577 }
4578
4579 /// `num_snapshots == MAX_STORED_SNAPSHOTS` (the boundary case)
4580 /// must validate when `duration` is large enough to keep every
4581 /// inter-boundary interval at or above the 100 ms minimum spacing
4582 /// (see `validate_rejects_tight_periodic_spacing` below). 64
4583 /// captures over a long duration is the documented happy path —
4584 /// pinning it here prevents an off-by-one in the cap gate from
4585 /// silently rejecting the canonical maximum.
4586 #[test]
4587 fn validate_accepts_num_snapshots_at_max_stored() {
4588 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4589 Ok(AssertResult::pass())
4590 }
4591 let cap = crate::scenario::snapshot::MAX_STORED_SNAPSHOTS as u32;
4592 // 100 s · 0.8 / 65 ≈ 1.23 s per inter-boundary interval —
4593 // comfortably above the 100 ms minimum spacing gate.
4594 let entry = KtstrTestEntry {
4595 name: "max_snapshots_ok",
4596 func: good_test_func,
4597 num_snapshots: cap,
4598 duration: Duration::from_secs(100),
4599 ..KtstrTestEntry::DEFAULT
4600 };
4601 entry
4602 .validate()
4603 .expect("num_snapshots == MAX_STORED_SNAPSHOTS at long duration must validate");
4604 }
4605
4606 /// `validate()` rejects `num_snapshots > 0` paired with
4607 /// `host_only == true`. Periodic capture freezes guest vCPUs via
4608 /// the freeze coordinator's rendezvous; a host-only entry never
4609 /// boots a VM, so there are no vCPUs to freeze and the periodic
4610 /// boundaries would fire against an empty bridge. Catching the
4611 /// combination at validate time surfaces the misconfiguration
4612 /// before dispatch instead of after a confusing host-only run
4613 /// that silently produced zero captures.
4614 #[test]
4615 fn validate_rejects_num_snapshots_with_host_only() {
4616 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4617 Ok(AssertResult::pass())
4618 }
4619 let entry = KtstrTestEntry {
4620 name: "host_only_periodic",
4621 func: good_test_func,
4622 host_only: true,
4623 num_snapshots: 1,
4624 ..KtstrTestEntry::DEFAULT
4625 };
4626 let err = entry
4627 .validate()
4628 .expect_err("host_only=true + num_snapshots>0 must be rejected");
4629 let msg = format!("{err}");
4630 assert!(
4631 msg.contains("host_only") && msg.contains("num_snapshots"),
4632 "expected host_only/num_snapshots diagnostic, got: {msg}",
4633 );
4634 assert!(
4635 msg.contains("host_only_periodic"),
4636 "error must name the offending entry, got: {msg}",
4637 );
4638 }
4639
4640 /// `host_only == true` with `num_snapshots == 0` (the default)
4641 /// is the legitimate host-side shape and must continue to
4642 /// validate. Pins the gate to fire only on the actual conflict
4643 /// (host_only=true AND num_snapshots>0) and not on every
4644 /// host-only entry — a future tightening that rejected every
4645 /// host-only test author would silently break the host-only
4646 /// surface.
4647 #[test]
4648 fn validate_accepts_host_only_with_zero_snapshots() {
4649 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4650 Ok(AssertResult::pass())
4651 }
4652 let entry = KtstrTestEntry {
4653 name: "host_only_no_periodic",
4654 func: good_test_func,
4655 host_only: true,
4656 num_snapshots: 0,
4657 ..KtstrTestEntry::DEFAULT
4658 };
4659 entry
4660 .validate()
4661 .expect("host_only=true + num_snapshots=0 must validate");
4662 }
4663
4664 /// `validate()` rejects an entry whose periodic boundaries would
4665 /// land closer than 100 ms apart. The freeze coordinator's
4666 /// periodic loop divides the 80 % usable span (10 % pre-buffer +
4667 /// 10 % post-buffer = 20 % buffer; the remainder is the usable
4668 /// span) into `num_snapshots + 1` equal intervals; if any
4669 /// interval falls under 100 ms the captures crowd into
4670 /// rendezvous serialisation slack and one or more boundaries
4671 /// will defer-and-drop. Refusing the entry is more honest than
4672 /// emitting a partial timeline.
4673 ///
4674 /// Bound math: a 1 s duration with `num_snapshots == 8` yields
4675 /// `(0.8 · 1e9 ns) / 9 ≈ 88.9 ms` per interval — under the 100 ms
4676 /// floor, so the gate must reject. Below the cap (8 < 64) so the
4677 /// rejection MUST come from the spacing check, not the
4678 /// MAX_STORED_SNAPSHOTS gate.
4679 #[test]
4680 fn validate_rejects_tight_periodic_spacing() {
4681 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4682 Ok(AssertResult::pass())
4683 }
4684 let entry = KtstrTestEntry {
4685 name: "tight_periodic_spacing",
4686 func: good_test_func,
4687 duration: Duration::from_secs(1),
4688 num_snapshots: 8,
4689 ..KtstrTestEntry::DEFAULT
4690 };
4691 let err = entry
4692 .validate()
4693 .expect_err("tight periodic spacing must be rejected");
4694 let msg = format!("{err}");
4695 assert!(
4696 msg.contains("100"),
4697 "error must mention the 100 ms floor, got: {msg}",
4698 );
4699 assert!(
4700 msg.contains("num_snapshots") || msg.contains("periodic"),
4701 "error must mention num_snapshots or periodic, got: {msg}",
4702 );
4703 assert!(
4704 msg.contains("tight_periodic_spacing"),
4705 "error must name the offending entry, got: {msg}",
4706 );
4707 }
4708
4709 /// Periodic spacing gate must NOT fire when boundaries are at
4710 /// or above the 100 ms floor. 12 s default duration · 0.8 / 2
4711 /// = 4.8 s per interval (`N == 1`) is comfortably above the
4712 /// floor. Pins the polarity of the spacing gate so a future
4713 /// tightening that rejected every reasonable cadence would
4714 /// surface here as a regression instead of silently breaking
4715 /// every periodic test.
4716 #[test]
4717 fn validate_accepts_loose_periodic_spacing() {
4718 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4719 Ok(AssertResult::pass())
4720 }
4721 let entry = KtstrTestEntry {
4722 name: "loose_periodic_spacing",
4723 func: good_test_func,
4724 // 12 s default duration · 0.8 / (1 + 1) = 4.8 s per
4725 // interval — well above 100 ms.
4726 num_snapshots: 1,
4727 ..KtstrTestEntry::DEFAULT
4728 };
4729 entry
4730 .validate()
4731 .expect("loose periodic spacing (4.8 s per boundary) must validate");
4732 }
4733
4734 /// `validate()` rejects an entry whose scheduler declares
4735 /// `config_file_def` but provides no `config_content`. The macro
4736 /// emits a `const _: () = assert!(...)` for attribute-built
4737 /// entries; this branch covers programmatic construction so
4738 /// dispatch never runs the scheduler binary without `--config`.
4739 #[test]
4740 fn validate_rejects_config_file_def_without_content() {
4741 static SCHED_WITH_CFG: Scheduler = Scheduler {
4742 name: "sched_with_cfg",
4743 binary: SchedulerSpec::Discover("sched_with_cfg_bin"),
4744 sysctls: &[],
4745 kargs: &[],
4746 assert: crate::assert::Assert::NO_OVERRIDES,
4747 cgroup_parent: None,
4748 sched_args: &[],
4749 topology: Topology {
4750 llcs: 1,
4751 cores_per_llc: 2,
4752 threads_per_core: 1,
4753 numa_nodes: 1,
4754 nodes: None,
4755 distances: None,
4756 llc_cores: None,
4757 },
4758 constraints: TopologyConstraints::DEFAULT,
4759 config_file: None,
4760 config_file_def: Some(("--config {file}", "/include-files/cfg.json")),
4761 kernels: &[],
4762 verifier_exclude_topologies: &[],
4763 manifest_dir: env!("CARGO_MANIFEST_DIR"),
4764 };
4765 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4766 Ok(AssertResult::pass())
4767 }
4768 let entry = KtstrTestEntry {
4769 name: "missing_config",
4770 func: good_test_func,
4771 scheduler: &SCHED_WITH_CFG,
4772 config_content: None,
4773 ..KtstrTestEntry::DEFAULT
4774 };
4775 let err = entry
4776 .validate()
4777 .expect_err("config_file_def without config_content must reject");
4778 let msg = format!("{err}");
4779 assert!(
4780 msg.contains("config_file_def") && msg.contains("config_content"),
4781 "expected config_file_def/config_content bail, got: {msg}"
4782 );
4783 assert!(
4784 msg.contains("missing_config"),
4785 "error must name the offending entry, got: {msg}"
4786 );
4787 }
4788
4789 /// `validate()` rejects an entry that supplies `config_content`
4790 /// while pairing with a scheduler that declares no
4791 /// `config_file_def`. Symmetric with the missing-content gate:
4792 /// the content would be silently dropped at dispatch.
4793 #[test]
4794 fn validate_rejects_content_without_config_file_def() {
4795 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4796 Ok(AssertResult::pass())
4797 }
4798 let entry = KtstrTestEntry {
4799 name: "stray_config",
4800 func: good_test_func,
4801 scheduler: &crate::test_support::Scheduler::EEVDF,
4802 config_content: Some("{}"),
4803 ..KtstrTestEntry::DEFAULT
4804 };
4805 let err = entry
4806 .validate()
4807 .expect_err("config_content without config_file_def must reject");
4808 let msg = format!("{err}");
4809 assert!(
4810 msg.contains("config_content") && msg.contains("config_file_def"),
4811 "expected config_content/config_file_def bail, got: {msg}"
4812 );
4813 assert!(
4814 msg.contains("stray_config"),
4815 "error must name the offending entry, got: {msg}"
4816 );
4817 }
4818
4819 /// `validate()` accepts both legitimate pairings: a scheduler
4820 /// with `config_file_def` paired with `config_content`, and a
4821 /// scheduler without `config_file_def` paired with no
4822 /// `config_content`. Pins the happy paths so a future tightening
4823 /// of the pairing gate can't silently break valid entries.
4824 #[test]
4825 fn validate_accepts_config_pairing() {
4826 static SCHED_WITH_CFG: Scheduler = Scheduler {
4827 name: "sched_paired",
4828 binary: SchedulerSpec::Discover("sched_paired_bin"),
4829 sysctls: &[],
4830 kargs: &[],
4831 assert: crate::assert::Assert::NO_OVERRIDES,
4832 cgroup_parent: None,
4833 sched_args: &[],
4834 topology: Topology {
4835 llcs: 1,
4836 cores_per_llc: 2,
4837 threads_per_core: 1,
4838 numa_nodes: 1,
4839 nodes: None,
4840 distances: None,
4841 llc_cores: None,
4842 },
4843 constraints: TopologyConstraints::DEFAULT,
4844 config_file: None,
4845 config_file_def: Some(("f:{file}", "/include-files/p.json")),
4846 kernels: &[],
4847 verifier_exclude_topologies: &[],
4848 manifest_dir: env!("CARGO_MANIFEST_DIR"),
4849 };
4850 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4851 Ok(AssertResult::pass())
4852 }
4853 // Scheduler with def + content set: accepted.
4854 let entry_paired = KtstrTestEntry {
4855 name: "paired_present",
4856 func: good_test_func,
4857 scheduler: &SCHED_WITH_CFG,
4858 config_content: Some("{\"layers\":[]}"),
4859 ..KtstrTestEntry::DEFAULT
4860 };
4861 entry_paired
4862 .validate()
4863 .expect("scheduler with config_file_def + content must validate");
4864 // Scheduler without def + content unset: also accepted.
4865 let entry_none = KtstrTestEntry {
4866 name: "neither_present",
4867 func: good_test_func,
4868 scheduler: &crate::test_support::Scheduler::EEVDF,
4869 config_content: None,
4870 ..KtstrTestEntry::DEFAULT
4871 };
4872 entry_none
4873 .validate()
4874 .expect("no config_file_def + no content must validate");
4875 }
4876
4877 /// `validate()` rejects an entry that sets
4878 /// `expect_scx_bpf_error_contains` without also setting
4879 /// `expect_err = true`. The matcher narrows which failure counts
4880 /// as the expected bug, so it only makes sense on expected-error
4881 /// tests. Without the gate a matcher on a pass-expected entry
4882 /// would be silently inert.
4883 #[test]
4884 fn validate_rejects_expect_scx_bpf_error_contains_without_expect_err() {
4885 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4886 Ok(AssertResult::pass())
4887 }
4888 let entry = KtstrTestEntry {
4889 name: "bad_contains",
4890 func: good_test_func,
4891 assert: crate::assert::Assert::NO_OVERRIDES
4892 .expect_scx_bpf_error_contains("apply_cell_config"),
4893 expect_err: false,
4894 ..KtstrTestEntry::DEFAULT
4895 };
4896 let err = entry
4897 .validate()
4898 .expect_err("matcher without expect_err must be rejected");
4899 let msg = format!("{err}");
4900 assert!(
4901 msg.contains("expect_scx_bpf_error_contains") && msg.contains("expect_err"),
4902 "diagnostic must name BOTH the matcher field AND expect_err: {msg}",
4903 );
4904 assert!(
4905 msg.contains("bad_contains"),
4906 "error must name the offending entry: {msg}",
4907 );
4908 }
4909
4910 /// Symmetric with the `_contains` rejection: setting
4911 /// `expect_scx_bpf_error_matches` without `expect_err = true`
4912 /// must also reject. Pins that the gate triggers on either
4913 /// matcher field — a future addition that only checked one
4914 /// would leave the other silently inert.
4915 #[test]
4916 fn validate_rejects_expect_scx_bpf_error_matches_without_expect_err() {
4917 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4918 Ok(AssertResult::pass())
4919 }
4920 let entry = KtstrTestEntry {
4921 name: "bad_matches",
4922 func: good_test_func,
4923 assert: crate::assert::Assert::NO_OVERRIDES
4924 .expect_scx_bpf_error_matches("apply_cell_config:[0-9]+"),
4925 expect_err: false,
4926 ..KtstrTestEntry::DEFAULT
4927 };
4928 let err = entry
4929 .validate()
4930 .expect_err("matcher without expect_err must be rejected");
4931 let msg = format!("{err}");
4932 assert!(
4933 msg.contains("expect_scx_bpf_error_matches") && msg.contains("expect_err"),
4934 "diagnostic must name BOTH the matcher field AND expect_err: {msg}",
4935 );
4936 assert!(
4937 msg.contains("bad_matches"),
4938 "error must name the offending entry: {msg}",
4939 );
4940 }
4941
4942 /// `survives_storm = true` + `expect_err = true` is rejected at
4943 /// validate (the programmatic path that bypasses the macro mutex) —
4944 /// contradictory polarity. The expect_err mutex is checked before the
4945 /// no-scheduler one, so this fires even on the DEFAULT (no-scheduler)
4946 /// entry.
4947 #[test]
4948 fn validate_rejects_survives_storm_with_expect_err() {
4949 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4950 Ok(AssertResult::pass())
4951 }
4952 let entry = KtstrTestEntry {
4953 name: "bad_survives_expect_err",
4954 func: good_test_func,
4955 survives_storm: true,
4956 expect_err: true,
4957 ..KtstrTestEntry::DEFAULT
4958 };
4959 let err = entry
4960 .validate()
4961 .expect_err("survives_storm + expect_err must be rejected");
4962 let msg = format!("{err}");
4963 assert!(
4964 msg.contains("survives_storm") && msg.contains("expect_err"),
4965 "diagnostic must name both survives_storm and expect_err: {msg}",
4966 );
4967 assert!(
4968 msg.contains("bad_survives_expect_err"),
4969 "error must name the offending entry: {msg}",
4970 );
4971 }
4972
4973 /// `survives_storm = true` with no active scheduler (the DEFAULT
4974 /// kernel-default) is rejected — nothing to die or be ejected.
4975 #[test]
4976 fn validate_rejects_survives_storm_without_active_scheduler() {
4977 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
4978 Ok(AssertResult::pass())
4979 }
4980 let entry = KtstrTestEntry {
4981 name: "bad_survives_no_sched",
4982 func: good_test_func,
4983 survives_storm: true,
4984 ..KtstrTestEntry::DEFAULT
4985 };
4986 let err = entry
4987 .validate()
4988 .expect_err("survives_storm without an active scheduler must be rejected");
4989 let msg = format!("{err}");
4990 assert!(
4991 msg.contains("survives_storm") && msg.contains("scheduler"),
4992 "diagnostic must name survives_storm and the missing scheduler: {msg}",
4993 );
4994 }
4995
4996 /// `survives_storm = true` + `expect_auto_repro = true` is rejected at
4997 /// validate — both are inversion intents (survives_storm forces a
4998 /// death fail to EXIT_FAIL; expect_auto_repro inverts a crash-with-repro
4999 /// fail to PASS), contradictory like survives_storm + expect_err. The
5000 /// macro twin is `macro_rejects_survives_storm_with_expect_auto_repro`.
5001 #[test]
5002 fn validate_rejects_survives_storm_with_expect_auto_repro() {
5003 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
5004 Ok(AssertResult::pass())
5005 }
5006 let entry = KtstrTestEntry {
5007 name: "bad_survives_expect_auto_repro",
5008 func: good_test_func,
5009 survives_storm: true,
5010 expect_auto_repro: true,
5011 ..KtstrTestEntry::DEFAULT
5012 };
5013 let err = entry
5014 .validate()
5015 .expect_err("survives_storm + expect_auto_repro must be rejected");
5016 let msg = format!("{err}");
5017 assert!(
5018 msg.contains("survives_storm") && msg.contains("expect_auto_repro"),
5019 "diagnostic must name both survives_storm and expect_auto_repro: {msg}",
5020 );
5021 }
5022
5023 /// `with_survives_storm` setter roundtrips onto the entry.
5024 #[test]
5025 fn with_survives_storm_sets_field() {
5026 let e = KtstrTestEntry::DEFAULT.with_survives_storm(true);
5027 assert!(e.survives_storm);
5028 }
5029
5030 /// Happy path: scx_bpf_error matchers paired with
5031 /// `expect_err = true` must validate cleanly. Pins the polarity
5032 /// of the gate so a future tightening that rejected every entry
5033 /// with a matcher would surface here instead of silently
5034 /// breaking every reproducer test.
5035 #[test]
5036 fn validate_accepts_expect_scx_bpf_error_matchers_with_expect_err() {
5037 fn good_test_func(_: &Ctx) -> Result<AssertResult> {
5038 Ok(AssertResult::pass())
5039 }
5040 let entry_contains = KtstrTestEntry {
5041 name: "good_contains",
5042 func: good_test_func,
5043 assert: crate::assert::Assert::NO_OVERRIDES
5044 .expect_scx_bpf_error_contains("apply_cell_config"),
5045 expect_err: true,
5046 ..KtstrTestEntry::DEFAULT
5047 };
5048 entry_contains
5049 .validate()
5050 .expect("contains matcher + expect_err=true must validate");
5051 let entry_matches = KtstrTestEntry {
5052 name: "good_matches",
5053 func: good_test_func,
5054 assert: crate::assert::Assert::NO_OVERRIDES
5055 .expect_scx_bpf_error_matches("apply_cell_config:[0-9]+"),
5056 expect_err: true,
5057 ..KtstrTestEntry::DEFAULT
5058 };
5059 entry_matches
5060 .validate()
5061 .expect("matches matcher + expect_err=true must validate");
5062 let entry_both = KtstrTestEntry {
5063 name: "good_both",
5064 func: good_test_func,
5065 assert: crate::assert::Assert::NO_OVERRIDES
5066 .expect_scx_bpf_error_contains("apply_cell_config")
5067 .expect_scx_bpf_error_matches("apply_cell_config:[0-9]+"),
5068 expect_err: true,
5069 ..KtstrTestEntry::DEFAULT
5070 };
5071 entry_both
5072 .validate()
5073 .expect("both matchers + expect_err=true must validate");
5074 }
5075
5076 #[test]
5077 fn ktstr_test_entry_default_rejected_by_empty_name() {
5078 // DEFAULT has name = "" which validate() rejects — so the
5079 // stub entry cannot accidentally dispatch. This pins that
5080 // invariant.
5081 let err = KtstrTestEntry::DEFAULT.validate().unwrap_err();
5082 let msg = format!("{err}");
5083 assert!(
5084 msg.contains("name") && msg.contains("non-empty"),
5085 "expected name-non-empty bail, got: {msg}"
5086 );
5087 }
5088
5089 #[test]
5090 fn default_test_func_returns_err() {
5091 // The stub bails with Err — NOT a panic. Callers that
5092 // accidentally leave `func: default_test_func` in their
5093 // entry must see a clean Err to surface the mistake.
5094 let (cgroups, topo) = dummy_ctx();
5095 let ctx = Ctx::builder(&cgroups, &topo)
5096 .duration(Duration::from_millis(1))
5097 .assert(crate::assert::Assert::NO_OVERRIDES)
5098 .build();
5099 let result = default_test_func(&ctx);
5100 let err = result.expect_err("default_test_func must return Err, not Ok");
5101 let msg = format!("{err}");
5102 assert!(
5103 msg.contains("KtstrTestEntry::DEFAULT func called"),
5104 "expected DEFAULT-called bail message, got: {msg}"
5105 );
5106 assert!(
5107 msg.contains("override func before use"),
5108 "expected actionable hint, got: {msg}"
5109 );
5110 }
5111
5112 // -- Scheduler method tests --
5113
5114 use super::super::test_helpers::validate_entry;
5115
5116 #[test]
5117 fn scheduler_eevdf_defaults() {
5118 let s = &Scheduler::EEVDF;
5119 assert_eq!(s.name, "eevdf");
5120 assert!(s.sysctls.is_empty());
5121 assert!(s.kargs.is_empty());
5122 assert!(s.assert.not_stuck.is_none());
5123 assert!(s.assert.max_imbalance_ratio.is_none());
5124 }
5125
5126 #[test]
5127 fn scheduler_named_builder() {
5128 static TEST_SYSCTLS: &[Sysctl] =
5129 &[Sysctl::new("kernel.sched_cfs_bandwidth_slice_us", "1000")];
5130 let s = Scheduler::named("test_sched")
5131 .binary(SchedulerSpec::Discover("test_bin"))
5132 .sysctls(TEST_SYSCTLS)
5133 .kargs(&["nosmt"]);
5134 assert_eq!(s.name, "test_sched");
5135 // Assert the routed content, not just the length: a setter that
5136 // stored a different non-empty slice (or swapped sysctls<->kargs)
5137 // would pass length-only checks but fail these.
5138 assert_eq!(s.sysctls.len(), 1);
5139 assert_eq!(s.sysctls[0].key(), "kernel.sched_cfs_bandwidth_slice_us");
5140 assert_eq!(s.sysctls[0].value(), "1000");
5141 assert_eq!(s.kargs.len(), 1);
5142 assert_eq!(s.kargs[0], "nosmt");
5143 }
5144
5145 #[test]
5146 fn scheduler_with_check() {
5147 let v = crate::assert::Assert::NO_OVERRIDES
5148 .check_not_stuck()
5149 .max_imbalance_ratio(3.0);
5150 let s = Scheduler::named("sched").assert(v);
5151 assert_eq!(s.assert.not_stuck, Some(true));
5152 assert_eq!(s.assert.max_imbalance_ratio, Some(3.0));
5153 }
5154
5155 #[test]
5156 fn scheduler_named_default_topology_matches_macro_hardcode() {
5157 // The `declare_scheduler!` macro at
5158 // `ktstr-macros/src/lib.rs` hardcodes
5159 // `(numa=1, llcs=1, cores_per_llc=2, threads_per_core=1)`
5160 // as the fallback when the user omits `topology = (...)`.
5161 // That hardcode mirrors `Scheduler::named`'s default Topology.
5162 // The two sites are mechanically coupled by convention but
5163 // not by code: a change to `Scheduler::named` here would
5164 // silently let the macro check stale values, producing
5165 // misleading "effective topology llcs (N)" errors and/or
5166 // false-positives. Pin the defaults here so a drift fails
5167 // this test loudly and points at both sites.
5168 let s = Scheduler::named("__macro_default_topology_pin__");
5169 assert_eq!(s.topology.numa_nodes, 1);
5170 assert_eq!(s.topology.llcs, 1);
5171 assert_eq!(s.topology.cores_per_llc, 2);
5172 assert_eq!(s.topology.threads_per_core, 1);
5173 }
5174
5175 // -- KtstrTestEntry::validate coverage --
5176
5177 #[test]
5178 fn ktstr_test_entry_validate_accepts_defaults() {
5179 let e = validate_entry("ok", 512, Duration::from_secs(2));
5180 e.validate().unwrap();
5181 }
5182
5183 #[test]
5184 fn ktstr_test_entry_validate_rejects_empty_name() {
5185 let e = validate_entry("", 512, Duration::from_secs(2));
5186 let err = e.validate().unwrap_err();
5187 let msg = format!("{err}");
5188 assert!(
5189 msg.contains("name") && msg.contains("non-empty"),
5190 "got: {msg}"
5191 );
5192 }
5193
5194 #[test]
5195 fn ktstr_test_entry_validate_rejects_zero_memory() {
5196 let e = validate_entry("t", 0, Duration::from_secs(2));
5197 let err = e.validate().unwrap_err();
5198 let msg = format!("{err}");
5199 assert!(
5200 msg.contains("memory_mib") && msg.contains("> 0") && msg.contains("'t'"),
5201 "got: {msg}"
5202 );
5203 }
5204
5205 #[test]
5206 fn ktstr_test_entry_validate_rejects_zero_duration() {
5207 let e = validate_entry("t", 512, Duration::ZERO);
5208 let err = e.validate().unwrap_err();
5209 let msg = format!("{err}");
5210 assert!(
5211 msg.contains("duration") && msg.contains("> 0"),
5212 "got: {msg}"
5213 );
5214 }
5215
5216 // -- TopologyConstraints tests --
5217
5218 #[test]
5219 fn topology_constraints_default_has_max_values() {
5220 let c = TopologyConstraints::DEFAULT;
5221 assert_eq!(c.max_llcs, Some(12));
5222 assert_eq!(c.max_numa_nodes, Some(1));
5223 assert_eq!(c.max_cpus, Some(192));
5224 }
5225
5226 #[test]
5227 fn topology_constraints_max_fields_set() {
5228 let c = TopologyConstraints {
5229 max_llcs: Some(16),
5230 max_numa_nodes: Some(4),
5231 max_cpus: Some(128),
5232 ..TopologyConstraints::DEFAULT
5233 };
5234 assert_eq!(c.max_llcs, Some(16));
5235 assert_eq!(c.max_numa_nodes, Some(4));
5236 assert_eq!(c.max_cpus, Some(128));
5237 assert_eq!(c.min_numa_nodes, 1);
5238 assert_eq!(c.min_llcs, 1);
5239 assert_eq!(c.min_cpus, 1);
5240 }
5241
5242 #[test]
5243 fn topology_constraints_with_chain_overrides_target_fields_only() {
5244 let c = TopologyConstraints::DEFAULT
5245 .with_min_numa_nodes(2)
5246 .with_max_numa_nodes(8)
5247 .with_min_llcs(3)
5248 .with_max_llcs(16)
5249 .with_requires_smt(true)
5250 .with_min_cpus(4)
5251 .with_max_cpus(64);
5252 assert_eq!(c.min_numa_nodes, 2);
5253 assert_eq!(c.max_numa_nodes, Some(8));
5254 assert_eq!(c.min_llcs, 3);
5255 assert_eq!(c.max_llcs, Some(16));
5256 assert!(c.requires_smt);
5257 assert_eq!(c.min_cpus, 4);
5258 assert_eq!(c.max_cpus, Some(64));
5259 }
5260
5261 #[test]
5262 fn topology_constraints_without_chain_clears_option_fields() {
5263 let c = TopologyConstraints::DEFAULT
5264 .without_max_numa_nodes()
5265 .without_max_llcs()
5266 .without_max_cpus();
5267 assert!(c.max_numa_nodes.is_none());
5268 assert!(c.max_llcs.is_none());
5269 assert!(c.max_cpus.is_none());
5270 // min fields untouched.
5271 assert_eq!(c.min_numa_nodes, 1);
5272 assert_eq!(c.min_llcs, 1);
5273 assert_eq!(c.min_cpus, 1);
5274 }
5275
5276 #[test]
5277 fn topology_constraints_with_chain_const_evaluable() {
5278 const C: TopologyConstraints = TopologyConstraints::DEFAULT
5279 .with_min_llcs(2)
5280 .with_max_llcs(4);
5281 assert_eq!(C.min_llcs, 2);
5282 assert_eq!(C.max_llcs, Some(4));
5283 }
5284
5285 #[test]
5286 fn topology_constraints_equality() {
5287 let a = TopologyConstraints::DEFAULT;
5288 let b = TopologyConstraints::DEFAULT;
5289 assert_eq!(a, b);
5290
5291 let c = TopologyConstraints {
5292 max_llcs: Some(8),
5293 ..TopologyConstraints::DEFAULT
5294 };
5295 assert_ne!(a, c);
5296 }
5297
5298 #[test]
5299 fn accepts_default_allows_within_limits() {
5300 let c = TopologyConstraints::DEFAULT;
5301 // 1 NUMA, 8 LLCs, 4 cores, 2 threads = 64 CPUs
5302 let t = Topology::new(1, 8, 4, 2);
5303 assert!(c.accepts(&t, 128, 16, 32));
5304 }
5305
5306 #[test]
5307 fn accepts_default_rejects_multi_numa() {
5308 let c = TopologyConstraints::DEFAULT;
5309 // 2 NUMA, 8 LLCs, 4 cores, 2 threads = 64 CPUs
5310 let t = Topology::new(2, 8, 4, 2);
5311 assert!(!c.accepts(&t, 128, 16, 32));
5312 }
5313
5314 #[test]
5315 fn accepts_default_rejects_too_many_llcs() {
5316 let c = TopologyConstraints::DEFAULT;
5317 // 16 LLCs exceeds max_llcs=12
5318 let t = Topology::new(1, 16, 2, 1);
5319 assert!(!c.accepts(&t, 128, 32, 32));
5320 }
5321
5322 #[test]
5323 fn accepts_none_means_no_limit() {
5324 let c = TopologyConstraints {
5325 max_llcs: None,
5326 max_numa_nodes: None,
5327 max_cpus: None,
5328 ..TopologyConstraints::DEFAULT
5329 };
5330 // 4 NUMA, 16 LLCs, 8 cores, 2 threads = 256 CPUs
5331 let t = Topology::new(4, 16, 8, 2);
5332 assert!(c.accepts(&t, 512, 32, 32));
5333 }
5334
5335 #[test]
5336 fn accepts_rejects_too_many_llcs() {
5337 let c = TopologyConstraints {
5338 max_llcs: Some(4),
5339 ..TopologyConstraints::DEFAULT
5340 };
5341 let t = Topology::new(1, 8, 2, 1);
5342 assert!(!c.accepts(&t, 128, 16, 32));
5343 }
5344
5345 #[test]
5346 fn accepts_allows_llcs_at_max() {
5347 let c = TopologyConstraints {
5348 max_llcs: Some(4),
5349 ..TopologyConstraints::DEFAULT
5350 };
5351 let t = Topology::new(1, 4, 2, 1);
5352 assert!(c.accepts(&t, 128, 16, 32));
5353 }
5354
5355 #[test]
5356 fn accepts_rejects_too_many_numa_nodes() {
5357 let c = TopologyConstraints {
5358 max_numa_nodes: Some(2),
5359 ..TopologyConstraints::DEFAULT
5360 };
5361 let t = Topology::new(4, 4, 2, 1);
5362 assert!(!c.accepts(&t, 128, 16, 32));
5363 }
5364
5365 #[test]
5366 fn accepts_allows_numa_at_max() {
5367 let c = TopologyConstraints {
5368 max_numa_nodes: Some(2),
5369 ..TopologyConstraints::DEFAULT
5370 };
5371 let t = Topology::new(2, 4, 2, 1);
5372 assert!(c.accepts(&t, 128, 16, 32));
5373 }
5374
5375 #[test]
5376 fn accepts_rejects_too_many_cpus() {
5377 let c = TopologyConstraints {
5378 max_cpus: Some(16),
5379 ..TopologyConstraints::DEFAULT
5380 };
5381 // 4 LLCs * 4 cores * 2 threads = 32 CPUs
5382 let t = Topology::new(1, 4, 4, 2);
5383 assert!(!c.accepts(&t, 128, 16, 32));
5384 }
5385
5386 #[test]
5387 fn accepts_allows_cpus_at_max() {
5388 let c = TopologyConstraints {
5389 max_cpus: Some(16),
5390 ..TopologyConstraints::DEFAULT
5391 };
5392 // 2 LLCs * 4 cores * 2 threads = 16 CPUs
5393 let t = Topology::new(1, 2, 4, 2);
5394 assert!(c.accepts(&t, 128, 16, 32));
5395 }
5396
5397 #[test]
5398 fn accepts_rejects_too_few_llcs() {
5399 let c = TopologyConstraints {
5400 min_llcs: 4,
5401 ..TopologyConstraints::DEFAULT
5402 };
5403 let t = Topology::new(1, 2, 4, 1);
5404 assert!(!c.accepts(&t, 128, 16, 32));
5405 }
5406
5407 #[test]
5408 fn accepts_rejects_exceeding_host_cpus() {
5409 let c = TopologyConstraints::DEFAULT;
5410 let t = Topology::new(1, 4, 4, 2); // 32 CPUs
5411 assert!(!c.accepts(&t, 16, 16, 32)); // host has only 16
5412 }
5413
5414 #[test]
5415 fn accepts_rejects_exceeding_host_llcs() {
5416 let c = TopologyConstraints::DEFAULT;
5417 let t = Topology::new(1, 8, 2, 1);
5418 assert!(!c.accepts(&t, 128, 4, 32)); // host has only 4 LLCs
5419 }
5420
5421 #[test]
5422 fn accepts_combined_min_and_max() {
5423 let c = TopologyConstraints {
5424 min_llcs: 2,
5425 max_llcs: Some(8),
5426 min_cpus: 4,
5427 max_cpus: Some(32),
5428 ..TopologyConstraints::DEFAULT
5429 };
5430 // 1 LLC, 4 CPUs -- rejected (min_llcs=2)
5431 assert!(!c.accepts(&Topology::new(1, 1, 4, 1), 128, 16, 32));
5432 // 2 LLCs, 4 CPUs -- accepted
5433 assert!(c.accepts(&Topology::new(1, 2, 2, 1), 128, 16, 32));
5434 // 16 LLCs, 32 CPUs -- rejected (max_llcs=8)
5435 assert!(!c.accepts(&Topology::new(1, 16, 2, 1), 128, 16, 32));
5436 // 8 LLCs, 16 CPUs -- accepted
5437 assert!(c.accepts(&Topology::new(1, 8, 2, 1), 128, 16, 32));
5438 }
5439
5440 #[test]
5441 fn accepts_requires_smt() {
5442 let c = TopologyConstraints {
5443 requires_smt: true,
5444 ..TopologyConstraints::DEFAULT
5445 };
5446 let no_smt = Topology::new(1, 2, 4, 1);
5447 let with_smt = Topology::new(1, 2, 4, 2);
5448 assert!(!c.accepts(&no_smt, 128, 16, 32));
5449 assert!(c.accepts(&with_smt, 128, 16, 32));
5450 }
5451
5452 #[test]
5453 fn accepts_rejects_too_few_numa_nodes() {
5454 let c = TopologyConstraints {
5455 min_numa_nodes: 2,
5456 max_numa_nodes: None,
5457 ..TopologyConstraints::DEFAULT
5458 };
5459 let t = Topology::new(1, 4, 4, 1);
5460 assert!(!c.accepts(&t, 128, 16, 32));
5461 }
5462
5463 #[test]
5464 fn accepts_rejects_too_few_cpus() {
5465 let c = TopologyConstraints {
5466 min_cpus: 32,
5467 ..TopologyConstraints::DEFAULT
5468 };
5469 // 2 LLCs * 4 cores * 2 threads = 16 CPUs
5470 let t = Topology::new(1, 2, 4, 2);
5471 assert!(!c.accepts(&t, 128, 16, 32));
5472 }
5473
5474 #[test]
5475 fn accepts_rejects_exceeding_host_cpus_per_llc() {
5476 let c = TopologyConstraints::DEFAULT;
5477 // cores_per_llc=8, threads_per_core=2 → 16 CPUs/LLC
5478 let t = Topology::new(1, 2, 8, 2);
5479 assert!(!c.accepts(&t, 128, 16, 8));
5480 }
5481
5482 // -- TopologyConstraints::accepts_verifier --
5483 //
5484 // The two beyond-host battery shapes added alongside this gate.
5485 // WIDE_192 stands in for 192cpu-11llc-smt's gating dimensions (11 LLCs,
5486 // 192 CPUs, 1 node, SMT — the gate reads only num_llcs/total_cpus/
5487 // numa/threads, not the per-LLC unevenness). NUMA2_2LLC: 2 nodes,
5488 // 2 LLCs, 32 CPUs, SMT.
5489 const WIDE_192: fn() -> Topology = || Topology::new(1, 11, 9, 2); // 198 (>host)
5490 const NUMA2_2LLC: fn() -> Topology = || Topology::new(2, 2, 8, 2); // 32, 2 nodes
5491
5492 #[test]
5493 fn accepts_verifier_default_admits_any_host_no_bound() {
5494 // DEFAULT caps (numa=1, llcs=12, cpus=192) are all "no opinion"
5495 // under accepts_verifier, and there is NO host-size bound: the
5496 // wide + multi-numa shapes list on ANY host, including a
5497 // deliberately tiny one. host_cpus is not even an argument.
5498 let c = TopologyConstraints::DEFAULT;
5499 assert!(c.accepts_verifier(&WIDE_192()));
5500 assert!(c.accepts_verifier(&NUMA2_2LLC()));
5501 // A truly enormous shape still lists (no ceiling at all).
5502 assert!(c.accepts_verifier(&Topology::new(1, 8, 200, 2))); // 3200 CPUs
5503 }
5504
5505 #[test]
5506 fn accepts_verifier_respects_explicit_non_default_cap() {
5507 // An explicitly-declared non-default max_cpus IS honored: it is a
5508 // deliberate scope statement, not the conservative default.
5509 let c = TopologyConstraints {
5510 max_cpus: Some(64),
5511 ..TopologyConstraints::DEFAULT
5512 };
5513 assert!(!c.accepts_verifier(&WIDE_192())); // 198 > 64
5514 // A non-default max_llcs likewise gates the wide LLC count.
5515 let c = TopologyConstraints {
5516 max_llcs: Some(4),
5517 ..TopologyConstraints::DEFAULT
5518 };
5519 assert!(!c.accepts_verifier(&WIDE_192())); // 11 > 4
5520 }
5521
5522 #[test]
5523 fn accepts_verifier_honors_min_floors_and_smt() {
5524 // min_* floors and requires_smt express test SCOPE and always
5525 // gate, unlike the ignored default caps.
5526 let c = TopologyConstraints {
5527 min_cpus: 512,
5528 ..TopologyConstraints::DEFAULT
5529 };
5530 assert!(!c.accepts_verifier(&WIDE_192())); // 198 < 512
5531 let c = TopologyConstraints {
5532 requires_smt: true,
5533 ..TopologyConstraints::DEFAULT
5534 };
5535 // A non-SMT wide shape is rejected under requires_smt.
5536 assert!(!c.accepts_verifier(&Topology::new(1, 11, 18, 1)));
5537 assert!(c.accepts_verifier(&WIDE_192())); // SMT present
5538 }
5539
5540 #[test]
5541 fn accepts_verifier_explicit_default_value_reads_as_no_cap() {
5542 // Writing the default value verbatim is indistinguishable from
5543 // leaving it at default — both read as "no cap". A scheduler
5544 // cannot re-assert the default as a hard verifier ceiling.
5545 let c = TopologyConstraints {
5546 max_cpus: Some(192), // == DEFAULT.max_cpus
5547 max_numa_nodes: Some(1), // == DEFAULT.max_numa_nodes
5548 max_llcs: Some(12), // == DEFAULT.max_llcs
5549 ..TopologyConstraints::DEFAULT
5550 };
5551 assert!(c.accepts_verifier(&WIDE_192()));
5552 assert!(c.accepts_verifier(&NUMA2_2LLC()));
5553 }
5554
5555 #[test]
5556 fn accepts_verifier_leaves_gauntlet_acceptance_unchanged() {
5557 // Regression pin: the verifier relaxation must not leak into the
5558 // perf-mode gauntlet gate. accepts / accepts_no_perf_mode keep
5559 // their strict host bound and default caps exactly as before.
5560 let c = TopologyConstraints::DEFAULT;
5561 // 64-CPU host: strict <= host_cpus keeps both wide shapes out of
5562 // the gauntlet even ignoring caps, and the caps reject them too.
5563 assert!(!c.accepts_no_perf_mode(&WIDE_192(), 64));
5564 assert!(!c.accepts_no_perf_mode(&NUMA2_2LLC(), 64));
5565 assert!(!c.accepts(&WIDE_192(), 4096, 4096, 4096)); // cap: numa? no — llcs 11<=12, cpus 198>192
5566 assert!(!c.accepts(&NUMA2_2LLC(), 4096, 4096, 4096)); // cap: numa 2>1
5567 // And the classic default-active presets still pass unchanged.
5568 assert!(c.accepts_no_perf_mode(&Topology::new(1, 8, 4, 2), 4096)); // 64cpu-8llc-smt
5569 assert!(c.accepts(&Topology::new(1, 8, 4, 2), 4096, 4096, 4096));
5570 }
5571
5572 // -- TopologyConstraints::validate --
5573
5574 #[test]
5575 fn validate_accepts_default_constraints() {
5576 // DEFAULT has min_numa_nodes=1, max_numa_nodes=Some(1);
5577 // min_llcs=1, max_llcs=Some(12); min_cpus=1, max_cpus=Some(192).
5578 // All min<=max — must pass.
5579 TopologyConstraints::DEFAULT
5580 .validate()
5581 .expect("DEFAULT constraints must be self-consistent");
5582 }
5583
5584 #[test]
5585 fn validate_rejects_inverted_numa_nodes() {
5586 let c = TopologyConstraints {
5587 min_numa_nodes: 5,
5588 max_numa_nodes: Some(2),
5589 ..TopologyConstraints::DEFAULT
5590 };
5591 let err = c
5592 .validate()
5593 .expect_err("inverted min/max_numa_nodes must be rejected");
5594 let msg = err.to_string();
5595 assert!(
5596 msg.contains("max_numa_nodes=2") && msg.contains("min_numa_nodes=5"),
5597 "diagnostic must name both bounds: got {msg}",
5598 );
5599 }
5600
5601 #[test]
5602 fn validate_rejects_inverted_llcs() {
5603 let c = TopologyConstraints {
5604 min_llcs: 8,
5605 max_llcs: Some(2),
5606 ..TopologyConstraints::DEFAULT
5607 };
5608 let err = c
5609 .validate()
5610 .expect_err("inverted min/max_llcs must be rejected");
5611 let msg = err.to_string();
5612 assert!(
5613 msg.contains("max_llcs=2") && msg.contains("min_llcs=8"),
5614 "diagnostic must name both bounds: got {msg}",
5615 );
5616 }
5617
5618 #[test]
5619 fn validate_rejects_inverted_cpus() {
5620 let c = TopologyConstraints {
5621 min_cpus: 64,
5622 max_cpus: Some(16),
5623 ..TopologyConstraints::DEFAULT
5624 };
5625 let err = c
5626 .validate()
5627 .expect_err("inverted min/max_cpus must be rejected");
5628 let msg = err.to_string();
5629 assert!(
5630 msg.contains("max_cpus=16") && msg.contains("min_cpus=64"),
5631 "diagnostic must name both bounds: got {msg}",
5632 );
5633 }
5634
5635 #[test]
5636 fn validate_accepts_max_equal_min() {
5637 // max == min is satisfiable (any topology with that exact
5638 // value matches), so the validator must allow it.
5639 let c = TopologyConstraints {
5640 min_numa_nodes: 3,
5641 max_numa_nodes: Some(3),
5642 min_llcs: 4,
5643 max_llcs: Some(4),
5644 min_cpus: 16,
5645 max_cpus: Some(16),
5646 ..TopologyConstraints::DEFAULT
5647 };
5648 c.validate()
5649 .expect("max==min is satisfiable and must be accepted");
5650 }
5651
5652 #[test]
5653 fn validate_accepts_open_upper_bound() {
5654 // None for max_* means "no upper bound" — never inverted.
5655 let c = TopologyConstraints {
5656 min_numa_nodes: 16,
5657 max_numa_nodes: None,
5658 min_llcs: 32,
5659 max_llcs: None,
5660 min_cpus: 1024,
5661 max_cpus: None,
5662 ..TopologyConstraints::DEFAULT
5663 };
5664 c.validate()
5665 .expect("None upper bounds must always validate");
5666 }
5667
5668 // -- KtstrTestEntry::validate wire-in for TopologyConstraints --
5669
5670 /// Pin that an inverted per-entry `constraints` field surfaces
5671 /// through `KtstrTestEntry::validate` with the documented
5672 /// `KtstrTestEntry '<name>'.constraints:` prefix wrap. Catches a
5673 /// regression that drops the per-entry `.validate()?` call at the
5674 /// wire-in site in `KtstrTestEntry::validate`.
5675 #[test]
5676 fn entry_validate_propagates_per_entry_constraints_error() {
5677 let entry = KtstrTestEntry {
5678 name: "test_inverted_entry",
5679 constraints: TopologyConstraints {
5680 min_numa_nodes: 5,
5681 max_numa_nodes: Some(2),
5682 ..TopologyConstraints::DEFAULT
5683 },
5684 ..KtstrTestEntry::DEFAULT
5685 };
5686 let err = entry
5687 .validate()
5688 .expect_err("inverted per-entry constraints must surface");
5689 let msg = err.to_string();
5690 assert!(
5691 msg.contains("KtstrTestEntry 'test_inverted_entry'.constraints:"),
5692 "wrap prefix must name the entry + constraints field: got {msg}",
5693 );
5694 assert!(
5695 msg.contains("max_numa_nodes=2") && msg.contains("min_numa_nodes=5"),
5696 "underlying validator diagnostic must be preserved through map_err: got {msg}",
5697 );
5698 }
5699
5700 /// Pin that an inverted scheduler-level `constraints` field
5701 /// surfaces through `KtstrTestEntry::validate` with the
5702 /// `KtstrTestEntry '<name>'.scheduler '<sched>'.constraints:`
5703 /// prefix wrap. Catches a regression that drops the
5704 /// `.scheduler.constraints.validate()?` call at the wire-in site.
5705 #[test]
5706 fn entry_validate_propagates_scheduler_constraints_error() {
5707 static BAD_SCHED: Scheduler = Scheduler {
5708 name: "bad_sched",
5709 binary: SchedulerSpec::Eevdf,
5710 sysctls: &[],
5711 kargs: &[],
5712 assert: crate::assert::Assert::NO_OVERRIDES,
5713 cgroup_parent: None,
5714 sched_args: &[],
5715 topology: Topology {
5716 llcs: 1,
5717 cores_per_llc: 1,
5718 threads_per_core: 1,
5719 numa_nodes: 1,
5720 nodes: None,
5721 distances: None,
5722 llc_cores: None,
5723 },
5724 constraints: TopologyConstraints {
5725 min_llcs: 8,
5726 max_llcs: Some(2),
5727 ..TopologyConstraints::DEFAULT
5728 },
5729 config_file: None,
5730 config_file_def: None,
5731 kernels: &[],
5732 verifier_exclude_topologies: &[],
5733 manifest_dir: env!("CARGO_MANIFEST_DIR"),
5734 };
5735 let entry = KtstrTestEntry {
5736 name: "test_inverted_scheduler",
5737 scheduler: &BAD_SCHED,
5738 ..KtstrTestEntry::DEFAULT
5739 };
5740 let err = entry
5741 .validate()
5742 .expect_err("inverted scheduler-level constraints must surface");
5743 let msg = err.to_string();
5744 assert!(
5745 msg.contains(
5746 "KtstrTestEntry 'test_inverted_scheduler'.scheduler 'bad_sched'.constraints:"
5747 ),
5748 "wrap prefix must name the entry + scheduler + constraints: got {msg}",
5749 );
5750 assert!(
5751 msg.contains("max_llcs=2") && msg.contains("min_llcs=8"),
5752 "underlying validator diagnostic must be preserved: got {msg}",
5753 );
5754 }
5755
5756 // -- SchedulerSpec::display_name --
5757
5758 #[test]
5759 fn display_name_eevdf() {
5760 assert_eq!(SchedulerSpec::Eevdf.display_name(), "eevdf");
5761 }
5762
5763 #[test]
5764 fn display_name_discover_returns_binary_name() {
5765 assert_eq!(
5766 SchedulerSpec::Discover("scx_mitosis").display_name(),
5767 "scx_mitosis"
5768 );
5769 }
5770
5771 #[test]
5772 fn display_name_path_returns_path_string() {
5773 assert_eq!(
5774 SchedulerSpec::Path("/usr/bin/scx_my_sched").display_name(),
5775 "/usr/bin/scx_my_sched"
5776 );
5777 }
5778
5779 #[test]
5780 fn display_name_kernel_builtin_returns_kernel() {
5781 assert_eq!(
5782 SchedulerSpec::KernelBuiltin {
5783 enable: &[],
5784 disable: &[],
5785 }
5786 .display_name(),
5787 "kernel"
5788 );
5789 }
5790
5791 // -- SchedulerSpec::scheduler_commit --
5792 //
5793 // Conservative by design: EVERY variant currently returns
5794 // None, including `Discover(_)`. `resolve_scheduler`'s three
5795 // steps can pick up a binary whose commit is unknown to this
5796 // process in two of the three (env override, `$PATH`), so
5797 // `Discover` returns None to avoid lying. The sidecar's nullable
5798 // semantics distinguish "unset" from a sentinel so consumers
5799 // can tell "no userspace binary" (Eevdf, KernelBuiltin) from
5800 // "external binary, commit unknown" (Path) and "discovered
5801 // binary, provenance unverified" (Discover). A future
5802 // introspection path (`binary --version`, ELF note, BuildId
5803 // lookup) can flip a variant to Some(..) when an authoritative
5804 // commit is available; until then, None keeps consumers from
5805 // attributing regressions to the wrong commit. See the method
5806 // doc for the per-variant rationale.
5807
5808 #[test]
5809 fn scheduler_commit_eevdf_returns_none() {
5810 assert!(
5811 SchedulerSpec::Eevdf.scheduler_commit().is_none(),
5812 "Eevdf has no userspace binary — scheduler_commit must \
5813 be None so the sidecar field distinguishes this case \
5814 from `Path(_)` (external, unknown commit). Got: {:?}",
5815 SchedulerSpec::Eevdf.scheduler_commit(),
5816 );
5817 }
5818
5819 #[test]
5820 fn scheduler_commit_discover_returns_none() {
5821 // `Discover` is resolved by `resolve_scheduler`'s three
5822 // steps. Only the build path guarantees the binary matches
5823 // the current tree; the env-override and cargo-test-mode
5824 // `$PATH` paths can pick up a binary whose commit is unknown
5825 // to this process. Synthesizing a commit would be a lie in
5826 // 2 of 3 cases — so the honest
5827 // answer today is `None`. A future enhancement that probes
5828 // the binary (e.g. `--version`, ELF note) can flip this to
5829 // `Some(..)` when an authoritative commit is available;
5830 // until then, `None` keeps consumers from attributing
5831 // regressions to the wrong commit.
5832 assert!(
5833 SchedulerSpec::Discover("scx_mitosis")
5834 .scheduler_commit()
5835 .is_none(),
5836 "Discover(_) must return None — resolve_scheduler's \
5837 env-override / `$PATH` steps can pick up a binary whose \
5838 commit doesn't match the workspace. Got: {:?}",
5839 SchedulerSpec::Discover("scx_mitosis").scheduler_commit(),
5840 );
5841 }
5842
5843 #[test]
5844 fn scheduler_commit_path_returns_none() {
5845 // External binaries have no reliable introspection path;
5846 // synthesizing a commit here would be a lie when the
5847 // binary was built from a different tree.
5848 assert!(
5849 SchedulerSpec::Path("/usr/bin/scx_external")
5850 .scheduler_commit()
5851 .is_none(),
5852 "Path(_) points at an externally-built binary — \
5853 scheduler_commit must be None so consumers don't treat \
5854 a fabricated commit as authoritative. Got: {:?}",
5855 SchedulerSpec::Path("/usr/bin/scx_external").scheduler_commit(),
5856 );
5857 }
5858
5859 #[test]
5860 fn scheduler_commit_kernel_builtin_returns_none() {
5861 // In-kernel schedulers have no userspace binary. The
5862 // running kernel's identity belongs in
5863 // `host.kernel_release`, not here.
5864 let spec = SchedulerSpec::KernelBuiltin {
5865 enable: &[],
5866 disable: &[],
5867 };
5868 assert!(
5869 spec.scheduler_commit().is_none(),
5870 "KernelBuiltin has no userspace binary — \
5871 scheduler_commit must be None. Got: {:?}",
5872 spec.scheduler_commit(),
5873 );
5874 }
5875
5876 // -- all_include_files aggregation tests --
5877 //
5878 // Pins the scheduler → payload → workloads → extras order. The
5879 // dedupe + archive-collision policy lives downstream in
5880 // `eval::dedupe_include_files`; this aggregator just gathers
5881 // raw spec strings.
5882
5883 /// No Payload and no extras declare include_files → empty result.
5884 /// Regression guard for `all_include_files` returning an implicit
5885 /// non-empty list (e.g. leaking a default).
5886 #[test]
5887 fn all_include_files_empty_when_nothing_declared() {
5888 let entry = KtstrTestEntry {
5889 name: "t",
5890 ..KtstrTestEntry::DEFAULT
5891 };
5892 assert!(entry.all_include_files().is_empty());
5893 }
5894
5895 /// Payload + workloads + extras merge in declaration order. Pins:
5896 /// - order is payload → workloads (preserving the slice order) →
5897 /// extra_include_files
5898 /// - duplicates are NOT deduped at this layer (that's eval's job)
5899 /// - the scheduler field is `&Scheduler` (no `include_files`
5900 /// surface), so the scheduler tier contributes nothing here
5901 #[test]
5902 fn all_include_files_merges_sources_in_order() {
5903 static PRIMARY: crate::test_support::Payload = crate::test_support::Payload {
5904 name: "primary",
5905 kind: crate::test_support::PayloadKind::Binary("fio"),
5906 output: crate::test_support::OutputFormat::ExitCode,
5907 default_args: &[],
5908 default_checks: &[],
5909 metrics: &[],
5910 include_files: &["fio"],
5911 uses_parent_pgrp: false,
5912 known_flags: None,
5913 };
5914 static WL_A: crate::test_support::Payload = crate::test_support::Payload {
5915 name: "wl_a",
5916 kind: crate::test_support::PayloadKind::Binary("stress-ng"),
5917 output: crate::test_support::OutputFormat::ExitCode,
5918 default_args: &[],
5919 default_checks: &[],
5920 metrics: &[],
5921 include_files: &["stress-ng"],
5922 uses_parent_pgrp: false,
5923 known_flags: None,
5924 };
5925 static WL_B: crate::test_support::Payload = crate::test_support::Payload {
5926 name: "wl_b",
5927 kind: crate::test_support::PayloadKind::Binary("schbench"),
5928 output: crate::test_support::OutputFormat::ExitCode,
5929 default_args: &[],
5930 default_checks: &[],
5931 metrics: &[],
5932 include_files: &["schbench"],
5933 uses_parent_pgrp: false,
5934 known_flags: None,
5935 };
5936 static WORKLOADS: &[&crate::test_support::Payload] = &[&WL_A, &WL_B];
5937 let entry = KtstrTestEntry {
5938 name: "t",
5939 payload: Some(&PRIMARY),
5940 workloads: WORKLOADS,
5941 extra_include_files: &["test-fixture.json"],
5942 ..KtstrTestEntry::DEFAULT
5943 };
5944 let got = entry.all_include_files();
5945 assert_eq!(
5946 got,
5947 vec!["fio", "stress-ng", "schbench", "test-fixture.json"],
5948 "aggregation order must be payload → workloads → extras",
5949 );
5950 }
5951
5952 /// Absent optional `payload` slot contributes nothing — the
5953 /// aggregator skips it without the `None → empty-push` misbehavior
5954 /// a future refactor might introduce. Scheduler tier no longer
5955 /// contributes after the `&Payload`→`&Scheduler` field-type change.
5956 #[test]
5957 fn all_include_files_skips_absent_payload() {
5958 let entry = KtstrTestEntry {
5959 name: "t",
5960 payload: None,
5961 workloads: &[],
5962 extra_include_files: &[],
5963 ..KtstrTestEntry::DEFAULT
5964 };
5965 assert!(entry.all_include_files().is_empty());
5966 }
5967
5968 /// Dedup-detection: two distinct `&'static Scheduler` consts with
5969 /// the same `name` field must panic when `find_scheduler` builds
5970 /// its name → scheduler map. Exercises the
5971 /// `build_scheduler_index_or_panic` branch against a mock slice
5972 /// since the real `KTSTR_SCHEDULERS` is the union of every
5973 /// `declare_scheduler!` registration in the linked test binary
5974 /// and so cannot host an intentional duplicate without
5975 /// poisoning every other test that calls `find_scheduler`.
5976 #[test]
5977 #[should_panic(expected = "duplicate scheduler name `dup_name_test`")]
5978 fn build_scheduler_index_or_panic_rejects_duplicate_names() {
5979 // Two consts with the same name. Address-distinct so
5980 // `std::ptr::eq` returns false and the dedup branch fires.
5981 static A: Scheduler = Scheduler::named("dup_name_test");
5982 static B: Scheduler = Scheduler::named("dup_name_test");
5983 let _ = build_scheduler_index_or_panic([&A, &B]);
5984 }
5985
5986 /// Distinct names build a populated index without panicking, and
5987 /// the returned map points back at the same `&'static Scheduler`
5988 /// references for lookup parity with `find_scheduler`.
5989 #[test]
5990 fn build_scheduler_index_or_panic_accepts_distinct_names() {
5991 static A: Scheduler = Scheduler::named("dup_name_a");
5992 static B: Scheduler = Scheduler::named("dup_name_b");
5993 let map = build_scheduler_index_or_panic([&A, &B]);
5994 assert!(std::ptr::eq(*map.get("dup_name_a").unwrap(), &A));
5995 assert!(std::ptr::eq(*map.get("dup_name_b").unwrap(), &B));
5996 }
5997
5998 /// Same `&'static Scheduler` passed twice (a benign re-export of
5999 /// the same const, not a true duplicate-name collision across
6000 /// distinct consts) does not panic — `std::ptr::eq` short-circuits
6001 /// the dedup branch. Linkme's distributed slice is allowed to
6002 /// emit the same registration through multiple paths; only a
6003 /// pointer-distinct duplicate is a misconfiguration.
6004 #[test]
6005 fn build_scheduler_index_or_panic_tolerates_pointer_identity_aliases() {
6006 static A: Scheduler = Scheduler::named("alias_test");
6007 let map = build_scheduler_index_or_panic([&A, &A]);
6008 assert!(std::ptr::eq(*map.get("alias_test").unwrap(), &A));
6009 }
6010
6011 #[test]
6012 fn topology_json_try_into_topology_accepts_single_cpu() {
6013 let topo: Topology = TopologyJson::SINGLE_CPU
6014 .try_into()
6015 .expect("SINGLE_CPU valid");
6016 assert_eq!(topo.numa_nodes, 1);
6017 assert_eq!(topo.llcs, 1);
6018 assert_eq!(topo.cores_per_llc, 1);
6019 assert_eq!(topo.threads_per_core, 1);
6020 assert!(topo.nodes.is_none());
6021 assert!(topo.distances.is_none());
6022 }
6023
6024 #[test]
6025 fn topology_json_try_into_topology_accepts_multi_cpu() {
6026 let json = TopologyJson {
6027 num_numa_nodes: 2,
6028 num_llcs: 4,
6029 cores_per_llc: 8,
6030 threads_per_core: 2,
6031 };
6032 let topo: Topology = json.try_into().expect("2x4x8x2 valid");
6033 assert_eq!(topo.numa_nodes, 2);
6034 assert_eq!(topo.llcs, 4);
6035 assert_eq!(topo.cores_per_llc, 8);
6036 assert_eq!(topo.threads_per_core, 2);
6037 }
6038
6039 #[test]
6040 fn topology_json_try_into_topology_rejects_zero_numa_nodes() {
6041 let json = TopologyJson {
6042 num_numa_nodes: 0,
6043 num_llcs: 1,
6044 cores_per_llc: 1,
6045 threads_per_core: 1,
6046 };
6047 let err = Topology::try_from(json).expect_err("zero numa_nodes must reject");
6048 assert!(
6049 err.contains("numa_nodes"),
6050 "error should mention numa_nodes: {err}"
6051 );
6052 }
6053
6054 #[test]
6055 fn topology_json_try_into_topology_rejects_zero_llcs() {
6056 let json = TopologyJson {
6057 num_numa_nodes: 1,
6058 num_llcs: 0,
6059 cores_per_llc: 1,
6060 threads_per_core: 1,
6061 };
6062 let err = Topology::try_from(json).expect_err("zero llcs must reject");
6063 assert!(err.contains("llcs"), "error should mention llcs: {err}");
6064 }
6065
6066 #[test]
6067 fn topology_json_try_into_topology_rejects_zero_cores() {
6068 let json = TopologyJson {
6069 num_numa_nodes: 1,
6070 num_llcs: 1,
6071 cores_per_llc: 0,
6072 threads_per_core: 1,
6073 };
6074 let err = Topology::try_from(json).expect_err("zero cores_per_llc must reject");
6075 assert!(
6076 err.contains("cores_per_llc"),
6077 "error should mention cores_per_llc: {err}"
6078 );
6079 }
6080
6081 #[test]
6082 fn topology_json_try_into_topology_rejects_zero_threads() {
6083 let json = TopologyJson {
6084 num_numa_nodes: 1,
6085 num_llcs: 1,
6086 cores_per_llc: 1,
6087 threads_per_core: 0,
6088 };
6089 let err = Topology::try_from(json).expect_err("zero threads_per_core must reject");
6090 assert!(
6091 err.contains("threads_per_core"),
6092 "error should mention threads_per_core: {err}"
6093 );
6094 }
6095
6096 #[test]
6097 fn topology_json_try_into_topology_rejects_indivisible_llcs() {
6098 // 3 LLCs across 2 NUMA nodes — not divisible.
6099 let json = TopologyJson {
6100 num_numa_nodes: 2,
6101 num_llcs: 3,
6102 cores_per_llc: 1,
6103 threads_per_core: 1,
6104 };
6105 let err = Topology::try_from(json).expect_err("indivisible llcs must reject");
6106 assert!(
6107 err.contains("divisible"),
6108 "error should mention divisibility: {err}"
6109 );
6110 }
6111
6112 #[test]
6113 fn topology_json_try_into_topology_rejects_overflow_total_cpus() {
6114 // 2 LLCs × (u32::MAX / 4) cores × 4 threads overflows u32.
6115 let json = TopologyJson {
6116 num_numa_nodes: 1,
6117 num_llcs: 2,
6118 cores_per_llc: u32::MAX / 4,
6119 threads_per_core: 4,
6120 };
6121 let err = Topology::try_from(json).expect_err("u32 overflow on total cpus must reject");
6122 assert!(
6123 err.contains("overflow"),
6124 "error should mention overflow: {err}"
6125 );
6126 }
6127
6128 #[test]
6129 fn topology_into_topology_json_drops_explicit_nodes_distances() {
6130 let topo = Topology {
6131 llcs: 4,
6132 cores_per_llc: 8,
6133 threads_per_core: 2,
6134 numa_nodes: 2,
6135 nodes: None,
6136 distances: None,
6137 llc_cores: None,
6138 };
6139 let json: TopologyJson = topo.into();
6140 assert_eq!(json.num_numa_nodes, 2);
6141 assert_eq!(json.num_llcs, 4);
6142 assert_eq!(json.cores_per_llc, 8);
6143 assert_eq!(json.threads_per_core, 2);
6144 }
6145
6146 #[test]
6147 fn topology_constraints_json_into_topology_constraints_preserves_fields() {
6148 let json = TopologyConstraintsJson {
6149 min_numa_nodes: 1,
6150 max_numa_nodes: Some(4),
6151 min_llcs: 2,
6152 max_llcs: Some(8),
6153 requires_smt: true,
6154 min_cpus: 4,
6155 max_cpus: Some(64),
6156 };
6157 let c: TopologyConstraints = json.into();
6158 assert_eq!(c.min_numa_nodes, 1);
6159 assert_eq!(c.max_numa_nodes, Some(4));
6160 assert_eq!(c.min_llcs, 2);
6161 assert_eq!(c.max_llcs, Some(8));
6162 assert!(c.requires_smt);
6163 assert_eq!(c.min_cpus, 4);
6164 assert_eq!(c.max_cpus, Some(64));
6165 }
6166
6167 #[test]
6168 fn topology_constraints_json_into_topology_constraints_handles_none_options() {
6169 let json = TopologyConstraintsJson {
6170 min_numa_nodes: 1,
6171 max_numa_nodes: None,
6172 min_llcs: 1,
6173 max_llcs: None,
6174 requires_smt: false,
6175 min_cpus: 1,
6176 max_cpus: None,
6177 };
6178 let c: TopologyConstraints = json.into();
6179 assert!(c.max_numa_nodes.is_none());
6180 assert!(c.max_llcs.is_none());
6181 assert!(c.max_cpus.is_none());
6182 }
6183
6184 /// Const-fn parity with the runtime `--cell-parent-cgroup` gate:
6185 /// a `cgroup_parent` declaration containing `..` must compile-fail
6186 /// (or panic at runtime when the const fn is evaluated
6187 /// dynamically). Mirrors `runtime::append_base_sched_args`
6188 /// rejecting `--cell-parent-cgroup=/foo/..` so declarative and
6189 /// CLI sources share the same validation contract.
6190 #[test]
6191 #[should_panic(expected = "must not contain `..` segments")]
6192 fn cgroup_path_new_panics_on_parent_dir_segment() {
6193 let _ = CgroupPath::new("/foo/..");
6194 }
6195
6196 /// Bare `/..` (ParentDir immediately after RootDir) — same
6197 /// rejection class as `/foo/..`, distinct shape.
6198 #[test]
6199 #[should_panic(expected = "must not contain `..` segments")]
6200 fn cgroup_path_new_panics_on_bare_parent_dir() {
6201 let _ = CgroupPath::new("/..");
6202 }
6203
6204 /// `/.` — only a CurDir segment after root, no Normal anywhere.
6205 /// Hits the `has_normal=false` final assert (CurDir segments are
6206 /// stripped per the auto-strip rule, matching Path::components).
6207 #[test]
6208 #[should_panic(expected = "at least one non-`.`/non-empty segment")]
6209 fn cgroup_path_new_panics_on_only_dot_segment() {
6210 let _ = CgroupPath::new("/.");
6211 }
6212
6213 /// Multiple consecutive slashes only — `///` produces 3 empty
6214 /// segments after the leading `/`. has_normal stays false →
6215 /// rejected by the final assert. Mirrors Path::components which
6216 /// collapses repeated separators and yields just `[RootDir]`.
6217 #[test]
6218 #[should_panic(expected = "at least one non-`.`/non-empty segment")]
6219 fn cgroup_path_new_panics_on_only_slashes() {
6220 let _ = CgroupPath::new("///");
6221 }
6222
6223 /// `/foo/./bar` is ACCEPTED — the const-fn auto-strips the
6224 /// CurDir segment, matching `Path::components` semantics that
6225 /// the runtime validator uses. The two validators stay in
6226 /// lockstep on this shape (the runtime test
6227 /// `append_base_sched_args_accepts_embedded_dot_segment` pins
6228 /// the same accept behavior on the runtime side).
6229 #[test]
6230 fn cgroup_path_new_accepts_embedded_dot_segment() {
6231 let _ = CgroupPath::new("/foo/./bar");
6232 }
6233
6234 /// Normal paths still pass — pin the accept path so a future
6235 /// over-tightening of the segment walker (e.g. rejecting
6236 /// trailing slash, or rejecting any segment of length 1) is
6237 /// caught.
6238 #[test]
6239 fn cgroup_path_new_accepts_normal_paths() {
6240 let _ = CgroupPath::new("/ktstr");
6241 let _ = CgroupPath::new("/sys/fs/cgroup/ktstr");
6242 let _ = CgroupPath::new("/a/b/c");
6243 let _ = CgroupPath::new("/foo/"); // trailing slash OK
6244 }
6245
6246 /// GAP 14: pin that `SchedulerSpec` values survive a
6247 /// `HashSet` insert/lookup roundtrip — i.e. the Hash + Eq
6248 /// derives are present and agree on every variant. A
6249 /// regression that dropped Hash (e.g. swapping to a String
6250 /// payload without re-deriving) would silently break dedup
6251 /// in gauntlet expansion (which uses HashSet to collapse
6252 /// duplicate scheduler variants across topology combinations).
6253 #[test]
6254 fn scheduler_spec_hashset_roundtrip() {
6255 use std::collections::HashSet;
6256 let mut set: HashSet<SchedulerSpec> = HashSet::new();
6257 set.insert(SchedulerSpec::Eevdf);
6258 set.insert(SchedulerSpec::Discover("scx_lavd"));
6259 set.insert(SchedulerSpec::Path("./scx_rusty"));
6260 set.insert(SchedulerSpec::KernelBuiltin {
6261 enable: &["CONFIG_SCHED_DEBUG"],
6262 disable: &["CONFIG_SCHED_AUTOGROUP"],
6263 });
6264 assert_eq!(set.len(), 4);
6265 assert!(set.contains(&SchedulerSpec::Eevdf));
6266 assert!(set.contains(&SchedulerSpec::Discover("scx_lavd")));
6267 let dup_added = set.insert(SchedulerSpec::Eevdf);
6268 assert!(
6269 !dup_added,
6270 "duplicate SchedulerSpec insert must collapse via Hash+Eq"
6271 );
6272 assert_eq!(set.len(), 4);
6273 }
6274
6275 /// GAP 14 sibling: pin that `BpfMapWrite` values survive a
6276 /// `HashSet` insert/lookup roundtrip — same rationale as
6277 /// `scheduler_spec_hashset_roundtrip` (the field uses an
6278 /// `&'static [&'static BpfMapWrite]` slice on `KtstrTestEntry`
6279 /// and dedup logic relies on the derived Hash+Eq).
6280 #[test]
6281 fn bpf_map_write_hashset_roundtrip() {
6282 use std::collections::HashSet;
6283 let w1 = BpfMapWrite::new(".data", "crash", 1);
6284 let w2 = BpfMapWrite::new(".data", "stall", 2);
6285 let w3 = BpfMapWrite::new(".other", "crash", 1);
6286 let mut set: HashSet<BpfMapWrite> = HashSet::new();
6287 set.insert(w1);
6288 set.insert(w2);
6289 set.insert(w3);
6290 assert_eq!(set.len(), 3);
6291 assert!(set.contains(&w1));
6292 let dup_added = set.insert(w1);
6293 assert!(
6294 !dup_added,
6295 "duplicate BpfMapWrite insert must collapse via Hash+Eq"
6296 );
6297 assert_eq!(set.len(), 3);
6298 }
6299
6300 // -- BpfMapWrite::new + Sysctl::new format-validation pins --
6301 //
6302 // Each `#[should_panic]` pins one branch of the const-assert
6303 // chain. A future relaxation of the format rules (e.g. dropping
6304 // the leading-`.` requirement on map_name_suffix) would have to
6305 // explicitly delete the corresponding test, surfacing the
6306 // semantic change rather than letting it pass silently.
6307
6308 /// Empty `map_name_suffix` is intent-only invalid (matches no
6309 /// loaded BPF map). const-assert catches it at construction.
6310 #[test]
6311 #[should_panic(expected = "map_name_suffix must not be empty")]
6312 fn bpf_map_write_new_rejects_empty_suffix() {
6313 let _ = BpfMapWrite::new("", "crash", 0);
6314 }
6315
6316 /// BPF section names start with `.` (`.bss`, `.data`, `.rodata`);
6317 /// a suffix without the leading `.` matches no real map.
6318 #[test]
6319 #[should_panic(expected = "must start with `.`")]
6320 fn bpf_map_write_new_rejects_missing_dot_prefix() {
6321 let _ = BpfMapWrite::new("bss", "crash", 0);
6322 }
6323
6324 #[test]
6325 #[should_panic(expected = "must not contain whitespace")]
6326 fn bpf_map_write_new_rejects_whitespace_in_suffix() {
6327 let _ = BpfMapWrite::new(".b s", "crash", 0);
6328 }
6329
6330 #[test]
6331 #[should_panic(expected = "must not contain path separators")]
6332 fn bpf_map_write_new_rejects_path_separator_in_suffix() {
6333 let _ = BpfMapWrite::new(".bss/data", "crash", 0);
6334 }
6335
6336 /// Valid construction round-trips through the getters. Pinned to
6337 /// catch a getter-vs-field divergence (e.g. if a future refactor
6338 /// caches a transformed value but forgets to update the getter).
6339 #[test]
6340 fn bpf_map_write_new_valid_round_trips() {
6341 let w = BpfMapWrite::new(".bss", "crash", 42);
6342 assert_eq!(w.map_name_suffix(), ".bss");
6343 assert_eq!(w.field(), "crash");
6344 assert_eq!(w.value(), 42);
6345 }
6346
6347 /// Empty `field` names no VAR; the write-time BTF resolver would find
6348 /// nothing. const-assert catches it at construction.
6349 #[test]
6350 #[should_panic(expected = "field must not be empty")]
6351 fn bpf_map_write_new_rejects_empty_field() {
6352 let _ = BpfMapWrite::new(".bss", "", 0);
6353 }
6354
6355 /// A BTF VAR name carries no whitespace; a spaced `field` is a typo
6356 /// that would never resolve.
6357 #[test]
6358 #[should_panic(expected = "field must not contain whitespace")]
6359 fn bpf_map_write_new_rejects_whitespace_in_field() {
6360 let _ = BpfMapWrite::new(".bss", "cr ash", 0);
6361 }
6362
6363 #[test]
6364 #[should_panic(expected = "field must not contain path separators")]
6365 fn bpf_map_write_new_rejects_path_separator_in_field() {
6366 let _ = BpfMapWrite::new(".bss", "a/b", 0);
6367 }
6368
6369 #[test]
6370 #[should_panic(expected = "field must be printable ASCII only")]
6371 fn bpf_map_write_new_rejects_control_byte_in_field() {
6372 let _ = BpfMapWrite::new(".bss", "cr\x01ash", 0);
6373 }
6374
6375 /// `.` is a dot-path separator; a leading/trailing `.` is an empty
6376 /// segment the BTF resolver could never match.
6377 #[test]
6378 #[should_panic(expected = "must not start or end with `.`")]
6379 fn bpf_map_write_new_rejects_trailing_dot_in_field() {
6380 let _ = BpfMapWrite::new(".bss", "crash.", 0);
6381 }
6382
6383 /// The leading half of the same start/end-dot guard (sibling
6384 /// `Sysctl::new` splits leading and trailing into separate pins; a
6385 /// regression dropping only the leading check must not slip past).
6386 #[test]
6387 #[should_panic(expected = "must not start or end with `.`")]
6388 fn bpf_map_write_new_rejects_leading_dot_in_field() {
6389 let _ = BpfMapWrite::new(".bss", ".crash", 0);
6390 }
6391
6392 /// A doubled `..` is an empty dot-path segment.
6393 #[test]
6394 #[should_panic(expected = "field must not contain `..`")]
6395 fn bpf_map_write_new_rejects_doubled_dot_in_field() {
6396 let _ = BpfMapWrite::new(".bss", "a..b", 0);
6397 }
6398
6399 /// An interior `.` separates non-empty dot-path segments and IS
6400 /// accepted — the field doc promises dot-paths (e.g.
6401 /// `sys_stat.avg_lat_cri`); pins that a future validator over-tightening
6402 /// to reject all `.` would break this.
6403 #[test]
6404 fn bpf_map_write_new_accepts_interior_dot_in_field() {
6405 assert_eq!(BpfMapWrite::new(".bss", "a.b", 1).field(), "a.b");
6406 }
6407
6408 #[test]
6409 #[should_panic(expected = "Sysctl key must not be empty")]
6410 fn sysctl_new_rejects_empty_key() {
6411 let _ = Sysctl::new("", "1");
6412 }
6413
6414 /// Common operator typo: writing the sysctl path in slash-form
6415 /// (`kernel/foo`) instead of dotted form (`kernel.foo`).
6416 #[test]
6417 #[should_panic(expected = "must use the dotted form")]
6418 fn sysctl_new_rejects_slash_in_key() {
6419 let _ = Sysctl::new("kernel/foo", "1");
6420 }
6421
6422 /// A bare single-segment key (`foo` instead of `kernel.foo`) is
6423 /// almost certainly a typo — the sysctl tree is always at least
6424 /// 2 segments deep.
6425 #[test]
6426 #[should_panic(expected = "must be namespaced")]
6427 fn sysctl_new_rejects_undotted_key() {
6428 let _ = Sysctl::new("foo", "1");
6429 }
6430
6431 #[test]
6432 #[should_panic(expected = "must not start or end with `.`")]
6433 fn sysctl_new_rejects_leading_dot_key() {
6434 let _ = Sysctl::new(".foo", "1");
6435 }
6436
6437 #[test]
6438 #[should_panic(expected = "must not start or end with `.`")]
6439 fn sysctl_new_rejects_trailing_dot_key() {
6440 let _ = Sysctl::new("foo.", "1");
6441 }
6442
6443 #[test]
6444 #[should_panic(expected = "value must not be empty")]
6445 fn sysctl_new_rejects_empty_value() {
6446 let _ = Sysctl::new("kernel.foo", "");
6447 }
6448
6449 #[test]
6450 #[should_panic(expected = "must not contain a newline")]
6451 fn sysctl_new_rejects_newline_in_value() {
6452 let _ = Sysctl::new("kernel.foo", "1\n2");
6453 }
6454
6455 /// `=` in the value would corrupt the `sysctl.<key>=<value>`
6456 /// cmdline form (parser would split on the wrong `=`).
6457 #[test]
6458 #[should_panic(expected = "must not contain `=`")]
6459 fn sysctl_new_rejects_equals_in_value() {
6460 let _ = Sysctl::new("kernel.foo", "1=2");
6461 }
6462
6463 #[test]
6464 fn sysctl_new_valid_round_trips() {
6465 let s = Sysctl::new("kernel.sched_cfs_bandwidth_slice_us", "1000");
6466 assert_eq!(s.key(), "kernel.sched_cfs_bandwidth_slice_us");
6467 assert_eq!(s.value(), "1000");
6468 }
6469
6470 // -- additional Sysctl key/value rejection cases --
6471
6472 #[test]
6473 #[should_panic(expected = "must not contain whitespace")]
6474 fn sysctl_new_rejects_space_in_key() {
6475 let _ = Sysctl::new(" kernel.foo", "1");
6476 }
6477
6478 #[test]
6479 #[should_panic(expected = "must not contain whitespace")]
6480 fn sysctl_new_rejects_tab_in_key() {
6481 let _ = Sysctl::new("kernel\t.foo", "1");
6482 }
6483
6484 #[test]
6485 #[should_panic(expected = "must not contain whitespace")]
6486 fn sysctl_new_rejects_newline_in_key() {
6487 let _ = Sysctl::new("kernel\n.foo", "1");
6488 }
6489
6490 #[test]
6491 #[should_panic(expected = "must not contain `=`")]
6492 fn sysctl_new_rejects_equals_in_key() {
6493 let _ = Sysctl::new("kernel=foo.bar", "1");
6494 }
6495
6496 #[test]
6497 #[should_panic(expected = "must be printable ASCII")]
6498 fn sysctl_new_rejects_control_byte_in_key() {
6499 let _ = Sysctl::new("kernel.\x01foo", "1");
6500 }
6501
6502 #[test]
6503 #[should_panic(expected = "must not contain `..`")]
6504 fn sysctl_new_rejects_double_dot_in_key() {
6505 let _ = Sysctl::new("kernel..foo", "1");
6506 }
6507
6508 #[test]
6509 #[should_panic(expected = "must not contain a carriage return")]
6510 fn sysctl_new_rejects_carriage_return_in_value() {
6511 let _ = Sysctl::new("kernel.foo", "1\r2");
6512 }
6513
6514 // -- additional BpfMapWrite suffix rejection cases --
6515
6516 #[test]
6517 #[should_panic(expected = "must be longer than a bare `.`")]
6518 fn bpf_map_write_new_rejects_bare_dot() {
6519 let _ = BpfMapWrite::new(".", "crash", 0);
6520 }
6521
6522 #[test]
6523 #[should_panic(expected = "must not start with `..`")]
6524 fn bpf_map_write_new_rejects_leading_double_dot() {
6525 let _ = BpfMapWrite::new("..bss", "crash", 0);
6526 }
6527
6528 #[test]
6529 #[should_panic(expected = "must be printable ASCII")]
6530 fn bpf_map_write_new_rejects_null_byte_in_suffix() {
6531 let _ = BpfMapWrite::new(".bss\0", "crash", 0);
6532 }
6533
6534 #[test]
6535 #[should_panic(expected = "must be printable ASCII")]
6536 fn bpf_map_write_new_rejects_control_byte_in_suffix() {
6537 let _ = BpfMapWrite::new(".b\x01ss", "crash", 0);
6538 }
6539
6540 /// Lock-step pin: `KtstrTestEntry::default()` must agree with
6541 /// `KtstrTestEntry::DEFAULT` field-by-field. The trait impl
6542 /// today delegates to the const, but a future divergence (e.g.
6543 /// someone "improves" `Default` to seed a different memory
6544 /// budget) would silently produce two construction paths
6545 /// disagreeing on what a baseline entry looks like —
6546 /// `..Default::default()` callers and `..KtstrTestEntry::DEFAULT`
6547 /// callers would yield different runs from "identical" code.
6548 #[test]
6549 fn ktstr_test_entry_default_matches_const() {
6550 let from_const = KtstrTestEntry::DEFAULT;
6551 let from_trait: KtstrTestEntry = Default::default();
6552 assert_eq!(from_trait.name, from_const.name);
6553 assert!(std::ptr::fn_addr_eq(from_trait.func, from_const.func));
6554 assert_eq!(from_trait.topology.llcs, from_const.topology.llcs);
6555 assert_eq!(
6556 from_trait.topology.cores_per_llc,
6557 from_const.topology.cores_per_llc
6558 );
6559 assert_eq!(
6560 from_trait.topology.threads_per_core,
6561 from_const.topology.threads_per_core
6562 );
6563 assert_eq!(
6564 from_trait.topology.numa_nodes,
6565 from_const.topology.numa_nodes
6566 );
6567 assert_eq!(from_trait.memory_mib, from_const.memory_mib);
6568 // Both default paths delegate to `Self::DEFAULT`, which sets
6569 // `scheduler: &Scheduler::EEVDF`. Rust may or may not dedupe
6570 // the `&CONST` materializations to the same address — pointer
6571 // equality is an implementation detail, not a contract.
6572 // Verify the scheduler-identity contract by NAME (the EEVDF
6573 // baseline has a unique stable name).
6574 assert_eq!(from_trait.scheduler.name, from_const.scheduler.name);
6575 assert_eq!(from_trait.scheduler.name, "eevdf");
6576 assert!(from_trait.payload.is_none() && from_const.payload.is_none());
6577 // Element-wise slice equality catches same-length content
6578 // drift (e.g. two different `&["--baseline=X"]` slices both
6579 // length 1 but with different X). Length-only compare would
6580 // miss that.
6581 assert_eq!(
6582 from_trait.workloads.len(),
6583 from_const.workloads.len(),
6584 "workloads count drift"
6585 );
6586 for (i, (a, b)) in from_trait
6587 .workloads
6588 .iter()
6589 .zip(from_const.workloads.iter())
6590 .enumerate()
6591 {
6592 assert!(
6593 std::ptr::eq(*a, *b),
6594 "workloads[{i}] pointer identity drift"
6595 );
6596 }
6597 assert_eq!(from_trait.auto_repro, from_const.auto_repro);
6598 assert_eq!(
6599 from_trait.extra_sched_args, from_const.extra_sched_args,
6600 "extra_sched_args content drift"
6601 );
6602 assert_eq!(from_trait.watchdog_timeout, from_const.watchdog_timeout);
6603 assert_eq!(
6604 from_trait.bpf_map_write.len(),
6605 from_const.bpf_map_write.len(),
6606 "bpf_map_write count drift"
6607 );
6608 for (i, (a, b)) in from_trait
6609 .bpf_map_write
6610 .iter()
6611 .zip(from_const.bpf_map_write.iter())
6612 .enumerate()
6613 {
6614 assert!(
6615 std::ptr::eq(*a, *b),
6616 "bpf_map_write[{i}] pointer identity drift"
6617 );
6618 }
6619 assert_eq!(
6620 from_trait.watch_bpf_maps.len(),
6621 from_const.watch_bpf_maps.len(),
6622 "watch_bpf_maps count drift"
6623 );
6624 for (i, (a, b)) in from_trait
6625 .watch_bpf_maps
6626 .iter()
6627 .zip(from_const.watch_bpf_maps.iter())
6628 .enumerate()
6629 {
6630 assert!(
6631 std::ptr::eq(*a, *b),
6632 "watch_bpf_maps[{i}] pointer identity drift"
6633 );
6634 }
6635 assert_eq!(from_trait.performance_mode, from_const.performance_mode);
6636 assert_eq!(from_trait.no_perf_mode, from_const.no_perf_mode);
6637 assert_eq!(from_trait.duration, from_const.duration);
6638 assert_eq!(from_trait.expect_err, from_const.expect_err);
6639 assert_eq!(from_trait.host_only, from_const.host_only);
6640 assert_eq!(
6641 from_trait.extra_include_files, from_const.extra_include_files,
6642 "extra_include_files content drift"
6643 );
6644 assert_eq!(from_trait.cleanup_budget, from_const.cleanup_budget);
6645 assert_eq!(from_trait.config_content, from_const.config_content);
6646 assert!(from_trait.disk.is_none() && from_const.disk.is_none());
6647 assert!(from_trait.post_vm.is_none() && from_const.post_vm.is_none());
6648 assert_eq!(
6649 from_trait.probe_dump_ready_gate,
6650 from_const.probe_dump_ready_gate
6651 );
6652 assert_eq!(from_trait.num_snapshots, from_const.num_snapshots);
6653 // `assert` field lock-step: Assert does not derive PartialEq,
6654 // so compare via `format_human()` (renders every
6655 // threshold field) plus the explicit bool field that
6656 // format_human omits.
6657 assert_eq!(
6658 from_trait.assert.format_human(),
6659 from_const.assert.format_human(),
6660 "Assert threshold-field drift between Default::default() and DEFAULT"
6661 );
6662 assert_eq!(
6663 from_trait.assert.enforce_monitor_thresholds,
6664 from_const.assert.enforce_monitor_thresholds,
6665 "Assert.enforce_monitor_thresholds drift between Default::default() and DEFAULT"
6666 );
6667 }
6668
6669 /// `default_post_vm_periodic_fired` MUST return Ok when periodic
6670 /// was NOT configured (`periodic_target == 0`) — the helper is
6671 /// a no-op for non-periodic tests so they pass through the
6672 /// macro-default path without spurious assertions.
6673 #[test]
6674 fn default_post_vm_periodic_fired_skips_when_periodic_disabled() {
6675 let r = crate::vmm::VmResult {
6676 periodic_target: 0,
6677 periodic_fired: 0,
6678 ..crate::vmm::VmResult::test_fixture()
6679 };
6680 super::default_post_vm_periodic_fired(&r)
6681 .expect("periodic_target == 0 must short-circuit to Ok");
6682 }
6683
6684 /// Build a synthetic non-placeholder `FailureDumpReport` —
6685 /// minimal but with `is_placeholder = false`. Used in the
6686 /// helpers below to drive the bridge's `periodic_real_count`
6687 /// without booting a real VM.
6688 fn real_report() -> crate::monitor::dump::FailureDumpReport {
6689 // Default puts `is_placeholder = false`; spell it explicitly
6690 // so a future Default-shape change doesn't silently flip the
6691 // test fixture.
6692 crate::monitor::dump::FailureDumpReport {
6693 schema: crate::monitor::dump::SCHEMA_SINGLE.to_string(),
6694 is_placeholder: false,
6695 ..Default::default()
6696 }
6697 }
6698
6699 fn placeholder_report(reason: &str) -> crate::monitor::dump::FailureDumpReport {
6700 crate::monitor::dump::FailureDumpReport::placeholder(reason)
6701 }
6702
6703 /// When periodic WAS configured AND at least one REAL (non-
6704 /// placeholder) snapshot landed on the bridge, the helper
6705 /// returns Ok. Pins the smoke-floor contract.
6706 #[test]
6707 fn default_post_vm_periodic_fired_ok_when_at_least_one_real_landed() {
6708 let r = crate::vmm::VmResult {
6709 periodic_target: 5,
6710 periodic_fired: 1,
6711 ..crate::vmm::VmResult::test_fixture()
6712 };
6713 r.snapshot_bridge.store("periodic_000", real_report());
6714 super::default_post_vm_periodic_fired(&r)
6715 .expect("at least one real periodic capture must surface as Ok");
6716 }
6717
6718 /// When periodic WAS configured AND every fired snapshot was
6719 /// only a placeholder (rendezvous-timeout or gate-suppressed),
6720 /// the helper MUST fail — the scheduler attached but produced
6721 /// zero useful BPF state. This is the case the new semantic
6722 /// catches that the old `periodic_fired >= 1` floor missed.
6723 #[test]
6724 fn default_post_vm_periodic_fired_fails_when_only_placeholders_landed() {
6725 let r = crate::vmm::VmResult {
6726 periodic_target: 3,
6727 periodic_fired: 3,
6728 // Readiness landed WELL INSIDE the capture window: the
6729 // structural starvation arm (readiness >= window end, or
6730 // window never resolved) must NOT engage, so the
6731 // placeholder-only shape exercises the real-count FAILURE
6732 // path this test pins. The fixture default (both None)
6733 // reads as window-never-resolved and would skip instead.
6734 periodic_prereqs_ready: Some(std::time::Duration::from_secs(1)),
6735 periodic_window_end: Some(std::time::Duration::from_secs(10)),
6736 ..crate::vmm::VmResult::test_fixture()
6737 };
6738 // All three fires produced placeholders.
6739 r.snapshot_bridge
6740 .store("periodic_000", placeholder_report("rendezvous timed out"));
6741 r.snapshot_bridge
6742 .store("periodic_001", placeholder_report("rendezvous timed out"));
6743 r.snapshot_bridge
6744 .store("periodic_002", placeholder_report("rendezvous timed out"));
6745 let err = super::default_post_vm_periodic_fired(&r)
6746 .expect_err("placeholder-only fills must surface as Err");
6747 let msg = err.to_string();
6748 assert!(
6749 msg.contains("no periodic snapshot produced real BPF state")
6750 && msg.contains("periodic_real_count=0")
6751 && msg.contains("periodic_fired=3")
6752 && msg.contains("target=3"),
6753 "diagnostic must name the real-count floor + carry both counters; got {msg}",
6754 );
6755 }
6756
6757 /// Pins the load-bearing tag-prefix discrimination: a bridge
6758 /// that holds ONLY non-periodic tagged reports (user
6759 /// `Op::CaptureSnapshot` captures, watchpoint fires, etc.)
6760 /// MUST surface `periodic_real_count == 0` even when those
6761 /// non-periodic reports are real (non-placeholder) and present
6762 /// in number. A regression that conflated "any real report" with
6763 /// "periodic real report" would pass this state spuriously.
6764 #[test]
6765 fn default_post_vm_periodic_fired_fails_when_only_non_periodic_tagged_reports_present() {
6766 let r = crate::vmm::VmResult {
6767 periodic_target: 3,
6768 periodic_fired: 3,
6769 // Readiness-in-time: keep the structural starvation arm
6770 // disengaged so this test exercises its own failure path
6771 // (see the placeholders-only sibling).
6772 periodic_prereqs_ready: Some(std::time::Duration::from_secs(1)),
6773 periodic_window_end: Some(std::time::Duration::from_secs(10)),
6774 ..crate::vmm::VmResult::test_fixture()
6775 };
6776 // Populate ONLY non-periodic-tagged reports — these come
6777 // from user `Op::CaptureSnapshot` calls or watchpoint
6778 // fires, not from the periodic dispatch loop. They MUST
6779 // NOT pollute the periodic floor.
6780 r.snapshot_bridge.store("user_capture", real_report());
6781 r.snapshot_bridge.store("snapshot_baseline", real_report());
6782 r.snapshot_bridge.store("watch_my_var", real_report());
6783 let err = super::default_post_vm_periodic_fired(&r).expect_err(
6784 "non-periodic tags MUST NOT count toward periodic_real_count; \
6785 bridge has 3 real reports but none periodic → must Err",
6786 );
6787 let msg = err.to_string();
6788 assert!(
6789 msg.contains("periodic_real_count=0"),
6790 "diagnostic must name the zero real-count; got {msg}",
6791 );
6792 }
6793
6794 /// When periodic WAS configured AND ONE real capture landed
6795 /// alongside N placeholder timeouts (the realistic flake case),
6796 /// the helper MUST return Ok — single-snapshot timeouts under
6797 /// load shouldn't punish a working scheduler. Pins the
6798 /// tolerance gap that the strict `== periodic_target` floor
6799 /// would have failed.
6800 #[test]
6801 fn default_post_vm_periodic_fired_ok_when_one_real_among_placeholders() {
6802 let r = crate::vmm::VmResult {
6803 periodic_target: 5,
6804 periodic_fired: 5,
6805 ..crate::vmm::VmResult::test_fixture()
6806 };
6807 r.snapshot_bridge
6808 .store("periodic_000", placeholder_report("rendezvous timed out"));
6809 r.snapshot_bridge.store("periodic_001", real_report());
6810 r.snapshot_bridge
6811 .store("periodic_002", placeholder_report("rendezvous timed out"));
6812 r.snapshot_bridge
6813 .store("periodic_003", placeholder_report("rendezvous timed out"));
6814 r.snapshot_bridge
6815 .store("periodic_004", placeholder_report("rendezvous timed out"));
6816 super::default_post_vm_periodic_fired(&r).expect(
6817 "one real capture among placeholders must Ok — tolerance for single-snapshot flakes",
6818 );
6819 }
6820
6821 /// Pins the early-return semantic in `default_post_vm_periodic_fired`
6822 /// (its `if result.periodic_target == 0` early return): the helper
6823 /// short-circuits to Ok on `periodic_target == 0` BEFORE
6824 /// checking `periodic_fired`. A regression that swapped these
6825 /// checks (e.g., "require fired matches target unconditionally")
6826 /// would break tests with `target=0, fired=5` (synthesized
6827 /// firings without a configured target). Currently impossible
6828 /// in production but cheap to pin.
6829 #[test]
6830 fn default_post_vm_periodic_fired_target_zero_fired_nonzero_returns_ok() {
6831 let r = crate::vmm::VmResult {
6832 periodic_target: 0,
6833 periodic_fired: 5,
6834 ..crate::vmm::VmResult::test_fixture()
6835 };
6836 super::default_post_vm_periodic_fired(&r)
6837 .expect("target == 0 takes priority over fired count; must Ok");
6838 }
6839
6840 /// When `result.success == false` the underlying VM run
6841 /// failed (crash / timeout / signal). The default helper MUST
6842 /// short-circuit to Ok so the runner's own failure-rendering
6843 /// path drives the diagnostic; emitting `periodic_fired=0` on
6844 /// top would mask the real cause. Even if periodic was
6845 /// configured AND no snapshot fired, the success=false branch
6846 /// dominates.
6847 #[test]
6848 fn default_post_vm_periodic_fired_skips_when_vm_run_failed() {
6849 let r = crate::vmm::VmResult {
6850 success: false,
6851 periodic_target: 5,
6852 periodic_fired: 0,
6853 ..crate::vmm::VmResult::test_fixture()
6854 };
6855 super::default_post_vm_periodic_fired(&r)
6856 .expect("vm-run-failed must short-circuit to Ok so the runner's diagnostic dominates");
6857 }
6858
6859 /// When periodic WAS configured BUT NO snapshot fired, the
6860 /// helper MUST return Err carrying both observed counters in
6861 /// the diagnostic. Pins that a regression to "always Ok" would
6862 /// surface immediately.
6863 #[test]
6864 fn default_post_vm_periodic_fired_fails_when_none_fired() {
6865 let r = crate::vmm::VmResult {
6866 periodic_target: 5,
6867 periodic_fired: 0,
6868 // Readiness-in-time: keep the structural starvation arm
6869 // disengaged so this test exercises its own failure path
6870 // (see the placeholders-only sibling).
6871 periodic_prereqs_ready: Some(std::time::Duration::from_secs(1)),
6872 periodic_window_end: Some(std::time::Duration::from_secs(10)),
6873 ..crate::vmm::VmResult::test_fixture()
6874 };
6875 let err = super::default_post_vm_periodic_fired(&r)
6876 .expect_err("periodic_fired == 0 with target > 0 must surface as Err");
6877 let msg = err.to_string();
6878 assert!(
6879 msg.contains("periodic_fired=0") && msg.contains("target=5"),
6880 "diagnostic must carry both counters; got {msg}",
6881 );
6882 }
6883
6884 /// `KtstrTestEntry::DEFAULT.expect_auto_repro` is `false`.
6885 /// Backward-compat pin: an existing entry constructed via
6886 /// `..KtstrTestEntry::DEFAULT` (the canonical spread-init
6887 /// pattern in the macro codegen and in user fixtures) MUST
6888 /// carry `expect_auto_repro = false` so the new assertion
6889 /// opt-in stays off by default. A regression that flipped the
6890 /// default to `true` would silently invert every failing
6891 /// test's verdict through the dispatch arm.
6892 #[test]
6893 fn default_expect_auto_repro_is_false() {
6894 const {
6895 assert!(
6896 !super::KtstrTestEntry::DEFAULT.expect_auto_repro,
6897 "DEFAULT must keep expect_auto_repro at false for backward-compat opt-in semantics"
6898 );
6899 }
6900 }
6901
6902 /// `with_expect_auto_repro(true)` flips the field on; passing
6903 /// `false` flips it back off. Pins the builder symmetry
6904 /// against the sibling `with_auto_repro` / `with_expect_err` /
6905 /// `with_host_only` setters and guards against a missing-
6906 /// setter regression for the new pub field.
6907 #[test]
6908 fn with_expect_auto_repro_sets_field() {
6909 let entry = super::KtstrTestEntry::DEFAULT.with_expect_auto_repro(true);
6910 assert!(
6911 entry.expect_auto_repro,
6912 "with_expect_auto_repro(true) must set the field true"
6913 );
6914 let entry = entry.with_expect_auto_repro(false);
6915 assert!(
6916 !entry.expect_auto_repro,
6917 "with_expect_auto_repro(false) must flip the field back to false"
6918 );
6919 }
6920
6921 // -- with_disk / without_disk builder methods --
6922 //
6923 // The field-via-struct-literal path is covered by the
6924 // validate_* host_only/disk tests above; these pin the
6925 // chainable setter/clearer pair (the documented programmatic
6926 // construction path) so a missing-setter or
6927 // sets-the-wrong-field regression surfaces. DiskConfig does not
6928 // derive PartialEq, so the round-trip is asserted on the
6929 // distinguishing `capacity_mib` field rather than whole-struct
6930 // equality.
6931
6932 #[test]
6933 fn with_disk_sets_some_and_carries_config() {
6934 // Distinguishing capacity (512 != DEFAULT 256) proves the
6935 // setter stores the SUPPLIED config, not a fresh default.
6936 let cfg = crate::vmm::disk_config::DiskConfig::DEFAULT.capacity_mib(512);
6937 let entry = KtstrTestEntry::DEFAULT
6938 .with_name("disk_setter")
6939 .with_disk(cfg);
6940 let got = entry.disk.expect("with_disk must populate Some");
6941 assert_eq!(
6942 got.capacity_mib, 512,
6943 "with_disk must carry the supplied DiskConfig's capacity_mib"
6944 );
6945 // DEFAULT starts with no disk — the setter is what changed it.
6946 assert!(
6947 KtstrTestEntry::DEFAULT.disk.is_none(),
6948 "DEFAULT must boot without a disk; with_disk is the only mutator here"
6949 );
6950 }
6951
6952 #[test]
6953 fn without_disk_clears_to_none() {
6954 let cfg = crate::vmm::disk_config::DiskConfig::DEFAULT.capacity_mib(512);
6955 let entry = KtstrTestEntry::DEFAULT
6956 .with_name("disk_clear")
6957 .with_disk(cfg)
6958 .without_disk();
6959 assert!(
6960 entry.disk.is_none(),
6961 "without_disk must return the disk field to None"
6962 );
6963 }
6964
6965 // -- with_networks / without_networks builder methods --
6966
6967 #[test]
6968 fn with_networks_carries_config_and_order() {
6969 // Distinguishing MACs (!= DEFAULT 02:00:00:00:00:01) prove the
6970 // setter stores the SUPPLIED list, in order. Two NICs pin the
6971 // multi-element path.
6972 const MAC0: [u8; 6] = [0x52, 0x54, 0x00, 0xab, 0xcd, 0xef];
6973 const MAC1: [u8; 6] = [0x52, 0x54, 0x00, 0x11, 0x22, 0x33];
6974 // A `const` slice binding promotes its borrow to `'static` (the
6975 // `.mac()` const-fn call blocks ad-hoc promotion of an inline `&[..]`).
6976 const NETS: &[crate::vmm::net_config::NetConfig] = &[
6977 crate::vmm::net_config::NetConfig::DEFAULT.mac(MAC0),
6978 crate::vmm::net_config::NetConfig::DEFAULT.mac(MAC1),
6979 ];
6980 let entry = KtstrTestEntry::DEFAULT
6981 .with_name("net_setter")
6982 .with_networks(NETS);
6983 assert_eq!(
6984 entry.networks.len(),
6985 2,
6986 "with_networks must store every NIC"
6987 );
6988 assert_eq!(
6989 entry.networks[0].mac, MAC0,
6990 "first NIC carries MAC0 in order"
6991 );
6992 assert_eq!(
6993 entry.networks[1].mac, MAC1,
6994 "second NIC carries MAC1 in order"
6995 );
6996 assert!(
6997 KtstrTestEntry::DEFAULT.networks.is_empty(),
6998 "DEFAULT must boot without a NIC; with_networks is the only mutator here"
6999 );
7000 }
7001
7002 #[test]
7003 fn without_networks_clears_to_empty() {
7004 let entry = KtstrTestEntry::DEFAULT
7005 .with_name("net_clear")
7006 .with_networks(&[crate::vmm::net_config::NetConfig::DEFAULT])
7007 .without_networks();
7008 assert!(
7009 entry.networks.is_empty(),
7010 "without_networks must return the networks field to empty"
7011 );
7012 }
7013
7014 /// `without_disk` does not touch `networks` and vice versa — the
7015 /// two clearers are independent. Pins against a copy-paste
7016 /// regression where one clearer nulls the wrong field.
7017 #[test]
7018 fn disk_and_network_clearers_are_independent() {
7019 // DiskConfig is Clone (not Copy), so build a fresh one per entry;
7020 // the NIC list is a `const` slice binding ('static-promoted — the
7021 // `.mac()` const-fn call blocks ad-hoc promotion of an inline `&[..]`).
7022 const NET: &[crate::vmm::net_config::NetConfig] =
7023 &[crate::vmm::net_config::NetConfig::DEFAULT.mac([0x52, 0x54, 0, 0, 0, 9])];
7024 // Clear disk only: networks must survive.
7025 let e1 = KtstrTestEntry::DEFAULT
7026 .with_name("indep_disk")
7027 .with_disk(crate::vmm::disk_config::DiskConfig::DEFAULT.capacity_mib(512))
7028 .with_networks(NET)
7029 .without_disk();
7030 assert!(e1.disk.is_none(), "without_disk must clear disk");
7031 assert!(
7032 !e1.networks.is_empty(),
7033 "without_disk must NOT clear networks"
7034 );
7035 // Clear networks only: disk must survive.
7036 let e2 = KtstrTestEntry::DEFAULT
7037 .with_name("indep_net")
7038 .with_disk(crate::vmm::disk_config::DiskConfig::DEFAULT.capacity_mib(512))
7039 .with_networks(NET)
7040 .without_networks();
7041 assert!(
7042 e2.networks.is_empty(),
7043 "without_networks must clear networks"
7044 );
7045 assert!(e2.disk.is_some(), "without_networks must NOT clear disk");
7046 }
7047
7048 // -- with_num_snapshots builder method --
7049
7050 /// `with_num_snapshots` stores the exact supplied count and a
7051 /// second call overrides it (the field is a plain `u32`, not an
7052 /// accumulator). DEFAULT is `0` (periodic disabled), so the
7053 /// setter is the only mutator.
7054 #[test]
7055 fn with_num_snapshots_sets_and_overrides_exact_count() {
7056 assert_eq!(
7057 KtstrTestEntry::DEFAULT.num_snapshots,
7058 0,
7059 "DEFAULT disables periodic capture (num_snapshots == 0)"
7060 );
7061 let entry = KtstrTestEntry::DEFAULT
7062 .with_name("snap")
7063 .with_num_snapshots(4);
7064 assert_eq!(
7065 entry.num_snapshots, 4,
7066 "with_num_snapshots must store the exact supplied count"
7067 );
7068 // A second call overrides rather than accumulating.
7069 let entry = entry.with_num_snapshots(0);
7070 assert_eq!(
7071 entry.num_snapshots, 0,
7072 "with_num_snapshots must OVERRIDE, not add to, the prior count"
7073 );
7074 }
7075
7076 // -- with_post_vm_unconditional / without_post_vm_unconditional --
7077
7078 fn unconditional_cb_ok(_r: &crate::vmm::VmResult) -> anyhow::Result<()> {
7079 Ok(())
7080 }
7081 fn conditional_cb_ok(_r: &crate::vmm::VmResult) -> anyhow::Result<()> {
7082 Ok(())
7083 }
7084
7085 #[test]
7086 fn with_post_vm_unconditional_sets_field() {
7087 assert!(
7088 KtstrTestEntry::DEFAULT.post_vm_unconditional.is_none(),
7089 "DEFAULT must leave post_vm_unconditional unset"
7090 );
7091 let entry = KtstrTestEntry::DEFAULT
7092 .with_name("uncond")
7093 .with_post_vm_unconditional(unconditional_cb_ok);
7094 let cb = entry
7095 .post_vm_unconditional
7096 .expect("with_post_vm_unconditional must populate Some");
7097 // Pointer identity proves the setter stored the SUPPLIED fn
7098 // pointer, not some sentinel.
7099 assert!(
7100 std::ptr::fn_addr_eq(
7101 cb,
7102 unconditional_cb_ok as crate::test_support::PostVmCallback
7103 ),
7104 "with_post_vm_unconditional must carry the supplied callback fn pointer"
7105 );
7106 }
7107
7108 #[test]
7109 fn without_post_vm_unconditional_clears_to_none() {
7110 let entry = KtstrTestEntry::DEFAULT
7111 .with_name("uncond_clear")
7112 .with_post_vm_unconditional(unconditional_cb_ok)
7113 .without_post_vm_unconditional();
7114 assert!(
7115 entry.post_vm_unconditional.is_none(),
7116 "without_post_vm_unconditional must return the field to None"
7117 );
7118 }
7119
7120 /// `without_post_vm_unconditional` must NOT disturb the
7121 /// conditional `post_vm` slot — the two callback slots are
7122 /// independent (a guest-success entry runs both; only
7123 /// `post_vm` is gated on guest-fail). Pins the docstring claim
7124 /// on `without_post_vm_unconditional` ("Does not affect the
7125 /// conditional with_post_vm callback if one is set").
7126 #[test]
7127 fn without_post_vm_unconditional_leaves_conditional_post_vm_intact() {
7128 let entry = KtstrTestEntry::DEFAULT
7129 .with_name("both_then_clear_uncond")
7130 .with_post_vm(conditional_cb_ok)
7131 .with_post_vm_unconditional(unconditional_cb_ok)
7132 .without_post_vm_unconditional();
7133 assert!(
7134 entry.post_vm_unconditional.is_none(),
7135 "without_post_vm_unconditional must clear its own slot"
7136 );
7137 let cond = entry
7138 .post_vm
7139 .expect("conditional post_vm must survive the unconditional clear");
7140 assert!(
7141 std::ptr::fn_addr_eq(
7142 cond,
7143 conditional_cb_ok as crate::test_support::PostVmCallback
7144 ),
7145 "the surviving post_vm must still be the conditional callback"
7146 );
7147 }
7148
7149 /// Both callback slots can be set on the same entry and carry
7150 /// DISTINCT fn pointers — pins the field doc on
7151 /// `post_vm_unconditional` ("Both post_vm and
7152 /// post_vm_unconditional may be set on the same entry").
7153 #[test]
7154 fn post_vm_and_unconditional_slots_are_separate() {
7155 let entry = KtstrTestEntry::DEFAULT
7156 .with_name("both_slots")
7157 .with_post_vm(conditional_cb_ok)
7158 .with_post_vm_unconditional(unconditional_cb_ok);
7159 let cond = entry.post_vm.expect("post_vm set");
7160 let uncond = entry
7161 .post_vm_unconditional
7162 .expect("post_vm_unconditional set");
7163 assert!(
7164 std::ptr::fn_addr_eq(
7165 cond,
7166 conditional_cb_ok as crate::test_support::PostVmCallback
7167 ),
7168 "post_vm slot must hold the conditional callback"
7169 );
7170 assert!(
7171 std::ptr::fn_addr_eq(
7172 uncond,
7173 unconditional_cb_ok as crate::test_support::PostVmCallback
7174 ),
7175 "post_vm_unconditional slot must hold the unconditional callback"
7176 );
7177 assert!(
7178 !std::ptr::fn_addr_eq(cond, uncond),
7179 "the two slots must hold DISTINCT fn pointers, not alias each other"
7180 );
7181 }
7182
7183 // -- SchedulerJson::from_scheduler --
7184 //
7185 // `from_scheduler` projects a `&Scheduler` into the JSON wire
7186 // shape the `--ktstr-list-schedulers` ctor emits. The binary_kind
7187 // tag is the load-bearing projection — the verifier dispatch
7188 // `match`es on it without re-parsing the string.
7189
7190 /// Each `SchedulerSpec` variant maps to the corresponding
7191 /// `BinaryKindJson` tag, carrying the binary string for
7192 /// Discover/Path and erasing it (no BPF to verify) for
7193 /// Eevdf/KernelBuiltin. Table-driven over all four variants so a
7194 /// future variant addition that forgets a `from_scheduler` arm
7195 /// fails here.
7196 #[test]
7197 fn from_scheduler_projects_binary_kind_for_every_spec() {
7198 // Discover → Discover(name)
7199 let s = Scheduler::named("disc").binary(SchedulerSpec::Discover("scx_rusty"));
7200 assert_eq!(
7201 SchedulerJson::from_scheduler(&s).binary_kind,
7202 BinaryKindJson::Discover("scx_rusty".to_string()),
7203 );
7204 // Path → Path(p)
7205 let s = Scheduler::named("pth").binary(SchedulerSpec::Path("/usr/bin/scx_x"));
7206 assert_eq!(
7207 SchedulerJson::from_scheduler(&s).binary_kind,
7208 BinaryKindJson::Path("/usr/bin/scx_x".to_string()),
7209 );
7210 // Eevdf → Eevdf (unit, string erased)
7211 let s = Scheduler::named("ee").binary(SchedulerSpec::Eevdf);
7212 assert_eq!(
7213 SchedulerJson::from_scheduler(&s).binary_kind,
7214 BinaryKindJson::Eevdf,
7215 );
7216 // KernelBuiltin → KernelBuiltin (unit; enable/disable commands erased)
7217 let s = Scheduler::named("kb").binary(SchedulerSpec::KernelBuiltin {
7218 enable: &["echo on"],
7219 disable: &["echo off"],
7220 });
7221 assert_eq!(
7222 SchedulerJson::from_scheduler(&s).binary_kind,
7223 BinaryKindJson::KernelBuiltin,
7224 );
7225 }
7226
7227 /// `from_scheduler` copies `name`, the four topology dimensions,
7228 /// execution setup, `sched_args`, `kernels`, verifier exclusions, and
7229 /// every constraint field into the wire shape. `EEVDF` defaults the topology to
7230 /// 1 numa × 1 llc × 2 cores × 1 thread (see `Scheduler::EEVDF`),
7231 /// and the constraints to `TopologyConstraints::DEFAULT`. Pins
7232 /// every projected field so a mis-mapped dimension (e.g. swapping
7233 /// llcs and cores) surfaces.
7234 /// The consuming-process resolution the runtime sentinel must yield
7235 /// in this test process: an orchestrator-pinned fallback when one is
7236 /// present (an outer `cargo ktstr` run), else cargo's own
7237 /// `CARGO_MANIFEST_DIR` for the test target's package.
7238 fn expected_runtime_manifest_dir() -> String {
7239 std::env::var(crate::KTSTR_MANIFEST_DIR_FALLBACK_ENV)
7240 .ok()
7241 .filter(|dir| !dir.is_empty())
7242 .unwrap_or_else(|| {
7243 std::env::var("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR")
7244 })
7245 }
7246
7247 #[test]
7248 fn effective_manifest_dir_prefers_explicit_then_runtime() {
7249 // An explicit declaration (declare_scheduler! or the const
7250 // builder) always wins over the runtime fallback.
7251 const EXPLICIT: Scheduler = Scheduler::named("explicit").manifest_dir("/declared/dir");
7252 assert_eq!(EXPLICIT.effective_manifest_dir(), "/declared/dir");
7253 // The direct-builder default is the empty sentinel — NOT a
7254 // compile-time env! baking ktstr's own package dir (downstream
7255 // that dir is the read-only cargo registry checkout, whose
7256 // workspace does not contain the consumer's scheduler).
7257 const NAMED: Scheduler = Scheduler::named("runtime");
7258 assert_eq!(NAMED.manifest_dir, "");
7259 assert_eq!(
7260 NAMED.effective_manifest_dir(),
7261 expected_runtime_manifest_dir(),
7262 );
7263 }
7264
7265 #[test]
7266 fn from_scheduler_copies_name_topology_args_kernels_constraints() {
7267 let json = SchedulerJson::from_scheduler(&Scheduler::EEVDF);
7268 assert_eq!(json.name, "eevdf");
7269 // EEVDF carries the empty manifest_dir sentinel, so the JSON
7270 // projection resolves it at runtime. In-repo under bare cargo
7271 // test / nextest that value is this crate's own dir —
7272 // byte-identical to the pre-sentinel compile-time `env!` baking.
7273 assert_eq!(json.manifest_dir, expected_runtime_manifest_dir());
7274 // EEVDF topology baseline.
7275 assert_eq!(json.topology.num_numa_nodes, 1);
7276 assert_eq!(json.topology.num_llcs, 1);
7277 assert_eq!(json.topology.cores_per_llc, 2);
7278 assert_eq!(json.topology.threads_per_core, 1);
7279 // EEVDF carries no sched_args, no kernel filter.
7280 assert!(json.sched_args.is_empty());
7281 assert!(json.sysctls.is_empty());
7282 assert!(json.kargs.is_empty());
7283 assert!(json.cgroup_parent.is_none());
7284 assert!(json.config_file.is_none());
7285 assert!(json.kernels.is_empty());
7286 assert!(json.verifier_exclude_topologies.is_empty());
7287 // Constraints mirror TopologyConstraints::DEFAULT.
7288 assert_eq!(json.constraints.min_numa_nodes, 1);
7289 assert_eq!(json.constraints.max_numa_nodes, Some(1));
7290 assert_eq!(json.constraints.min_llcs, 1);
7291 assert_eq!(json.constraints.max_llcs, Some(12));
7292 assert!(!json.constraints.requires_smt);
7293 assert_eq!(json.constraints.min_cpus, 1);
7294 assert_eq!(json.constraints.max_cpus, Some(192));
7295 }
7296
7297 /// Non-default fields round-trip through the projection: a
7298 /// scheduler with an overridden topology, explicit guest setup,
7299 /// `sched_args`, `kernels`, and tightened `constraints` projects each
7300 /// verbatim.
7301 /// `Scheduler::topology(numa, llcs, cores, threads)` maps the
7302 /// argument order to the `Topology` fields, so this also pins
7303 /// that the projection reads `num_numa_nodes()`/`num_llcs()`
7304 /// (not the raw struct fields in a swapped order).
7305 #[test]
7306 fn from_scheduler_projects_overridden_fields_verbatim() {
7307 static ARGS: &[&str] = &["--slice-us", "20000"];
7308 static SYSCTLS: &[Sysctl] = &[
7309 Sysctl::new("kernel.sched_rr_timeslice_ms", "10"),
7310 Sysctl::new("kernel.sched_rr_timeslice_ms", "25"),
7311 Sysctl::new("kernel.numa_balancing", "0"),
7312 ];
7313 static KARGS: &[&str] = &["nosmt", "iomem=relaxed"];
7314 static KERNELS: &[&str] = &["6.14", "6.15..6.16"];
7315 static VERIFIER_EXCLUDES: &[&str] = &["240cpu-15llc-nosmt"];
7316 let s = Scheduler::named("custom")
7317 .binary_discover("scx_custom")
7318 // 2 numa × 4 llcs × 8 cores × 2 threads
7319 .topology(2, 4, 8, 2)
7320 .sched_args(ARGS)
7321 .sysctls(SYSCTLS)
7322 .kargs(KARGS)
7323 .cgroup_parent("/custom")
7324 .config_file("scheduler.toml")
7325 .kernels(KERNELS)
7326 .verifier_exclude_topologies(VERIFIER_EXCLUDES)
7327 .constraints(
7328 TopologyConstraints::DEFAULT
7329 .with_min_numa_nodes(2)
7330 .with_max_numa_nodes(4)
7331 .with_requires_smt(true),
7332 );
7333 let json = SchedulerJson::from_scheduler(&s);
7334 assert_eq!(json.name, "custom");
7335 assert_eq!(
7336 json.binary_kind,
7337 BinaryKindJson::Discover("scx_custom".to_string())
7338 );
7339 assert_eq!(json.topology.num_numa_nodes, 2);
7340 assert_eq!(json.topology.num_llcs, 4);
7341 assert_eq!(json.topology.cores_per_llc, 8);
7342 assert_eq!(json.topology.threads_per_core, 2);
7343 assert_eq!(json.sched_args, vec!["--slice-us", "20000"]);
7344 assert_eq!(
7345 json.sysctls,
7346 vec![
7347 SysctlJson {
7348 key: "kernel.sched_rr_timeslice_ms".into(),
7349 value: "10".into(),
7350 },
7351 SysctlJson {
7352 key: "kernel.sched_rr_timeslice_ms".into(),
7353 value: "25".into(),
7354 },
7355 SysctlJson {
7356 key: "kernel.numa_balancing".into(),
7357 value: "0".into(),
7358 },
7359 ],
7360 "sysctl projection must preserve order and duplicate keys",
7361 );
7362 assert_eq!(json.kargs, vec!["nosmt", "iomem=relaxed"]);
7363 assert_eq!(json.cgroup_parent.as_deref(), Some("/custom"));
7364 assert_eq!(json.config_file.as_deref(), Some("scheduler.toml"));
7365 assert_eq!(json.kernels, vec!["6.14", "6.15..6.16"]);
7366 assert_eq!(json.verifier_exclude_topologies, vec!["240cpu-15llc-nosmt"],);
7367 assert_eq!(json.constraints.min_numa_nodes, 2);
7368 assert_eq!(json.constraints.max_numa_nodes, Some(4));
7369 assert!(json.constraints.requires_smt);
7370 }
7371
7372 /// The projected `SchedulerJson` survives a serde JSON round-trip with
7373 /// field-for-field equality — it is the `scheduler` field of each
7374 /// [`SchedulerListEntry`] the `--ktstr-list-schedulers` ctor serializes,
7375 /// so this is the exact shape a consumer deserializes. Exercises the
7376 /// `#[serde(tag = "kind", content = "value")]` adjacent tagging on
7377 /// `BinaryKindJson` (Discover serializes as
7378 /// `{"kind":"discover","value":"..."}`).
7379 #[test]
7380 fn from_scheduler_json_roundtrips_through_serde() {
7381 let s = Scheduler::named("rt")
7382 .binary_discover("scx_rt")
7383 .topology(1, 2, 4, 2)
7384 .sched_args(&["--x"])
7385 .kernels(&["6.14"]);
7386 let json = SchedulerJson::from_scheduler(&s);
7387 let text = serde_json::to_string(&json).expect("serialize SchedulerJson");
7388 // The adjacent-tagged binary_kind must surface its tag/value.
7389 assert!(
7390 text.contains("\"kind\":\"discover\"") && text.contains("\"value\":\"scx_rt\""),
7391 "Discover must serialize as kind/value adjacent tag, got: {text}"
7392 );
7393 let back: SchedulerJson = serde_json::from_str(&text).expect("deserialize SchedulerJson");
7394 assert_eq!(
7395 back, json,
7396 "SchedulerJson must round-trip through serde unchanged"
7397 );
7398 }
7399
7400 /// `manifest_dir` was added to the scheduler-list wire shape after the
7401 /// original probe protocol. Older JSON remains readable so a CLI can
7402 /// diagnose a mixed-version binary explicitly instead of failing at
7403 /// deserialization before it can name the offending declaration.
7404 #[test]
7405 fn scheduler_json_missing_manifest_dir_defaults_empty() {
7406 let json = SchedulerJson::from_scheduler(&Scheduler::EEVDF);
7407 let mut value = serde_json::to_value(json).expect("serialize SchedulerJson");
7408 value
7409 .as_object_mut()
7410 .expect("SchedulerJson is an object")
7411 .remove("manifest_dir");
7412 let back: SchedulerJson =
7413 serde_json::from_value(value).expect("legacy SchedulerJson deserializes");
7414 assert!(back.manifest_dir.is_empty());
7415 }
7416
7417 /// Execution-identity fields were added after the original scheduler-list
7418 /// wire protocol. A CLI must still deserialize an older linked test binary
7419 /// and treat every omitted field as its no-op declaration default.
7420 #[test]
7421 fn scheduler_json_missing_execution_identity_fields_default_empty() {
7422 static SYSCTLS: &[Sysctl] = &[Sysctl::new("kernel.numa_balancing", "0")];
7423 let json = SchedulerJson::from_scheduler(
7424 &Scheduler::named("legacy")
7425 .sysctls(SYSCTLS)
7426 .kargs(&["nosmt"])
7427 .cgroup_parent("/legacy")
7428 .config_file("legacy.toml"),
7429 );
7430 let mut value = serde_json::to_value(json).expect("serialize SchedulerJson");
7431 let object = value
7432 .as_object_mut()
7433 .expect("SchedulerJson serializes as an object");
7434 for field in ["sysctls", "kargs", "cgroup_parent", "config_file"] {
7435 assert!(
7436 object.remove(field).is_some(),
7437 "fixture must contain {field}"
7438 );
7439 }
7440 let back: SchedulerJson =
7441 serde_json::from_value(value).expect("legacy SchedulerJson deserializes");
7442 assert!(back.sysctls.is_empty());
7443 assert!(back.kargs.is_empty());
7444 assert!(back.cgroup_parent.is_none());
7445 assert!(back.config_file.is_none());
7446 }
7447
7448 /// `SchedulerJson` equality is the declaration identity used by recursive
7449 /// verifier discovery. Every execution setup field must therefore make an
7450 /// otherwise same-name declaration unequal.
7451 #[test]
7452 fn scheduler_json_execution_fields_participate_in_identity() {
7453 static SYSCTLS: &[Sysctl] = &[Sysctl::new("kernel.numa_balancing", "0")];
7454 static SYSCTLS_AB: &[Sysctl] = &[
7455 Sysctl::new("kernel.sched_rr_timeslice_ms", "10"),
7456 Sysctl::new("kernel.sched_rr_timeslice_ms", "25"),
7457 ];
7458 static SYSCTLS_BA: &[Sysctl] = &[
7459 Sysctl::new("kernel.sched_rr_timeslice_ms", "25"),
7460 Sysctl::new("kernel.sched_rr_timeslice_ms", "10"),
7461 ];
7462 let baseline = SchedulerJson::from_scheduler(&Scheduler::named("same"));
7463 let variants = [
7464 SchedulerJson::from_scheduler(&Scheduler::named("same").sysctls(SYSCTLS)),
7465 SchedulerJson::from_scheduler(&Scheduler::named("same").kargs(&["nosmt"])),
7466 SchedulerJson::from_scheduler(&Scheduler::named("same").cgroup_parent("/identity")),
7467 SchedulerJson::from_scheduler(&Scheduler::named("same").config_file("identity.toml")),
7468 ];
7469 for variant in variants {
7470 assert_ne!(
7471 variant, baseline,
7472 "execution setup must participate in SchedulerJson identity",
7473 );
7474 }
7475 assert_ne!(
7476 SchedulerJson::from_scheduler(&Scheduler::named("same").sysctls(SYSCTLS_AB)),
7477 SchedulerJson::from_scheduler(&Scheduler::named("same").sysctls(SYSCTLS_BA)),
7478 "sysctl declaration order must participate in SchedulerJson identity",
7479 );
7480 }
7481
7482 /// [`SchedulerListEntry`] — the `--ktstr-list-schedulers` wire element (a
7483 /// [`SchedulerJson`] plus `test_count`) — survives a serde round-trip
7484 /// field-for-field, the exact shape `cargo ktstr affected` deserializes.
7485 #[test]
7486 fn scheduler_list_entry_roundtrips_through_serde() {
7487 let s = Scheduler::named("rt")
7488 .binary_discover("scx_rt")
7489 .topology(1, 2, 4, 2)
7490 .kernels(&["6.14"]);
7491 let entry = SchedulerListEntry {
7492 scheduler: SchedulerJson::from_scheduler(&s),
7493 test_count: 3,
7494 };
7495 let text = serde_json::to_string(&entry).expect("serialize SchedulerListEntry");
7496 assert!(
7497 text.contains("\"test_count\":3"),
7498 "test_count must serialize, got: {text}"
7499 );
7500 let back: SchedulerListEntry =
7501 serde_json::from_str(&text).expect("deserialize SchedulerListEntry");
7502 assert_eq!(back, entry, "SchedulerListEntry must round-trip unchanged");
7503 }
7504
7505 #[test]
7506 fn scheduler_manifest_probe_roundtrips_all_payloads_together() {
7507 let scheduler = Scheduler::named("rt")
7508 .binary_discover("scx_rt")
7509 .manifest_dir("/workspace");
7510 let manifest = SchedulerManifestProbe {
7511 declarations: vec![SchedulerListEntry {
7512 scheduler: SchedulerJson::from_scheduler(&scheduler),
7513 test_count: 2,
7514 }],
7515 artifact_requirements: vec![SchedulerArtifactRequirement {
7516 binary_kind: BinaryKindJson::Discover("scx_rt".into()),
7517 manifest_dir: "/workspace".into(),
7518 schedulers: vec!["rt".into()],
7519 use_count: 2,
7520 }],
7521 tests: vec![SchedulerTestJson {
7522 test: "boot_smoke".into(),
7523 scheduler: "rt".into(),
7524 }],
7525 };
7526 let text = serde_json::to_string(&manifest).expect("serialize SchedulerManifestProbe");
7527 assert!(
7528 text.contains("\"declarations\"")
7529 && text.contains("\"artifact_requirements\"")
7530 && text.contains("\"tests\""),
7531 "the combined protocol carries every scheduler probe payload: {text}",
7532 );
7533 let back: SchedulerManifestProbe =
7534 serde_json::from_str(&text).expect("deserialize SchedulerManifestProbe");
7535 assert_eq!(back, manifest);
7536 }
7537
7538 #[test]
7539 fn scheduler_manifest_counts_and_maps_primary_and_staged_uses() {
7540 let primary = Scheduler::named("primary");
7541 let staged_a = Scheduler::named("staged_a");
7542 let staged_b = Scheduler::named("staged_b");
7543 let staged = [&staged_a, &staged_b];
7544
7545 let declarations = collect_scheduler_list_entries_from(
7546 [&primary, &staged_a, &staged_b],
7547 [(&primary, staged.as_slice())],
7548 );
7549 assert_eq!(
7550 declarations
7551 .iter()
7552 .map(|entry| (entry.scheduler.name.as_str(), entry.test_count,))
7553 .collect::<Vec<_>>(),
7554 [("primary", 1), ("staged_a", 1), ("staged_b", 1)],
7555 "a staged-only scheduler is still exercised by the test",
7556 );
7557
7558 let tests = collect_scheduler_tests_from([("scheduler_swap", &primary, staged.as_slice())]);
7559 assert_eq!(
7560 tests
7561 .iter()
7562 .map(|entry| (entry.test.as_str(), entry.scheduler.as_str(),))
7563 .collect::<Vec<_>>(),
7564 [
7565 ("scheduler_swap", "primary"),
7566 ("scheduler_swap", "staged_a"),
7567 ("scheduler_swap", "staged_b"),
7568 ],
7569 "change-scoped selection must retain every scheduler the test can run",
7570 );
7571 }
7572
7573 #[test]
7574 fn scheduler_artifact_requirements_dedupe_primary_and_staged_uses() {
7575 let first = Scheduler::named("first")
7576 .binary_discover("scx_shared")
7577 .manifest_dir("/workspace");
7578 let alias = Scheduler::named("alias")
7579 .binary_discover("scx_shared")
7580 .manifest_dir("/workspace");
7581 let path = Scheduler::named("path")
7582 .binary(SchedulerSpec::Path("/opt/scx_path"))
7583 .manifest_dir("/other");
7584 let requirements = collect_scheduler_artifact_requirements([&first, &alias, &first, &path]);
7585 assert_eq!(requirements.len(), 2);
7586 assert_eq!(
7587 requirements[0],
7588 SchedulerArtifactRequirement {
7589 binary_kind: BinaryKindJson::Discover("scx_shared".into()),
7590 manifest_dir: "/workspace".into(),
7591 schedulers: vec!["alias".into(), "first".into()],
7592 use_count: 3,
7593 },
7594 );
7595 assert_eq!(
7596 requirements[1],
7597 SchedulerArtifactRequirement {
7598 binary_kind: BinaryKindJson::Path("/opt/scx_path".into()),
7599 manifest_dir: "/other".into(),
7600 schedulers: vec!["path".into()],
7601 use_count: 1,
7602 },
7603 );
7604 }
7605
7606 /// [`SchedulerTestJson`] — the `--ktstr-list-scheduler-tests` wire element
7607 /// (test name + its scheduler's name) — survives a serde round-trip
7608 /// field-for-field, the exact shape `cargo ktstr --relevant` deserializes to
7609 /// map each test to its scheduler.
7610 #[test]
7611 fn scheduler_test_json_roundtrips_through_serde() {
7612 let entry = SchedulerTestJson {
7613 test: "boot_smoke".to_string(),
7614 scheduler: "scx_rt".to_string(),
7615 };
7616 let text = serde_json::to_string(&entry).expect("serialize SchedulerTestJson");
7617 assert!(
7618 text.contains("\"test\":\"boot_smoke\"") && text.contains("\"scheduler\":\"scx_rt\""),
7619 "both fields must serialize, got: {text}"
7620 );
7621 let back: SchedulerTestJson =
7622 serde_json::from_str(&text).expect("deserialize SchedulerTestJson");
7623 assert_eq!(back, entry, "SchedulerTestJson must round-trip unchanged");
7624 }
7625}