ktstr/workload/config/
workload.rs

1//! Top-level workload configuration: the [`WorkloadConfig`] struct,
2//! its `Default`, and the chainable builder methods on
3//! `impl WorkloadConfig`.
4//!
5//! WorkloadConfig is the primary group's shape — what each worker
6//! does (`work_type`), how many (`num_workers`), what scheduler
7//! policy / memory policy / nice / clone mode they get, and an
8//! optional `composed` list of secondary [`WorkSpec`] groups that
9//! spawn alongside.
10//!
11//! Validation lives on [`WorkloadConfig::validate`]: it gates
12//! invariants that must hold BEFORE any worker context exists —
13//! currently `num_workers > 0` (primary + every composed entry;
14//! rejects vacuously-passing zero-worker workloads where every
15//! assertion would trivially pass) and `mem_policy` empty-nodemask
16//! rejection (primary + every composed entry).
17
18use std::borrow::Cow;
19
20use super::super::{AffinityIntent, WorkType};
21use super::{CloneMode, MemPolicy, MpolFlags, SchedPolicy, WorkSpec};
22
23/// Configuration for spawning a group of worker processes.
24//
25// PartialEq (not Eq): the [`Self::composed`] field is
26// `Vec<WorkSpec>`, and `WorkSpec` is `PartialEq`-only because of
27// its `workers_pct: Option<f64>` field — see the derive comment on
28// [`WorkSpec`] for the IEEE-754 NaN rationale. Production
29// WorkSpec values are NaN-free at construction (the
30// `WorkSpec::workers_pct` builder rejects NaN), so the inherited
31// f64 semantics do not surface at typical call sites.
32#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
33// See [`WorkType`]'s `#[serde(bound(...))]` comment — embedding
34// `WorkType` propagates the same lifetime-bound issue, so we pass
35// through the same explicit empty bound.
36#[serde(bound(deserialize = ""))]
37pub struct WorkloadConfig {
38    /// Number of worker processes to fork. Concrete `usize` (not
39    /// `Option`): `WorkloadConfig` is the spawn-time configuration
40    /// passed to `WorkloadHandle::spawn`, by which point the worker
41    /// count must be known. The Option-to-usize coalescing happens
42    /// upstream at `resolve_num_workers`, which
43    /// reads [`crate::workload::WorkSpec::num_workers`]
44    /// (`Option<usize>` — `None` falls back to
45    /// `Ctx::workers_per_cgroup`) and produces the resolved value
46    /// passed to `Self::for_scenario_engine`. The type asymmetry
47    /// is deliberate: `WorkSpec` is the user-facing declarative
48    /// spec where `None` means "inherit the cgroup-level default",
49    /// `WorkloadConfig` is the spawn-time concrete config where
50    /// `usize` is the only sensible type.
51    pub num_workers: usize,
52    /// Per-worker affinity intent. Resolved at spawn time via the
53    /// same gate as composed entries (see [`Self::composed`]):
54    /// [`AffinityIntent::Inherit`] (resolved to
55    /// `ResolvedAffinity::None`),
56    /// [`AffinityIntent::Exact`] (resolved to
57    /// `ResolvedAffinity::Fixed`), and
58    /// [`AffinityIntent::RandomSubset`] (resolved to
59    /// `ResolvedAffinity::Random` — sampling deferred per-worker
60    /// at spawn time) are accepted at `WorkloadHandle::spawn`.
61    /// Topology-aware variants (`SingleCpu`, `LlcAligned`,
62    /// `CrossCgroup`, `SmtSiblingPair`) require scenario context
63    /// and are rejected with an actionable diagnostic.
64    /// Type-unified with [`WorkSpec::affinity`] so a test author
65    /// writes the same affinity expression at the top level and
66    /// inside `composed` entries.
67    pub affinity: AffinityIntent,
68    /// What each worker does.
69    pub work_type: WorkType,
70    /// Park each worker after it has counted at least `n` outer-loop
71    /// iterations instead of spinning until stop. `None` (the
72    /// default) preserves the run-until-stop behavior every workload
73    /// user relies on; `Some(n)` makes the worker publish its final
74    /// iteration count and then sleep-poll for the stop request,
75    /// collapsing background load once it has proven whatever the
76    /// caller needed the iterations to prove. Used by the verifier
77    /// dispatch probe (`Some(1)`), which only needs each worker to
78    /// take a single dispatch — not to burn a CPU until teardown.
79    /// `#[serde(default)]` so the field round-trips over the
80    /// host→guest wire without breaking configs serialized before it
81    /// existed.
82    #[serde(default)]
83    pub park_after_iterations: Option<u64>,
84    /// Signal a shared eventfd once each fork worker has counted its
85    /// first outer-loop iteration, so a waiter (the verifier dispatch
86    /// probe) can block on the edge instead of polling
87    /// `snapshot_iterations`. `false` (the default) creates no eventfd
88    /// and every worker runs unchanged; `true` makes
89    /// [`WorkloadHandle::spawn`](crate::workload::WorkloadHandle::spawn)
90    /// allocate an `eventfd(EFD_NONBLOCK|EFD_CLOEXEC)` before the fork
91    /// loop and each fork worker `write(2)` a single `1` the first time
92    /// its iteration count reaches 1 — the counter sums the per-worker
93    /// signals so `WorkloadHandle::wait_first_iteration_all` can wake as
94    /// soon as `n` workers have advanced. Independent of
95    /// `park_after_iterations`: the probe sets both, and a worker signals
96    /// once BEFORE parking. Only fork workers signal (thread / pcomm
97    /// dispatch pass a `-1` fd and never write). `#[serde(default)]` so
98    /// the field round-trips over the host→guest wire without breaking
99    /// configs serialized before it existed.
100    #[serde(default)]
101    pub signal_first_iteration: bool,
102    /// Linux scheduling policy.
103    pub sched_policy: SchedPolicy,
104    /// NUMA memory placement policy.
105    pub mem_policy: MemPolicy,
106    /// Optional mode flags for `set_mempolicy(2)`.
107    pub mpol_flags: MpolFlags,
108    /// Per-worker nice value applied via `setpriority(2)` after
109    /// fork, before the work loop. Range `-20..=19` per `MIN_NICE`
110    /// / `MAX_NICE` in `kernel/sys.c`'s `setpriority` syscall;
111    /// values outside this window are clamped kernel-side. `None`
112    /// (the default) skips the syscall entirely so the worker
113    /// inherits the parent's nice value; `Some(n)` invokes
114    /// `setpriority(PRIO_PROCESS, 0, n)` unconditionally — a user
115    /// who wants the worker to land on nice 0 regardless of the
116    /// parent's nice (or a cgroup-level default stored at
117    /// [`CgroupDef::default_nice`](crate::scenario::ops::CgroupDef::default_nice))
118    /// writes `Some(0)`, distinct from `None`.
119    ///
120    /// Values below the calling task's current nice require
121    /// `CAP_SYS_NICE` (the kernel's `can_nice` check fires on
122    /// `niceval < task_nice(p)`, not only on negatives — the
123    /// `set_one_prio` gate at `kernel/sys.c` returns `EACCES` to
124    /// unprivileged callers when `is_nice_reduction` rejects the
125    /// requested value). With `Some(0)` on a parent at `nice=5`,
126    /// `setpriority` returns `EACCES` without the capability.
127    /// `None` (inherit) is always safe. Failures are logged once
128    /// via stderr and do not abort the worker — the
129    /// scheduling-policy and affinity sites use the same idiom.
130    pub nice: Option<i32>,
131    /// How to create each worker. Defaults to [`CloneMode::Fork`].
132    pub clone_mode: CloneMode,
133    /// Worker process name set via `prctl(PR_SET_NAME)` after fork.
134    /// The setter rejects > 15 bytes (TASK_COMM_LEN-1) at
135    /// construction so the operator sees the cap at the call site
136    /// instead of debugging a truncated comm. `None` inherits the
137    /// binary name. Mirrors [`WorkSpec::comm`] so the primary group
138    /// exposes the same scheduler-matcher knob composed entries
139    /// already do.
140    pub comm: Option<Cow<'static, str>>,
141    /// Effective UID set via `setresuid(uid, uid, uid)` after fork.
142    /// `None` inherits the parent's euid. Mirrors [`WorkSpec::uid`].
143    pub uid: Option<u32>,
144    /// Effective GID set via `setresgid(gid, gid, gid)` after fork.
145    /// `None` inherits the parent's egid. Mirrors [`WorkSpec::gid`].
146    pub gid: Option<u32>,
147    /// Restrict worker affinity to the CPUs of this NUMA node.
148    /// Applied via `sched_setaffinity` after fork. Mirrors
149    /// [`WorkSpec::numa_node`].
150    pub numa_node: Option<u32>,
151    /// Secondary worker groups spawned alongside the primary group
152    /// described by the top-level fields. Each entry is a
153    /// [`WorkSpec`] with its own `work_type`, `num_workers`,
154    /// `sched_policy`, `affinity`, etc. Composed groups are spawned
155    /// in declaration order after the primary group; their workers
156    /// run concurrently with the primary's for the lifetime of the
157    /// `WorkloadHandle`. The default (an empty vec) skips the
158    /// composed pass and behaves exactly as the pre-composition
159    /// spawn.
160    ///
161    /// All groups share the same stop signal —
162    /// `WorkloadHandle::stop_and_collect` terminates primary plus
163    /// every composed group atomically. Per-group stop is not
164    /// supported.
165    ///
166    /// Reports carry `WorkerReport::group_idx` = 0 for the primary
167    /// group and 1..=N for composed entries in declaration order.
168    ///
169    /// # Worked example
170    ///
171    /// Build a multi-group workload — primary `SpinWait(2)` plus
172    /// one `PipeIo(2)` composed group plus one `YieldHeavy(1)`
173    /// composed group — using either the replacing
174    /// [`composed`](Self::composed) setter or the appending
175    /// [`push_composed`](Self::push_composed) chain:
176    ///
177    /// ```
178    /// use ktstr::workload::{WorkSpec, WorkType, WorkloadConfig};
179    ///
180    /// // Append style: each call adds one group to the existing list.
181    /// let cfg = WorkloadConfig::default()
182    ///     .work_type(WorkType::SpinWait)
183    ///     .workers(2)
184    ///     .push_composed(
185    ///         WorkSpec::default()
186    ///             .work_type(WorkType::pipe_io(64))
187    ///             .workers(2),
188    ///     )
189    ///     .push_composed(
190    ///         WorkSpec::default()
191    ///             .work_type(WorkType::YieldHeavy)
192    ///             .workers(1),
193    ///     );
194    /// assert_eq!(cfg.composed.len(), 2);
195    ///
196    /// // Replace style: one call passes every composed group at once.
197    /// let cfg2 = WorkloadConfig::default()
198    ///     .work_type(WorkType::SpinWait)
199    ///     .workers(2)
200    ///     .composed([
201    ///         WorkSpec::default().work_type(WorkType::pipe_io(64)).workers(2),
202    ///         WorkSpec::default().work_type(WorkType::YieldHeavy).workers(1),
203    ///     ]);
204    /// assert_eq!(cfg2.composed.len(), 2);
205    /// ```
206    ///
207    /// # Resolution rules at spawn time
208    ///
209    /// Composed [`WorkSpec`] entries must specify
210    /// [`WorkSpec::num_workers`] (`Some(n)`); the `None` default
211    /// resolved by the scenario engine via
212    /// `Ctx::workers_per_cgroup` is unreachable from
213    /// `WorkloadHandle::spawn` and is rejected with an actionable
214    /// diagnostic.
215    ///
216    /// Composed [`WorkSpec::affinity`] accepts the no-context
217    /// variants [`AffinityIntent::Inherit`] (resolved to
218    /// `ResolvedAffinity::None`), [`AffinityIntent::Exact`]
219    /// (resolved to `ResolvedAffinity::Fixed`), and
220    /// [`AffinityIntent::RandomSubset`] (resolved to
221    /// `ResolvedAffinity::Random` — sampling deferred per-worker
222    /// at spawn time). The topology-aware variants (`SingleCpu`,
223    /// `LlcAligned`, `CrossCgroup`, `SmtSiblingPair`) are rejected
224    /// because spawn() has no access to the
225    /// [`crate::topology::TestTopology`] / cpuset state that the
226    /// scenario engine threads in.
227    ///
228    /// Composed entries inherit the parent
229    /// [`WorkloadConfig::clone_mode`] — the dispatch path
230    /// (fork vs thread) is a workload-wide property, so
231    /// [`WorkSpec`] carries no `clone_mode` field of its own.
232    ///
233    /// Composition is single-level — a [`WorkSpec`] inside
234    /// `composed` has no `composed` field of its own.
235    #[serde(default, skip_serializing_if = "Vec::is_empty")]
236    pub composed: Vec<WorkSpec>,
237}
238
239impl Default for WorkloadConfig {
240    fn default() -> Self {
241        Self {
242            num_workers: 1,
243            affinity: AffinityIntent::Inherit,
244            work_type: WorkType::SpinWait,
245            park_after_iterations: None,
246            signal_first_iteration: false,
247            sched_policy: SchedPolicy::Normal,
248            mem_policy: MemPolicy::Default,
249            mpol_flags: MpolFlags::NONE,
250            nice: None,
251            clone_mode: CloneMode::Fork,
252            comm: None,
253            uid: None,
254            gid: None,
255            numa_node: None,
256            composed: Vec::new(),
257        }
258    }
259}
260
261impl WorkloadConfig {
262    /// Construct a `WorkloadConfig` for scenario-engine spawn
263    /// dispatch (apply_setup non-pcomm, Op::Spawn). The signature
264    /// pins `clone_mode =
265    /// CloneMode::Fork` in the constructor body so callers can't
266    /// accidentally route a Thread-mode workload through these
267    /// sites — a Thread-mode spawn would migrate the scenario
268    /// runner's tgid into the test cgroup when move_tasks fires,
269    /// per `kernel/cgroup/cgroup.c::cgroup_procs_write_start`
270    /// (cgroup.procs writes are process-scoped). The
271    /// previously-needed `debug_assert_eq!(wl.clone_mode, Fork)`
272    /// guards collapse into the type system.
273    ///
274    /// `work_type` is taken as an arg (not pulled from `work.work_type`)
275    /// because apply_setup's per-WorkSpec resolution layers a
276    /// `ctx.work_type_override` over the spec-declared type; passing
277    /// the resolved value keeps that call site honest.
278    ///
279    /// `affinity` is taken as an arg (not `work.affinity`) because
280    /// all three call sites pre-resolve the intent via
281    /// `intent_for_spawn` against the cgroup cpuset before
282    /// dispatch.
283    ///
284    /// **Do NOT pass `work.num_workers.unwrap()` / `work.affinity` /
285    /// `work.work_type` directly** — that bypasses the resolution
286    /// layer (workers_pct → ceil(cpuset * pct), cgroup-cpuset-aware
287    /// intent_for_spawn, work_type override) and silently produces
288    /// wrong counts / wrong affinity / wrong type. Always pass the
289    /// resolved values from `resolve_num_workers` /
290    /// `intent_for_spawn` / `resolve_work_type`; the args/fields
291    /// asymmetry is deliberate and the resolution layer is
292    /// load-bearing.
293    ///
294    /// `composed` always empty: the scenario-engine spawn dispatch
295    /// emits one WorkloadConfig per WorkSpec from the resolved
296    /// `non_pcomm_works` list, so composition is upstream. A future
297    /// "composed in single spawn" optimization would need a
298    /// sibling constructor, not a parameterized one.
299    ///
300    /// Bails when `work.pcomm.is_some()`: the scenario-engine spawn
301    /// dispatch (apply_setup non-pcomm path, Op::Spawn) forks one
302    /// process per worker and does not
303    /// route through `spawn_pcomm_cgroup`, so `task->group_leader->comm`
304    /// would be left at the binary name rather than the requested
305    /// pcomm value — workers spawn but scheduler matchers filtering
306    /// on the group_leader comm see zero matches. Mirrors the
307    /// `composed[i].pcomm.is_some()` bail at
308    /// `WorkloadHandle::spawn`. Test authors wanting pcomm route via
309    /// `CgroupDef::pcomm` + apply_setup pcomm-aware fan-out, or call
310    /// `WorkloadHandle::spawn_pcomm_cgroup` directly.
311    pub(crate) fn for_scenario_engine(
312        work: &WorkSpec,
313        num_workers: usize,
314        affinity: AffinityIntent,
315        work_type: WorkType,
316    ) -> anyhow::Result<Self> {
317        if work.pcomm.is_some() {
318            anyhow::bail!(
319                "WorkSpec::pcomm is unsupported in the scenario-engine \
320                 spawn dispatch (apply_setup non-pcomm path, \
321                 Op::Spawn) — those sites fork \
322                 one process per worker rather than threading inside \
323                 a pcomm container, so `task->group_leader->comm` \
324                 would stay at the binary name. To run with a \
325                 specific group-leader comm, declare \
326                 `CgroupDef::pcomm` (apply_setup picks up the pcomm-\
327                 aware coalesce path) or call \
328                 `WorkloadHandle::spawn_pcomm_cgroup` directly.",
329            );
330        }
331        Ok(Self {
332            num_workers,
333            affinity,
334            work_type,
335            park_after_iterations: None,
336            signal_first_iteration: false,
337            sched_policy: work.sched_policy,
338            mem_policy: work.mem_policy.clone(),
339            mpol_flags: work.mpol_flags,
340            nice: work.nice,
341            clone_mode: CloneMode::Fork,
342            comm: work.comm.clone(),
343            uid: work.uid,
344            gid: work.gid,
345            numa_node: work.numa_node,
346            composed: Vec::new(),
347        })
348    }
349
350    /// Validate the config before spawn. Fails loud on invariants
351    /// that the worker-spawn path otherwise handles by silent
352    /// degradation — in particular `mem_policy` variants that
353    /// require a non-empty nodemask (Bind / Interleave / PreferredMany /
354    /// WeightedInterleave with an empty BTreeSet).
355    ///
356    /// # Why a config-layer gate
357    ///
358    /// `apply_mempolicy_with_flags` (called from the worker's hot
359    /// path in BOTH forked-child and thread-mode contexts) currently
360    /// handles an empty node-set by logging to `stderr` and
361    /// returning — the worker silently proceeds with default kernel
362    /// placement instead of the requested NUMA binding. That
363    /// silent-skip is a silent-drop bug (the test reports success
364    /// while the actual workload ran with the wrong placement).
365    ///
366    /// A hypothetical fix-it-in-the-worker design — `libc::_exit(1)`
367    /// on an empty node-set inside the worker — was rejected because
368    /// it is unsound for thread-mode workers: `_exit` invokes
369    /// `exit_group(2)` (verified at kernel/exit.c::do_group_exit →
370    /// `zap_other_threads`) which terminates EVERY thread in the
371    /// caller's tgid. A thread-mode worker shares its tgid with the
372    /// test runner, so an inner `_exit(1)` would kill the runner.
373    /// Rejecting at the config layer keeps the failure visible as a
374    /// returnable `Result` BEFORE any worker context exists,
375    /// regardless of clone-mode dispatch, and avoids the exit_group
376    /// hazard entirely.
377    ///
378    /// # What is validated
379    ///
380    /// Two gates, in order:
381    /// 1. `num_workers > 0` on the primary group and on every
382    ///    composed [`WorkSpec`] entry — zero workers emit no
383    ///    `WorkerReport`s and downstream assertions would vacuously
384    ///    pass. Composed entries also route through
385    ///    `WorkloadHandle::spawn` (via `GroupParams::from_composed`)
386    ///    directly, bypassing the scenario-engine's
387    ///    `resolve_num_workers` resolver, so the gate must live
388    ///    here to catch `composed[i].num_workers=0` before the spawn
389    ///    cascade forks anything.
390    /// 2. `mem_policy` on the primary group and on every composed
391    ///    [`WorkSpec`] entry.
392    ///
393    /// Per-entry errors name the offending slot (`"primary"` or
394    /// `"composed[N] (group_idx M)"`) so the test author can
395    /// locate the misconfigured group. Gate (1) runs first so the
396    /// more-fundamental "no workers" diagnostic surfaces before a
397    /// secondary mem_policy failure (which becomes moot when no
398    /// worker exists to bind).
399    ///
400    /// # Scope
401    ///
402    /// Validates `mem_policy` and `num_workers > 0`. Other field
403    /// invariants are validated at their own use sites:
404    /// `workers_pct` via `WorkSpec::resolve_workers_pct`,
405    /// [`WorkType`] payloads via per-variant constructors and
406    /// `validate_workload_admission`, [`AffinityIntent`] topology
407    /// rules at the scenario-engine `resolve_affinity_for_cgroup`
408    /// resolver. This method is the home for invariants that must
409    /// hold BEFORE any worker context (threads, forks, cgroups)
410    /// exists — `mem_policy` qualifies because of the silent-skip +
411    /// `exit_group` hazard noted above; `num_workers == 0`
412    /// qualifies because every downstream gate becomes
413    /// vacuous-pass. Future fields with the same
414    /// "must-fail-before-spawn" shape belong here too.
415    ///
416    /// # Return type
417    ///
418    /// Returns [`anyhow::Result`] (composite-layer convention used
419    /// by sibling composite validators
420    /// `crate::test_support::entry::KtstrTestEntry::validate` and
421    /// `crate::test_support::entry::TopologyConstraints::validate`
422    /// — they wrap leaf validators that return
423    /// `Result<(), String>` with slot-context). The leaf validator
424    /// [`MemPolicy::validate`] returns `Result<(), String>` to match
425    /// the leaf convention used by every per-spec validator in the
426    /// project.
427    pub fn validate(&self) -> anyhow::Result<()> {
428        // num_workers gate runs FIRST so the operator sees the more-
429        // fundamental "no workers" diagnostic before mem_policy
430        // failures (which become moot when no worker exists to bind).
431        if self.num_workers == 0 {
432            anyhow::bail!(
433                "WorkloadConfig.num_workers=0 is not allowed — \
434                 zero workers emit no WorkerReports and downstream \
435                 assertions would vacuously pass. Use at least 1 \
436                 worker or drop the WorkloadConfig entirely."
437            );
438        }
439        for (idx, spec) in self.composed.iter().enumerate() {
440            // composed entries route through `WorkloadHandle::spawn`
441            // (via `GroupParams::from_composed`) directly, bypassing
442            // the scenario engine's `resolve_num_workers` —
443            // the gate must live here for the spawn entry to catch
444            // composed[i].num_workers=0 before forking.
445            if spec.num_workers == Some(0) {
446                anyhow::bail!(
447                    "WorkloadConfig.composed[{idx}].num_workers=0 \
448                     (group_idx {}): zero workers in a composed group \
449                     emit no WorkerReports for the group; drop the \
450                     entry or use >= 1 worker",
451                    idx + 1,
452                );
453            }
454        }
455        self.mem_policy
456            .validate()
457            .map_err(|e| anyhow::anyhow!("WorkloadConfig.mem_policy (primary group): {e}",))?;
458        for (idx, spec) in self.composed.iter().enumerate() {
459            spec.mem_policy.validate().map_err(|e| {
460                anyhow::anyhow!(
461                    "WorkloadConfig.composed[{idx}].mem_policy (group_idx {}): {e}",
462                    idx + 1,
463                )
464            })?;
465        }
466        Ok(())
467    }
468
469    /// Set the number of worker processes.
470    #[must_use = "builder methods consume self; bind the result"]
471    pub fn workers(mut self, n: usize) -> Self {
472        self.num_workers = n;
473        self
474    }
475
476    /// Set the per-worker affinity intent.
477    ///
478    /// At `WorkloadHandle::spawn`, [`AffinityIntent::Inherit`],
479    /// [`AffinityIntent::Exact`], and [`AffinityIntent::RandomSubset`]
480    /// are accepted; topology-aware variants (`SingleCpu`,
481    /// `LlcAligned`, `CrossCgroup`, `SmtSiblingPair`) require
482    /// scenario context and are rejected.
483    ///
484    /// Idiomatic short form for an exact CPU set:
485    /// `cfg.affinity(AffinityIntent::exact([0, 1]))`.
486    #[must_use = "builder methods consume self; bind the result"]
487    pub fn affinity(mut self, a: AffinityIntent) -> Self {
488        self.affinity = a;
489        self
490    }
491
492    /// Set the work type.
493    #[must_use = "builder methods consume self; bind the result"]
494    pub fn work_type(mut self, wt: WorkType) -> Self {
495        self.work_type = wt;
496        self
497    }
498
499    /// Set the park-after-iterations knob. `Some(n)` parks each
500    /// worker once it has counted `n` outer-loop iterations; `None`
501    /// (the default) runs every worker until stop. Takes an
502    /// `Option<u64>` rather than a bare `u64` so a call site can
503    /// thread a computed opt-in through without an intermediate
504    /// branch. See [`WorkloadConfig::park_after_iterations`].
505    #[must_use = "builder methods consume self; bind the result"]
506    pub fn park_after_iterations(mut self, n: Option<u64>) -> Self {
507        self.park_after_iterations = n;
508        self
509    }
510
511    /// Set the first-iteration eventfd-signal knob. `true` makes each
512    /// fork worker signal a shared eventfd once it counts its first
513    /// outer-loop iteration so a waiter can block on the edge via
514    /// `WorkloadHandle::wait_first_iteration_all`
515    /// instead of polling; `false` (the default) creates no eventfd. See
516    /// [`WorkloadConfig::signal_first_iteration`].
517    #[must_use = "builder methods consume self; bind the result"]
518    pub fn signal_first_iteration(mut self, on: bool) -> Self {
519        self.signal_first_iteration = on;
520        self
521    }
522
523    /// Set the Linux scheduling policy.
524    #[must_use = "builder methods consume self; bind the result"]
525    pub fn sched_policy(mut self, p: SchedPolicy) -> Self {
526        self.sched_policy = p;
527        self
528    }
529
530    /// Set the NUMA memory placement policy.
531    #[must_use = "builder methods consume self; bind the result"]
532    pub fn mem_policy(mut self, p: MemPolicy) -> Self {
533        self.mem_policy = p;
534        self
535    }
536
537    /// Set the NUMA memory policy mode flags.
538    #[must_use = "builder methods consume self; bind the result"]
539    pub fn mpol_flags(mut self, f: MpolFlags) -> Self {
540        self.mpol_flags = f;
541        self
542    }
543
544    /// Set the per-worker nice value applied via `setpriority(2)`.
545    ///
546    /// Stores `Some(n)` on the config; the spawn pipeline calls
547    /// `setpriority(PRIO_PROCESS, 0, n)` unconditionally (including
548    /// `n == 0`). The "skip the syscall, inherit the parent's nice"
549    /// state is the type-level default `None` — set the field via
550    /// `..Default::default()` (or leave the builder unchained) when
551    /// you want inherit semantics. Values below the calling task's
552    /// current nice require `CAP_SYS_NICE`; see
553    /// [`WorkloadConfig::nice`] for the full `can_nice` rule.
554    #[must_use = "builder methods consume self; bind the result"]
555    pub fn nice(mut self, n: i32) -> Self {
556        self.nice = Some(n);
557        self
558    }
559
560    /// Set the clone mode used when spawning each worker.
561    ///
562    /// [`CloneMode::Fork`] (the default) preserves historical
563    /// behavior. See [`CloneMode`] for the full menu and dispatch
564    /// status.
565    #[must_use = "builder methods consume self; bind the result"]
566    pub fn clone_mode(mut self, m: CloneMode) -> Self {
567        self.clone_mode = m;
568        self
569    }
570
571    /// Set the worker process name via `prctl(PR_SET_NAME)`.
572    ///
573    /// # Panics
574    ///
575    /// Panics on programmer-error inputs — mirrors
576    /// [`crate::workload::WorkSpec::pcomm`]'s `# Panics`:
577    /// - Empty string.
578    /// - Interior NUL byte (prctl C-string truncation).
579    /// - More than 15 bytes (`TASK_COMM_LEN - 1` cap).
580    ///
581    /// See
582    /// `validate_task_comm_string`
583    /// for the centralized rationale; `name.len()` is the BYTE
584    /// length (UTF-8 multi-byte chars count as their byte width).
585    #[must_use = "builder methods consume self; bind the result"]
586    pub fn comm(mut self, name: impl Into<Cow<'static, str>>) -> Self {
587        let name: Cow<'static, str> = name.into();
588        crate::workload::validate_task_comm_string("WorkloadConfig::comm", &name);
589        self.comm = Some(name);
590        self
591    }
592
593    /// Set the worker's effective UID via `setresuid`.
594    #[must_use = "builder methods consume self; bind the result"]
595    pub fn uid(mut self, uid: u32) -> Self {
596        self.uid = Some(uid);
597        self
598    }
599
600    /// Set the worker's effective GID via `setresgid`.
601    #[must_use = "builder methods consume self; bind the result"]
602    pub fn gid(mut self, gid: u32) -> Self {
603        self.gid = Some(gid);
604        self
605    }
606
607    /// Restrict worker affinity to a NUMA node's CPU set.
608    #[must_use = "builder methods consume self; bind the result"]
609    pub fn numa_node(mut self, node: u32) -> Self {
610        self.numa_node = Some(node);
611        self
612    }
613
614    /// Replace the composed worker groups (replacing setter).
615    ///
616    /// Pass an iterator of [`WorkSpec`] entries; the existing
617    /// `composed` vec is REPLACED with the supplied entries. Each
618    /// will be spawned as an independent group alongside the
619    /// primary described by the top-level fields. Pass an empty
620    /// iterator to clear any previously-set composed groups.
621    ///
622    /// Use this when you have all groups in hand at once. To add
623    /// one group at a time to an existing list, use the appending
624    /// [`push_composed`](Self::push_composed) instead.
625    ///
626    /// See [`Self::composed`] for the resolution rules applied to
627    /// each entry's `num_workers` / `affinity` fields at spawn time.
628    #[must_use = "builder methods consume self; bind the result"]
629    pub fn composed(mut self, specs: impl IntoIterator<Item = WorkSpec>) -> Self {
630        self.composed = specs.into_iter().collect();
631        self
632    }
633
634    /// Append a single composed worker group to the existing list
635    /// (appending setter).
636    ///
637    /// The supplied [`WorkSpec`] is PUSHED onto the existing
638    /// `composed` vec; previously-set groups are preserved.
639    /// Convenience for chained construction:
640    /// `cfg.push_composed(a).push_composed(b)` produces
641    /// `composed: [a, b]`.
642    ///
643    /// Use this when building the group list incrementally. To
644    /// replace the entire list in one call, use the replacing
645    /// [`composed`](Self::composed) instead.
646    #[must_use = "builder methods consume self; bind the result"]
647    pub fn push_composed(mut self, spec: WorkSpec) -> Self {
648        self.composed.push(spec);
649        self
650    }
651}
652
653#[cfg(test)]
654mod tests {
655    use super::*;
656    use std::collections::BTreeSet;
657
658    #[test]
659    fn validate_rejects_zero_num_workers_on_primary() {
660        let cfg = WorkloadConfig {
661            num_workers: 0,
662            ..Default::default()
663        };
664        let err = cfg.validate().expect_err("num_workers=0 must bail");
665        let msg = format!("{err:#}");
666        assert!(msg.contains("num_workers=0 is not allowed"), "{msg}");
667        assert!(msg.contains("vacuously pass"), "{msg}");
668    }
669
670    #[test]
671    fn validate_rejects_zero_num_workers_on_composed_entry() {
672        let cfg = WorkloadConfig {
673            num_workers: 1,
674            composed: vec![WorkSpec::default().workers(0)],
675            ..Default::default()
676        };
677        let err = cfg
678            .validate()
679            .expect_err("composed[0].num_workers=0 must bail");
680        let msg = format!("{err:#}");
681        assert!(
682            msg.contains("composed[0]"),
683            "must cite the entry idx: {msg}"
684        );
685        assert!(msg.contains("group_idx 1"), "1-indexed group_idx: {msg}");
686    }
687
688    #[test]
689    fn validate_accepts_one_or_more_workers_on_primary_and_composed() {
690        let cfg = WorkloadConfig {
691            num_workers: 1,
692            composed: vec![WorkSpec::default().workers(2)],
693            ..Default::default()
694        };
695        cfg.validate().expect("1+composed(2) must validate ok");
696    }
697
698    #[test]
699    fn validate_rejects_zero_workers_before_mempolicy() {
700        // Zero workers + invalid mem_policy: zero-worker check must
701        // fire first so the operator's primary diagnostic is the
702        // more-fundamental "no workers" rather than the secondary
703        // "bad mempolicy" message.
704        let cfg = WorkloadConfig {
705            num_workers: 0,
706            mem_policy: MemPolicy::Bind(BTreeSet::new()), // invalid
707            ..Default::default()
708        };
709        let err = cfg
710            .validate()
711            .expect_err("zero workers + bad policy must bail on num_workers first");
712        let msg = format!("{err:#}");
713        assert!(
714            msg.contains("num_workers=0"),
715            "zero-workers msg surfaces: {msg}"
716        );
717        assert!(!msg.contains("mem_policy"), "mempolicy msg deferred: {msg}");
718    }
719
720    #[test]
721    #[should_panic(expected = "WorkloadConfig::comm: empty string rejected")]
722    fn workload_config_comm_rejects_empty() {
723        let _ = WorkloadConfig::default().comm("");
724    }
725
726    /// The first-iteration signal knob defaults to `false` (no eventfd,
727    /// unchanged workers) and the builder flips it.
728    #[test]
729    fn signal_first_iteration_default_false_and_builder() {
730        assert!(
731            !WorkloadConfig::default().signal_first_iteration,
732            "signal_first_iteration must default to false",
733        );
734        assert!(
735            WorkloadConfig::default()
736                .signal_first_iteration(true)
737                .signal_first_iteration,
738            "builder must set the knob true",
739        );
740        assert!(
741            !WorkloadConfig::default()
742                .signal_first_iteration(true)
743                .signal_first_iteration(false)
744                .signal_first_iteration,
745            "builder must set the knob back to false",
746        );
747    }
748
749    #[test]
750    #[should_panic(expected = "interior NUL byte")]
751    fn workload_config_comm_rejects_interior_nul() {
752        let _ = WorkloadConfig::default().comm("foo\0bar");
753    }
754
755    /// Per-builder boundary pin: a future refactor that re-routes
756    /// WorkloadConfig::comm around the shared
757    /// `validate_task_comm_string` helper would surface here even
758    /// if the helper-level tests still pass.
759    #[test]
760    fn workload_config_comm_accepts_15_byte_boundary() {
761        let fifteen = "a".repeat(15);
762        let cfg = WorkloadConfig::default().comm(fifteen.clone());
763        assert_eq!(cfg.comm.as_deref(), Some(fifteen.as_str()));
764    }
765
766    #[test]
767    #[should_panic(expected = "16 bytes")]
768    fn workload_config_comm_rejects_16_byte_overflow() {
769        let _ = WorkloadConfig::default().comm("a".repeat(16));
770    }
771}