Skip to main content

allot_shared/
config.rs

1use std::{collections::BTreeMap, fs, io, path::Path};
2
3use serde::{Deserialize, Deserializer, Serialize, de};
4
5use crate::{
6    Error, Result,
7    types::{JobClass, JobProfile},
8};
9
10/// Daemon configuration, read from `config.toml`.
11///
12/// Every value has a default, so a user file only lists what it changes. Tables merge field
13/// by field over the defaults; arrays such as `classifier.rules` replace the default list as
14/// a whole. Unknown keys are rejected so that typos surface instead of being ignored.
15#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
16#[serde(default, deny_unknown_fields)]
17pub struct Config {
18    /// HTTP listener settings.
19    pub daemon: DaemonConfig,
20    /// How much of the machine the admission engine keeps free.
21    pub admission: AdmissionConfig,
22    /// How past runs change a request's estimate.
23    pub estimates: EstimatesConfig,
24    /// When the machine counts as quiet enough for a benchmark.
25    pub benchmark: BenchmarkConfig,
26    /// Lease lifetime settings.
27    pub leases: LeaseConfig,
28    /// How long ended leases and job history are kept.
29    pub retention: RetentionConfig,
30    /// PreToolUse hook behavior.
31    pub hook: HookConfig,
32    /// The profile and minimum cores behind each [`JobClass`].
33    pub classes: ClassProfiles,
34    /// Named profiles sized between the classes, chosen by name like a class.
35    pub presets: Presets,
36    /// Which shell commands count as heavy.
37    pub classifier: ClassifierConfig,
38    /// How leases use cgroups on Linux; ignored on other OSes.
39    pub linux: LinuxConfig,
40}
41
42impl Config {
43    /// Parses and validates a TOML document. Missing values take their defaults.
44    ///
45    /// # Errors
46    ///
47    /// Returns [`Error::ConfigParse`] for malformed TOML, unknown keys, or wrongly typed
48    /// values, and [`Error::Config`] for values out of range.
49    pub fn from_toml(text: &str) -> Result<Self> {
50        let config: Self = toml::from_str(text)?;
51        config.validate()?;
52        Ok(config)
53    }
54
55    /// Loads the file at `path`, or the defaults when the file does not exist.
56    ///
57    /// # Errors
58    ///
59    /// Returns [`Error::ConfigFile`] naming `path` when the file exists but cannot be read,
60    /// or holds what [`Config::from_toml`] rejects.
61    pub fn load(path: &Path) -> Result<Self> {
62        let loaded = match fs::read_to_string(path) {
63            Ok(text) => Self::from_toml(&text),
64            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Self::default()),
65            Err(error) => Err(error.into()),
66        };
67        loaded.map_err(|reason| Error::ConfigFile {
68            path: path.to_owned(),
69            reason: Box::new(reason),
70        })
71    }
72
73    /// Checks every value against its allowed range.
74    ///
75    /// # Errors
76    ///
77    /// Returns [`Error::Config`] naming the first invalid value.
78    pub fn validate(&self) -> Result<()> {
79        ensure(self.daemon.port != 0, "daemon.port must not be 0")?;
80        ensure(
81            (0.0..100.0).contains(&self.admission.headroom_pct),
82            "admission.headroom_pct must be at least 0 and below 100",
83        )?;
84        ensure(
85            self.estimates.min_runs > 0,
86            "estimates.min_runs must be positive",
87        )?;
88        ensure(
89            is_pct(self.estimates.margin_pct),
90            "estimates.margin_pct must be 0 to 100",
91        )?;
92        ensure(
93            is_pct(self.benchmark.quiet_cpu_pct),
94            "benchmark.quiet_cpu_pct must be 0 to 100",
95        )?;
96        ensure(
97            is_pct(self.benchmark.quiet_gpu_pct),
98            "benchmark.quiet_gpu_pct must be 0 to 100",
99        )?;
100        ensure(
101            self.benchmark.quiet_secs > 0,
102            "benchmark.quiet_secs must be positive",
103        )?;
104        ensure(
105            self.benchmark.max_quiet_wait_secs >= self.benchmark.quiet_secs,
106            "benchmark.max_quiet_wait_secs must be at least quiet_secs",
107        )?;
108        ensure(
109            self.leases.heartbeat_ttl_secs > 0,
110            "leases.heartbeat_ttl_secs must be positive",
111        )?;
112        let retention = &self.retention;
113        ensure(
114            retention.lease_days > 0,
115            "retention.lease_days must be positive",
116        )?;
117        ensure(
118            retention.history_days > 0,
119            "retention.history_days must be positive",
120        )?;
121        ensure(
122            retention.keep_runs_per_job > 0,
123            "retention.keep_runs_per_job must be positive",
124        )?;
125        ensure(
126            retention.max_job_runs >= retention.keep_runs_per_job,
127            "retention.max_job_runs must be at least keep_runs_per_job",
128        )?;
129        for class in JobClass::ALL {
130            if let Some(reason) = self.classes.get(class).invalid_reason() {
131                return Err(Error::Config(format!(
132                    "classes.{}: {reason}",
133                    class.as_str()
134                )));
135            }
136        }
137        for (name, sizing) in &self.presets.0 {
138            let well_formed = !name.is_empty()
139                && name
140                    .bytes()
141                    .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_');
142            ensure(
143                well_formed,
144                format!("presets.{name}: names use only a-z, 0-9 and _"),
145            )?;
146            ensure(
147                JobClass::ALL.iter().all(|class| class.as_str() != name),
148                format!("presets.{name}: a class already has this name"),
149            )?;
150            if let Some(reason) = sizing.invalid_reason() {
151                return Err(Error::Config(format!("presets.{name}: {reason}")));
152            }
153        }
154        for (index, rule) in self.classifier.rules.iter().enumerate() {
155            let has_blank =
156                rule.program.trim().is_empty() || rule.args.iter().any(|arg| arg.trim().is_empty());
157            ensure(
158                !has_blank,
159                format!("classifier.rules[{index}] has a blank program or arg"),
160            )?;
161        }
162        let flags = &self.classifier.light_flags;
163        ensure(
164            flags.iter().all(|flag| !flag.trim().is_empty()),
165            "classifier.light_flags must not contain blank entries",
166        )?;
167        Ok(())
168    }
169}
170
171fn ensure(condition: bool, message: impl Into<String>) -> Result<()> {
172    if condition {
173        Ok(())
174    } else {
175        Err(Error::Config(message.into()))
176    }
177}
178
179fn is_pct(value: f32) -> bool {
180    (0.0..=100.0).contains(&value)
181}
182
183/// HTTP listener settings.
184#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
185#[serde(default, deny_unknown_fields)]
186pub struct DaemonConfig {
187    /// Port on `127.0.0.1`.
188    pub port: u16,
189}
190
191impl Default for DaemonConfig {
192    fn default() -> Self {
193        Self { port: 47_823 }
194    }
195}
196
197/// How much of the machine the admission engine keeps free.
198#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
199#[serde(default, deny_unknown_fields)]
200pub struct AdmissionConfig {
201    /// Share of each resource (cores, RAM, GPU, VRAM) never handed out to leases, so the
202    /// desktop and unleased work stay responsive.
203    pub headroom_pct: f32,
204}
205
206impl Default for AdmissionConfig {
207    fn default() -> Self {
208        Self { headroom_pct: 15.0 }
209    }
210}
211
212/// How past runs change a request's estimate. Raising to what similar runs used always
213/// happens; lowering is what these keys control.
214#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
215#[serde(default, deny_unknown_fields)]
216pub struct EstimatesConfig {
217    /// Whether a request may reserve less than it declares once its runs used less.
218    pub lower: bool,
219    /// Clean runs needed before a value lowers.
220    pub min_runs: u32,
221    /// Added on top of what the runs used, so a run slightly heavier than the last ones
222    /// still fits its reservation.
223    pub margin_pct: f32,
224}
225
226impl Default for EstimatesConfig {
227    fn default() -> Self {
228        Self {
229            lower: true,
230            min_runs: 3,
231            margin_pct: 10.0,
232        }
233    }
234}
235
236/// When the machine counts as quiet enough for a benchmark.
237#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
238#[serde(default, deny_unknown_fields)]
239pub struct BenchmarkConfig {
240    /// Total CPU load at or below which the machine is quiet.
241    pub quiet_cpu_pct: f32,
242    /// GPU engine load at or below which the machine is quiet.
243    pub quiet_gpu_pct: f32,
244    /// The window the loads are averaged over once no other lease is active. The machine is
245    /// quiet when both averages are at or below their limits.
246    pub quiet_secs: u64,
247    /// How long a drained machine may stay above the limits before a waiting benchmark is
248    /// granted anyway, marked as not quiet. At least `quiet_secs`.
249    pub max_quiet_wait_secs: u64,
250}
251
252impl Default for BenchmarkConfig {
253    fn default() -> Self {
254        Self {
255            quiet_cpu_pct: 10.0,
256            quiet_gpu_pct: 10.0,
257            quiet_secs: 10,
258            max_quiet_wait_secs: 60,
259        }
260    }
261}
262
263/// Lease lifetime settings.
264#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
265#[serde(default, deny_unknown_fields)]
266pub struct LeaseConfig {
267    /// A lease without a heartbeat for this long expires.
268    pub heartbeat_ttl_secs: u64,
269    /// An active lease ends once no command runs under it and its holder's session has been
270    /// idle for this long, for holders that forget `release_lease`; 0 turns this off.
271    pub idle_release_secs: u64,
272}
273
274impl Default for LeaseConfig {
275    fn default() -> Self {
276        Self {
277            heartbeat_ttl_secs: 60,
278            idle_release_secs: 180,
279        }
280    }
281}
282
283/// How long ended leases and job history are kept. The daemon prunes once an hour.
284#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
285#[serde(default, deny_unknown_fields)]
286pub struct RetentionConfig {
287    /// Released and expired leases, with their audit trail, are deleted this many days after
288    /// they ended.
289    pub lease_days: u64,
290    /// Job runs are deleted this many days after they ended, except the newest
291    /// `keep_runs_per_job` of each job.
292    pub history_days: u64,
293    /// Runs of each job kept regardless of age, so estimates survive long breaks. The
294    /// estimator reads the newest 20.
295    pub keep_runs_per_job: u64,
296    /// Hard cap on stored job runs; the oldest beyond it are deleted whatever their job.
297    pub max_job_runs: u64,
298}
299
300impl Default for RetentionConfig {
301    fn default() -> Self {
302        Self {
303            lease_days: 30,
304            history_days: 90,
305            keep_runs_per_job: 20,
306            max_job_runs: 5_000,
307        }
308    }
309}
310
311/// PreToolUse hook behavior.
312#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
313#[serde(default, deny_unknown_fields)]
314pub struct HookConfig {
315    /// Allow heavy commands when the daemon is unreachable. Off means every heavy command is
316    /// denied until the daemon is back.
317    pub fail_open: bool,
318}
319
320impl Default for HookConfig {
321    fn default() -> Self {
322        Self { fail_open: true }
323    }
324}
325
326/// How leases use cgroups on Linux; ignored on other OSes.
327///
328/// Each active lease runs in a systemd scope of its own, which gives exact usage and a kill
329/// that ends every process at once. Caps on what a lease may use are opt-in, because a job
330/// that outgrows its declared profile is slowed down by them.
331#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
332#[serde(default, deny_unknown_fields)]
333pub struct LinuxConfig {
334    /// Run each lease in its own cgroup scope when the systemd user manager allows it. Off
335    /// follows the process tree instead, as without systemd.
336    pub scopes: bool,
337    /// Cap a lease's CPU time at its reserved cores.
338    pub enforce_cpu: bool,
339    /// Throttle a lease above its reserved RAM (`MemoryHigh`); it is never killed for memory.
340    pub enforce_memory: bool,
341}
342
343impl Default for LinuxConfig {
344    fn default() -> Self {
345        Self {
346            scopes: true,
347            enforce_cpu: false,
348            enforce_memory: false,
349        }
350    }
351}
352
353/// A class or preset: the profile a lease of it asks for, and the fewest cores it may start
354/// with. The minimum is a key of the same table, such as `min_cores` in `[classes.cpu_heavy]`.
355#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
356pub struct Sizing {
357    /// What a lease of it asks for.
358    #[serde(flatten)]
359    pub profile: JobProfile,
360    /// The fewest cores a lease of it may start with; `None` takes
361    /// [`JobProfile::default_min_cores`], so the default follows a changed `cores`.
362    #[serde(skip_serializing_if = "Option::is_none")]
363    pub min_cores: Option<f32>,
364}
365
366impl Sizing {
367    /// `profile` with the default minimum.
368    pub const fn of(profile: JobProfile) -> Self {
369        Self {
370            profile,
371            min_cores: None,
372        }
373    }
374
375    /// The fewest cores a lease of it may start with: the configured minimum or the default.
376    pub fn minimum(&self) -> f32 {
377        self.min_cores
378            .unwrap_or_else(|| self.profile.default_min_cores())
379    }
380
381    /// Why the profile or its minimum is unusable, or `None` when both are in range.
382    pub fn invalid_reason(&self) -> Option<&'static str> {
383        self.profile.invalid_reason().or_else(|| {
384            self.min_cores
385                .and_then(|min_cores| self.profile.min_cores_reason(min_cores))
386        })
387    }
388}
389
390/// The profile and minimum cores behind each [`JobClass`].
391///
392/// A partial table such as `[classes.gpu_heavy]` with only `vram_mb` keeps that class's own
393/// defaults for the other fields, not zeros.
394#[derive(Debug, Clone, PartialEq, Serialize)]
395pub struct ClassProfiles {
396    /// Sizing of [`JobClass::Light`].
397    pub light: Sizing,
398    /// Sizing of [`JobClass::CpuHeavy`].
399    pub cpu_heavy: Sizing,
400    /// Sizing of [`JobClass::GpuHeavy`].
401    pub gpu_heavy: Sizing,
402    /// Sizing of [`JobClass::Mixed`].
403    pub mixed: Sizing,
404}
405
406impl ClassProfiles {
407    /// Returns the sizing configured for `class`.
408    pub fn get(&self, class: JobClass) -> &Sizing {
409        match class {
410            JobClass::Light => &self.light,
411            JobClass::CpuHeavy => &self.cpu_heavy,
412            JobClass::GpuHeavy => &self.gpu_heavy,
413            JobClass::Mixed => &self.mixed,
414        }
415    }
416}
417
418impl Default for ClassProfiles {
419    fn default() -> Self {
420        Self {
421            light: Sizing::of(JobProfile {
422                cores: 1.0,
423                ram_mb: 512,
424                gpu_pct: 0.0,
425                vram_mb: 0,
426                est_secs: 30,
427            }),
428            cpu_heavy: Sizing::of(JobProfile {
429                cores: 8.0,
430                ram_mb: 4096,
431                gpu_pct: 0.0,
432                vram_mb: 0,
433                est_secs: 300,
434            }),
435            gpu_heavy: Sizing::of(JobProfile {
436                cores: 2.0,
437                ram_mb: 4096,
438                gpu_pct: 80.0,
439                vram_mb: 4096,
440                est_secs: 600,
441            }),
442            mixed: Sizing::of(JobProfile {
443                cores: 6.0,
444                ram_mb: 8192,
445                gpu_pct: 50.0,
446                vram_mb: 2048,
447                est_secs: 600,
448            }),
449        }
450    }
451}
452
453impl<'de> Deserialize<'de> for ClassProfiles {
454    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
455    where
456        D: Deserializer<'de>,
457    {
458        let overrides = ClassOverrides::deserialize(deserializer)?;
459        let defaults = Self::default();
460        Ok(Self {
461            light: overrides.light.apply(defaults.light),
462            cpu_heavy: overrides.cpu_heavy.apply(defaults.cpu_heavy),
463            gpu_heavy: overrides.gpu_heavy.apply(defaults.gpu_heavy),
464            mixed: overrides.mixed.apply(defaults.mixed),
465        })
466    }
467}
468
469#[derive(Default, Deserialize)]
470#[serde(default, deny_unknown_fields)]
471struct ClassOverrides {
472    light: ProfileOverride,
473    cpu_heavy: ProfileOverride,
474    gpu_heavy: ProfileOverride,
475    mixed: ProfileOverride,
476}
477
478#[derive(Default, Deserialize)]
479#[serde(deny_unknown_fields)]
480struct ProfileOverride {
481    cores: Option<f32>,
482    ram_mb: Option<u64>,
483    gpu_pct: Option<f32>,
484    vram_mb: Option<u64>,
485    est_secs: Option<u64>,
486    min_cores: Option<f32>,
487}
488
489impl ProfileOverride {
490    fn apply(self, base: Sizing) -> Sizing {
491        let profile = base.profile;
492        Sizing {
493            profile: JobProfile {
494                cores: self.cores.unwrap_or(profile.cores),
495                ram_mb: self.ram_mb.unwrap_or(profile.ram_mb),
496                gpu_pct: self.gpu_pct.unwrap_or(profile.gpu_pct),
497                vram_mb: self.vram_mb.unwrap_or(profile.vram_mb),
498                est_secs: self.est_secs.unwrap_or(profile.est_secs),
499            },
500            min_cores: self.min_cores.or(base.min_cores),
501        }
502    }
503}
504
505/// Named profiles between the classes, by name, each with its minimum cores.
506///
507/// A `[presets.<name>]` table changes that preset field by field, like a class, or adds a new
508/// one, which needs at least `cores` and `ram_mb` (GPU and VRAM default to 0, the run time
509/// to 300 s). The default presets stay unless overridden.
510#[derive(Debug, Clone, PartialEq, Serialize)]
511#[serde(transparent)]
512pub struct Presets(pub BTreeMap<String, Sizing>);
513
514/// Run time of a new preset that gives none.
515const PRESET_EST_SECS: u64 = 300;
516
517impl Presets {
518    /// The sizing of preset `name`.
519    pub fn get(&self, name: &str) -> Option<&Sizing> {
520        self.0.get(name)
521    }
522
523    /// The preset names, sorted.
524    pub fn names(&self) -> impl Iterator<Item = &str> {
525        self.0.keys().map(String::as_str)
526    }
527}
528
529impl Default for Presets {
530    fn default() -> Self {
531        let preset = |cores, ram_mb, gpu_pct, vram_mb, est_secs| {
532            Sizing::of(JobProfile {
533                cores,
534                ram_mb,
535                gpu_pct,
536                vram_mb,
537                est_secs,
538            })
539        };
540        Self(BTreeMap::from([
541            ("cpu_small".to_owned(), preset(2.0, 1024, 0.0, 0, 60)),
542            ("cpu_medium".to_owned(), preset(4.0, 2048, 0.0, 0, 180)),
543            ("gpu_small".to_owned(), preset(1.0, 2048, 30.0, 2048, 300)),
544            ("quick".to_owned(), preset(4.0, 2048, 0.0, 0, 10)),
545            ("low_impact".to_owned(), preset(0.25, 256, 0.0, 0, 60)),
546        ]))
547    }
548}
549
550impl<'de> Deserialize<'de> for Presets {
551    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
552    where
553        D: Deserializer<'de>,
554    {
555        let overrides = BTreeMap::<String, ProfileOverride>::deserialize(deserializer)?;
556        let mut presets = Self::default();
557        for (name, value) in overrides {
558            let profile = match presets.0.get(&name) {
559                Some(&base) => value.apply(base),
560                None => {
561                    let (Some(cores), Some(ram_mb)) = (value.cores, value.ram_mb) else {
562                        return Err(de::Error::custom(format!(
563                            "new preset `{name}` needs both cores and ram_mb"
564                        )));
565                    };
566                    value.apply(Sizing::of(JobProfile {
567                        cores,
568                        ram_mb,
569                        gpu_pct: 0.0,
570                        vram_mb: 0,
571                        est_secs: PRESET_EST_SECS,
572                    }))
573                }
574            };
575            presets.0.insert(name, profile);
576        }
577        Ok(presets)
578    }
579}
580
581/// Which shell commands count as heavy.
582#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
583#[serde(default, deny_unknown_fields)]
584pub struct ClassifierConfig {
585    /// Rules checked against every simple command in a command line, in order.
586    pub rules: Vec<HeavyRule>,
587    /// A simple command containing any of these arguments only prints and exits, so it is
588    /// light even when a rule matches it, for example `cargo build --help`.
589    pub light_flags: Vec<String>,
590}
591
592impl Default for ClassifierConfig {
593    fn default() -> Self {
594        Self {
595            rules: vec![
596                HeavyRule::new(
597                    "cargo",
598                    &["build", "test", "run", "bench"],
599                    JobClass::CpuHeavy,
600                ),
601                HeavyRule::new("pnpm", &["build*", "test*"], JobClass::CpuHeavy),
602                HeavyRule::new("msbuild", &[], JobClass::CpuHeavy),
603                HeavyRule::new("cmake", &["--build"], JobClass::CpuHeavy),
604                HeavyRule::new("python*", &["train*.py"], JobClass::GpuHeavy),
605                HeavyRule::new("py", &["train*.py"], JobClass::GpuHeavy),
606            ],
607            light_flags: ["--help", "-h", "--version", "-V", "/?"]
608                .map(String::from)
609                .to_vec(),
610        }
611    }
612}
613
614/// Marks a simple command as heavy when its program and arguments match.
615///
616/// Matching ignores case, and `*` matches any run of characters.
617#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
618#[serde(deny_unknown_fields)]
619pub struct HeavyRule {
620    /// Program name without directory or extension, for example `cargo` or `python*`.
621    pub program: String,
622    /// Any one of these makes the command heavy; empty matches any arguments. A pattern that
623    /// starts with `-` matches that flag anywhere in the command; any other pattern matches
624    /// the first positional argument (the first one not starting with `-` or `+`).
625    #[serde(default)]
626    pub args: Vec<String>,
627    /// Class the matched command needs a lease for.
628    pub class: JobClass,
629}
630
631impl HeavyRule {
632    fn new(program: &str, args: &[&str], class: JobClass) -> Self {
633        Self {
634            program: program.into(),
635            args: args.iter().map(|&arg| arg.into()).collect(),
636            class,
637        }
638    }
639}
640
641#[cfg(test)]
642mod tests {
643    use std::env;
644
645    use super::*;
646    use crate::mutate::mutations;
647
648    fn config_error(text: &str) -> String {
649        match Config::from_toml(text) {
650            Err(Error::Config(message)) => message,
651            other => panic!("expected Error::Config, got {other:?}"),
652        }
653    }
654
655    #[test]
656    fn test_config_empty_document_yields_defaults() {
657        assert_eq!(Config::from_toml("").unwrap(), Config::default());
658    }
659
660    #[test]
661    fn test_config_default_passes_validation() {
662        Config::default().validate().unwrap();
663    }
664
665    #[test]
666    fn test_config_default_toml_round_trip_preserves_every_value() {
667        let text = toml::to_string(&Config::default()).unwrap();
668        assert_eq!(Config::from_toml(&text).unwrap(), Config::default());
669    }
670
671    #[test]
672    fn test_config_presets_merge_over_defaults_and_add_new_ones() {
673        let config = Config::from_toml(
674            "[presets.cpu_small]\ncores = 3.0\n\n[presets.render_preview]\ncores = 2.0\n\
675             ram_mb = 3000\ngpu_pct = 40.0\n",
676        )
677        .unwrap();
678        let defaults = Presets::default();
679        let small = config.presets.get("cpu_small").unwrap();
680        assert_eq!(small.profile.cores, 3.0);
681        assert_eq!(
682            small.profile.est_secs,
683            defaults.get("cpu_small").unwrap().profile.est_secs
684        );
685        let preview = config.presets.get("render_preview").unwrap().profile;
686        assert_eq!((preview.gpu_pct, preview.vram_mb), (40.0, 0));
687        assert_eq!(preview.est_secs, PRESET_EST_SECS);
688        assert_eq!(config.presets.get("quick"), defaults.get("quick"));
689    }
690
691    #[test]
692    fn test_config_presets_reject_bad_names_and_incomplete_new_ones() {
693        assert!(config_error("[presets.cpu_heavy]\ncores = 1.0\nram_mb = 1\n").contains("class"));
694        assert!(config_error("[presets.Big]\ncores = 1.0\nram_mb = 1\n").contains("a-z"));
695        assert!(config_error("[presets.quick]\ngpu_pct = 140.0\n").contains("presets.quick"));
696        let incomplete = Config::from_toml("[presets.huge]\ncores = 12.0\n").unwrap_err();
697        assert!(incomplete.to_string().contains("ram_mb"), "{incomplete}");
698    }
699
700    #[test]
701    fn test_default_presets_are_quick_and_low_impact_where_named() {
702        let presets = Presets::default();
703        let profile = |name| presets.get(name).unwrap().profile;
704        assert!(profile("quick").is_quick());
705        assert!(profile("low_impact").is_low_impact());
706        assert!(!profile("cpu_small").is_quick());
707        assert!(!profile("cpu_small").is_low_impact());
708    }
709
710    #[test]
711    fn test_config_partial_table_merges_over_defaults() {
712        let config = Config::from_toml(
713            "[leases]\nheartbeat_ttl_secs = 90\n\n[classes.gpu_heavy]\nvram_mb = 8192\n",
714        )
715        .unwrap();
716        let defaults = Config::default();
717        assert_eq!(config.leases.heartbeat_ttl_secs, 90);
718        assert_eq!(
719            config.leases.idle_release_secs,
720            defaults.leases.idle_release_secs
721        );
722        assert_eq!(config.classes.gpu_heavy.profile.vram_mb, 8192);
723        assert_eq!(
724            config.classes.gpu_heavy.profile.cores,
725            defaults.classes.gpu_heavy.profile.cores
726        );
727        assert_eq!(config.classes.cpu_heavy, defaults.classes.cpu_heavy);
728        assert_eq!(config.daemon, defaults.daemon);
729        assert_eq!(config.classifier, defaults.classifier);
730    }
731
732    #[test]
733    fn test_config_default_minimums_are_half_with_at_least_one_core() {
734        let config = Config::default();
735        let class = |class| config.classes.get(class).minimum();
736        assert_eq!(class(JobClass::Light), 1.0);
737        assert_eq!(class(JobClass::CpuHeavy), 4.0);
738        assert_eq!(class(JobClass::GpuHeavy), 1.0);
739        assert_eq!(class(JobClass::Mixed), 3.0);
740        let preset = |name| config.presets.get(name).unwrap().minimum();
741        assert_eq!(preset("cpu_small"), 1.0);
742        assert_eq!(preset("cpu_medium"), 2.0);
743        assert_eq!(preset("gpu_small"), 1.0);
744        assert_eq!(preset("quick"), 2.0);
745        assert_eq!(preset("low_impact"), 0.25);
746    }
747
748    #[test]
749    fn test_config_min_cores_overrides_and_default_follows_changed_cores() {
750        let config = Config::from_toml(
751            "[classes.cpu_heavy]\nmin_cores = 6.0\n\n[classes.mixed]\ncores = 10.0\n\n\
752             [presets.quick]\nmin_cores = 1.5\n\n[presets.wide]\ncores = 12.0\nram_mb = 1024\n",
753        )
754        .unwrap();
755        assert_eq!(config.classes.cpu_heavy.minimum(), 6.0);
756        assert_eq!(config.classes.cpu_heavy.profile.cores, 8.0);
757        assert_eq!(config.classes.mixed.minimum(), 5.0);
758        assert_eq!(config.presets.get("quick").unwrap().minimum(), 1.5);
759        assert_eq!(config.presets.get("wide").unwrap().minimum(), 6.0);
760    }
761
762    #[test]
763    fn test_config_min_cores_out_of_range_names_the_table_and_key() {
764        for (table, keys) in [
765            ("classes.cpu_heavy", "min_cores = 0.0"),
766            ("classes.light", "min_cores = 1.5"),
767            ("classes.mixed", "cores = 2.0\nmin_cores = 3.0"),
768            ("presets.cpu_small", "min_cores = -1.0"),
769            ("presets.cpu_small", "min_cores = nan"),
770        ] {
771            let message = config_error(&format!("[{table}]\n{keys}\n"));
772            let named = message.contains(table) && message.contains("min_cores");
773            assert!(named, "{message}");
774        }
775    }
776
777    #[test]
778    fn test_config_min_cores_round_trips_and_stays_out_when_unset() {
779        let text = toml::to_string(&Config::default()).unwrap();
780        assert!(!text.contains("min_cores"), "{text}");
781        let config = Config::from_toml("[classes.gpu_heavy]\nmin_cores = 2.0\n").unwrap();
782        let text = toml::to_string(&config).unwrap();
783        assert_eq!(Config::from_toml(&text).unwrap(), config);
784        assert_eq!(config.classes.gpu_heavy.min_cores, Some(2.0));
785    }
786
787    #[test]
788    fn test_config_linux_table_defaults_to_scopes_without_caps_and_merges() {
789        let defaults = LinuxConfig::default();
790        assert!(defaults.scopes);
791        assert!(!defaults.enforce_cpu);
792        assert!(!defaults.enforce_memory);
793
794        let config = Config::from_toml("[linux]\nenforce_memory = true\n").unwrap();
795        assert_eq!(
796            config.linux,
797            LinuxConfig {
798                enforce_memory: true,
799                ..defaults
800            }
801        );
802        let result = Config::from_toml("[linux]\nenforce_io = true\n");
803        assert!(matches!(result, Err(Error::ConfigParse(_))));
804    }
805
806    #[test]
807    fn test_config_estimates_default_and_override_field_by_field() {
808        let defaults = EstimatesConfig::default();
809        assert_eq!(
810            (defaults.lower, defaults.min_runs, defaults.margin_pct),
811            (true, 3, 10.0)
812        );
813        assert_eq!(Config::from_toml("").unwrap().estimates, defaults);
814        let config = Config::from_toml("[estimates]\nmin_runs = 5\n").unwrap();
815        assert_eq!(
816            config.estimates,
817            EstimatesConfig {
818                min_runs: 5,
819                ..defaults
820            }
821        );
822        let config = Config::from_toml("[estimates]\nlower = false\nmargin_pct = 0\n").unwrap();
823        assert!(!config.estimates.lower);
824        assert_eq!(config.estimates.margin_pct, 0.0);
825        let result = Config::from_toml("[estimates]\nlower_ram = false\n");
826        assert!(matches!(result, Err(Error::ConfigParse(_))));
827    }
828
829    #[test]
830    fn test_config_integer_percentage_parses_as_float() {
831        let config = Config::from_toml("[admission]\nheadroom_pct = 20\n").unwrap();
832        assert_eq!(config.admission.headroom_pct, 20.0);
833    }
834
835    #[test]
836    fn test_config_user_rules_replace_default_rules() {
837        let config = Config::from_toml(
838            "[[classifier.rules]]\nprogram = \"python\"\nargs = [\"train.py\"]\nclass = \"gpu_heavy\"\n",
839        )
840        .unwrap();
841        assert_eq!(
842            config.classifier.rules,
843            vec![HeavyRule::new("python", &["train.py"], JobClass::GpuHeavy)]
844        );
845    }
846
847    #[test]
848    fn test_config_rule_without_args_matches_any_arguments() {
849        let config =
850            Config::from_toml("[[classifier.rules]]\nprogram = \"ninja\"\nclass = \"cpu_heavy\"\n")
851                .unwrap();
852        assert!(config.classifier.rules[0].args.is_empty());
853    }
854
855    #[test]
856    fn test_config_user_rules_keep_default_light_flags() {
857        let config =
858            Config::from_toml("[[classifier.rules]]\nprogram = \"ninja\"\nclass = \"cpu_heavy\"\n")
859                .unwrap();
860        let defaults = ClassifierConfig::default();
861        assert_eq!(config.classifier.light_flags, defaults.light_flags);
862        assert!(defaults.light_flags.contains(&"--help".to_owned()));
863    }
864
865    #[test]
866    fn test_config_blank_light_flag_is_rejected() {
867        let message = config_error("[classifier]\nlight_flags = [\"--help\", \"\"]\n");
868        assert!(message.contains("classifier.light_flags"));
869    }
870
871    #[test]
872    fn test_config_unknown_key_is_rejected() {
873        let result = Config::from_toml("[leases]\nheartbeat_tll_secs = 90\n");
874        assert!(matches!(result, Err(Error::ConfigParse(_))));
875        let result = Config::from_toml("[classes.mixed]\nvram = 1024\n");
876        assert!(matches!(result, Err(Error::ConfigParse(_))));
877        let result = Config::from_toml("[classes.huge]\ncores = 32\n");
878        assert!(matches!(result, Err(Error::ConfigParse(_))));
879    }
880
881    #[test]
882    fn test_config_wrong_type_is_rejected() {
883        let result = Config::from_toml("[daemon]\nport = \"eighty\"\n");
884        assert!(matches!(result, Err(Error::ConfigParse(_))));
885    }
886
887    #[test]
888    fn test_config_out_of_range_values_name_the_key() {
889        assert!(config_error("[daemon]\nport = 0\n").contains("daemon.port"));
890        assert!(config_error("[admission]\nheadroom_pct = 100\n").contains("headroom_pct"));
891        assert!(config_error("[estimates]\nmin_runs = 0\n").contains("estimates.min_runs"));
892        assert!(config_error("[estimates]\nmargin_pct = -5\n").contains("estimates.margin_pct"));
893        assert!(config_error("[benchmark]\nquiet_cpu_pct = 120\n").contains("quiet_cpu_pct"));
894        assert!(config_error("[benchmark]\nquiet_secs = 0\n").contains("quiet_secs"));
895        let short_wait = "[benchmark]\nquiet_secs = 30\nmax_quiet_wait_secs = 20\n";
896        assert!(config_error(short_wait).contains("max_quiet_wait_secs"));
897        assert!(config_error("[leases]\nheartbeat_ttl_secs = 0\n").contains("heartbeat_ttl"));
898        assert!(config_error("[classes.mixed]\ngpu_pct = 150\n").contains("classes.mixed"));
899        assert!(config_error("[retention]\nlease_days = 0\n").contains("retention.lease_days"));
900        assert!(config_error("[retention]\nhistory_days = 0\n").contains("history_days"));
901        assert!(config_error("[retention]\nkeep_runs_per_job = 0\n").contains("keep_runs"));
902        let small_cap = "[retention]\nkeep_runs_per_job = 50\nmax_job_runs = 10\n";
903        assert!(config_error(small_cap).contains("retention.max_job_runs"));
904    }
905
906    #[test]
907    fn test_config_load_invalid_file_names_the_file_and_the_key() {
908        let path =
909            env::temp_dir().join(format!("allot-shared-test-bad-{}.toml", std::process::id()));
910        fs::write(&path, "[leases]\nheartbeat_ttl_secs = 0\n").unwrap();
911        let loaded = Config::load(&path);
912        fs::remove_file(&path).unwrap();
913        let message = loaded.unwrap_err().to_string();
914        assert!(
915            message.starts_with(&path.display().to_string()),
916            "{message}"
917        );
918        assert!(message.contains("leases.heartbeat_ttl_secs"), "{message}");
919    }
920
921    #[test]
922    fn test_config_malformed_documents_fail_without_panicking() {
923        let text = toml::to_string(&Config::default()).unwrap();
924        for variant in mutations(&text, 0x5eed, 2_000) {
925            match Config::from_toml(&variant) {
926                Ok(config) => config.validate().unwrap(),
927                Err(error) => assert!(!error.to_string().is_empty()),
928            }
929        }
930    }
931
932    #[test]
933    fn test_config_wrongly_typed_value_names_its_key() {
934        let text = toml::to_string(&Config::default()).unwrap();
935        let mut checked = 0;
936        for (index, line) in text.lines().enumerate() {
937            let Some((key, _)) = line.split_once(" = ") else {
938                continue;
939            };
940            for wrong in ["\"text\"", "[1, 2]", "{ x = 1 }", "-1", "true", "1.5", "0"] {
941                let mut lines: Vec<&str> = text.lines().collect();
942                let replaced = format!("{key} = {wrong}");
943                lines[index] = &replaced;
944                // A replacement of the right type and range is simply accepted.
945                if let Err(error) = Config::from_toml(&lines.join("\n")) {
946                    let message = error.to_string();
947                    assert!(message.contains(key.trim()), "{key} = {wrong}: {message}");
948                    checked += 1;
949                }
950            }
951        }
952        assert!(checked > 50, "only {checked} rejections were checked");
953    }
954
955    #[test]
956    fn test_config_blank_rule_program_is_rejected() {
957        let message =
958            config_error("[[classifier.rules]]\nprogram = \" \"\nclass = \"cpu_heavy\"\n");
959        assert!(message.contains("classifier.rules[0]"));
960    }
961
962    #[test]
963    fn test_config_load_missing_file_yields_defaults() {
964        let path = env::temp_dir()
965            .join("allot-shared-test-missing")
966            .join("config.toml");
967        assert_eq!(Config::load(&path).unwrap(), Config::default());
968    }
969
970    #[test]
971    fn test_config_load_existing_file_parses_it() {
972        let path = env::temp_dir().join(format!("allot-shared-test-{}.toml", std::process::id()));
973        fs::write(&path, "[hook]\nfail_open = false\n").unwrap();
974        let loaded = Config::load(&path);
975        fs::remove_file(&path).unwrap();
976        assert!(!loaded.unwrap().hook.fail_open);
977    }
978}