allot-shared 0.5.0

Internal to Allot, no stable API: protocol, config, and path types
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
use std::ops::AddAssign;

use serde::{Deserialize, Serialize};

/// Identifies a lease. Assigned by the daemon's database when the lease is first stored.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct LeaseId(pub i64);

/// Identifies a Claude Code session by its `CLAUDE_CODE_SESSION_ID`.
///
/// The MCP server reads the value from its environment and the hook reads `session_id` from
/// its stdin JSON; both see the same string.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SessionKey(pub String);

/// The process a session's leases live and die with.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Holder {
    /// Session the leases belong to.
    pub session: SessionKey,
    /// PID of the session's Claude Code process (`claude.exe` on Windows, `claude` elsewhere),
    /// the direct parent of its MCP server and its hooks.
    pub pid: u32,
    /// Start time of `pid` in seconds since the Unix epoch. Every OS reuses PIDs, so a process
    /// with the same PID but another start time is not the holder.
    pub pid_start_time: u64,
}

/// One measurement averaged over the sampler's rolling windows.
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub struct Rolling {
    /// Average over the last second.
    pub avg_1s: f32,
    /// Average over the last 10 seconds.
    pub avg_10s: f32,
    /// Average over the last 60 seconds.
    pub avg_60s: f32,
}

/// Machine-wide CPU load.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CpuStats {
    /// Number of logical processors.
    pub logical_cores: u32,
    /// Total load as a percentage of all logical processors.
    pub usage_pct: Rolling,
    /// Load of each logical processor over the last second.
    pub per_core_pct: Vec<f32>,
}

/// Machine-wide physical memory and commit charge.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemStats {
    /// Installed physical memory.
    pub total_mb: u64,
    /// Physical memory in use.
    pub used_mb: u64,
    /// Physical memory available to new allocations without paging.
    pub available_mb: u64,
    /// Committed virtual memory.
    pub commit_used_mb: u64,
    /// Commit limit: physical memory plus page files.
    pub commit_limit_mb: u64,
    /// The part of `used_mb` the OS gives up for new allocations with no harm to the machine,
    /// which admission does not count as load. Only macOS reports any.
    #[serde(default)]
    pub reclaimable_mb: u64,
}

/// Utilization of one GPU's engine groups, as percentages.
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub struct GpuEngines {
    /// 3D (graphics) engines.
    pub three_d_pct: Rolling,
    /// Compute engines.
    pub compute_pct: Rolling,
    /// Copy engines.
    pub copy_pct: Rolling,
    /// Video encode and decode engines.
    pub video_pct: Rolling,
}

impl GpuEngines {
    /// Load of the busiest engine group, read from the window `pick` selects.
    pub fn busiest(&self, pick: fn(&Rolling) -> f32) -> f32 {
        [
            self.three_d_pct,
            self.compute_pct,
            self.copy_pct,
            self.video_pct,
        ]
        .iter()
        .map(pick)
        .fold(0.0, f32::max)
    }
}

/// One GPU adapter.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GpuAdapter {
    /// Adapter name, for example `NVIDIA GeForce RTX 4070`.
    pub name: String,
    /// Stable ID of the adapter: on Windows its LUID as it appears in PDH instance names, for
    /// example `0x00000000_0x0000d1a2`; other OSes use their own stable ID.
    pub luid: String,
    /// Engine utilization.
    pub engines: GpuEngines,
    /// Dedicated video memory in use. On a unified-memory adapter, the system memory the GPU
    /// has allocated, which RAM use already counts.
    pub dedicated_used_mb: u64,
    /// Dedicated video memory installed, when the OS reports it; `None` on a unified-memory
    /// adapter, which has none of its own.
    pub dedicated_total_mb: Option<u64>,
    /// Shared system memory in use by the adapter.
    pub shared_used_mb: u64,
    /// Whether the adapter's video memory is the machine's RAM, as on Apple Silicon. Admission
    /// then counts video memory against RAM.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub unified_memory: bool,
    /// Where the numbers come from.
    #[serde(default, skip_serializing_if = "is_default")]
    pub source: GpuSource,
    /// How well the source measures each process's engine load.
    #[serde(default, skip_serializing_if = "is_default")]
    pub process_load: Accuracy,
    /// How well the source measures each process's video memory.
    #[serde(default, skip_serializing_if = "is_default")]
    pub process_memory: Accuracy,
}

