1use std::ops::AddAssign;
2
3use serde::{Deserialize, Serialize};
4
5#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
8#[serde(transparent)]
9pub struct LeaseId(pub i64);
10
11#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
16#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
17#[serde(transparent)]
18pub struct SessionKey(pub String);
19
20#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct Holder {
24 pub session: SessionKey,
26 pub pid: u32,
29 pub pid_start_time: u64,
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
36pub struct Rolling {
37 pub avg_1s: f32,
39 pub avg_10s: f32,
41 pub avg_60s: f32,
43}
44
45#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
47pub struct CpuStats {
48 pub logical_cores: u32,
50 pub usage_pct: Rolling,
52 pub per_core_pct: Vec<f32>,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
58pub struct MemStats {
59 pub total_mb: u64,
61 pub used_mb: u64,
63 pub available_mb: u64,
65 pub commit_used_mb: u64,
67 pub commit_limit_mb: u64,
69 #[serde(default)]
72 pub reclaimable_mb: u64,
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
77pub struct GpuEngines {
78 pub three_d_pct: Rolling,
80 pub compute_pct: Rolling,
82 pub copy_pct: Rolling,
84 pub video_pct: Rolling,
86}
87
88impl GpuEngines {
89 pub fn busiest(&self, pick: fn(&Rolling) -> f32) -> f32 {
91 [
92 self.three_d_pct,
93 self.compute_pct,
94 self.copy_pct,
95 self.video_pct,
96 ]
97 .iter()
98 .map(pick)
99 .fold(0.0, f32::max)
100 }
101}
102
103#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
105pub struct GpuAdapter {
106 pub name: String,
108 pub luid: String,
111 pub engines: GpuEngines,
113 pub dedicated_used_mb: u64,
116 pub dedicated_total_mb: Option<u64>,
119 pub shared_used_mb: u64,
121 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
124 pub unified_memory: bool,
125 #[serde(default, skip_serializing_if = "is_default")]
127 pub source: GpuSource,
128 #[serde(default, skip_serializing_if = "is_default")]
130 pub process_load: Accuracy,
131 #[serde(default, skip_serializing_if = "is_default")]
133 pub process_memory: Accuracy,
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
138#[serde(rename_all = "snake_case")]
139#[non_exhaustive]
140pub enum GpuSource {
141 #[default]
144 Pdh,
145 Nvml,
147 DrmFdinfo,
149 Iokit,
151}
152
153#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
156#[serde(rename_all = "snake_case")]
157#[non_exhaustive]
158pub enum Accuracy {
159 #[default]
161 Exact,
162 Estimated,
164 Unavailable,
166}
167
168#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
170#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
171pub struct ResourceUsage {
172 pub cores: f32,
174 pub ram_mb: u64,
176 pub gpu_pct: f32,
178 pub vram_mb: u64,
180}
181
182impl AddAssign for ResourceUsage {
183 fn add_assign(&mut self, other: Self) {
184 self.cores += other.cores;
185 self.ram_mb += other.ram_mb;
186 self.gpu_pct += other.gpu_pct;
187 self.vram_mb += other.vram_mb;
188 }
189}
190
191#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
193pub struct ProcessUsage {
194 pub pid: u32,
196 pub name: String,
198 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub exe: Option<String>,
201 pub usage: ResourceUsage,
203}
204
205#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
207pub struct SessionUsage {
208 pub holder: Holder,
210 pub usage: ResourceUsage,
212 pub processes: Vec<ProcessUsage>,
214}
215
216#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
218pub struct Snapshot {
219 pub taken_at_ms: i64,
221 pub cpu: CpuStats,
223 pub memory: MemStats,
225 pub gpus: Vec<GpuAdapter>,
227 pub sessions: Vec<SessionUsage>,
229 pub unattributed: ResourceUsage,
231 #[serde(default, skip_serializing_if = "Vec::is_empty")]
233 pub drives: Vec<DriveUsage>,
234}
235
236#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
239pub struct DriveUsage {
240 pub name: String,
243 pub total_mb: u64,
245 pub used_mb: u64,
247 pub read_bytes_per_sec: u64,
249 pub write_bytes_per_sec: u64,
251}
252
253#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
255#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
256pub struct JobProfile {
257 pub cores: f32,
259 pub ram_mb: u64,
261 pub gpu_pct: f32,
263 pub vram_mb: u64,
265 pub est_secs: u64,
267}
268
269impl JobProfile {
270 pub fn invalid_reason(&self) -> Option<&'static str> {
272 if !(self.cores.is_finite() && self.cores >= 0.0) {
273 Some("cores must be a finite number of at least 0")
274 } else if !(0.0..=100.0).contains(&self.gpu_pct) {
275 Some("gpu_pct must be between 0 and 100")
276 } else {
277 None
278 }
279 }
280
281 pub fn default_min_cores(&self) -> f32 {
284 (self.cores / 2.0).max(self.cores.min(1.0))
285 }
286
287 pub fn min_cores_reason(&self, min_cores: f32) -> Option<&'static str> {
290 if !(min_cores.is_finite() && min_cores > 0.0) {
291 Some("min_cores must be a finite number above 0")
292 } else if min_cores > self.cores {
293 Some("min_cores must be at most cores")
294 } else {
295 None
296 }
297 }
298
299 pub fn is_quick(&self) -> bool {
302 self.est_secs <= QUICK_MAX_SECS
303 }
304
305 pub fn is_low_impact(&self) -> bool {
308 self.cores <= LOW_IMPACT_MAX_CORES
309 && self.ram_mb <= LOW_IMPACT_MAX_RAM_MB
310 && self.gpu_pct == 0.0
311 && self.vram_mb == 0
312 }
313}
314
315pub const QUICK_MAX_SECS: u64 = 15;
317
318pub const LOW_IMPACT_MAX_CORES: f32 = 0.25;
320
321pub const LOW_IMPACT_MAX_RAM_MB: u64 = 256;
323
324#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
326#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
327#[serde(rename_all = "snake_case")]
328#[non_exhaustive]
329pub enum JobClass {
330 Light,
332 CpuHeavy,
334 GpuHeavy,
336 Mixed,
338}
339
340impl JobClass {
341 pub const ALL: [Self; 4] = [Self::Light, Self::CpuHeavy, Self::GpuHeavy, Self::Mixed];
343
344 pub fn as_str(self) -> &'static str {
346 match self {
347 Self::Light => "light",
348 Self::CpuHeavy => "cpu_heavy",
349 Self::GpuHeavy => "gpu_heavy",
350 Self::Mixed => "mixed",
351 }
352 }
353}
354
355#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
357#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
358#[serde(rename_all = "snake_case")]
359#[non_exhaustive]
360pub enum LeaseKind {
361 Normal,
363 BenchmarkExclusive,
365}
366
367impl LeaseKind {
368 pub const ALL: [Self; 2] = [Self::Normal, Self::BenchmarkExclusive];
370
371 pub fn as_str(self) -> &'static str {
373 match self {
374 Self::Normal => "normal",
375 Self::BenchmarkExclusive => "benchmark_exclusive",
376 }
377 }
378}
379
380#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
382#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
383#[serde(rename_all = "snake_case")]
384#[non_exhaustive]
385pub enum LeaseState {
386 Queued,
388 Active,
390 Released,
392 Expired,
394}
395
396impl LeaseState {
397 pub const ALL: [Self; 4] = [Self::Queued, Self::Active, Self::Released, Self::Expired];
399
400 pub fn as_str(self) -> &'static str {
402 match self {
403 Self::Queued => "queued",
404 Self::Active => "active",
405 Self::Released => "released",
406 Self::Expired => "expired",
407 }
408 }
409}
410
411#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
416#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
417#[serde(rename_all = "snake_case")]
418#[non_exhaustive]
419pub enum EndCause {
420 Released,
422 Expired,
424 Killed,
426 Removed,
428}
429
430impl EndCause {
431 pub const ALL: [Self; 4] = [Self::Released, Self::Expired, Self::Killed, Self::Removed];
433
434 pub fn as_str(self) -> &'static str {
436 match self {
437 Self::Released => "released",
438 Self::Expired => "expired",
439 Self::Killed => "killed",
440 Self::Removed => "removed",
441 }
442 }
443
444 pub fn ended_state(self) -> LeaseState {
448 match self {
449 Self::Released => LeaseState::Released,
450 Self::Expired | Self::Killed | Self::Removed => LeaseState::Expired,
451 }
452 }
453
454 pub fn is_notice(self) -> bool {
456 matches!(self, Self::Killed | Self::Removed)
457 }
458}
459
460#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
462#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
463pub struct Lease {
464 pub id: LeaseId,
466 pub holder: Holder,
468 pub kind: LeaseKind,
470 pub state: LeaseState,
472 pub class: Option<JobClass>,
474 pub profile: JobProfile,
477 #[serde(default, skip_serializing_if = "Option::is_none")]
480 pub asked_cores: Option<f32>,
481 #[serde(default, skip_serializing_if = "Option::is_none")]
484 pub min_cores: Option<f32>,
485 pub label: String,
487 #[serde(default)]
489 pub cwd: String,
490 pub requested_at_ms: i64,
492 pub granted_at_ms: Option<i64>,
494 pub ended_at_ms: Option<i64>,
496 pub expires_at_ms: i64,
498 #[serde(default, skip_serializing_if = "Option::is_none")]
501 pub end_cause: Option<EndCause>,
502 #[serde(default, skip_serializing_if = "Option::is_none")]
505 pub binding: Option<LeaseBinding>,
506 #[serde(default, skip_serializing_if = "Option::is_none")]
509 pub isolation: Option<LeaseIsolation>,
510}
511
512impl Lease {
513 pub fn asked_profile(&self) -> JobProfile {
516 JobProfile {
517 cores: self.asked_cores.unwrap_or(self.profile.cores),
518 ..self.profile
519 }
520 }
521}
522
523#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
525#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
526pub struct LeaseIsolation {
527 pub kind: IsolationKind,
529 pub scope: Option<String>,
532 pub limits: EnforcedLimits,
534}
535
536#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
538#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
539#[serde(rename_all = "snake_case")]
540#[non_exhaustive]
541pub enum IsolationKind {
542 Cgroup,
544 Tree,
546}
547
548#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
550#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
551pub struct EnforcedLimits {
552 pub cpu_cores: Option<f32>,
554 pub memory_high_mb: Option<u64>,
556 pub memory_max_mb: Option<u64>,
558}
559
560pub(crate) fn is_default<T: Default + PartialEq>(value: &T) -> bool {
562 *value == T::default()
563}
564
565#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
568#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
569pub struct LeaseBinding {
570 pub tool_use_id: String,
572 pub bound_at_ms: i64,
575 pub root: Option<BoundProcess>,
577}
578
579#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
581#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
582pub struct BoundProcess {
583 pub pid: u32,
585 pub start_time: u64,
587}
588
589#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
595#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
596pub struct NoiseReport {
597 pub avg_cpu_pct: f32,
599 pub peak_cpu_pct: f32,
601 pub avg_gpu_pct: f32,
603 pub peak_gpu_pct: f32,
605 pub quiet_at_start: bool,
608}
609
610#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
613#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
614pub struct BusyUsage {
615 pub cores: f32,
617 pub gpu_pct: f32,
619}
620
621#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
623#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
624pub struct JobRun {
625 pub lease_id: Option<LeaseId>,
627 #[serde(default, skip_serializing_if = "Option::is_none")]
629 pub session: Option<SessionKey>,
630 #[serde(default, skip_serializing_if = "Option::is_none")]
632 pub end_cause: Option<EndCause>,
633 pub fingerprint: String,
635 pub command: String,
637 pub cwd: String,
639 pub declared: JobProfile,
641 pub peak: ResourceUsage,
643 pub avg: ResourceUsage,
645 #[serde(default, skip_serializing_if = "Option::is_none")]
648 pub busy: Option<BusyUsage>,
649 pub started_at_ms: i64,
651 pub ended_at_ms: i64,
653 pub noise: Option<NoiseReport>,
655 pub overlapped: bool,
658}
659
660#[cfg(test)]
661mod tests {
662 use super::*;
663 use crate::test_support::{assert_json_round_trip, sample_lease, sample_snapshot};
664
665 fn profile_with(cores: f32, gpu_pct: f32) -> JobProfile {
666 JobProfile {
667 cores,
668 ram_mb: 1024,
669 gpu_pct,
670 vram_mb: 0,
671 est_secs: 60,
672 }
673 }
674
675 #[test]
676 fn test_snapshot_json_round_trip_preserves_every_field() {
677 assert_json_round_trip(&sample_snapshot());
678 }
679
680 #[test]
681 fn test_lease_json_round_trip_preserves_every_field() {
682 assert_json_round_trip(&sample_lease());
683 }
684
685 #[test]
686 fn test_lease_json_uses_snake_case_enums_and_bare_ids() {
687 let value = serde_json::to_value(sample_lease()).unwrap();
688 assert_eq!(value["id"], 7);
689 assert_eq!(value["holder"]["session"], "3f2a9c1e-session");
690 assert_eq!(value["kind"], "benchmark_exclusive");
691 assert_eq!(value["state"], "active");
692 assert_eq!(value["class"], "cpu_heavy");
693 }
694
695 #[test]
696 fn test_enum_as_str_matches_serde_name() {
697 for class in JobClass::ALL {
698 assert_eq!(serde_json::to_value(class).unwrap(), class.as_str());
699 }
700 for kind in LeaseKind::ALL {
701 assert_eq!(serde_json::to_value(kind).unwrap(), kind.as_str());
702 }
703 for state in LeaseState::ALL {
704 assert_eq!(serde_json::to_value(state).unwrap(), state.as_str());
705 }
706 for cause in EndCause::ALL {
707 assert_eq!(serde_json::to_value(cause).unwrap(), cause.as_str());
708 }
709 }
710
711 #[test]
712 fn test_lease_with_end_cause_round_trips_and_writes_snake_case() {
713 let lease = Lease {
714 state: LeaseState::Released,
715 ended_at_ms: Some(1_793_000_090_000),
716 end_cause: Some(EndCause::Killed),
717 ..sample_lease()
718 };
719 assert_json_round_trip(&lease);
720 assert_eq!(serde_json::to_value(&lease).unwrap()["end_cause"], "killed");
721 }
722
723 #[test]
724 fn test_lease_without_end_cause_omits_the_field() {
725 let value = serde_json::to_value(sample_lease()).unwrap();
726 assert!(value.get("end_cause").is_none());
727 assert!(value.get("binding").is_none());
728 }
729
730 #[test]
731 fn test_lease_with_asked_and_min_cores_round_trips_and_omits_them_when_unknown() {
732 let lease = Lease {
733 asked_cores: Some(8.0),
734 min_cores: Some(4.0),
735 ..sample_lease()
736 };
737 assert_json_round_trip(&lease);
738 let value = serde_json::to_value(&lease).unwrap();
739 assert_eq!(value["asked_cores"], 8.0);
740 assert_eq!(value["min_cores"], 4.0);
741 let unknown = serde_json::to_value(sample_lease()).unwrap();
742 assert!(unknown.get("asked_cores").is_none());
743 assert!(unknown.get("min_cores").is_none());
744 }
745
746 #[test]
747 fn test_lease_with_binding_round_trips_with_and_without_root() {
748 let pending = LeaseBinding {
749 tool_use_id: "toolu_01AbC".into(),
750 bound_at_ms: 1_793_000_013_000,
751 root: None,
752 };
753 let bound = LeaseBinding {
754 root: Some(BoundProcess {
755 pid: 30_112,
756 start_time: 1_793_000_013,
757 }),
758 ..pending.clone()
759 };
760 for binding in [pending, bound] {
761 assert_json_round_trip(&Lease {
762 binding: Some(binding),
763 ..sample_lease()
764 });
765 }
766 }
767
768 #[test]
769 fn test_v0_1_shapes_decode_without_new_fields() {
770 let mut lease = serde_json::to_value(sample_lease()).unwrap();
771 lease.as_object_mut().unwrap().remove("end_cause");
772 let lease: Lease = serde_json::from_value(lease).unwrap();
773 assert_eq!(lease.end_cause, None);
774 assert_eq!(lease.binding, None);
775 assert_eq!(lease.isolation, None);
776 assert_eq!((lease.asked_cores, lease.min_cores), (None, None));
777
778 let mut snapshot = serde_json::to_value(sample_snapshot()).unwrap();
779 snapshot.as_object_mut().unwrap().remove("drives");
780 snapshot["sessions"][0]["processes"][0]
781 .as_object_mut()
782 .unwrap()
783 .remove("exe");
784 let snapshot: Snapshot = serde_json::from_value(snapshot).unwrap();
785 assert!(snapshot.drives.is_empty());
786 assert_eq!(snapshot.sessions[0].processes[0].exe, None);
787 }
788
789 #[test]
790 fn test_windows_adapter_and_lease_omit_every_cross_platform_field() {
791 let snapshot = serde_json::to_value(sample_snapshot()).unwrap();
792 let gpu = snapshot["gpus"][0].as_object().unwrap();
793 for field in ["unified_memory", "source", "process_load", "process_memory"] {
794 assert!(gpu.get(field).is_none(), "{field}");
795 }
796 let lease = serde_json::to_value(sample_lease()).unwrap();
797 assert!(lease.get("isolation").is_none());
798 }
799
800 #[test]
801 fn test_adapter_from_an_older_allotd_is_a_windows_adapter() {
802 let mut value = serde_json::to_value(&sample_snapshot().gpus[0]).unwrap();
803 let object = value.as_object_mut().unwrap();
804 for field in ["unified_memory", "source", "process_load", "process_memory"] {
805 object.remove(field);
806 }
807 let gpu: GpuAdapter = serde_json::from_value(value).unwrap();
808 assert!(!gpu.unified_memory);
809 assert_eq!(gpu.source, GpuSource::Pdh);
810 assert_eq!(gpu.process_load, Accuracy::Exact);
811 assert_eq!(gpu.process_memory, Accuracy::Exact);
812 }
813
814 #[test]
815 fn test_unified_adapter_round_trips_and_writes_snake_case() {
816 let gpu = GpuAdapter {
817 name: "Apple M3 Max".into(),
818 luid: "4294969310".into(),
819 dedicated_used_mb: 9_216,
820 dedicated_total_mb: None,
821 shared_used_mb: 0,
822 unified_memory: true,
823 source: GpuSource::Iokit,
824 process_load: Accuracy::Estimated,
825 process_memory: Accuracy::Unavailable,
826 ..sample_snapshot().gpus[0].clone()
827 };
828 assert_json_round_trip(&gpu);
829 let value = serde_json::to_value(&gpu).unwrap();
830 assert_eq!(value["unified_memory"], true);
831 assert_eq!(value["source"], "iokit");
832 assert_eq!(value["process_load"], "estimated");
833 assert_eq!(value["process_memory"], "unavailable");
834 let fdinfo = serde_json::to_value(GpuSource::DrmFdinfo).unwrap();
835 assert_eq!(fdinfo, "drm_fdinfo");
836 }
837
838 #[test]
839 fn test_lease_with_isolation_round_trips_for_cgroup_and_tree() {
840 let cgroup = LeaseIsolation {
841 kind: IsolationKind::Cgroup,
842 scope: Some("allot-lease-7.scope".into()),
843 limits: EnforcedLimits {
844 cpu_cores: Some(8.0),
845 memory_high_mb: Some(4096),
846 memory_max_mb: Some(6144),
847 },
848 };
849 let tree = LeaseIsolation {
850 kind: IsolationKind::Tree,
851 scope: None,
852 limits: EnforcedLimits::default(),
853 };
854 for isolation in [cgroup, tree] {
855 assert_json_round_trip(&Lease {
856 isolation: Some(isolation),
857 ..sample_lease()
858 });
859 }
860 let value = serde_json::to_value(Lease {
861 isolation: Some(LeaseIsolation {
862 kind: IsolationKind::Tree,
863 scope: None,
864 limits: EnforcedLimits::default(),
865 }),
866 ..sample_lease()
867 })
868 .unwrap();
869 assert_eq!(value["isolation"]["kind"], "tree");
870 assert!(value["isolation"]["scope"].is_null());
871 assert!(value["isolation"]["limits"]["memory_max_mb"].is_null());
872 }
873
874 #[test]
875 fn test_snapshot_without_drives_and_exe_omits_both_fields() {
876 let mut snapshot = sample_snapshot();
877 snapshot.drives.clear();
878 snapshot.sessions[0].processes[0].exe = None;
879 let value = serde_json::to_value(snapshot).unwrap();
880 assert!(value.get("drives").is_none());
881 assert!(value["sessions"][0]["processes"][0].get("exe").is_none());
882 }
883
884 #[test]
885 fn test_gpu_engines_busiest_reads_the_picked_window_of_the_busiest_group() {
886 let rolling = |avg_1s, avg_10s| Rolling {
887 avg_1s,
888 avg_10s,
889 avg_60s: 0.0,
890 };
891 let engines = GpuEngines {
892 three_d_pct: rolling(12.0, 40.0),
893 compute_pct: rolling(55.5, 20.0),
894 copy_pct: rolling(1.0, 1.0),
895 video_pct: rolling(0.0, 0.0),
896 };
897 assert_eq!(engines.busiest(|load| load.avg_1s), 55.5);
898 assert_eq!(engines.busiest(|load| load.avg_10s), 40.0);
899 assert_eq!(GpuEngines::default().busiest(|load| load.avg_1s), 0.0);
900 }
901
902 #[test]
903 fn test_resource_usage_add_assign_sums_every_field() {
904 let mut total = ResourceUsage {
905 cores: 1.5,
906 ram_mb: 100,
907 gpu_pct: 10.0,
908 vram_mb: 64,
909 };
910 total += ResourceUsage {
911 cores: 2.25,
912 ram_mb: 50,
913 gpu_pct: 5.5,
914 vram_mb: 0,
915 };
916 assert_eq!(
917 total,
918 ResourceUsage {
919 cores: 3.75,
920 ram_mb: 150,
921 gpu_pct: 15.5,
922 vram_mb: 64,
923 }
924 );
925 }
926
927 #[test]
928 fn test_noise_report_json_round_trip_preserves_every_field() {
929 assert_json_round_trip(&NoiseReport {
930 avg_cpu_pct: 2.5,
931 peak_cpu_pct: 9.0,
932 avg_gpu_pct: 0.5,
933 peak_gpu_pct: 3.25,
934 quiet_at_start: false,
935 });
936 }
937
938 #[test]
939 fn test_lease_without_cwd_field_deserializes_with_empty_cwd() {
940 let mut value = serde_json::to_value(sample_lease()).unwrap();
941 value.as_object_mut().unwrap().remove("cwd");
942 let lease: Lease = serde_json::from_value(value).unwrap();
943 assert_eq!(lease.cwd, "");
944 }
945
946 #[test]
947 fn test_job_run_json_round_trip_preserves_every_field() {
948 let usage = ResourceUsage {
949 cores: 6.5,
950 ram_mb: 2800,
951 gpu_pct: 0.0,
952 vram_mb: 0,
953 };
954 assert_json_round_trip(&JobRun {
955 lease_id: Some(LeaseId(3)),
956 session: Some(SessionKey("3f2a9c1e-session".into())),
957 end_cause: Some(EndCause::Killed),
958 fingerprint: r"cargo build -p allotd|e:\work\app".into(),
959 command: "cargo build -p allotd 2>&1".into(),
960 cwd: r"E:\work\app".into(),
961 declared: profile_with(8.0, 0.0),
962 peak: usage,
963 avg: usage,
964 busy: Some(BusyUsage {
965 cores: 7.25,
966 gpu_pct: 0.0,
967 }),
968 started_at_ms: 1_793_000_000_000,
969 ended_at_ms: 1_793_000_095_000,
970 noise: None,
971 overlapped: true,
972 });
973 }
974
975 #[test]
976 fn test_job_profile_invalid_reason_in_range_is_none() {
977 assert_eq!(profile_with(0.0, 0.0).invalid_reason(), None);
978 assert_eq!(profile_with(16.0, 100.0).invalid_reason(), None);
979 }
980
981 #[test]
982 fn test_job_profile_invalid_reason_out_of_range_names_field() {
983 assert!(
984 profile_with(-1.0, 0.0)
985 .invalid_reason()
986 .unwrap()
987 .contains("cores")
988 );
989 assert!(
990 profile_with(f32::NAN, 0.0)
991 .invalid_reason()
992 .unwrap()
993 .contains("cores")
994 );
995 assert!(
996 profile_with(1.0, 101.0)
997 .invalid_reason()
998 .unwrap()
999 .contains("gpu_pct")
1000 );
1001 assert!(
1002 profile_with(1.0, f32::NAN)
1003 .invalid_reason()
1004 .unwrap()
1005 .contains("gpu_pct")
1006 );
1007 }
1008}