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 is_quick(&self) -> bool {
284 self.est_secs <= QUICK_MAX_SECS
285 }
286
287 pub fn is_low_impact(&self) -> bool {
290 self.cores <= LOW_IMPACT_MAX_CORES
291 && self.ram_mb <= LOW_IMPACT_MAX_RAM_MB
292 && self.gpu_pct == 0.0
293 && self.vram_mb == 0
294 }
295}
296
297pub const QUICK_MAX_SECS: u64 = 15;
299
300pub const LOW_IMPACT_MAX_CORES: f32 = 0.25;
302
303pub const LOW_IMPACT_MAX_RAM_MB: u64 = 256;
305
306#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
308#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
309#[serde(rename_all = "snake_case")]
310#[non_exhaustive]
311pub enum JobClass {
312 Light,
314 CpuHeavy,
316 GpuHeavy,
318 Mixed,
320}
321
322impl JobClass {
323 pub const ALL: [Self; 4] = [Self::Light, Self::CpuHeavy, Self::GpuHeavy, Self::Mixed];
325
326 pub fn as_str(self) -> &'static str {
328 match self {
329 Self::Light => "light",
330 Self::CpuHeavy => "cpu_heavy",
331 Self::GpuHeavy => "gpu_heavy",
332 Self::Mixed => "mixed",
333 }
334 }
335}
336
337#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
339#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
340#[serde(rename_all = "snake_case")]
341#[non_exhaustive]
342pub enum LeaseKind {
343 Normal,
345 BenchmarkExclusive,
347}
348
349impl LeaseKind {
350 pub const ALL: [Self; 2] = [Self::Normal, Self::BenchmarkExclusive];
352
353 pub fn as_str(self) -> &'static str {
355 match self {
356 Self::Normal => "normal",
357 Self::BenchmarkExclusive => "benchmark_exclusive",
358 }
359 }
360}
361
362#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
364#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
365#[serde(rename_all = "snake_case")]
366#[non_exhaustive]
367pub enum LeaseState {
368 Queued,
370 Active,
372 Released,
374 Expired,
376}
377
378impl LeaseState {
379 pub const ALL: [Self; 4] = [Self::Queued, Self::Active, Self::Released, Self::Expired];
381
382 pub fn as_str(self) -> &'static str {
384 match self {
385 Self::Queued => "queued",
386 Self::Active => "active",
387 Self::Released => "released",
388 Self::Expired => "expired",
389 }
390 }
391}
392
393#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
398#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
399#[serde(rename_all = "snake_case")]
400#[non_exhaustive]
401pub enum EndCause {
402 Released,
404 Expired,
406 Killed,
408 Removed,
410}
411
412impl EndCause {
413 pub const ALL: [Self; 4] = [Self::Released, Self::Expired, Self::Killed, Self::Removed];
415
416 pub fn as_str(self) -> &'static str {
418 match self {
419 Self::Released => "released",
420 Self::Expired => "expired",
421 Self::Killed => "killed",
422 Self::Removed => "removed",
423 }
424 }
425
426 pub fn ended_state(self) -> LeaseState {
430 match self {
431 Self::Released => LeaseState::Released,
432 Self::Expired | Self::Killed | Self::Removed => LeaseState::Expired,
433 }
434 }
435
436 pub fn is_notice(self) -> bool {
438 matches!(self, Self::Killed | Self::Removed)
439 }
440}
441
442#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
444#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
445pub struct Lease {
446 pub id: LeaseId,
448 pub holder: Holder,
450 pub kind: LeaseKind,
452 pub state: LeaseState,
454 pub class: Option<JobClass>,
456 pub profile: JobProfile,
458 pub label: String,
460 #[serde(default)]
462 pub cwd: String,
463 pub requested_at_ms: i64,
465 pub granted_at_ms: Option<i64>,
467 pub ended_at_ms: Option<i64>,
469 pub expires_at_ms: i64,
471 #[serde(default, skip_serializing_if = "Option::is_none")]
474 pub end_cause: Option<EndCause>,
475 #[serde(default, skip_serializing_if = "Option::is_none")]
478 pub binding: Option<LeaseBinding>,
479 #[serde(default, skip_serializing_if = "Option::is_none")]
482 pub isolation: Option<LeaseIsolation>,
483}
484
485#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
487#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
488pub struct LeaseIsolation {
489 pub kind: IsolationKind,
491 pub scope: Option<String>,
494 pub limits: EnforcedLimits,
496}
497
498#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
500#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
501#[serde(rename_all = "snake_case")]
502#[non_exhaustive]
503pub enum IsolationKind {
504 Cgroup,
506 Tree,
508}
509
510#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
512#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
513pub struct EnforcedLimits {
514 pub cpu_cores: Option<f32>,
516 pub memory_high_mb: Option<u64>,
518 pub memory_max_mb: Option<u64>,
520}
521
522pub(crate) fn is_default<T: Default + PartialEq>(value: &T) -> bool {
524 *value == T::default()
525}
526
527#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
530#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
531pub struct LeaseBinding {
532 pub tool_use_id: String,
534 pub bound_at_ms: i64,
537 pub root: Option<BoundProcess>,
539}
540
541#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
543#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
544pub struct BoundProcess {
545 pub pid: u32,
547 pub start_time: u64,
549}
550
551#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
557#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
558pub struct NoiseReport {
559 pub avg_cpu_pct: f32,
561 pub peak_cpu_pct: f32,
563 pub avg_gpu_pct: f32,
565 pub peak_gpu_pct: f32,
567 pub quiet_at_start: bool,
570}
571
572#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
575#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
576pub struct BusyUsage {
577 pub cores: f32,
579 pub gpu_pct: f32,
581}
582
583#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
585#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
586pub struct JobRun {
587 pub lease_id: Option<LeaseId>,
589 #[serde(default, skip_serializing_if = "Option::is_none")]
591 pub session: Option<SessionKey>,
592 #[serde(default, skip_serializing_if = "Option::is_none")]
594 pub end_cause: Option<EndCause>,
595 pub fingerprint: String,
597 pub command: String,
599 pub cwd: String,
601 pub declared: JobProfile,
603 pub peak: ResourceUsage,
605 pub avg: ResourceUsage,
607 #[serde(default, skip_serializing_if = "Option::is_none")]
610 pub busy: Option<BusyUsage>,
611 pub started_at_ms: i64,
613 pub ended_at_ms: i64,
615 pub noise: Option<NoiseReport>,
617 pub overlapped: bool,
620}
621
622#[cfg(test)]
623mod tests {
624 use super::*;
625 use crate::test_support::{assert_json_round_trip, sample_lease, sample_snapshot};
626
627 fn profile_with(cores: f32, gpu_pct: f32) -> JobProfile {
628 JobProfile {
629 cores,
630 ram_mb: 1024,
631 gpu_pct,
632 vram_mb: 0,
633 est_secs: 60,
634 }
635 }
636
637 #[test]
638 fn test_snapshot_json_round_trip_preserves_every_field() {
639 assert_json_round_trip(&sample_snapshot());
640 }
641
642 #[test]
643 fn test_lease_json_round_trip_preserves_every_field() {
644 assert_json_round_trip(&sample_lease());
645 }
646
647 #[test]
648 fn test_lease_json_uses_snake_case_enums_and_bare_ids() {
649 let value = serde_json::to_value(sample_lease()).unwrap();
650 assert_eq!(value["id"], 7);
651 assert_eq!(value["holder"]["session"], "3f2a9c1e-session");
652 assert_eq!(value["kind"], "benchmark_exclusive");
653 assert_eq!(value["state"], "active");
654 assert_eq!(value["class"], "cpu_heavy");
655 }
656
657 #[test]
658 fn test_enum_as_str_matches_serde_name() {
659 for class in JobClass::ALL {
660 assert_eq!(serde_json::to_value(class).unwrap(), class.as_str());
661 }
662 for kind in LeaseKind::ALL {
663 assert_eq!(serde_json::to_value(kind).unwrap(), kind.as_str());
664 }
665 for state in LeaseState::ALL {
666 assert_eq!(serde_json::to_value(state).unwrap(), state.as_str());
667 }
668 for cause in EndCause::ALL {
669 assert_eq!(serde_json::to_value(cause).unwrap(), cause.as_str());
670 }
671 }
672
673 #[test]
674 fn test_lease_with_end_cause_round_trips_and_writes_snake_case() {
675 let lease = Lease {
676 state: LeaseState::Released,
677 ended_at_ms: Some(1_793_000_090_000),
678 end_cause: Some(EndCause::Killed),
679 ..sample_lease()
680 };
681 assert_json_round_trip(&lease);
682 assert_eq!(serde_json::to_value(&lease).unwrap()["end_cause"], "killed");
683 }
684
685 #[test]
686 fn test_lease_without_end_cause_omits_the_field() {
687 let value = serde_json::to_value(sample_lease()).unwrap();
688 assert!(value.get("end_cause").is_none());
689 assert!(value.get("binding").is_none());
690 }
691
692 #[test]
693 fn test_lease_with_binding_round_trips_with_and_without_root() {
694 let pending = LeaseBinding {
695 tool_use_id: "toolu_01AbC".into(),
696 bound_at_ms: 1_793_000_013_000,
697 root: None,
698 };
699 let bound = LeaseBinding {
700 root: Some(BoundProcess {
701 pid: 30_112,
702 start_time: 1_793_000_013,
703 }),
704 ..pending.clone()
705 };
706 for binding in [pending, bound] {
707 assert_json_round_trip(&Lease {
708 binding: Some(binding),
709 ..sample_lease()
710 });
711 }
712 }
713
714 #[test]
715 fn test_v0_1_shapes_decode_without_new_fields() {
716 let mut lease = serde_json::to_value(sample_lease()).unwrap();
717 lease.as_object_mut().unwrap().remove("end_cause");
718 let lease: Lease = serde_json::from_value(lease).unwrap();
719 assert_eq!(lease.end_cause, None);
720 assert_eq!(lease.binding, None);
721 assert_eq!(lease.isolation, None);
722
723 let mut snapshot = serde_json::to_value(sample_snapshot()).unwrap();
724 snapshot.as_object_mut().unwrap().remove("drives");
725 snapshot["sessions"][0]["processes"][0]
726 .as_object_mut()
727 .unwrap()
728 .remove("exe");
729 let snapshot: Snapshot = serde_json::from_value(snapshot).unwrap();
730 assert!(snapshot.drives.is_empty());
731 assert_eq!(snapshot.sessions[0].processes[0].exe, None);
732 }
733
734 #[test]
735 fn test_windows_adapter_and_lease_omit_every_cross_platform_field() {
736 let snapshot = serde_json::to_value(sample_snapshot()).unwrap();
737 let gpu = snapshot["gpus"][0].as_object().unwrap();
738 for field in ["unified_memory", "source", "process_load", "process_memory"] {
739 assert!(gpu.get(field).is_none(), "{field}");
740 }
741 let lease = serde_json::to_value(sample_lease()).unwrap();
742 assert!(lease.get("isolation").is_none());
743 }
744
745 #[test]
746 fn test_adapter_from_an_older_allotd_is_a_windows_adapter() {
747 let mut value = serde_json::to_value(&sample_snapshot().gpus[0]).unwrap();
748 let object = value.as_object_mut().unwrap();
749 for field in ["unified_memory", "source", "process_load", "process_memory"] {
750 object.remove(field);
751 }
752 let gpu: GpuAdapter = serde_json::from_value(value).unwrap();
753 assert!(!gpu.unified_memory);
754 assert_eq!(gpu.source, GpuSource::Pdh);
755 assert_eq!(gpu.process_load, Accuracy::Exact);
756 assert_eq!(gpu.process_memory, Accuracy::Exact);
757 }
758
759 #[test]
760 fn test_unified_adapter_round_trips_and_writes_snake_case() {
761 let gpu = GpuAdapter {
762 name: "Apple M3 Max".into(),
763 luid: "4294969310".into(),
764 dedicated_used_mb: 9_216,
765 dedicated_total_mb: None,
766 shared_used_mb: 0,
767 unified_memory: true,
768 source: GpuSource::Iokit,
769 process_load: Accuracy::Estimated,
770 process_memory: Accuracy::Unavailable,
771 ..sample_snapshot().gpus[0].clone()
772 };
773 assert_json_round_trip(&gpu);
774 let value = serde_json::to_value(&gpu).unwrap();
775 assert_eq!(value["unified_memory"], true);
776 assert_eq!(value["source"], "iokit");
777 assert_eq!(value["process_load"], "estimated");
778 assert_eq!(value["process_memory"], "unavailable");
779 let fdinfo = serde_json::to_value(GpuSource::DrmFdinfo).unwrap();
780 assert_eq!(fdinfo, "drm_fdinfo");
781 }
782
783 #[test]
784 fn test_lease_with_isolation_round_trips_for_cgroup_and_tree() {
785 let cgroup = LeaseIsolation {
786 kind: IsolationKind::Cgroup,
787 scope: Some("allot-lease-7.scope".into()),
788 limits: EnforcedLimits {
789 cpu_cores: Some(8.0),
790 memory_high_mb: Some(4096),
791 memory_max_mb: Some(6144),
792 },
793 };
794 let tree = LeaseIsolation {
795 kind: IsolationKind::Tree,
796 scope: None,
797 limits: EnforcedLimits::default(),
798 };
799 for isolation in [cgroup, tree] {
800 assert_json_round_trip(&Lease {
801 isolation: Some(isolation),
802 ..sample_lease()
803 });
804 }
805 let value = serde_json::to_value(Lease {
806 isolation: Some(LeaseIsolation {
807 kind: IsolationKind::Tree,
808 scope: None,
809 limits: EnforcedLimits::default(),
810 }),
811 ..sample_lease()
812 })
813 .unwrap();
814 assert_eq!(value["isolation"]["kind"], "tree");
815 assert!(value["isolation"]["scope"].is_null());
816 assert!(value["isolation"]["limits"]["memory_max_mb"].is_null());
817 }
818
819 #[test]
820 fn test_snapshot_without_drives_and_exe_omits_both_fields() {
821 let mut snapshot = sample_snapshot();
822 snapshot.drives.clear();
823 snapshot.sessions[0].processes[0].exe = None;
824 let value = serde_json::to_value(snapshot).unwrap();
825 assert!(value.get("drives").is_none());
826 assert!(value["sessions"][0]["processes"][0].get("exe").is_none());
827 }
828
829 #[test]
830 fn test_gpu_engines_busiest_reads_the_picked_window_of_the_busiest_group() {
831 let rolling = |avg_1s, avg_10s| Rolling {
832 avg_1s,
833 avg_10s,
834 avg_60s: 0.0,
835 };
836 let engines = GpuEngines {
837 three_d_pct: rolling(12.0, 40.0),
838 compute_pct: rolling(55.5, 20.0),
839 copy_pct: rolling(1.0, 1.0),
840 video_pct: rolling(0.0, 0.0),
841 };
842 assert_eq!(engines.busiest(|load| load.avg_1s), 55.5);
843 assert_eq!(engines.busiest(|load| load.avg_10s), 40.0);
844 assert_eq!(GpuEngines::default().busiest(|load| load.avg_1s), 0.0);
845 }
846
847 #[test]
848 fn test_resource_usage_add_assign_sums_every_field() {
849 let mut total = ResourceUsage {
850 cores: 1.5,
851 ram_mb: 100,
852 gpu_pct: 10.0,
853 vram_mb: 64,
854 };
855 total += ResourceUsage {
856 cores: 2.25,
857 ram_mb: 50,
858 gpu_pct: 5.5,
859 vram_mb: 0,
860 };
861 assert_eq!(
862 total,
863 ResourceUsage {
864 cores: 3.75,
865 ram_mb: 150,
866 gpu_pct: 15.5,
867 vram_mb: 64,
868 }
869 );
870 }
871
872 #[test]
873 fn test_noise_report_json_round_trip_preserves_every_field() {
874 assert_json_round_trip(&NoiseReport {
875 avg_cpu_pct: 2.5,
876 peak_cpu_pct: 9.0,
877 avg_gpu_pct: 0.5,
878 peak_gpu_pct: 3.25,
879 quiet_at_start: false,
880 });
881 }
882
883 #[test]
884 fn test_lease_without_cwd_field_deserializes_with_empty_cwd() {
885 let mut value = serde_json::to_value(sample_lease()).unwrap();
886 value.as_object_mut().unwrap().remove("cwd");
887 let lease: Lease = serde_json::from_value(value).unwrap();
888 assert_eq!(lease.cwd, "");
889 }
890
891 #[test]
892 fn test_job_run_json_round_trip_preserves_every_field() {
893 let usage = ResourceUsage {
894 cores: 6.5,
895 ram_mb: 2800,
896 gpu_pct: 0.0,
897 vram_mb: 0,
898 };
899 assert_json_round_trip(&JobRun {
900 lease_id: Some(LeaseId(3)),
901 session: Some(SessionKey("3f2a9c1e-session".into())),
902 end_cause: Some(EndCause::Killed),
903 fingerprint: r"cargo build -p allotd|e:\work\app".into(),
904 command: "cargo build -p allotd 2>&1".into(),
905 cwd: r"E:\work\app".into(),
906 declared: profile_with(8.0, 0.0),
907 peak: usage,
908 avg: usage,
909 busy: Some(BusyUsage {
910 cores: 7.25,
911 gpu_pct: 0.0,
912 }),
913 started_at_ms: 1_793_000_000_000,
914 ended_at_ms: 1_793_000_095_000,
915 noise: None,
916 overlapped: true,
917 });
918 }
919
920 #[test]
921 fn test_job_profile_invalid_reason_in_range_is_none() {
922 assert_eq!(profile_with(0.0, 0.0).invalid_reason(), None);
923 assert_eq!(profile_with(16.0, 100.0).invalid_reason(), None);
924 }
925
926 #[test]
927 fn test_job_profile_invalid_reason_out_of_range_names_field() {
928 assert!(
929 profile_with(-1.0, 0.0)
930 .invalid_reason()
931 .unwrap()
932 .contains("cores")
933 );
934 assert!(
935 profile_with(f32::NAN, 0.0)
936 .invalid_reason()
937 .unwrap()
938 .contains("cores")
939 );
940 assert!(
941 profile_with(1.0, 101.0)
942 .invalid_reason()
943 .unwrap()
944 .contains("gpu_pct")
945 );
946 assert!(
947 profile_with(1.0, f32::NAN)
948 .invalid_reason()
949 .unwrap()
950 .contains("gpu_pct")
951 );
952 }
953}