/// Where a GPU adapter's numbers come from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum GpuSource {
    /// Windows performance counters. allotd builds that do not name a source ran on Windows
    /// only, so a missing source means this.
    #[default]
    Pdh,
    /// NVIDIA's management library, on Linux.
    Nvml,
    /// The DRM drivers' per-client statistics in `/proc/<pid>/fdinfo`, on Linux.
    DrmFdinfo,
    /// IOKit accelerator statistics, on macOS.
    Iokit,
}

/// How well a GPU source measures something per process.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Accuracy {
    /// Measured per process.
    #[default]
    Exact,
    /// Measured, but only roughly; the machine total is the reliable figure.
    Estimated,
    /// Not measured: per-process values read 0.
    Unavailable,
}

/// Resources used by a process or a group of processes, in the units of [`JobProfile`].
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub struct ResourceUsage {
    /// CPU load in logical cores, for example `2.5` for two and a half busy cores.
    pub cores: f32,
    /// Resident memory; on macOS the physical footprint, as Activity Monitor shows it.
    pub ram_mb: u64,
    /// GPU engine load as a percentage of one adapter.
    pub gpu_pct: f32,
    /// Dedicated video memory.
    pub vram_mb: u64,
}

impl AddAssign for ResourceUsage {
    fn add_assign(&mut self, other: Self) {
        self.cores += other.cores;
        self.ram_mb += other.ram_mb;
        self.gpu_pct += other.gpu_pct;
        self.vram_mb += other.vram_mb;
    }
}

/// Usage of a single process.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProcessUsage {
    /// Process ID.
    pub pid: u32,
    /// Executable name, for example `cargo.exe`.
    pub name: String,
    /// Full path of the executable, when the sampler could read it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exe: Option<String>,
    /// Resources the process uses.
    pub usage: ResourceUsage,
}

/// Usage of a session's whole process subtree.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SessionUsage {
    /// The session and its root process.
    pub holder: Holder,
    /// Sum over every process in the subtree.
    pub usage: ResourceUsage,
    /// CPU load of the subtree averaged over the last 10 seconds, in logical cores, or over
    /// the samples since the session was first seen. The machine's `avg_10s` covers the same
    /// window, so the two can be subtracted.
    #[serde(default)]
    pub cores_10s: f32,
    /// The processes in the subtree, busiest first.
    pub processes: Vec<ProcessUsage>,
}

/// A point-in-time view of the machine.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Snapshot {
    /// When the sample was taken, in milliseconds since the Unix epoch.
    pub taken_at_ms: i64,
    /// CPU load.
    pub cpu: CpuStats,
    /// Memory use.
    pub memory: MemStats,
    /// Every GPU adapter.
    pub gpus: Vec<GpuAdapter>,
    /// Usage of each registered session.
    pub sessions: Vec<SessionUsage>,
    /// Usage of processes outside every registered session.
    pub unattributed: ResourceUsage,
    /// Every fixed drive, by drive letter on Windows and by mount point elsewhere.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub drives: Vec<DriveUsage>,
}

/// Space and activity of one fixed drive.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DriveUsage {
    /// Drive letter with its colon on Windows, for example `C:`; mount point elsewhere, for
    /// example `/home`.
    pub name: String,
    /// Capacity of the volume.
    pub total_mb: u64,
    /// Space in use.
    pub used_mb: u64,
    /// Bytes read per second over the last second.
    pub read_bytes_per_sec: u64,
    /// Bytes written per second over the last second.
    pub write_bytes_per_sec: u64,
}

/// Resources a job is expected to need while it runs.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct JobProfile {
    /// Logical cores the job keeps busy.
    pub cores: f32,
    /// Peak resident memory.
    pub ram_mb: u64,
    /// GPU engine load as a percentage of one adapter.
    pub gpu_pct: f32,
    /// Peak dedicated video memory.
    pub vram_mb: u64,
    /// Expected run time.
    pub est_secs: u64,
}

