ktstr_macros/
lib.rs

1use proc_macro::TokenStream;
2use quote::quote;
3use syn::{DeriveInput, parse_macro_input};
4
5#[allow(dead_code)]
6mod kernel_path;
7
8mod claim;
9mod common;
10mod json;
11mod ktstr_test;
12mod payload;
13mod scheduler;
14mod test_entry;
15
16/// Register a manually constructed `KtstrTestEntry`.
17///
18/// This is the manual-entry counterpart to [`macro@ktstr_test`]: it registers the
19/// static in `KTSTR_TESTS` and emits the versioned ELF scheduler-manifest
20/// record consumed by `cargo ktstr`. Manual entries with staged schedulers
21/// should use `#[ktstr_test]`, whose attribute grammar can project every
22/// staged edge into the stamp.
23#[proc_macro_attribute]
24pub fn ktstr_test_entry(attr: TokenStream, item: TokenStream) -> TokenStream {
25    if !attr.is_empty() {
26        return syn::Error::new(
27            proc_macro2::Span::call_site(),
28            "ktstr_test_entry does not accept arguments",
29        )
30        .to_compile_error()
31        .into();
32    }
33    let item = parse_macro_input!(item as syn::ItemStatic);
34    test_entry::expand(item)
35        .unwrap_or_else(syn::Error::into_compile_error)
36        .into()
37}
38
39/// Attribute macro that registers a function as a ktstr integration test.
40///
41/// The annotated function must have signature `fn(&ktstr::scenario::Ctx) ->
42/// anyhow::Result<ktstr::assert::AssertResult>`. The macro:
43///
44/// 1. Renames the original function to `__ktstr_inner_{name}`.
45/// 2. Registers it in the `KTSTR_TESTS` distributed slice via linkme.
46/// 3. Emits a `#[test]` wrapper that boots a VM and runs the function
47///    inside it.
48///
49/// Every attribute is optional. Most take a `key = value` form; the
50/// sixteen boolean attributes (`auto_repro`, `expect_auto_repro`,
51/// `not_stuck`, `isolation`, `performance_mode`, `pci`, `no_perf_mode`,
52/// `requires_smt`, `expect_err`, `survives_storm`, `allow_inconclusive`,
53/// `fail_on_rq_clock_stuck`, `host_only`, `ignore`, `kaslr`, `wprof`) also accept a
54/// bare form as shorthand for `= true` — e.g.
55/// `#[ktstr_test(host_only)]` is equivalent to
56/// `#[ktstr_test(host_only = true)]`. Of the sixteen, `auto_repro`
57/// and `kaslr` are the two whose default is `true`, so the bare form
58/// is a no-op; `auto_repro = false` / `kaslr = false` are the only
59/// way to disable each. The other fourteen default to `false`, so the
60/// bare form is the meaningful shorthand.
61///
62/// The accepted attributes and their defaults are the fields of
63/// `ktstr::test_support::KtstrTestEntry` (runtime metadata) and
64/// `ktstr::assert::Assert` (checking thresholds). A few are
65/// worth calling out because their names differ from the underlying
66/// field or because they have nontrivial defaults:
67///
68///   - `llcs = N` — number of LLCs (default: inherited from
69///     scheduler, or 1).
70///   - `cores = N` (default: inherited from scheduler, or 2)
71///   - `threads = N` (default: inherited from scheduler, or 1)
72///   - `numa_nodes = N` (default: inherited from scheduler, or 1)
73///   - `memory_mib = N` — per-test minimum memory in MiB (default:
74///     256). The declaration-derived floor is
75///     `max(total_cpus * 64, 256, memory_mib)` MiB; deferred sizing
76///     can raise the final allocation further to fit the prepared
77///     initramfs. For tests with more than 4 vCPUs the cpu-based
78///     floor dominates the macro default. At or below 4 vCPUs the
79///     absolute 256-MiB floor wins. Setting `memory_mib` above
80///     the cpu-based floor is only meaningful when the test needs
81///     more headroom than the per-cpu budget. The unit is binary
82///     mebibytes; the conversion at VM-launch is `value << 20`
83///     bytes, not decimal megabytes.
84///   - `duration_s = N` — scenario run duration in seconds; maps
85///     onto `KtstrTestEntry::duration`
86///   - `watchdog_timeout_s = N` — watchdog fire threshold in
87///     seconds; maps onto `KtstrTestEntry::watchdog_timeout`
88///   - `cleanup_budget_ms = N` — sub-watchdog cap on host-side VM
89///     teardown wall time; maps onto `KtstrTestEntry::cleanup_budget`
90///     as `Duration::from_millis(N)`. Default: `None` (unenforced).
91///   - `num_snapshots = N` — fire `N` periodic
92///     `freeze_and_dispatch(FreezeMode::Capture { gate_on_exit_kind: false })` boundaries inside the workload's
93///     10 %–90 % window, stored on the host
94///     `SnapshotBridge` under `periodic_NNN`. `0` (default)
95///     disables periodic capture entirely. Maps onto
96///     `KtstrTestEntry::num_snapshots`; runtime
97///     `KtstrTestEntry::validate` rejects values past the bridge
98///     cap (`MAX_STORED_SNAPSHOTS`), `host_only = true`, and
99///     duration / `N` settings that would land boundaries closer
100///     than 100 ms apart.
101///   - `scheduler = PATH` — path to a `const Scheduler` (typically
102///     produced by `declare_scheduler!(...)`). Maps onto
103///     `KtstrTestEntry::scheduler`, which is typed
104///     `&'static Scheduler`. Default: `&Scheduler::EEVDF`, the
105///     no-scx placeholder that runs under the kernel's default
106///     scheduler.
107///   - `payload = PATH` — path to a `const Payload` used as the
108///     primary binary workload (must be `PayloadKind::Binary`;
109///     runtime-enforced). Default: `None` (scheduler-only test).
110///     Coexists with `scheduler = PATH` — the payload runs *under*
111///     the selected scheduler.
112///   - `workloads = [PATH, PATH, ...]` — additional `const Payload`
113///     references composed with the primary via `Ctx::payload` in
114///     the test body. Default: `&[]`. Must not contain the same
115///     path as `payload` — reject at expansion time to catch the
116///     common "fio as primary AND workload" slip.
117///   - `auto_repro = bool` (default: `true`)
118///   - `wprof = bool` (default: `false`; requires the `wprof`
119///     cargo feature on ktstr) — attach `/bin/wprof` to the
120///     test's VM(s) and ship the Perfetto trace to the host.
121///   - `wprof_args = "..."` (requires the `wprof` cargo feature)
122///     — override `WprofConfig::default_args`. Only meaningful
123///     with `wprof = true`. Parsed as space-separated tokens.
124///   - `host_only = bool` (default: `false`) — run the test function
125///     on the host instead of inside a VM
126///   - `no_perf_mode = bool` (default: `false`) — decouple the
127///     virtual topology from host hardware. The VM is built with
128///     the declared `numa_nodes` / `llcs` / `cores` / `threads`
129///     even on smaller hosts; vCPU pinning, hugepages, NUMA mbind,
130///     RT scheduling, and KVM exit suppression are skipped, and
131///     gauntlet preset filtering relaxes host-topology checks
132///     to the single "host has enough total CPUs" inequality.
133///     Mutually exclusive with `performance_mode = true`. Maps onto
134///     `KtstrTestEntry::no_perf_mode`.
135///   - `post_vm = PATH` — host-side callback invoked after
136///     `vm.run()` returns, with access to the full `VmResult`.
137///     Use for assertions that need host-side state — e.g.
138///     draining `VmResult.snapshot_bridge` after a snapshot
139///     capture pipeline fires inside the guest. The function
140///     must have signature
141///     `fn(&ktstr::vmm::VmResult) -> anyhow::Result<()>`. PATH
142///     accepts any Rust path-expression that resolves to a value
143///     of that fn type — both free-function refs
144///     (`my_post_vm_check`) AND UFCS method refs
145///     (`VmResult::assert_wprof_pb_landed`) work via Rust's
146///     function-item-to-fn-pointer coercion, so a method that
147///     already has the right `&self -> Result<()>` shape can be
148///     pointed at directly without wrapping in a one-line
149///     delegating free fn.
150///     SUPPRESSED on guest-reported fail — see
151///     `post_vm_unconditional` for the always-runs sibling.
152///     Default: `None` (no callback).
153///   - `post_vm_unconditional = PATH` — host-side callback that
154///     always runs after `vm.run()` returns, bypassing the
155///     guest-fail suppression that gates `post_vm`. Same
156///     signature as `post_vm` and PATH accepts the same form:
157///     any Rust path-expression resolving to a value of that fn
158///     type — both free-function refs AND UFCS method refs
159///     (`VmResult::assert_wprof_pb_landed`-style) work via
160///     function-item-to-fn-pointer coercion. Use when the
161///     callback must observe host-side state regardless of
162///     guest-side outcome (e.g. verifying a sidecar artifact
163///     landed even when the guest reported a deliberate fail).
164///     The callback is responsible for guarding against missing
165///     state when the scheduler crashed before producing it —
166///     the canonical guard is
167///     `if !result.success { return Ok(()); }` at the top of the
168///     callback body. Setting `post_vm_unconditional` does NOT
169///     invert the test verdict — a guest-reported fail still
170///     fails the test even if the unconditional callback returns
171///     Ok. Both attributes may be set on the same entry (both
172///     errors surface via `combine_post_vm_errs` when both
173///     fire). Default: `None` (no callback).
174///   - `disk = PATH` — path to a `const DiskConfig` attached to the
175///     VM as a virtio-blk device at `/dev/vda`. Construct via
176///     `DiskConfig::DEFAULT.with_name("data")` or similar const-fn
177///     chain (the `with_name` builder takes `&'static str` so the
178///     full expression is const-evaluable). Maps onto
179///     `KtstrTestEntry::disk`. Default: `None` (no disk).
180///     Mutually exclusive with `host_only = true` —
181///     `host_only` skips the VM boot that owns the device lifecycle,
182///     so a `disk` attached under `host_only` would never bind;
183///     `KtstrTestEntry::validate` rejects the pairing at runtime.
184///   - `networks = [PATH, ...]` — array of `const NetConfig` paths, one
185///     virtio-net device per element (in-VMM loopback backend). On x86_64
186///     each lands on its own virtio-pci function (PCI slots 1..=N, one INTx
187///     GSI apiece); aarch64 takes a single virtio-MMIO NIC (build() errors
188///     on more than one). Construct
189///     each via `NetConfig::DEFAULT.mac(...)` or `NetConfig::DEFAULT`
190///     (const-fn chain). Maps onto `KtstrTestEntry::networks`. Default: `[]`
191///     (no NIC). Like `disk`, mutually exclusive with `host_only`.
192///   - `config = EXPR` — inline scheduler config content, written
193///     into the guest at the path declared by the scheduler's
194///     `config_file_def`. `EXPR` is either a string literal or a
195///     path to a `const &'static str` (e.g. `LAYERED_CONFIG`).
196///     Maps onto `KtstrTestEntry::config_content`. Required when
197///     the scheduler declares `config_file_def`; rejected when the
198///     scheduler does not. The pairing is enforced at compile time
199///     via a `const` assertion against `Scheduler::config_file_def`,
200///     and again at runtime by `KtstrTestEntry::validate` so direct
201///     programmatic-entry construction sees the same gate.
202///   - `expect_scx_bpf_error_contains = EXPR` — literal-substring
203///     matcher applied to the captured `scx_bpf_error` text in
204///     reproducer mode. `EXPR` is either a string literal or a path
205///     to a `const &'static str`. Maps onto
206///     `Assert::expect_scx_bpf_error_contains`. Requires
207///     `expect_err = true` (rejected at construction otherwise by
208///     `KtstrTestEntry::validate`). Empty strings panic at
209///     construction. When both `_contains` and `_matches` are set,
210///     the evaluator ANDs them — every set matcher must hit.
211///   - `expect_scx_bpf_error_matches = EXPR` — regex matcher with
212///     the same accepted forms and gating as `_contains`. Maps onto
213///     `Assert::expect_scx_bpf_error_matches`. Validated at
214///     construction: empty patterns, invalid regex syntax, and any
215///     pattern satisfying `is_match("")` all panic immediately. The
216///     `is_match("")` predicate catches two no-op classes with one
217///     check: patterns that match every position (e.g. `a?`, `.*`,
218///     `(?:)`) trivially pass against any corpus, and patterns that
219///     match only the empty string (e.g. `^$`) trivially fail
220///     against any non-empty corpus — both are equally useless pins.
221///     Bare `\b` slips the gate (no word characters in `""`); see
222///     `Assert::expect_scx_bpf_error_matches` for the operator
223///     direction.
224///   - `survives_storm` — assert the scx scheduler SURVIVES the run
225///     (does not die or get ejected during any hold); the positive
226///     inverse of `expect_err`. Requires an active scheduler and is
227///     mutually exclusive with both `expect_err` and `expect_auto_repro`
228///     (rejected at macro-parse and by `KtstrTestEntry::validate`).
229///     Enforced on scenarios driven through `execute_defs` /
230///     `execute_steps` / `execute_scenario` (which run the scheduler
231///     liveness probe); a survival violation surfaces as a failing exit
232///     with a survival-specific explainer.
233///   - `extra_include_files = ["PATH", "PATH", ...]` — host-side
234///     file paths to bundle into the guest initramfs beyond what
235///     the entry's `scheduler` / `payload` / `workloads` already
236///     declare via their own `include_files`. Use this for
237///     test-level dependencies that don't belong on a specific
238///     Payload: auxiliary data files, per-test helper scripts,
239///     fixtures. Each element must be a string literal (no
240///     expressions). Maps onto
241///     `KtstrTestEntry::extra_include_files` and is unioned with
242///     the per-payload specs at `run_ktstr_test` time via
243///     `KtstrTestEntry::all_include_files`. Default: `[]`.
244///     Path resolution: bare names (no `/`) search `PATH`; paths
245///     containing `/` are absolute or relative to the test process
246///     current directory; directories are walked recursively at
247///     test-run time (rejected by `cargo ktstr export` since the
248///     `.run` packager handles regular files only — recursive
249///     directory packaging is a v2 enhancement); a missing file
250///     fails loudly at setup with an actionable error naming the
251///     missing path.
252///
253/// Duplicate keys: each attribute KEY may appear at most once per
254/// `#[ktstr_test]` invocation; duplicate keys (whether the values
255/// match or differ) fail at expansion rather than silently letting
256/// the later value win. `#[ktstr_test(host_only = false,
257/// host_only)]` and `#[ktstr_test(llcs = 4, llcs = 8)]` both fail.
258/// The bare form (`host_only`) and explicit form (`host_only =
259/// true`) of the same attribute collide as well — they refer to
260/// the same slot. List values like `workloads = [FIO, FIO]` are
261/// NOT affected by this rule; the duplicate check is on attribute
262/// keys, not on values within an array. `payload = ...` and
263/// `workloads = [..]` keep their tailored messages directing the
264/// author to the right home for extras; `config = ...` and
265/// `expect_scx_bpf_error_{contains,matches} = ...` likewise have
266/// tailored wording; every other attribute uses a uniform
267/// "duplicate attribute" diagnostic.
268///
269/// Path / list forms: `#[ktstr_test(crate::host_only)]` (a
270/// multi-segment path, whether bare or as a key in
271/// `crate::host_only = true`) is rejected with a targeted message
272/// naming both valid forms with concrete examples — the macro only
273/// accepts bare single-segment idents because routing dispatches on
274/// the ident string against `BOOL_ATTR_NAMES` or the value-attr match
275/// arms (enumerated in `VALUE_ATTR_NAMES`).
276/// `#[ktstr_test(host_only(false))]` (parenthesised
277/// arguments) is rejected with a separate targeted message naming
278/// the attribute and the two valid forms (`= value` or bare); the
279/// same diagnostic fires for `crate::host_only(false)` so the
280/// operator sees one combined error rather than chasing two.
281#[proc_macro_attribute]
282pub fn ktstr_test(attr: TokenStream, item: TokenStream) -> TokenStream {
283    match ktstr_test::ktstr_test_impl(attr.into(), item.into()) {
284        Ok(ts) => ts.into(),
285        Err(e) => e.to_compile_error().into(),
286    }
287}
288
289/// Function-style macro that registers a `Scheduler` const.
290///
291/// # Syntax
292///
293/// ```rust,ignore
294/// use ktstr::prelude::*;
295///
296/// declare_scheduler!(MY_SCHED, {
297///     name = "my_sched",
298///     binary = "scx_my_sched",
299///     cgroup_parent = "/ktstr",
300///     sched_args = ["--exit-dump-len", "1048576"],
301///     kernels = ["6.14", "7.0..=7.2"],
302///     verifier_exclude_topologies = ["240cpu-15llc-nosmt"],
303///     constraints = TopologyConstraints {
304///         min_llcs: 1, max_llcs: Some(8), max_cpus: Some(64),
305///         ..TopologyConstraints::DEFAULT
306///     },
307/// });
308/// ```
309///
310/// # Generated items
311///
312/// Given `declare_scheduler!(MITOSIS, { ... })`:
313///
314/// - `pub static MITOSIS: ::ktstr::test_support::Scheduler` — the declared
315///   scheduler value. No `_PAYLOAD` suffix; the const IS the
316///   `Scheduler`.
317/// - A hidden `static __KTSTR_SCHED_REG_MITOSIS: &'static Scheduler`
318///   registered in `KTSTR_SCHEDULERS` (`ktstr::test_support::KTSTR_SCHEDULERS`)
319///   via linkme for in-process lookup.
320/// - A hidden, versioned scheduler-manifest record in a link-retained ELF
321///   section. `cargo ktstr` reads this record directly from warmed test
322///   binaries, so verifier discovery does not start each binary.
323///
324/// # Visibility prefix
325///
326/// An optional Rust visibility prefix may precede the const name:
327///
328/// ```rust,ignore
329/// declare_scheduler!(MY_SCHED, { ... });             // defaults to `pub`
330/// declare_scheduler!(pub MY_SCHED, { ... });          // explicit `pub`
331/// declare_scheduler!(pub(crate) MY_SCHED, { ... });   // crate-local
332/// declare_scheduler!(pub(super) MY_SCHED, { ... });   // parent-module
333/// declare_scheduler!(pub(in crate::test_support) MY_SCHED, { ... });
334/// ```
335///
336/// Omitting the prefix defaults to `pub` — schedulers are normally
337/// public so the verifier and other crates can reference them; an
338/// explicit prefix is needed only when the declaration sits inside
339/// a module that wants to narrow the exposed name. (Field content
340/// shown above as `{ ... }` is elided; consult the Syntax example
341/// for the required fields.) The hidden registry static (see
342/// Generated items above) is always `static` (private) regardless
343/// of the user-facing const's visibility — `linkme` gathers it via
344/// link-section walking, not Rust name resolution, so the slice
345/// mechanism works at every visibility level.
346///
347/// # Accepted fields
348///
349/// Exactly one scheduler-source must be declared: `binary`,
350/// `binary_path`, or the `kernel_builtin_enable` + `kernel_builtin_disable`
351/// pair. The three options select between the matching
352/// `SchedulerSpec` variants. To run under the kernel default
353/// instead, reference `ktstr::test_support::Scheduler::EEVDF`
354/// directly rather than declaring a new scheduler.
355///
356/// | Field | Required | Description |
357/// |---|---|---|
358/// | `name = "..."` | yes | Scheduler name (sidecar / logs). |
359/// | `binary = "..."` | one source | Binary name → `SchedulerSpec::Discover(...)`. Matched against `[[bin]]` names in `target/{debug,release}/`, the test binary's directory, or `KTSTR_SCHEDULER` env var. Often equal to the cargo package name but not required to be. |
360/// | `binary_path = "/abs/path"` | one source | Absolute filesystem path → `SchedulerSpec::Path(...)`. The runtime does not auto-build this variant: the file must already exist at the path when the test runs. Use for prebuilt binaries that live outside the cargo discovery cascade. Macro-time validation rejects empty strings, relative paths, and `~`-prefixed paths (no compile-time tilde expansion); existence is the runtime's job. |
361/// | `kernel_builtin_enable = [..]` + `kernel_builtin_disable = [..]` | one source | Two string-array literals that together select `SchedulerSpec::KernelBuiltin { enable: &[..], disable: &[..] }`. The framework writes the enable commands to the guest's `/sched_enable` and the disable commands to `/sched_disable` (see `src/vmm/initramfs.rs`), and the guest interpreter runs each entry once at scenario start / teardown. Both fields must be set together — setting only one is rejected. The interpreter (`src/vmm/rust_init/dump.rs`) accepts EXACTLY ONE shell-line shape: `echo VALUE > /path` (plus blank lines and `#` comments). Pipes, `>>`, `;`, variable expansion, and any other syntax silently no-ops at runtime, so the macro rejects entries that don't match `echo … > /…` at expand time. At least one of the two arrays must be non-empty: a pair that supplies neither enable nor disable commands is equivalent to the EEVDF baseline — reference `Scheduler::EEVDF` for that. Note: `cargo ktstr export` currently bails on KernelBuiltin schedulers (`src/export.rs`); declarations using this variant cannot be reproduced via the export-to-shar workflow until that limitation is lifted. |
362/// | `topology = (numa, llcs, cores, threads)` | no | Default VM topology. Default: `(1, 1, 2, 1)` (from `Scheduler::named`). Validated at compile time: each value must be non-zero, and `llcs` must be a multiple of `numa`. |
363/// | `cgroup_parent = "..."` | no | Cgroup parent path (must begin with `/`). |
364/// | `sched_args = [..]` | no | Scheduler CLI args prepended before per-test `extra_sched_args`. |
365/// | `sysctls = [Sysctl::new("k", "v"), ..]` | no | Guest sysctls. |
366/// | `kargs = [..]` | no | Extra guest kernel cmdline args. |
367/// | `kernels = ["6.14", "7.0..=7.2", ..]` | no | Kernel specs the verifier sweeps. Same parser as the `--kernel` CLI flag — accepts exact versions, ranges (`..` or `..=`, both inclusive), git refs (`git+URL#tag=NAME`), paths, and cache keys. Each entry is validated at macro-expand time via the same `KernelId::parse` + `validate` the verifier uses at runtime; empty entries, inverted ranges, and `..`-containing strings whose endpoints aren't version-shaped (e.g. `"abc..def"`) are rejected. |
368/// | `verifier_exclude_topologies = ["preset", ..]` | no | Exact gauntlet preset names omitted only from this scheduler's verifier matrix. Use for named topology exceptions that cannot be expressed without over-broad min/max constraints. Ordinary tests and gauntlet variants are unchanged. Empty means no exclusions; empty, duplicate, and `/`-containing entries are rejected at macro-expand time. |
369/// | `constraints = TopologyConstraints { .. }` | no | Gauntlet preset constraints — maps directly onto `Scheduler::constraints`. Filters which gauntlet topology presets exercise this scheduler. When given as a struct literal, the macro additionally cross-checks each literal field against the effective topology (explicit `topology` field if present, otherwise the `(1, 1, 2, 1)` default from `Scheduler::named`) and rejects infeasible pairings; non-struct-literal forms (e.g. `OTHER::CONST_CONSTRAINTS`) skip that check. |
370/// | `assert = Assert::NO_OVERRIDES.method().chain()` | no | Scheduler-wide assertion overrides — maps directly onto `Scheduler::assert`. Merged with `Assert::default_checks()` and the per-test `assert` at runtime (`default ← scheduler ← per-test`). Accepts any const-evaluable expression: a const path like `Assert::NO_OVERRIDES`, a const-fn call like `Assert::default_checks()`, or a chain of const-fn setters like `Assert::NO_OVERRIDES.check_not_stuck().max_gap_ms(50)`. The macro accepts MethodCall chains and Path-rooted (type/module-prefixed) Calls — only bare single-segment lowercase Calls like `helper()` are rejected as non-const free-fn patterns; non-const methods on a Path receiver slip through and surface as a deep const-eval failure at the spread site. |
371/// | `config_file = "..."` | no | Host-side config file path. |
372/// | `config_file_def = ("--config {file}", "/include-files/cfg.json")` | no | Inline-config plumbing — maps directly onto `Scheduler::config_file_def`. 2-tuple of string literals: arg_template (CLI arg with `{file}` placeholder substituted at run time) and guest_path (absolute path where the framework writes the JSON inside the guest). Distinct from `config_file` (which references a pre-existing host file). The macro validates: tuple-arity = 2, both elements non-empty string literals, `{file}` placeholder present in arg_template, guest_path absolute. |
373///
374/// # Const naming rules
375///
376/// The first argument must be a SCREAMING_SNAKE_CASE identifier and
377/// must NOT be one of the reserved built-in names (`EEVDF`,
378/// `KERNEL_DEFAULT`). The macro emits a `compile_error!` if either rule
379/// is violated.
380#[proc_macro]
381pub fn declare_scheduler(input: TokenStream) -> TokenStream {
382    match scheduler::declare_scheduler_inner(input.into()) {
383        Ok(ts) => ts.into(),
384        Err(e) => e.to_compile_error().into(),
385    }
386}
387
388/// Derive macro that generates a `Payload` const from an annotated
389/// struct for a userspace binary workload (stress-ng, fio, and
390/// similar tools test authors compose under a scheduler).
391///
392/// # Required struct-level attributes (`#[payload(...)]`)
393///
394/// - `binary = "..."` — the binary name resolved by the guest's
395///   include-files infrastructure (required). Becomes
396///   `PayloadKind::Binary(name)` (`ktstr::test_support::PayloadKind::Binary`),
397///   and is also auto-prepended to the emitted `include_files` slice
398///   so the binary is packaged into the initramfs without needing a
399///   separate `#[include_files("...")]` entry. Extra auxiliary files
400///   (helpers, configs, fixtures) still go on `#[include_files(...)]`.
401///
402/// # Optional struct-level attributes
403///
404/// - `name = "..."` — short name used in logs and sidecar records.
405///   Defaults to the binary name.
406/// - `output = Json | ExitCode` — how the framework extracts
407///   metrics from the payload's stdout. The variant names match the
408///   `OutputFormat` enum and the `Polarity` kwarg grammar. Defaults
409///   to `ExitCode`.
410///
411/// # Optional outer attributes
412///
413/// - `#[default_args("--a", "--b", ...)]` — variadic string
414///   literals appended to the binary's argv when the payload runs.
415///   May repeat across multiple `#[default_args(...)]` attrs; entries
416///   accumulate in source order.
417/// - `#[default_check(...)]` — one `MetricCheck` (`ktstr::test_support::MetricCheck`)
418///   construction expression (e.g. `min("iops", 1000.0)`,
419///   `exit_code_eq(0)`). May repeat; entries accumulate in source
420///   order. Both `min(...)` and `MetricCheck::min(...)` are accepted: the
421///   macro prepends `::ktstr::test_support::MetricCheck::` when the
422///   expression doesn't already spell `MetricCheck::` on its callee path,
423///   so bare constructors work without an import and qualified
424///   constructors read naturally in modules that already have
425///   `MetricCheck` in scope.
426/// - `#[metric(name = "...", polarity = ..., unit = "...")]` —
427///   kwarg form. `polarity` is one of `HigherBetter`, `LowerBetter`,
428///   `TargetValue(f64)`, `Unknown`. May repeat; entries accumulate.
429/// - `#[include_files("helper", "config.json", ...)]` — variadic
430///   string literals appended to the emitted `include_files` slice
431///   after the auto-injected binary entry. Each entry passes through
432///   the same resolver used by the CLI `-i` flag (bare names search
433///   host `PATH`; explicit paths must exist; directories are walked).
434///   The primary binary is already packaged automatically, so this
435///   attribute is only needed for auxiliary files the payload
436///   depends on.
437///
438/// # Const name derivation
439///
440/// Strip trailing `"Payload"` suffix (if present), then convert to
441/// `SCREAMING_SNAKE_CASE`. `FioPayload` → `FIO`,
442/// `StressNgPayload` → `STRESS_NG`, `Fio` (no suffix) → `FIO`.
443///
444/// # Example
445///
446/// ```rust,ignore
447/// use ktstr::prelude::*;
448///
449/// #[derive(Payload)]
450/// #[payload(binary = "fio", output = Json)]
451/// #[default_args("--output-format=json", "--minimal")]
452/// #[default_check(exit_code_eq(0))]
453/// #[metric(name = "jobs.0.read.iops", polarity = HigherBetter, unit = "iops")]
454/// struct FioPayload;
455/// ```
456#[proc_macro_derive(
457    Payload,
458    attributes(payload, default_args, default_check, metric, include_files)
459)]
460pub fn derive_payload(input: TokenStream) -> TokenStream {
461    let input = parse_macro_input!(input as DeriveInput);
462    match payload::derive_payload_inner(input) {
463        Ok(ts) => ts.into(),
464        Err(e) => e.to_compile_error().into(),
465    }
466}
467
468/// Generate per-field claim accessors on a stats struct.
469///
470/// See the `claim` module docs for the dispatch rules and label
471/// invariant. Reject non-struct inputs and tuple-struct inputs — the
472/// claim API is keyed on field names, which tuple structs do not have.
473#[proc_macro_derive(Claim, attributes(claim))]
474pub fn derive_claim(input: TokenStream) -> TokenStream {
475    let input = parse_macro_input!(input as DeriveInput);
476    match claim::derive_claim_inner(input) {
477        Ok(ts) => ts.into(),
478        Err(e) => e.to_compile_error().into(),
479    }
480}
481
482/// Convert JSON-like Rust tokens into a `&'static str` at compile time.
483///
484/// Accepts a superset of JSON syntax using Rust token trees:
485/// - Objects: `{ "key": value, ... }`
486/// - Arrays: `[value, ...]`
487/// - Strings: `"hello"`
488/// - Numbers: `42`, `3.14`, `-1`
489/// - Booleans: `true`, `false`
490/// - Null: `null`
491/// - Trailing commas are stripped
492///
493/// ```rust,ignore
494/// const CFG: &str = ktstr::json!({
495///     "layers": [{
496///         "name": "batch",
497///         "kind": { "Grouped": { "cpus_range": [0, 4] } },
498///     }],
499/// });
500/// ```
501#[proc_macro]
502pub fn json(input: TokenStream) -> TokenStream {
503    let mut out = String::new();
504    json::tokens_to_json(&mut out, proc_macro2::TokenStream::from(input));
505    let lit = syn::LitStr::new(&out, proc_macro2::Span::call_site());
506    TokenStream::from(quote! { #lit })
507}
508
509#[cfg(test)]
510mod tests {
511    use super::*;
512    use quote::quote;
513
514    #[test]
515    fn camel_to_screaming_snake_acronym_run() {
516        assert_eq!(
517            payload::camel_to_screaming_snake("HTTPServer"),
518            "HTTP_SERVER"
519        );
520    }
521
522    #[test]
523    fn camel_to_screaming_snake_single_word() {
524        assert_eq!(payload::camel_to_screaming_snake("Llc"), "LLC");
525    }
526
527    #[test]
528    fn camel_to_screaming_snake_all_caps_passthrough() {
529        assert_eq!(payload::camel_to_screaming_snake("LLC"), "LLC");
530    }
531
532    #[test]
533    fn option_tokens_some_int() {
534        let opt: Option<u32> = Some(42);
535        let ts = ktstr_test::option_tokens(&opt);
536        assert_eq!(ts.to_string(), quote! { Some(42u32) }.to_string());
537    }
538
539    #[test]
540    fn option_tokens_none_int() {
541        let opt: Option<u32> = None;
542        let ts = ktstr_test::option_tokens(&opt);
543        assert_eq!(ts.to_string(), quote! { None }.to_string());
544    }
545
546    #[test]
547    fn option_tokens_some_bool() {
548        let opt: Option<bool> = Some(true);
549        let ts = ktstr_test::option_tokens(&opt);
550        assert_eq!(ts.to_string(), quote! { Some(true) }.to_string());
551    }
552
553    /// Pins the two attribute-name registries the unknown-attribute diagnostic
554    /// is derived from: they must be internally duplicate-free, disjoint (a
555    /// name is a bool flag XOR a value attr, never both), and sum to the full
556    /// accepted set. A maintainer adding an attribute to the wrong slice — or
557    /// to both — silently shifts the user-facing "expected:" list; this catches
558    /// it. (The complementary direction — a name in a slice with no handling
559    /// match arm — is guarded at parse time by the unknown-attribute catch-all
560    /// `assert!`.)
561    #[test]
562    fn attr_name_registries_disjoint_and_complete() {
563        use std::collections::HashSet;
564        let bool_names = ktstr_test::BOOL_ATTR_NAMES;
565        let value_names = ktstr_test::VALUE_ATTR_NAMES;
566        let bool_set: HashSet<&str> = bool_names.iter().copied().collect();
567        let value_set: HashSet<&str> = value_names.iter().copied().collect();
568        // No duplicates within either slice.
569        assert_eq!(
570            bool_set.len(),
571            bool_names.len(),
572            "BOOL_ATTR_NAMES has duplicate entries",
573        );
574        assert_eq!(
575            value_set.len(),
576            value_names.len(),
577            "VALUE_ATTR_NAMES has duplicate entries",
578        );
579        // Disjoint: an attribute is a bool flag XOR a value attr.
580        let overlap: Vec<&str> = bool_set.intersection(&value_set).copied().collect();
581        assert!(
582            overlap.is_empty(),
583            "BOOL_ATTR_NAMES and VALUE_ATTR_NAMES overlap: {overlap:?}",
584        );
585        // Cardinality pin: 16 bool + 50 value = 66 accepted attributes.
586        assert_eq!(bool_names.len(), 16, "bool attribute count changed");
587        assert_eq!(value_names.len(), 50, "value attribute count changed");
588    }
589
590    /// Contract pin: `ktstr_test::AttrValues::default()` is the single source of
591    /// truth for every `#[ktstr_test]` macro default since step 2/4 of
592    /// the parse-loop refactor. Without a field-by-field positive
593    /// assertion a maintainer editing the [`Default`] impl can shift
594    /// any user-visible default (auto_repro, kaslr, memory_mib, the
595    /// gauntlet caps, etc.) with zero test feedback. Same precedent
596    /// as `resolve_host_cgroup_parent_env_unset_returns_default` in
597    /// src/test_support/dispatch_tests.rs pinning a runtime const
598    /// against production source.
599    #[test]
600    fn attr_values_default_matches_documented_macro_defaults() {
601        let d = ktstr_test::AttrValues::default();
602
603        // -- Topology --
604        assert_eq!(d.llcs, ktstr_test::DEFAULT_LLCS);
605        assert_eq!(d.cores, ktstr_test::DEFAULT_CORES);
606        assert_eq!(d.threads, ktstr_test::DEFAULT_THREADS);
607        assert_eq!(d.numa_nodes, 1);
608        assert!(!d.llcs_set);
609        assert!(!d.cores_set);
610        assert!(!d.threads_set);
611        assert!(!d.numa_nodes_set);
612
613        // -- Memory + duration --
614        assert_eq!(d.memory_mib, ktstr_test::DEFAULT_MEMORY_MIB);
615        assert!(!d.memory_mib_set);
616        assert_eq!(d.duration_s, 2);
617        assert!(!d.duration_s_set);
618        assert_eq!(d.cleanup_budget_ms, None);
619        assert_eq!(d.watchdog_timeout_s, 4);
620        assert!(!d.watchdog_timeout_s_set);
621
622        // -- Scheduler refs --
623        assert!(d.scheduler.is_none());
624        assert!(d.payload.is_none());
625        assert!(d.workloads.is_none());
626        assert!(d.staged_schedulers.is_none());
627        assert!(d.bpf_map_write.is_none());
628        assert!(d.post_vm.is_none());
629        assert!(d.post_vm_unconditional.is_none());
630        assert!(d.disk.is_none());
631        assert!(d.networks.is_none());
632
633        // -- Assert overrides --
634        assert_eq!(d.not_stuck, None);
635        assert_eq!(d.isolation, None);
636        assert_eq!(d.max_gap_ms, None);
637        assert_eq!(d.max_spread_pct, None);
638        assert_eq!(d.max_imbalance_ratio, None);
639        assert_eq!(d.max_local_dsq_depth, None);
640        assert_eq!(d.fail_on_rq_clock_stuck, None);
641        assert_eq!(d.sustained_samples, None);
642        assert_eq!(d.max_throughput_cv, None);
643        assert_eq!(d.min_work_rate, None);
644        assert_eq!(d.max_fallback_rate, None);
645        assert_eq!(d.max_keep_last_rate, None);
646        assert_eq!(d.max_p99_wake_latency_ns, None);
647        assert_eq!(d.max_wake_latency_cv, None);
648        assert_eq!(d.min_iteration_rate, None);
649        assert_eq!(d.max_migration_ratio, None);
650        assert_eq!(d.min_page_locality, None);
651        assert_eq!(d.max_cross_node_migration_ratio, None);
652        assert_eq!(d.max_slow_tier_ratio, None);
653
654        // -- TopologyConstraints --
655        assert_eq!(d.min_numa_nodes, 1);
656        assert!(!d.min_numa_nodes_set);
657        assert_eq!(d.min_llcs, 1);
658        assert!(!d.min_llcs_set);
659        assert!(!d.requires_smt);
660        assert!(!d.requires_smt_set);
661        assert_eq!(d.min_cpus, 1);
662        assert!(!d.min_cpus_set);
663        assert_eq!(d.max_llcs, Some(12));
664        assert!(!d.max_llcs_set);
665        assert_eq!(d.max_numa_nodes, Some(1));
666        assert!(!d.max_numa_nodes_set);
667        assert_eq!(d.max_cpus, Some(192));
668        assert!(!d.max_cpus_set);
669        assert_eq!(d.cpu_budget, None);
670
671        // -- Bool attrs (auto_repro + kaslr default TRUE; others false) --
672        assert!(d.auto_repro);
673        assert!(!d.auto_repro_set);
674        assert!(!d.expect_auto_repro);
675        assert!(!d.expect_auto_repro_set);
676        assert!(!d.performance_mode);
677        assert!(!d.performance_mode_set);
678        assert!(!d.no_perf_mode);
679        assert!(!d.no_perf_mode_set);
680        assert!(!d.expect_err);
681        assert!(!d.expect_err_set);
682        assert!(!d.allow_inconclusive);
683        assert!(!d.allow_inconclusive_set);
684        assert!(!d.host_only);
685        assert!(!d.host_only_set);
686        assert!(!d.ignore_test);
687        assert!(d.kaslr);
688        assert!(!d.kaslr_set);
689        assert!(!d.wprof);
690        assert!(!d.wprof_set);
691        assert_eq!(d.num_snapshots, 0);
692        assert!(!d.num_snapshots_set);
693
694        // -- Strings + tokens --
695        assert!(d.extra_sched_args.is_empty());
696        assert!(d.extra_include_files.is_empty());
697        assert_eq!(d.workload_root_cgroup, None);
698        assert!(d.wprof_args.is_none());
699        assert!(d.expect_scx_bpf_error_contains_tokens.is_none());
700        assert!(d.expect_scx_bpf_error_matches_tokens.is_none());
701        assert!(d.config_expr.is_none());
702        assert!(!d.config_set);
703    }
704
705    // -- expect_auto_repro macro-parse positive tests --
706    //
707    // Synthesize each attribute spelling, invoke ktstr_test_impl
708    // directly (bypassing proc_macro::TokenStream which panics outside
709    // a procedural-macro invocation), parse the output back into a
710    // syn AST, locate the `static __KTSTR_ENTRY_*: KtstrTestEntry =
711    // KtstrTestEntry { ... };` registration emitted by the macro, and
712    // assert the `expect_auto_repro` field is either:
713    //   - absent (omitted spelling — DEFAULT spread carries false), or
714    //   - present with a `Lit::Bool { value: true/false }` value.
715    //
716    // The AST round-trip (rather than substring matching on the
717    // output's `.to_string()`) guards against two failure modes:
718    //   1. proc_macro2 version drift in colon/whitespace formatting —
719    //      a future proc_macro2 release that emits `field: true` (no
720    //      space) vs `field : true` (current) would silently flip a
721    //      substring-matching test from PASS to FAIL or vice versa.
722    //   2. structural defects that a substring check cannot detect —
723    //      wrong outer struct name, wrong field value type (e.g. a
724    //      String literal where a bool is expected), or a phantom
725    //      sub-literal elsewhere in the output that happens to
726    //      contain the same substring.
727    //
728    // For spellings that set expect_auto_repro = true, the cross-
729    // attribute validation pass (added at the same time as the field)
730    // requires a scheduler attribute + wprof attribute to be present.
731    // The fixture inputs satisfy those preconditions so the parser
732    // reaches codegen without rejection.
733
734    /// Type-erased extraction from a `syn::Expr` for the
735    /// [`field_value_in_static_entry`] helper. Each impl panics with
736    /// a descriptive error if the expression shape doesn't match the
737    /// expected literal kind — same wrong-type-rejection contract as
738    /// the single-purpose helper this generalization replaces.
739    trait ExtractFromExpr: Sized {
740        fn extract_or_panic(field_name: &str, expr: &syn::Expr) -> Self;
741    }
742
743    impl ExtractFromExpr for bool {
744        fn extract_or_panic(field_name: &str, expr: &syn::Expr) -> Self {
745            match expr {
746                syn::Expr::Lit(syn::ExprLit {
747                    lit: syn::Lit::Bool(b),
748                    ..
749                }) => b.value,
750                other => panic!("{field_name} field value must be a Lit::Bool; got {other:?}"),
751            }
752        }
753    }
754
755    impl ExtractFromExpr for u32 {
756        fn extract_or_panic(field_name: &str, expr: &syn::Expr) -> Self {
757            match expr {
758                syn::Expr::Lit(syn::ExprLit {
759                    lit: syn::Lit::Int(i),
760                    ..
761                }) => i
762                    .base10_parse::<u32>()
763                    .unwrap_or_else(|e| panic!("{field_name} field value parse as u32: {e}")),
764                other => panic!("{field_name} field value must be a Lit::Int (u32); got {other:?}"),
765            }
766        }
767    }
768
769    impl ExtractFromExpr for u64 {
770        fn extract_or_panic(field_name: &str, expr: &syn::Expr) -> Self {
771            match expr {
772                syn::Expr::Lit(syn::ExprLit {
773                    lit: syn::Lit::Int(i),
774                    ..
775                }) => i
776                    .base10_parse::<u64>()
777                    .unwrap_or_else(|e| panic!("{field_name} field value parse as u64: {e}")),
778                other => panic!("{field_name} field value must be a Lit::Int (u64); got {other:?}"),
779            }
780        }
781    }
782
783    impl ExtractFromExpr for String {
784        fn extract_or_panic(field_name: &str, expr: &syn::Expr) -> Self {
785            match expr {
786                syn::Expr::Lit(syn::ExprLit {
787                    lit: syn::Lit::Str(s),
788                    ..
789                }) => s.value(),
790                other => panic!("{field_name} field value must be a Lit::Str; got {other:?}"),
791            }
792        }
793    }
794
795    impl ExtractFromExpr for syn::Path {
796        fn extract_or_panic(field_name: &str, expr: &syn::Expr) -> Self {
797            match expr {
798                syn::Expr::Path(p) => p.path.clone(),
799                other => panic!("{field_name} field value must be an Expr::Path; got {other:?}"),
800            }
801        }
802    }
803
804    /// Locate the `__KTSTR_ENTRY_*` static the macro emits and return
805    /// the value of its `field_name` field if explicitly set, or
806    /// `None` if the field is absent from the struct literal
807    /// (omitted spellings fall through to the
808    /// `..KtstrTestEntry::DEFAULT` spread).
809    ///
810    /// Generalized from the single-field `expect_auto_repro` helper
811    /// to read any field whose value-type implements
812    /// [`ExtractFromExpr`] (bool, u32, u64, String, syn::Path).
813    /// The wrong-value-type rejection moves into the per-type
814    /// `extract_or_panic` impl — a field whose expression doesn't
815    /// match the requested type panics with a message naming both
816    /// the field and the expected type.
817    ///
818    /// Verifies along the way:
819    /// - exactly one `__KTSTR_ENTRY_*` static is emitted (panics on
820    ///   zero or multiple — a future codegen change that emitted
821    ///   two prefixed statics would silently key off the first
822    ///   without the count assertion),
823    /// - its declared type's last path segment is `KtstrTestEntry`,
824    /// - its initializer is a struct literal whose path's last
825    ///   segment is `KtstrTestEntry` (catches a regression that
826    ///   wrapped the literal in a different outer struct),
827    /// - any present `field_name` field's value matches the
828    ///   requested type (panics via [`ExtractFromExpr::extract_or_panic`]
829    ///   otherwise).
830    fn field_value_in_static_entry<T: ExtractFromExpr>(
831        output: &proc_macro2::TokenStream,
832        field_name: &str,
833    ) -> Option<T> {
834        let file: syn::File =
835            syn::parse2(output.clone()).expect("macro output must parse as a syn::File");
836        let static_candidates: Vec<&syn::ItemStatic> = file
837            .items
838            .iter()
839            .filter_map(|item| match item {
840                syn::Item::Static(s) if s.ident.to_string().starts_with("__KTSTR_ENTRY_") => {
841                    Some(s)
842                }
843                _ => None,
844            })
845            .collect();
846        assert_eq!(
847            static_candidates.len(),
848            1,
849            "macro must emit exactly one __KTSTR_ENTRY_* static; found {}",
850            static_candidates.len()
851        );
852        let static_item = static_candidates[0];
853        let static_type_last = match static_item.ty.as_ref() {
854            syn::Type::Path(tp) => tp.path.segments.last().map(|s| s.ident.to_string()),
855            _ => None,
856        };
857        assert_eq!(
858            static_type_last.as_deref(),
859            Some("KtstrTestEntry"),
860            "static type's last path segment must be KtstrTestEntry"
861        );
862        let expr_struct = match static_item.expr.as_ref() {
863            syn::Expr::Struct(s) => s,
864            other => panic!("static initializer must be a struct literal; got {other:?}"),
865        };
866        let struct_last = expr_struct
867            .path
868            .segments
869            .last()
870            .map(|s| s.ident.to_string());
871        assert_eq!(
872            struct_last.as_deref(),
873            Some("KtstrTestEntry"),
874            "struct-literal path's last segment must be KtstrTestEntry"
875        );
876        for field in &expr_struct.fields {
877            let ident_matches = matches!(
878                &field.member,
879                syn::Member::Named(ident) if ident == field_name
880            );
881            if !ident_matches {
882                continue;
883            }
884            return Some(T::extract_or_panic(field_name, &field.expr));
885        }
886        None
887    }
888
889    /// `#[ktstr_test(expect_auto_repro)]` (bare form) emits
890    /// `expect_auto_repro: true` as a field on the
891    /// `KtstrTestEntry` struct literal. Pins the bare-flag arm of
892    /// the macro's bool-slot parser. Gated on the `wprof` feature: the
893    /// attr pairs `wprof` with `expect_auto_repro` (the latter requires the
894    /// former), and the macro only accepts `wprof` when the feature is on —
895    /// so this case can only parse successfully under `--features wprof`.
896    #[cfg(feature = "wprof")]
897    #[test]
898    fn macro_parses_expect_auto_repro_bare_to_true() {
899        let attr = quote! { scheduler = SCHED, wprof, expect_auto_repro };
900        let item = quote! {
901            fn t(_: &ktstr::scenario::Ctx) -> anyhow::Result<ktstr::assert::AssertResult> {
902                Ok(ktstr::assert::AssertResult::pass())
903            }
904        };
905        let out = ktstr_test::ktstr_test_impl(attr, item)
906            .expect("bare attribute must parse successfully");
907        assert_eq!(
908            field_value_in_static_entry::<bool>(&out, "expect_auto_repro"),
909            Some(true),
910            "bare `expect_auto_repro` must emit a `expect_auto_repro: true` field"
911        );
912    }
913
914    /// `#[ktstr_test(expect_auto_repro = true)]` emits
915    /// `expect_auto_repro: true`. Pins the explicit-true arm. Gated on the
916    /// `wprof` feature (the attr requires `wprof`, accepted only with the
917    /// feature on).
918    #[cfg(feature = "wprof")]
919    #[test]
920    fn macro_parses_expect_auto_repro_explicit_true() {
921        let attr = quote! { scheduler = SCHED, wprof, expect_auto_repro = true };
922        let item = quote! {
923            fn t(_: &ktstr::scenario::Ctx) -> anyhow::Result<ktstr::assert::AssertResult> {
924                Ok(ktstr::assert::AssertResult::pass())
925            }
926        };
927        let out = ktstr_test::ktstr_test_impl(attr, item)
928            .expect("explicit-true attribute must parse successfully");
929        assert_eq!(
930            field_value_in_static_entry::<bool>(&out, "expect_auto_repro"),
931            Some(true),
932            "explicit `expect_auto_repro = true` must emit a `expect_auto_repro: true` field"
933        );
934    }
935
936    /// `#[ktstr_test(expect_auto_repro = false)]` emits
937    /// `expect_auto_repro: false`. Pins the explicit-false arm
938    /// against a regression that conflated explicit-false with
939    /// omission (which would silently leave DEFAULT untouched and
940    /// lose the user's negative declaration). No cross-attribute
941    /// gates apply when expect_auto_repro is false — the only
942    /// rejection arms trigger on the true value.
943    #[test]
944    fn macro_parses_expect_auto_repro_explicit_false() {
945        let attr = quote! { expect_auto_repro = false };
946        let item = quote! {
947            fn t(_: &ktstr::scenario::Ctx) -> anyhow::Result<ktstr::assert::AssertResult> {
948                Ok(ktstr::assert::AssertResult::pass())
949            }
950        };
951        let out = ktstr_test::ktstr_test_impl(attr, item)
952            .expect("explicit-false attribute must parse successfully");
953        assert_eq!(
954            field_value_in_static_entry::<bool>(&out, "expect_auto_repro"),
955            Some(false),
956            "explicit `expect_auto_repro = false` must emit a `expect_auto_repro: false` field"
957        );
958    }
959
960    /// Omitting the attribute entirely emits NO
961    /// `expect_auto_repro` field — the generated struct literal
962    /// uses the `..KtstrTestEntry::DEFAULT` spread to inherit the
963    /// false default. Pins backward-compat: an existing
964    /// `#[ktstr_test(...)]` with no expect_auto_repro must not
965    /// gain a phantom field that flips the entry's behavior.
966    #[test]
967    fn macro_parses_omitted_expect_auto_repro_leaves_field_unemitted() {
968        let attr = quote! {};
969        let item = quote! {
970            fn t(_: &ktstr::scenario::Ctx) -> anyhow::Result<ktstr::assert::AssertResult> {
971                Ok(ktstr::assert::AssertResult::pass())
972            }
973        };
974        let out = ktstr_test::ktstr_test_impl(attr, item)
975            .expect("attribute-less invocation must parse successfully");
976        assert_eq!(
977            field_value_in_static_entry::<bool>(&out, "expect_auto_repro"),
978            None,
979            "omitted attribute must NOT emit any `expect_auto_repro` field — DEFAULT spread carries the false"
980        );
981    }
982
983    /// `#[ktstr_test(scheduler = SCHED, survives_storm)]` emits
984    /// `survives_storm: true`. Pins BOOL_ATTR_NAMES + assign_bool + codegen.
985    /// A scheduler token is present so the mutex does not reject.
986    #[test]
987    fn macro_parses_survives_storm_bare_to_true() {
988        let attr = quote! { scheduler = SCHED, survives_storm };
989        let item = quote! {
990            fn t(_: &ktstr::scenario::Ctx) -> anyhow::Result<ktstr::assert::AssertResult> {
991                Ok(ktstr::assert::AssertResult::pass())
992            }
993        };
994        let out = ktstr_test::ktstr_test_impl(attr, item)
995            .expect("bare survives_storm with a scheduler must parse");
996        assert_eq!(
997            field_value_in_static_entry::<bool>(&out, "survives_storm"),
998            Some(true),
999            "bare `survives_storm` must emit `survives_storm: true`"
1000        );
1001    }
1002
1003    /// `#[ktstr_test(survives_storm = false)]` emits `survives_storm: false`
1004    /// and needs no scheduler (the mutex only fires on the true value).
1005    #[test]
1006    fn macro_parses_survives_storm_explicit_false() {
1007        let attr = quote! { survives_storm = false };
1008        let item = quote! {
1009            fn t(_: &ktstr::scenario::Ctx) -> anyhow::Result<ktstr::assert::AssertResult> {
1010                Ok(ktstr::assert::AssertResult::pass())
1011            }
1012        };
1013        let out = ktstr_test::ktstr_test_impl(attr, item)
1014            .expect("explicit-false survives_storm must parse");
1015        assert_eq!(
1016            field_value_in_static_entry::<bool>(&out, "survives_storm"),
1017            Some(false),
1018            "explicit `survives_storm = false` must emit `survives_storm: false`"
1019        );
1020    }
1021
1022    /// `survives_storm` + `expect_err` is rejected at macro parse —
1023    /// contradictory polarity. Pins the `validate_survives_storm_mutex`
1024    /// expect_err arm.
1025    #[test]
1026    fn macro_rejects_survives_storm_with_expect_err() {
1027        let attr = quote! { scheduler = SCHED, survives_storm, expect_err = true };
1028        let item = quote! {
1029            fn t(_: &ktstr::scenario::Ctx) -> anyhow::Result<ktstr::assert::AssertResult> {
1030                Ok(ktstr::assert::AssertResult::pass())
1031            }
1032        };
1033        let err = ktstr_test::ktstr_test_impl(attr, item).unwrap_err();
1034        assert!(
1035            err.to_string().contains("survives_storm") && err.to_string().contains("expect_err"),
1036            "diagnostic must name both survives_storm and expect_err: {err}"
1037        );
1038    }
1039
1040    /// `survives_storm` without a scheduler is rejected at macro parse —
1041    /// the kernel default has no scx scheduler to die or be ejected.
1042    #[test]
1043    fn macro_rejects_survives_storm_without_scheduler() {
1044        let attr = quote! { survives_storm };
1045        let item = quote! {
1046            fn t(_: &ktstr::scenario::Ctx) -> anyhow::Result<ktstr::assert::AssertResult> {
1047                Ok(ktstr::assert::AssertResult::pass())
1048            }
1049        };
1050        let err = ktstr_test::ktstr_test_impl(attr, item).unwrap_err();
1051        assert!(
1052            err.to_string().contains("survives_storm") && err.to_string().contains("scheduler"),
1053            "diagnostic must name survives_storm and the missing scheduler: {err}"
1054        );
1055    }
1056
1057    /// `survives_storm` + `expect_auto_repro` is rejected at macro parse —
1058    /// both are inversion intents (survives_storm forces a death fail to
1059    /// EXIT_FAIL; expect_auto_repro inverts a crash-with-repro fail to
1060    /// PASS). Feature-agnostic: `validate_cross_attr` runs the
1061    /// survives_storm mutex (which fires on the `expect_auto_repro` arm)
1062    /// BEFORE the `#[cfg(not(feature = "wprof"))]` wprof-required rejection,
1063    /// so the diagnostic names both regardless of the `wprof` feature —
1064    /// unlike the positive parse tests, which need `--features wprof` to
1065    /// reach codegen successfully. The runtime twin is
1066    /// `validate_rejects_survives_storm_with_expect_auto_repro`.
1067    #[test]
1068    fn macro_rejects_survives_storm_with_expect_auto_repro() {
1069        let attr = quote! { scheduler = SCHED, wprof, survives_storm, expect_auto_repro };
1070        let item = quote! {
1071            fn t(_: &ktstr::scenario::Ctx) -> anyhow::Result<ktstr::assert::AssertResult> {
1072                Ok(ktstr::assert::AssertResult::pass())
1073            }
1074        };
1075        let err = ktstr_test::ktstr_test_impl(attr, item).unwrap_err();
1076        assert!(
1077            err.to_string().contains("survives_storm")
1078                && err.to_string().contains("expect_auto_repro"),
1079            "diagnostic must name both survives_storm and expect_auto_repro: {err}"
1080        );
1081    }
1082
1083    // -- check_visible_lit (commit f4018278) --------------------------
1084
1085    #[test]
1086    fn check_visible_lit_visible_string_passes() {
1087        let expr: syn::Expr = syn::parse_quote!("hello");
1088        scheduler::check_visible_lit("hello", &expr, "name")
1089            .expect("non-empty visible string must pass");
1090    }
1091
1092    #[test]
1093    fn check_visible_lit_empty_string_rejected() {
1094        let expr: syn::Expr = syn::parse_quote!("");
1095        let err = scheduler::check_visible_lit("", &expr, "name").unwrap_err();
1096        assert!(
1097            err.to_string()
1098                .contains("`name` must contain at least one visible character"),
1099            "expected `name` visible-empty diagnostic, got: {err}"
1100        );
1101    }
1102
1103    #[test]
1104    fn check_visible_lit_whitespace_only_rejected() {
1105        let expr: syn::Expr = syn::parse_quote!("   ");
1106        let err = scheduler::check_visible_lit("   ", &expr, "binary").unwrap_err();
1107        assert!(
1108            err.to_string()
1109                .contains("`binary` must contain at least one visible character"),
1110            "expected `binary` visible-empty diagnostic, got: {err}"
1111        );
1112    }
1113
1114    #[test]
1115    fn check_visible_lit_invisible_only_rejected() {
1116        let expr: syn::Expr = syn::parse_quote!("zwsp");
1117        let err = scheduler::check_visible_lit("\u{200B}", &expr, "binary_path").unwrap_err();
1118        assert!(
1119            err.to_string()
1120                .contains("`binary_path` must contain at least one visible character"),
1121            "expected `binary_path` visible-empty diagnostic, got: {err}"
1122        );
1123    }
1124
1125    // -- validate_kernel_builtin_pair (commit 753ecf9e) ---------------
1126
1127    #[test]
1128    fn validate_kernel_builtin_pair_both_set_passes() {
1129        let span = proc_macro2::Span::call_site();
1130        scheduler::validate_kernel_builtin_pair(Some(span), Some(span))
1131            .expect("both set is valid (KernelBuiltin)");
1132    }
1133
1134    #[test]
1135    fn validate_kernel_builtin_pair_neither_set_passes() {
1136        scheduler::validate_kernel_builtin_pair(None, None)
1137            .expect("neither set is valid (not KernelBuiltin)");
1138    }
1139
1140    #[test]
1141    fn validate_kernel_builtin_pair_enable_only_rejected() {
1142        let span = proc_macro2::Span::call_site();
1143        let err = scheduler::validate_kernel_builtin_pair(Some(span), None).unwrap_err();
1144        assert!(
1145            err.to_string()
1146                .contains("`kernel_builtin_enable` set without `kernel_builtin_disable`"),
1147            "expected enable-without-disable diagnostic, got: {err}"
1148        );
1149    }
1150
1151    #[test]
1152    fn validate_kernel_builtin_pair_disable_only_rejected() {
1153        let span = proc_macro2::Span::call_site();
1154        let err = scheduler::validate_kernel_builtin_pair(None, Some(span)).unwrap_err();
1155        assert!(
1156            err.to_string()
1157                .contains("`kernel_builtin_disable` set without `kernel_builtin_enable`"),
1158            "expected disable-without-enable diagnostic, got: {err}"
1159        );
1160    }
1161
1162    // -- validate_exactly_one_source (commit 7c796939) ----------------
1163
1164    #[test]
1165    fn validate_exactly_one_source_none_rejected() {
1166        let span = proc_macro2::Span::call_site();
1167        let err = scheduler::validate_exactly_one_source(false, false, false, span).unwrap_err();
1168        assert!(
1169            err.to_string().contains("no scheduler source declared"),
1170            "expected no-source diagnostic, got: {err}"
1171        );
1172    }
1173
1174    #[test]
1175    fn validate_exactly_one_source_only_binary_passes() {
1176        let span = proc_macro2::Span::call_site();
1177        scheduler::validate_exactly_one_source(true, false, false, span)
1178            .expect("binary-only is valid");
1179    }
1180
1181    #[test]
1182    fn validate_exactly_one_source_only_binary_path_passes() {
1183        let span = proc_macro2::Span::call_site();
1184        scheduler::validate_exactly_one_source(false, true, false, span)
1185            .expect("binary_path-only is valid");
1186    }
1187
1188    #[test]
1189    fn validate_exactly_one_source_only_kernel_builtin_passes() {
1190        let span = proc_macro2::Span::call_site();
1191        scheduler::validate_exactly_one_source(false, false, true, span)
1192            .expect("kernel_builtin-only is valid");
1193    }
1194
1195    #[test]
1196    fn validate_exactly_one_source_binary_and_path_rejected() {
1197        let span = proc_macro2::Span::call_site();
1198        let err = scheduler::validate_exactly_one_source(true, true, false, span).unwrap_err();
1199        assert!(
1200            err.to_string()
1201                .contains("more than one scheduler source declared"),
1202            "expected multi-source diagnostic, got: {err}"
1203        );
1204    }
1205
1206    #[test]
1207    fn validate_exactly_one_source_all_three_rejected() {
1208        let span = proc_macro2::Span::call_site();
1209        let err = scheduler::validate_exactly_one_source(true, true, true, span).unwrap_err();
1210        assert!(
1211            err.to_string()
1212                .contains("more than one scheduler source declared"),
1213            "expected multi-source diagnostic, got: {err}"
1214        );
1215    }
1216
1217    // -- validate_kernel_name_collision (commit 7480df1c) -------------
1218
1219    #[test]
1220    fn validate_kernel_name_collision_non_kernel_passes() {
1221        let expr: syn::Expr = syn::parse_quote!("scx_mitosis");
1222        scheduler::validate_kernel_name_collision(true, "scx_mitosis", Some(&expr))
1223            .expect("non-`kernel` name is valid");
1224    }
1225
1226    #[test]
1227    fn validate_kernel_name_collision_not_kernel_builtin_passes() {
1228        let expr: syn::Expr = syn::parse_quote!("kernel");
1229        scheduler::validate_kernel_name_collision(false, "kernel", Some(&expr))
1230            .expect("`kernel` name is valid when not KernelBuiltin variant");
1231    }
1232
1233    #[test]
1234    fn validate_kernel_name_collision_exact_kernel_rejected() {
1235        let expr: syn::Expr = syn::parse_quote!("kernel");
1236        let err =
1237            scheduler::validate_kernel_name_collision(true, "kernel", Some(&expr)).unwrap_err();
1238        assert!(
1239            err.to_string()
1240                .contains("collides with the KernelBuiltin variant's display_name"),
1241            "expected collision diagnostic, got: {err}"
1242        );
1243    }
1244
1245    #[test]
1246    fn validate_kernel_name_collision_case_insensitive_rejected() {
1247        let expr: syn::Expr = syn::parse_quote!("Kernel");
1248        let err =
1249            scheduler::validate_kernel_name_collision(true, "Kernel", Some(&expr)).unwrap_err();
1250        assert!(
1251            err.to_string()
1252                .contains("collides with the KernelBuiltin variant's display_name"),
1253            "expected case-insensitive collision diagnostic, got: {err}"
1254        );
1255    }
1256
1257    #[test]
1258    fn validate_kernel_name_collision_whitespace_padded_rejected() {
1259        let expr: syn::Expr = syn::parse_quote!("  Kernel  ");
1260        let err =
1261            scheduler::validate_kernel_name_collision(true, "  Kernel  ", Some(&expr)).unwrap_err();
1262        assert!(
1263            err.to_string()
1264                .contains("collides with the KernelBuiltin variant's display_name"),
1265            "expected whitespace-insensitive collision diagnostic, got: {err}"
1266        );
1267    }
1268
1269    // -- validate_payload_workloads_dedup (commit 26352fd7) -----------
1270
1271    #[test]
1272    fn validate_payload_workloads_dedup_empty_workloads_passes() {
1273        let payload: Option<syn::Path> = Some(syn::parse_quote!(FIO));
1274        ktstr_test::validate_payload_workloads_dedup(&payload, &[])
1275            .expect("empty workloads is valid");
1276    }
1277
1278    #[test]
1279    fn validate_payload_workloads_dedup_disjoint_passes() {
1280        let payload: Option<syn::Path> = Some(syn::parse_quote!(FIO));
1281        let workloads: Vec<syn::Path> =
1282            vec![syn::parse_quote!(STRESS_NG), syn::parse_quote!(NETPERF)];
1283        ktstr_test::validate_payload_workloads_dedup(&payload, &workloads)
1284            .expect("disjoint workloads is valid");
1285    }
1286
1287    #[test]
1288    fn validate_payload_workloads_dedup_primary_in_workloads_rejected() {
1289        let payload: Option<syn::Path> = Some(syn::parse_quote!(FIO));
1290        let workloads: Vec<syn::Path> = vec![syn::parse_quote!(STRESS_NG), syn::parse_quote!(FIO)];
1291        let err = ktstr_test::validate_payload_workloads_dedup(&payload, &workloads).unwrap_err();
1292        assert!(
1293            err.to_string().contains("appears in both"),
1294            "expected payload-in-workloads diagnostic, got: {err}"
1295        );
1296    }
1297
1298    #[test]
1299    fn validate_payload_workloads_dedup_pairwise_duplicate_rejected() {
1300        let payload: Option<syn::Path> = None;
1301        let workloads: Vec<syn::Path> = vec![syn::parse_quote!(FIO), syn::parse_quote!(FIO)];
1302        let err = ktstr_test::validate_payload_workloads_dedup(&payload, &workloads).unwrap_err();
1303        assert!(
1304            err.to_string().contains("appears twice"),
1305            "expected pairwise-dupe diagnostic, got: {err}"
1306        );
1307    }
1308
1309    #[test]
1310    fn declare_scheduler_rejects_duplicate_verifier_topology_exclusions() {
1311        let err = scheduler::declare_scheduler_inner(quote! {
1312            TEST_SCHED, {
1313                name = "test_sched",
1314                binary = "scx_test",
1315                verifier_exclude_topologies = ["4cpu-1llc-nosmt", "4cpu-1llc-nosmt"],
1316            }
1317        })
1318        .unwrap_err();
1319        assert!(
1320            err.to_string()
1321                .contains("duplicate `verifier_exclude_topologies` entry `4cpu-1llc-nosmt`"),
1322            "unexpected diagnostic: {err}",
1323        );
1324    }
1325
1326    #[test]
1327    fn declare_scheduler_rejects_slash_in_verifier_topology_exclusion() {
1328        let err = scheduler::declare_scheduler_inner(quote! {
1329            TEST_SCHED, {
1330                name = "test_sched",
1331                binary = "scx_test",
1332                verifier_exclude_topologies = ["4cpu/1llc-nosmt"],
1333            }
1334        })
1335        .unwrap_err();
1336        assert!(
1337            err.to_string().contains("must not contain `/`"),
1338            "unexpected diagnostic: {err}",
1339        );
1340    }
1341}