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 #[serde(default)]
216 pub cores_10s: f32,
217 pub processes: Vec<ProcessUsage>,
219}
220
221#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
223pub struct Snapshot {
224 pub taken_at_ms: i64,
226 pub cpu: CpuStats,
228 pub memory: MemStats,
230 pub gpus: Vec<GpuAdapter>,
232 pub sessions: Vec<SessionUsage>,
234 pub unattributed: ResourceUsage,
236 #[serde(default, skip_serializing_if = "Vec::is_empty")]
238 pub drives: Vec<DriveUsage>,
239}
240
241#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
243#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
244pub struct DriveUsage {
245 pub name: String,
248 pub total_mb: u64,
250 pub used_mb: u64,
252 pub read_bytes_per_sec: u64,
254 pub write_bytes_per_sec: u64,
256}
257
258#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
260#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
261pub struct JobProfile {
262 pub cores: f32,
264 pub ram_mb: u64,
266 pub gpu_pct: f32,
268 pub vram_mb: u64,
270 pub est_secs: u64,
272}
273
274impl JobProfile {
275 pub fn invalid_reason(&self) -> Option<&'static str> {
277 if !(self.cores.is_finite() && self.cores >= 0.0) {
278 Some("cores must be a finite number of at least 0")
279 } else if !(0.0..=100.0).contains(&self.gpu_pct) {
280 Some("gpu_pct must be between 0 and 100")
281 } else {
282 None
283 }
284 }
285
286 pub fn default_min_cores(&self) -> f32 {
289 (self.cores / 2.0).max(self.cores.min(1.0))
290 }
291
292 pub fn min_cores_reason(&self, min_cores: f32) -> Option<&'static str> {
295 if !(min_cores.is_finite() && min_cores > 0.0) {
296 Some("min_cores must be a finite number above 0")
297 } else if min_cores > self.cores {
298 Some("min_cores must be at most cores")
299 } else {
300 None
301 }
302 }
303
304 pub fn is_quick(&self) -> bool {
307 self.est_secs <= QUICK_MAX_SECS
308 }
309
310 pub fn is_low_impact(&self) -> bool {
313 self.cores <= LOW_IMPACT_MAX_CORES
314 && self.ram_mb <= LOW_IMPACT_MAX_RAM_MB
315 && self.gpu_pct == 0.0
316 && self.vram_mb == 0
317 }
318}
319
320pub const QUICK_MAX_SECS: u64 = 15;
322
323pub const LOW_IMPACT_MAX_CORES: f32 = 0.25;
325
326pub const LOW_IMPACT_MAX_RAM_MB: u64 = 256;
328
329#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
331#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
332#[serde(rename_all = "snake_case")]
333#[non_exhaustive]
334pub enum JobClass {
335 Light,
337 CpuHeavy,
339 GpuHeavy,
341 Mixed,
343}
344
345impl JobClass {
346 pub const ALL: [Self; 4] = [Self::Light, Self::CpuHeavy, Self::GpuHeavy, Self::Mixed];
348
349 pub fn as_str(self) -> &'static str {
351 match self {
352 Self::Light => "light",
353 Self::CpuHeavy => "cpu_heavy",
354 Self::GpuHeavy => "gpu_heavy",
355 Self::Mixed => "mixed",
356 }
357 }
358}
359
360#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
362#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
363#[serde(rename_all = "snake_case")]
364#[non_exhaustive]
365pub enum LeaseKind {
366 Normal,
368 BenchmarkExclusive,
370}
371
372impl LeaseKind {
373 pub const ALL: [Self; 2] = [Self::Normal, Self::BenchmarkExclusive];
375
376 pub fn as_str(self) -> &'static str {
378 match self {
379 Self::Normal => "normal",
380 Self::BenchmarkExclusive => "benchmark_exclusive",
381 }
382 }
383}
384
385#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
387#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
388#[serde(rename_all = "snake_case")]
389#[non_exhaustive]
390pub enum LeaseState {
391 Queued,
393 Active,
395 Released,
397 Expired,
399}
400
401impl LeaseState {
402 pub const ALL: [Self; 4] = [Self::Queued, Self::Active, Self::Released, Self::Expired];
404
405 pub fn as_str(self) -> &'static str {
407 match self {
408 Self::Queued => "queued",
409 Self::Active => "active",
410 Self::Released => "released",
411 Self::Expired => "expired",
412 }
413 }
414}
415
416#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
421#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
422#[serde(rename_all = "snake_case")]
423#[non_exhaustive]
424pub enum EndCause {
425 Released,
427 Expired,
429 Killed,
431 Removed,
433}
434
435impl EndCause {
436 pub const ALL: [Self; 4] = [Self::Released, Self::Expired, Self::Killed, Self::Removed];
438
439 pub fn as_str(self) -> &'static str {
441 match self {
442 Self::Released => "released",
443 Self::Expired => "expired",
444 Self::Killed => "killed",
445 Self::Removed => "removed",
446 }
447 }
448
449 pub fn ended_state(self) -> LeaseState {
453 match self {
454 Self::Released => LeaseState::Released,
455 Self::Expired | Self::Killed | Self::Removed => LeaseState::Expired,
456 }
457 }
458
459 pub fn is_notice(self) -> bool {
461 matches!(self, Self::Killed | Self::Removed)
462 }
463}
464
465#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
467#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
468pub struct Lease {
469 pub id: LeaseId,
471 pub holder: Holder,
473 pub kind: LeaseKind,
475 pub state: LeaseState,
477 pub class: Option<JobClass>,
479 pub profile: JobProfile,
482 #[serde(default, skip_serializing_if = "Option::is_none")]
485 pub asked_cores: Option<f32>,
486 #[serde(default, skip_serializing_if = "Option::is_none")]
489 pub min_cores: Option<f32>,
490 #[serde(default, skip_serializing_if = "Option::is_none")]
494 pub declared_cores: Option<f32>,
495 pub label: String,
497 #[serde(default)]
499 pub cwd: String,
500 pub requested_at_ms: i64,
502 pub granted_at_ms: Option<i64>,
504 pub ended_at_ms: Option<i64>,
506 pub expires_at_ms: i64,
508 #[serde(default, skip_serializing_if = "Option::is_none")]
511 pub end_cause: Option<EndCause>,
512 #[serde(default, skip_serializing_if = "Option::is_none")]
515 pub binding: Option<LeaseBinding>,
516 #[serde(default, skip_serializing_if = "Option::is_none")]
519 pub isolation: Option<LeaseIsolation>,
520}
521
522impl Lease {
523 pub fn asked_profile(&self) -> JobProfile {
526 JobProfile {
527 cores: self.asked_cores.unwrap_or(self.profile.cores),
528 ..self.profile
529 }
530 }
531}
532
533#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
535#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
536pub struct LeaseIsolation {
537 pub kind: IsolationKind,
539 pub scope: Option<String>,
542 pub limits: EnforcedLimits,
544}
545
546#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
548#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
549#[serde(rename_all = "snake_case")]
550#[non_exhaustive]
551pub enum IsolationKind {
552 Cgroup,
554 Tree,
556}
557
558#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
560#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
561pub struct EnforcedLimits {
562 pub cpu_cores: Option<f32>,
564 pub memory_high_mb: Option<u64>,
566 pub memory_max_mb: Option<u64>,
568}
569
570pub(crate) fn is_default<T: Default + PartialEq>(value: &T) -> bool {
572 *value == T::default()
573}
574
575#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
578#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
579pub struct LeaseBinding {
580 pub tool_use_id: String,
582 pub bound_at_ms: i64,
585 pub root: Option<BoundProcess>,
587}
588
589#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
591#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
592pub struct BoundProcess {
593 pub pid: u32,
595 pub start_time: u64,
597}
598
599#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
605#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
606pub struct NoiseReport {
607 pub avg_cpu_pct: f32,
609 pub peak_cpu_pct: f32,
611 pub avg_gpu_pct: f32,
613 pub peak_gpu_pct: f32,
615 pub quiet_at_start: bool,
618}
619
620#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
623#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
624pub struct BusyUsage {
625 pub cores: f32,
627 pub gpu_pct: f32,
629}
630
631#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
633#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
634pub struct JobRun {
635 pub lease_id: Option<LeaseId>,
637 #[serde(default, skip_serializing_if = "Option::is_none")]
639 pub session: Option<SessionKey>,
640 #[serde(default, skip_serializing_if = "Option::is_none")]
642 pub end_cause: Option<EndCause>,
643 pub fingerprint: String,
645 pub command: String,
647 pub cwd: String,
649 pub declared: JobProfile,
651 pub peak: ResourceUsage,
653 pub avg: ResourceUsage,
655 #[serde(default, skip_serializing_if = "Option::is_none")]
658 pub busy: Option<BusyUsage>,
659 pub started_at_ms: i64,
661 pub ended_at_ms: i64,
663 pub noise: Option<NoiseReport>,
665 pub overlapped: bool,
668}
669
670#[cfg(test)]
671mod tests {
672 use super::*;
673 use crate::test_support::{assert_json_round_trip, sample_lease, sample_snapshot};
674
675 fn profile_with(cores: f32, gpu_pct: f32) -> JobProfile {
676 JobProfile {
677 cores,
678 ram_mb: 1024,
679 gpu_pct,
680 vram_mb: 0,
681 est_secs: 60,
682 }
683 }
684
685 #[test]
686 fn test_snapshot_json_round_trip_preserves_every_field() {
687 assert_json_round_trip(&sample_snapshot());
688 }
689
690 #[test]
691 fn test_lease_json_round_trip_preserves_every_field() {
692 assert_json_round_trip(&sample_lease());
693 }
694
695 #[test]
696 fn test_lease_json_uses_snake_case_enums_and_bare_ids() {
697 let value = serde_json::to_value(sample_lease()).unwrap();
698 assert_eq!(value["id"], 7);
699 assert_eq!(value["holder"]["session"], "3f2a9c1e-session");
700 assert_eq!(value["kind"], "benchmark_exclusive");
701 assert_eq!(value["state"], "active");
702 assert_eq!(value["class"], "cpu_heavy");
703 }
704
705 #[test]
706 fn test_enum_as_str_matches_serde_name() {
707 for class in JobClass::ALL {
708 assert_eq!(serde_json::to_value(class).unwrap(), class.as_str());
709 }
710 for kind in LeaseKind::ALL {
711 assert_eq!(serde_json::to_value(kind).unwrap(), kind.as_str());
712 }
713 for state in LeaseState::ALL {
714 assert_eq!(serde_json::to_value(state).unwrap(), state.as_str());
715 }
716 for cause in EndCause::ALL {
717 assert_eq!(serde_json::to_value(cause).unwrap(), cause.as_str());
718 }
719 }
720
721 #[test]
722 fn test_lease_with_end_cause_round_trips_and_writes_snake_case() {
723 let lease = Lease {
724 state: LeaseState::Released,
725 ended_at_ms: Some(1_793_000_090_000),
726 end_cause: Some(EndCause::Killed),
727 ..sample_lease()
728 };
729 assert_json_round_trip(&lease);
730 assert_eq!(serde_json::to_value(&lease).unwrap()["end_cause"], "killed");
731 }
732
733 #[test]
734 fn test_lease_without_end_cause_omits_the_field() {
735 let value = serde_json::to_value(sample_lease()).unwrap();
736 assert!(value.get("end_cause").is_none());
737 assert!(value.get("binding").is_none());
738 }
739
740 #[test]
741 fn test_lease_with_asked_and_min_cores_round_trips_and_omits_them_when_unknown() {
742 let lease = Lease {
743 asked_cores: Some(8.0),
744 min_cores: Some(4.0),
745 declared_cores: None,
746 ..sample_lease()
747 };
748 assert_json_round_trip(&lease);
749 let value = serde_json::to_value(&lease).unwrap();
750 assert_eq!(value["asked_cores"], 8.0);
751 assert_eq!(value["min_cores"], 4.0);
752 let unknown = serde_json::to_value(sample_lease()).unwrap();
753 assert!(unknown.get("asked_cores").is_none());
754 assert!(unknown.get("min_cores").is_none());
755 }
756
757 #[test]
758 fn test_lease_with_binding_round_trips_with_and_without_root() {
759 let pending = LeaseBinding {
760 tool_use_id: "toolu_01AbC".into(),
761 bound_at_ms: 1_793_000_013_000,
762 root: None,
763 };
764 let bound = LeaseBinding {
765 root: Some(BoundProcess {
766 pid: 30_112,
767 start_time: 1_793_000_013,
768 }),
769 ..pending.clone()
770 };
771 for binding in [pending, bound] {
772 assert_json_round_trip(&Lease {
773 binding: Some(binding),
774 ..sample_lease()
775 });
776 }
777 }
778
779 #[test]
780 fn test_v0_1_shapes_decode_without_new_fields() {
781 let mut lease = serde_json::to_value(sample_lease()).unwrap();
782 lease.as_object_mut().unwrap().remove("end_cause");
783 let lease: Lease = serde_json::from_value(lease).unwrap();
784 assert_eq!(lease.end_cause, None);
785 assert_eq!(lease.binding, None);
786 assert_eq!(lease.isolation, None);
787 assert_eq!((lease.asked_cores, lease.min_cores), (None, None));
788
789 let mut snapshot = serde_json::to_value(sample_snapshot()).unwrap();
790 snapshot.as_object_mut().unwrap().remove("drives");
791 snapshot["sessions"][0]["processes"][0]
792 .as_object_mut()
793 .unwrap()
794 .remove("exe");
795 let snapshot: Snapshot = serde_json::from_value(snapshot).unwrap();
796 assert!(snapshot.drives.is_empty());
797 assert_eq!(snapshot.sessions[0].processes[0].exe, None);
798 }
799
800 #[test]
801 fn test_windows_adapter_and_lease_omit_every_cross_platform_field() {
802 let snapshot = serde_json::to_value(sample_snapshot()).unwrap();
803 let gpu = snapshot["gpus"][0].as_object().unwrap();
804 for field in ["unified_memory", "source", "process_load", "process_memory"] {
805 assert!(gpu.get(field).is_none(), "{field}");
806 }
807 let lease = serde_json::to_value(sample_lease()).unwrap();
808 assert!(lease.get("isolation").is_none());
809 }
810
811 #[test]
812 fn test_adapter_from_an_older_allotd_is_a_windows_adapter() {
813 let mut value = serde_json::to_value(&sample_snapshot().gpus[0]).unwrap();
814 let object = value.as_object_mut().unwrap();
815 for field in ["unified_memory", "source", "process_load", "process_memory"] {
816 object.remove(field);
817 }
818 let gpu: GpuAdapter = serde_json::from_value(value).unwrap();
819 assert!(!gpu.unified_memory);
820 assert_eq!(gpu.source, GpuSource::Pdh);
821 assert_eq!(gpu.process_load, Accuracy::Exact);
822 assert_eq!(gpu.process_memory, Accuracy::Exact);
823 }
824
825 #[test]
826 fn test_unified_adapter_round_trips_and_writes_snake_case() {
827 let gpu = GpuAdapter {
828 name: "Apple M3 Max".into(),
829 luid: "4294969310".into(),
830 dedicated_used_mb: 9_216,
831 dedicated_total_mb: None,
832 shared_used_mb: 0,
833 unified_memory: true,
834 source: GpuSource::Iokit,
835 process_load: Accuracy::Estimated,
836 process_memory: Accuracy::Unavailable,
837 ..sample_snapshot().gpus[0].clone()
838 };
839 assert_json_round_trip(&gpu);
840 let value = serde_json::to_value(&gpu).unwrap();
841 assert_eq!(value["unified_memory"], true);
842 assert_eq!(value["source"], "iokit");
843 assert_eq!(value["process_load"], "estimated");
844 assert_eq!(value["process_memory"], "unavailable");
845 let fdinfo = serde_json::to_value(GpuSource::DrmFdinfo).unwrap();
846 assert_eq!(fdinfo, "drm_fdinfo");
847 }
848
849 #[test]
850 fn test_lease_with_isolation_round_trips_for_cgroup_and_tree() {
851 let cgroup = LeaseIsolation {
852 kind: IsolationKind::Cgroup,
853 scope: Some("allot-lease-7.scope".into()),
854 limits: EnforcedLimits {
855 cpu_cores: Some(8.0),
856 memory_high_mb: Some(4096),
857 memory_max_mb: Some(6144),
858 },
859 };
860 let tree = LeaseIsolation {
861 kind: IsolationKind::Tree,
862 scope: None,
863 limits: EnforcedLimits::default(),
864 };
865 for isolation in [cgroup, tree] {
866 assert_json_round_trip(&Lease {
867 isolation: Some(isolation),
868 ..sample_lease()
869 });
870 }
871 let value = serde_json::to_value(Lease {
872 isolation: Some(LeaseIsolation {
873 kind: IsolationKind::Tree,
874 scope: None,
875 limits: EnforcedLimits::default(),
876 }),
877 ..sample_lease()
878 })
879 .unwrap();
880 assert_eq!(value["isolation"]["kind"], "tree");
881 assert!(value["isolation"]["scope"].is_null());
882 assert!(value["isolation"]["limits"]["memory_max_mb"].is_null());
883 }
884
885 #[test]
886 fn test_snapshot_without_drives_and_exe_omits_both_fields() {
887 let mut snapshot = sample_snapshot();
888 snapshot.drives.clear();
889 snapshot.sessions[0].processes[0].exe = None;
890 let value = serde_json::to_value(snapshot).unwrap();
891 assert!(value.get("drives").is_none());
892 assert!(value["sessions"][0]["processes"][0].get("exe").is_none());
893 }
894
895 #[test]
896 fn test_gpu_engines_busiest_reads_the_picked_window_of_the_busiest_group() {
897 let rolling = |avg_1s, avg_10s| Rolling {
898 avg_1s,
899 avg_10s,
900 avg_60s: 0.0,
901 };
902 let engines = GpuEngines {
903 three_d_pct: rolling(12.0, 40.0),
904 compute_pct: rolling(55.5, 20.0),
905 copy_pct: rolling(1.0, 1.0),
906 video_pct: rolling(0.0, 0.0),
907 };
908 assert_eq!(engines.busiest(|load| load.avg_1s), 55.5);
909 assert_eq!(engines.busiest(|load| load.avg_10s), 40.0);
910 assert_eq!(GpuEngines::default().busiest(|load| load.avg_1s), 0.0);
911 }
912
913 #[test]
914 fn test_resource_usage_add_assign_sums_every_field() {
915 let mut total = ResourceUsage {
916 cores: 1.5,
917 ram_mb: 100,
918 gpu_pct: 10.0,
919 vram_mb: 64,
920 };
921 total += ResourceUsage {
922 cores: 2.25,
923 ram_mb: 50,
924 gpu_pct: 5.5,
925 vram_mb: 0,
926 };
927 assert_eq!(
928 total,
929 ResourceUsage {
930 cores: 3.75,
931 ram_mb: 150,
932 gpu_pct: 15.5,
933 vram_mb: 64,
934 }
935 );
936 }
937
938 #[test]
939 fn test_noise_report_json_round_trip_preserves_every_field() {
940 assert_json_round_trip(&NoiseReport {
941 avg_cpu_pct: 2.5,
942 peak_cpu_pct: 9.0,
943 avg_gpu_pct: 0.5,
944 peak_gpu_pct: 3.25,
945 quiet_at_start: false,
946 });
947 }
948
949 #[test]
950 fn test_lease_without_cwd_field_deserializes_with_empty_cwd() {
951 let mut value = serde_json::to_value(sample_lease()).unwrap();
952 value.as_object_mut().unwrap().remove("cwd");
953 let lease: Lease = serde_json::from_value(value).unwrap();
954 assert_eq!(lease.cwd, "");
955 }
956
957 #[test]
958 fn test_job_run_json_round_trip_preserves_every_field() {
959 let usage = ResourceUsage {
960 cores: 6.5,
961 ram_mb: 2800,
962 gpu_pct: 0.0,
963 vram_mb: 0,
964 };
965 assert_json_round_trip(&JobRun {
966 lease_id: Some(LeaseId(3)),
967 session: Some(SessionKey("3f2a9c1e-session".into())),
968 end_cause: Some(EndCause::Killed),
969 fingerprint: r"cargo build -p allotd|e:\work\app".into(),
970 command: "cargo build -p allotd 2>&1".into(),
971 cwd: r"E:\work\app".into(),
972 declared: profile_with(8.0, 0.0),
973 peak: usage,
974 avg: usage,
975 busy: Some(BusyUsage {
976 cores: 7.25,
977 gpu_pct: 0.0,
978 }),
979 started_at_ms: 1_793_000_000_000,
980 ended_at_ms: 1_793_000_095_000,
981 noise: None,
982 overlapped: true,
983 });
984 }
985
986 #[test]
987 fn test_job_profile_invalid_reason_in_range_is_none() {
988 assert_eq!(profile_with(0.0, 0.0).invalid_reason(), None);
989 assert_eq!(profile_with(16.0, 100.0).invalid_reason(), None);
990 }
991
992 #[test]
993 fn test_job_profile_invalid_reason_out_of_range_names_field() {
994 assert!(
995 profile_with(-1.0, 0.0)
996 .invalid_reason()
997 .unwrap()
998 .contains("cores")
999 );
1000 assert!(
1001 profile_with(f32::NAN, 0.0)
1002 .invalid_reason()
1003 .unwrap()
1004 .contains("cores")
1005 );
1006 assert!(
1007 profile_with(1.0, 101.0)
1008 .invalid_reason()
1009 .unwrap()
1010 .contains("gpu_pct")
1011 );
1012 assert!(
1013 profile_with(1.0, f32::NAN)
1014 .invalid_reason()
1015 .unwrap()
1016 .contains("gpu_pct")
1017 );
1018 }
1019}