impl JobProfile {
    /// Returns why the profile is unusable, or `None` when every value is in range.
    pub fn invalid_reason(&self) -> Option<&'static str> {
        if !(self.cores.is_finite() && self.cores >= 0.0) {
            Some("cores must be a finite number of at least 0")
        } else if !(0.0..=100.0).contains(&self.gpu_pct) {
            Some("gpu_pct must be between 0 and 100")
        } else {
            None
        }
    }

    /// The minimum of a class or preset that names none: half the cores, but at least one
    /// core, or all of them when there are fewer. `light` (1 core) never shrinks.
    pub fn default_min_cores(&self) -> f32 {
        (self.cores / 2.0).max(self.cores.min(1.0))
    }

    /// Returns why `min_cores` cannot be the fewest cores this profile starts with, or `None`
    /// when `0 < min_cores <= cores`.
    pub fn min_cores_reason(&self, min_cores: f32) -> Option<&'static str> {
        if !(min_cores.is_finite() && min_cores > 0.0) {
            Some("min_cores must be a finite number above 0")
        } else if min_cores > self.cores {
            Some("min_cores must be at most cores")
        } else {
            None
        }
    }

    /// Whether a job of this profile ends within [`QUICK_MAX_SECS`]: a normal lease for it may
    /// start while a benchmark still waits for other leases to end.
    pub fn is_quick(&self) -> bool {
        self.est_secs <= QUICK_MAX_SECS
    }

    /// Whether a job of this profile loads the machine less than an idle desktop app: a
    /// normal lease for it may run beside a benchmark.
    pub fn is_low_impact(&self) -> bool {
        self.cores <= LOW_IMPACT_MAX_CORES
            && self.ram_mb <= LOW_IMPACT_MAX_RAM_MB
            && self.gpu_pct == 0.0
            && self.vram_mb == 0
    }
}

/// The longest expected run time of a quick job.
pub const QUICK_MAX_SECS: u64 = 15;

/// The most cores a low-impact job may use.
pub const LOW_IMPACT_MAX_CORES: f32 = 0.25;

/// The most memory a low-impact job may use.
pub const LOW_IMPACT_MAX_RAM_MB: u64 = 256;

/// Named job profiles. Their values come from the `[classes]` section of the config.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum JobClass {
    /// Short jobs that barely load the machine.
    Light,
    /// Compiles, test suites, and other CPU-bound work.
    CpuHeavy,
    /// Training, rendering, games, and other GPU-bound work.
    GpuHeavy,
    /// Jobs that load both the CPU and the GPU.
    Mixed,
}

impl JobClass {
    /// Every class, in declaration order.
    pub const ALL: [Self; 4] = [Self::Light, Self::CpuHeavy, Self::GpuHeavy, Self::Mixed];

    /// The name used in config files and on the wire, for example `cpu_heavy`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Light => "light",
            Self::CpuHeavy => "cpu_heavy",
            Self::GpuHeavy => "gpu_heavy",
            Self::Mixed => "mixed",
        }
    }
}

/// How a lease shares the machine.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum LeaseKind {
    /// Runs alongside other leases as long as their reservations fit.
    Normal,
    /// Runs alone on a quiet machine so that measurements are not disturbed.
    BenchmarkExclusive,
}

impl LeaseKind {
    /// Every kind, in declaration order.
    pub const ALL: [Self; 2] = [Self::Normal, Self::BenchmarkExclusive];

    /// The name used in storage and on the wire, for example `benchmark_exclusive`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Normal => "normal",
            Self::BenchmarkExclusive => "benchmark_exclusive",
        }
    }
}

/// Where a lease is in its lifecycle.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum LeaseState {
    /// Waiting for resources.
    Queued,
    /// Granted; its reservation counts against the machine.
    Active,
    /// Released by its holder.
    Released,
    /// Ended by the daemon because the heartbeat stopped or the holder died.
    Expired,
}

impl LeaseState {
    /// Every state, in declaration order.
    pub const ALL: [Self; 4] = [Self::Queued, Self::Active, Self::Released, Self::Expired];

