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