    /// The name used in storage and on the wire, for example `queued`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Queued => "queued",
            Self::Active => "active",
            Self::Released => "released",
            Self::Expired => "expired",
        }
    }
}

/// Why a lease ended.
///
/// Kept apart from [`LeaseState`], whose values are fixed by the database's CHECK constraints
/// and by older `allot-mcp` builds that reject unknown states.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum EndCause {
    /// Its holder released it.
    Released,
    /// The daemon ended it because the heartbeat stopped or the holder died.
    Expired,
    /// The user stopped the job and its process tree.
    Killed,
    /// The user removed the request from the queue before it started.
    Removed,
}

impl EndCause {
    /// Every cause, in declaration order.
    pub const ALL: [Self; 4] = [Self::Released, Self::Expired, Self::Killed, Self::Removed];

    /// The name used in storage and on the wire, for example `killed`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Released => "released",
            Self::Expired => "expired",
            Self::Killed => "killed",
            Self::Removed => "removed",
        }
    }

    /// The state a lease that ended this way is stored in. Kills and removals end in
    /// `Expired`: the daemon ended the lease, not its holder, and older clients drop expired
    /// leases the same way.
    pub fn ended_state(self) -> LeaseState {
        match self {
            Self::Released => LeaseState::Released,
            Self::Expired | Self::Killed | Self::Removed => LeaseState::Expired,
        }
    }

    /// Whether the user caused it, so the holder's session must be told once.
    pub fn is_notice(self) -> bool {
        matches!(self, Self::Killed | Self::Removed)
    }
}

/// A reservation of machine resources for one job.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Lease {
    /// Lease ID.
    pub id: LeaseId,
    /// Session that owns the lease.
    pub holder: Holder,
    /// How the lease shares the machine.
    pub kind: LeaseKind,
    /// Lifecycle state.
    pub state: LeaseState,
    /// Class the profile was taken from, or `None` for a custom profile.
    pub class: Option<JobClass>,
    /// Resources reserved while the lease is active. Its cores are what the lease was granted,
    /// which is fewer than `asked_cores` when the grant shrank to fit.
    pub profile: JobProfile,
    /// Cores the request asked for, after history raised them; `None` for leases from before
    /// minimums were recorded, which asked for `profile.cores`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub asked_cores: Option<f32>,
    /// The fewest cores the lease may start with; `None` for leases from before minimums were
    /// recorded, which may not shrink.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_cores: Option<f32>,
    /// Cores the request declared before history lowered them; `None` when history did not
    /// lower them. A lowered lease counts at these cores for its first seconds, before its
    /// job's load shows in the 10 s averages.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub declared_cores: Option<f32>,
    /// What the lease is for, usually the command that will run.
    pub label: String,
    /// Working directory of the command, or empty when the requester did not say.
    #[serde(default)]
    pub cwd: String,
    /// When the lease was requested, in milliseconds since the Unix epoch.
    pub requested_at_ms: i64,
    /// When the lease became active.
    pub granted_at_ms: Option<i64>,
    /// When the lease was released or expired.
    pub ended_at_ms: Option<i64>,
    /// When the lease expires unless a heartbeat arrives first.
    pub expires_at_ms: i64,
    /// Why the lease ended; `None` while it is queued or active, and for leases that ended
    /// before causes were recorded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_cause: Option<EndCause>,
    /// The command the lease's holder last reported running under it; `None` until the hook
    /// reports one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub binding: Option<LeaseBinding>,
    /// How the lease's command is kept apart from the rest of the machine; `None` where allotd
    /// does not report it, as on Windows.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub isolation: Option<LeaseIsolation>,
}

impl Lease {
    /// The profile the lease asked for: its reservation with the cores it asked for, which
    /// differ only when the grant shrank it to fit.
    pub fn asked_profile(&self) -> JobProfile {
        JobProfile {
            cores: self.asked_cores.unwrap_or(self.profile.cores),
            ..self.profile
        }
    }
}

/// How a lease's command is accounted for and stopped.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LeaseIsolation {
    /// Whether the command runs in its own cgroup or is followed as a process tree.
    pub kind: IsolationKind,
    /// Name of the systemd scope that holds the command, for example
    /// `allot-lease-42.scope`; `None` without a cgroup.
    pub scope: Option<String>,
    /// Caps the OS enforces on the command.
    pub limits: EnforcedLimits,
}

/// How a lease's processes are found and stopped.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum IsolationKind {
    /// A cgroup of its own: exact usage, and a kill ends every process in it at once.
    Cgroup,
    /// The process tree under the command's root, followed sample by sample.
    Tree,
}

/// Caps the OS enforces on a lease's cgroup; each is `None` when not enforced.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub struct EnforcedLimits {
    /// CPU time limit in logical cores.
    pub cpu_cores: Option<f32>,
    /// Memory above which the OS throttles the command and reclaims its memory.
    pub memory_high_mb: Option<u64>,
    /// Memory at which the OS kills the command.
    pub memory_max_mb: Option<u64>,
}

/// Whether `value` is its type's default, which such fields leave off the wire.
pub(crate) fn is_default<T: Default + PartialEq>(value: &T) -> bool {
    *value == T::default()
}

/// The command a lease covers, as the PreToolUse hook reported it, and the process tree it
/// runs as once that is found. A later report for the same lease replaces it.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LeaseBinding {
    /// Claude Code's ID for the tool call that runs the command.
    pub tool_use_id: String,
    /// When the hook reported the command, in milliseconds since the Unix epoch. Processes
    /// that started before it are never part of the command.
    pub bound_at_ms: i64,
    /// Root of the command's process tree; `None` until it is found.
    pub root: Option<BoundProcess>,
}

/// One process, identified across PID reuse.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct BoundProcess {
    /// Process ID.
    pub pid: u32,
    /// Start time of `pid` in seconds since the Unix epoch, as in [`Holder::pid_start_time`].
    pub start_time: u64,
}

/// Load from processes outside the holder's session while a benchmark lease was active.
///
/// CPU is the summed per-process load of every other session and of processes outside all
/// sessions. Kernel and interrupt time belongs to no process, so it is not counted: it would
/// otherwise charge the benchmark's own system time as noise.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct NoiseReport {
    /// Average CPU load of other processes, as a percentage of all logical processors.
    pub avg_cpu_pct: f32,
    /// Peak CPU load of other processes.
    pub peak_cpu_pct: f32,
    /// Average GPU engine load of other processes, as a percentage of one adapter.
    pub avg_gpu_pct: f32,
    /// Peak GPU engine load of other processes.
    pub peak_gpu_pct: f32,
    /// Whether the machine met the quiet limits when the lease was granted. `false` means it
    /// was granted anyway after the longest quiet wait.
    pub quiet_at_start: bool,
}

/// Average load of a lease holder's session over only the samples in which it was busy, so
/// the idle time before and after the command does not water the load down.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct BusyUsage {
    /// Average CPU load in logical cores.
    pub cores: f32,
    /// Average GPU engine load as a percentage of one adapter.
    pub gpu_pct: f32,
}

/// One finished lease with what its holder's session used, kept for history-based estimates.
#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JobRun {
    /// Lease the job ran under, if the lease is still stored.
    pub lease_id: Option<LeaseId>,
    /// Session that ran the job; `None` for runs recorded before sessions were.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session: Option<SessionKey>,
    /// Why the run ended; `None` for runs recorded before causes were.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_cause: Option<EndCause>,
    /// Normalized command plus working directory, used to find similar runs.
    pub fingerprint: String,
    /// The lease's label, usually the command as it was run.
    pub command: String,
    /// Working directory of the command.
    pub cwd: String,
    /// Profile the lease reserved, which may already include an earlier estimate.
    pub declared: JobProfile,
    /// Peak usage of the holder's session during the run.
    pub peak: ResourceUsage,
    /// Average usage of the holder's session during the run.
    pub avg: ResourceUsage,
    /// Average load while the session was busy; `None` when it never was, and for runs
    /// recorded before this was measured.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub busy: Option<BusyUsage>,
    /// Start of the run, in milliseconds since the Unix epoch.
    pub started_at_ms: i64,
    /// End of the run, in milliseconds since the Unix epoch.
    pub ended_at_ms: i64,
    /// Background load during the run; recorded only for benchmark leases.
    pub noise: Option<NoiseReport>,
    /// Whether the session held another active lease during the run. Usage is measured per
    /// session, so such a run mixes several jobs and estimates leave it out.
    pub overlapped: bool,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::{assert_json_round_trip, sample_lease, sample_snapshot};

    fn profile_with(cores: f32, gpu_pct: f32) -> JobProfile {
        JobProfile {
            cores,
            ram_mb: 1024,
            gpu_pct,
            vram_mb: 0,
            est_secs: 60,
        }
    }

    #[test]
    fn test_snapshot_json_round_trip_preserves_every_field() {
        assert_json_round_trip(&sample_snapshot());
    }

    #[test]
    fn test_lease_json_round_trip_preserves_every_field() {
        assert_json_round_trip(&sample_lease());
    }

    #[test]
    fn test_lease_json_uses_snake_case_enums_and_bare_ids() {
        let value = serde_json::to_value(sample_lease()).unwrap();
        assert_eq!(value["id"], 7);
        assert_eq!(value["holder"]["session"], "3f2a9c1e-session");
        assert_eq!(value["kind"], "benchmark_exclusive");
        assert_eq!(value["state"], "active");
        assert_eq!(value["class"], "cpu_heavy");
    }

    #[test]
    fn test_enum_as_str_matches_serde_name() {
        for class in JobClass::ALL {
            assert_eq!(serde_json::to_value(class).unwrap(), class.as_str());
        }
        for kind in LeaseKind::ALL {
            assert_eq!(serde_json::to_value(kind).unwrap(), kind.as_str());
        }
        for state in LeaseState::ALL {
            assert_eq!(serde_json::to_value(state).unwrap(), state.as_str());
        }
        for cause in EndCause::ALL {
            assert_eq!(serde_json::to_value(cause).unwrap(), cause.as_str());
        }
    }

    #[test]
    fn test_lease_with_end_cause_round_trips_and_writes_snake_case() {
        let lease = Lease {
            state: LeaseState::Released,
            ended_at_ms: Some(1_793_000_090_000),
            end_cause: Some(EndCause::Killed),
            ..sample_lease()
        };
        assert_json_round_trip(&lease);
        assert_eq!(serde_json::to_value(&lease).unwrap()["end_cause"], "killed");
    }

    #[test]
    fn test_lease_without_end_cause_omits_the_field() {
        let value = serde_json::to_value(sample_lease()).unwrap();
        assert!(value.get("end_cause").is_none());
        assert!(value.get("binding").is_none());
    }

    #[test]
    fn test_lease_with_asked_and_min_cores_round_trips_and_omits_them_when_unknown() {
        let lease = Lease {
            asked_cores: Some(8.0),
            min_cores: Some(4.0),
            declared_cores: None,
            ..sample_lease()
        };
        assert_json_round_trip(&lease);
        let value = serde_json::to_value(&lease).unwrap();
        assert_eq!(value["asked_cores"], 8.0);
        assert_eq!(value["min_cores"], 4.0);
        let unknown = serde_json::to_value(sample_lease()).unwrap();
        assert!(unknown.get("asked_cores").is_none());
        assert!(unknown.get("min_cores").is_none());
    }

    #[test]
    fn test_lease_with_binding_round_trips_with_and_without_root() {
        let pending = LeaseBinding {
            tool_use_id: "toolu_01AbC".into(),
            bound_at_ms: 1_793_000_013_000,
            root: None,
        };
        let bound = LeaseBinding {
            root: Some(BoundProcess {
                pid: 30_112,
                start_time: 1_793_000_013,
            }),
            ..pending.clone()
        };
        for binding in [pending, bound] {
            assert_json_round_trip(&Lease {
                binding: Some(binding),
                ..sample_lease()
            });
        }
    }

    #[test]
    fn test_v0_1_shapes_decode_without_new_fields() {
        let mut lease = serde_json::to_value(sample_lease()).unwrap();
        lease.as_object_mut().unwrap().remove("end_cause");
        let lease: Lease = serde_json::from_value(lease).unwrap();
        assert_eq!(lease.end_cause, None);
        assert_eq!(lease.binding, None);
        assert_eq!(lease.isolation, None);
        assert_eq!((lease.asked_cores, lease.min_cores), (None, None));

        let mut snapshot = serde_json::to_value(sample_snapshot()).unwrap();
        snapshot.as_object_mut().unwrap().remove("drives");
        snapshot["sessions"][0]["processes"][0]
            .as_object_mut()
            .unwrap()
            .remove("exe");
        let snapshot: Snapshot = serde_json::from_value(snapshot).unwrap();
        assert!(snapshot.drives.is_empty());
        assert_eq!(snapshot.sessions[0].processes[0].exe, None);
    }

    #[test]
    fn test_windows_adapter_and_lease_omit_every_cross_platform_field() {
        let snapshot = serde_json::to_value(sample_snapshot()).unwrap();
        let gpu = snapshot["gpus"][0].as_object().unwrap();
        for field in ["unified_memory", "source", "process_load", "process_memory"] {
            assert!(gpu.get(field).is_none(), "{field}");
        }
        let lease = serde_json::to_value(sample_lease()).unwrap();
        assert!(lease.get("isolation").is_none());
    }

    #[test]
    fn test_adapter_from_an_older_allotd_is_a_windows_adapter() {
        let mut value = serde_json::to_value(&sample_snapshot().gpus[0]).unwrap();
        let object = value.as_object_mut().unwrap();
        for field in ["unified_memory", "source", "process_load", "process_memory"] {
            object.remove(field);
        }
        let gpu: GpuAdapter = serde_json::from_value(value).unwrap();
        assert!(!gpu.unified_memory);
        assert_eq!(gpu.source, GpuSource::Pdh);
        assert_eq!(gpu.process_load, Accuracy::Exact);
        assert_eq!(gpu.process_memory, Accuracy::Exact);
    }

    #[test]
    fn test_unified_adapter_round_trips_and_writes_snake_case() {
        let gpu = GpuAdapter {
            name: "Apple M3 Max".into(),
            luid: "4294969310".into(),
            dedicated_used_mb: 9_216,
            dedicated_total_mb: None,
            shared_used_mb: 0,
            unified_memory: true,
            source: GpuSource::Iokit,
            process_load: Accuracy::Estimated,
            process_memory: Accuracy::Unavailable,
            ..sample_snapshot().gpus[0].clone()
        };
        assert_json_round_trip(&gpu);
        let value = serde_json::to_value(&gpu).unwrap();
        assert_eq!(value["unified_memory"], true);
        assert_eq!(value["source"], "iokit");
        assert_eq!(value["process_load"], "estimated");
        assert_eq!(value["process_memory"], "unavailable");
        let fdinfo = serde_json::to_value(GpuSource::DrmFdinfo).unwrap();
        assert_eq!(fdinfo, "drm_fdinfo");
    }

    #[test]
    fn test_lease_with_isolation_round_trips_for_cgroup_and_tree() {
        let cgroup = LeaseIsolation {
            kind: IsolationKind::Cgroup,
            scope: Some("allot-lease-7.scope".into()),
            limits: EnforcedLimits {
                cpu_cores: Some(8.0),
                memory_high_mb: Some(4096),
                memory_max_mb: Some(6144),
            },
        };
        let tree = LeaseIsolation {
            kind: IsolationKind::Tree,
            scope: None,
            limits: EnforcedLimits::default(),
        };
        for isolation in [cgroup, tree] {
            assert_json_round_trip(&Lease {
                isolation: Some(isolation),
                ..sample_lease()
            });
        }
        let value = serde_json::to_value(Lease {
            isolation: Some(LeaseIsolation {
                kind: IsolationKind::Tree,
                scope: None,
                limits: EnforcedLimits::default(),
            }),
            ..sample_lease()
        })
        .unwrap();
        assert_eq!(value["isolation"]["kind"], "tree");
        assert!(value["isolation"]["scope"].is_null());
        assert!(value["isolation"]["limits"]["memory_max_mb"].is_null());
    }

    #[test]
    fn test_snapshot_without_drives_and_exe_omits_both_fields() {
        let mut snapshot = sample_snapshot();
        snapshot.drives.clear();
        snapshot.sessions[0].processes[0].exe = None;
        let value = serde_json::to_value(snapshot).unwrap();
        assert!(value.get("drives").is_none());
        assert!(value["sessions"][0]["processes"][0].get("exe").is_none());
    }

    #[test]
    fn test_gpu_engines_busiest_reads_the_picked_window_of_the_busiest_group() {
        let rolling = |avg_1s, avg_10s| Rolling {
            avg_1s,
            avg_10s,
            avg_60s: 0.0,
        };
        let engines = GpuEngines {
            three_d_pct: rolling(12.0, 40.0),
            compute_pct: rolling(55.5, 20.0),
            copy_pct: rolling(1.0, 1.0),
            video_pct: rolling(0.0, 0.0),
        };
        assert_eq!(engines.busiest(|load| load.avg_1s), 55.5);
        assert_eq!(engines.busiest(|load| load.avg_10s), 40.0);
        assert_eq!(GpuEngines::default().busiest(|load| load.avg_1s), 0.0);
    }

    #[test]
    fn test_resource_usage_add_assign_sums_every_field() {
        let mut total = ResourceUsage {
            cores: 1.5,
            ram_mb: 100,
            gpu_pct: 10.0,
            vram_mb: 64,
        };
        total += ResourceUsage {
            cores: 2.25,
            ram_mb: 50,
            gpu_pct: 5.5,
            vram_mb: 0,
        };
        assert_eq!(
            total,
            ResourceUsage {
                cores: 3.75,
                ram_mb: 150,
                gpu_pct: 15.5,
                vram_mb: 64,
            }
        );
    }

    #[test]
    fn test_noise_report_json_round_trip_preserves_every_field() {
        assert_json_round_trip(&NoiseReport {
            avg_cpu_pct: 2.5,
            peak_cpu_pct: 9.0,
            avg_gpu_pct: 0.5,
            peak_gpu_pct: 3.25,
            quiet_at_start: false,
        });
    }

    #[test]
    fn test_lease_without_cwd_field_deserializes_with_empty_cwd() {
        let mut value = serde_json::to_value(sample_lease()).unwrap();
        value.as_object_mut().unwrap().remove("cwd");
        let lease: Lease = serde_json::from_value(value).unwrap();
        assert_eq!(lease.cwd, "");
    }

    #[test]
    fn test_job_run_json_round_trip_preserves_every_field() {
        let usage = ResourceUsage {
            cores: 6.5,
            ram_mb: 2800,
            gpu_pct: 0.0,
            vram_mb: 0,
        };
        assert_json_round_trip(&JobRun {
            lease_id: Some(LeaseId(3)),
            session: Some(SessionKey("3f2a9c1e-session".into())),
            end_cause: Some(EndCause::Killed),
            fingerprint: r"cargo build -p allotd|e:\work\app".into(),
            command: "cargo build -p allotd 2>&1".into(),
            cwd: r"E:\work\app".into(),
            declared: profile_with(8.0, 0.0),
            peak: usage,
            avg: usage,
            busy: Some(BusyUsage {
                cores: 7.25,
                gpu_pct: 0.0,
            }),
            started_at_ms: 1_793_000_000_000,
            ended_at_ms: 1_793_000_095_000,
            noise: None,
            overlapped: true,
        });
    }

    #[test]
    fn test_job_profile_invalid_reason_in_range_is_none() {
        assert_eq!(profile_with(0.0, 0.0).invalid_reason(), None);
        assert_eq!(profile_with(16.0, 100.0).invalid_reason(), None);
    }

    #[test]
    fn test_job_profile_invalid_reason_out_of_range_names_field() {
        assert!(
            profile_with(-1.0, 0.0)
                .invalid_reason()
                .unwrap()
                .contains("cores")
        );
        assert!(
            profile_with(f32::NAN, 0.0)
                .invalid_reason()
                .unwrap()
                .contains("cores")
        );
        assert!(
            profile_with(1.0, 101.0)
                .invalid_reason()
                .unwrap()
                .contains("gpu_pct")
        );
        assert!(
            profile_with(1.0, f32::NAN)
                .invalid_reason()
                .unwrap()
                .contains("gpu_pct")
        );
    }
}