Skip to main content

allot_shared/
types.rs

1use std::ops::AddAssign;
2
3use serde::{Deserialize, Serialize};
4
5/// Identifies a lease. Assigned by the daemon's database when the lease is first stored.
6#[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/// Identifies a Claude Code session by its `CLAUDE_CODE_SESSION_ID`.
12///
13/// The MCP server reads the value from its environment and the hook reads `session_id` from
14/// its stdin JSON; both see the same string.
15#[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/// The process a session's leases live and die with.
21#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct Holder {
24    /// Session the leases belong to.
25    pub session: SessionKey,
26    /// PID of the session's Claude Code process (`claude.exe` on Windows, `claude` elsewhere),
27    /// the direct parent of its MCP server and its hooks.
28    pub pid: u32,
29    /// Start time of `pid` in seconds since the Unix epoch. Every OS reuses PIDs, so a process
30    /// with the same PID but another start time is not the holder.
31    pub pid_start_time: u64,
32}
33
34/// One measurement averaged over the sampler's rolling windows.
35#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
36pub struct Rolling {
37    /// Average over the last second.
38    pub avg_1s: f32,
39    /// Average over the last 10 seconds.
40    pub avg_10s: f32,
41    /// Average over the last 60 seconds.
42    pub avg_60s: f32,
43}
44
45/// Machine-wide CPU load.
46#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
47pub struct CpuStats {
48    /// Number of logical processors.
49    pub logical_cores: u32,
50    /// Total load as a percentage of all logical processors.
51    pub usage_pct: Rolling,
52    /// Load of each logical processor over the last second.
53    pub per_core_pct: Vec<f32>,
54}
55
56/// Machine-wide physical memory and commit charge.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
58pub struct MemStats {
59    /// Installed physical memory.
60    pub total_mb: u64,
61    /// Physical memory in use.
62    pub used_mb: u64,
63    /// Physical memory available to new allocations without paging.
64    pub available_mb: u64,
65    /// Committed virtual memory.
66    pub commit_used_mb: u64,
67    /// Commit limit: physical memory plus page files.
68    pub commit_limit_mb: u64,
69    /// The part of `used_mb` the OS gives up for new allocations with no harm to the machine,
70    /// which admission does not count as load. Only macOS reports any.
71    #[serde(default)]
72    pub reclaimable_mb: u64,
73}
74
75/// Utilization of one GPU's engine groups, as percentages.
76#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
77pub struct GpuEngines {
78    /// 3D (graphics) engines.
79    pub three_d_pct: Rolling,
80    /// Compute engines.
81    pub compute_pct: Rolling,
82    /// Copy engines.
83    pub copy_pct: Rolling,
84    /// Video encode and decode engines.
85    pub video_pct: Rolling,
86}
87
88impl GpuEngines {
89    /// Load of the busiest engine group, read from the window `pick` selects.
90    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/// One GPU adapter.
104#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
105pub struct GpuAdapter {
106    /// Adapter name, for example `NVIDIA GeForce RTX 4070`.
107    pub name: String,
108    /// Stable ID of the adapter: on Windows its LUID as it appears in PDH instance names, for
109    /// example `0x00000000_0x0000d1a2`; other OSes use their own stable ID.
110    pub luid: String,
111    /// Engine utilization.
112    pub engines: GpuEngines,
113    /// Dedicated video memory in use. On a unified-memory adapter, the system memory the GPU
114    /// has allocated, which RAM use already counts.
115    pub dedicated_used_mb: u64,
116    /// Dedicated video memory installed, when the OS reports it; `None` on a unified-memory
117    /// adapter, which has none of its own.
118    pub dedicated_total_mb: Option<u64>,
119    /// Shared system memory in use by the adapter.
120    pub shared_used_mb: u64,
121    /// Whether the adapter's video memory is the machine's RAM, as on Apple Silicon. Admission
122    /// then counts video memory against RAM.
123    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
124    pub unified_memory: bool,
125    /// Where the numbers come from.
126    #[serde(default, skip_serializing_if = "is_default")]
127    pub source: GpuSource,
128    /// How well the source measures each process's engine load.
129    #[serde(default, skip_serializing_if = "is_default")]
130    pub process_load: Accuracy,
131    /// How well the source measures each process's video memory.
132    #[serde(default, skip_serializing_if = "is_default")]
133    pub process_memory: Accuracy,
134}
135
136/// Where a GPU adapter's numbers come from.
137#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
138#[serde(rename_all = "snake_case")]
139#[non_exhaustive]
140pub enum GpuSource {
141    /// Windows performance counters. allotd builds that do not name a source ran on Windows
142    /// only, so a missing source means this.
143    #[default]
144    Pdh,
145    /// NVIDIA's management library, on Linux.
146    Nvml,
147    /// The DRM drivers' per-client statistics in `/proc/<pid>/fdinfo`, on Linux.
148    DrmFdinfo,
149    /// IOKit accelerator statistics, on macOS.
150    Iokit,
151}
152
153/// How well a GPU source measures something per process.
154#[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    /// Measured per process.
160    #[default]
161    Exact,
162    /// Measured, but only roughly; the machine total is the reliable figure.
163    Estimated,
164    /// Not measured: per-process values read 0.
165    Unavailable,
166}
167
168/// Resources used by a process or a group of processes, in the units of [`JobProfile`].
169#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
170#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
171pub struct ResourceUsage {
172    /// CPU load in logical cores, for example `2.5` for two and a half busy cores.
173    pub cores: f32,
174    /// Resident memory; on macOS the physical footprint, as Activity Monitor shows it.
175    pub ram_mb: u64,
176    /// GPU engine load as a percentage of one adapter.
177    pub gpu_pct: f32,
178    /// Dedicated video memory.
179    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/// Usage of a single process.
192#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
193pub struct ProcessUsage {
194    /// Process ID.
195    pub pid: u32,
196    /// Executable name, for example `cargo.exe`.
197    pub name: String,
198    /// Full path of the executable, when the sampler could read it.
199    #[serde(default, skip_serializing_if = "Option::is_none")]
200    pub exe: Option<String>,
201    /// Resources the process uses.
202    pub usage: ResourceUsage,
203}
204
205/// Usage of a session's whole process subtree.
206#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
207pub struct SessionUsage {
208    /// The session and its root process.
209    pub holder: Holder,
210    /// Sum over every process in the subtree.
211    pub usage: ResourceUsage,
212    /// The processes in the subtree, busiest first.
213    pub processes: Vec<ProcessUsage>,
214}
215
216/// A point-in-time view of the machine.
217#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
218pub struct Snapshot {
219    /// When the sample was taken, in milliseconds since the Unix epoch.
220    pub taken_at_ms: i64,
221    /// CPU load.
222    pub cpu: CpuStats,
223    /// Memory use.
224    pub memory: MemStats,
225    /// Every GPU adapter.
226    pub gpus: Vec<GpuAdapter>,
227    /// Usage of each registered session.
228    pub sessions: Vec<SessionUsage>,
229    /// Usage of processes outside every registered session.
230    pub unattributed: ResourceUsage,
231    /// Every fixed drive, by drive letter on Windows and by mount point elsewhere.
232    #[serde(default, skip_serializing_if = "Vec::is_empty")]
233    pub drives: Vec<DriveUsage>,
234}
235
236/// Space and activity of one fixed drive.
237#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
239pub struct DriveUsage {
240    /// Drive letter with its colon on Windows, for example `C:`; mount point elsewhere, for
241    /// example `/home`.
242    pub name: String,
243    /// Capacity of the volume.
244    pub total_mb: u64,
245    /// Space in use.
246    pub used_mb: u64,
247    /// Bytes read per second over the last second.
248    pub read_bytes_per_sec: u64,
249    /// Bytes written per second over the last second.
250    pub write_bytes_per_sec: u64,
251}
252
253/// Resources a job is expected to need while it runs.
254#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
255#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
256pub struct JobProfile {
257    /// Logical cores the job keeps busy.
258    pub cores: f32,
259    /// Peak resident memory.
260    pub ram_mb: u64,
261    /// GPU engine load as a percentage of one adapter.
262    pub gpu_pct: f32,
263    /// Peak dedicated video memory.
264    pub vram_mb: u64,
265    /// Expected run time.
266    pub est_secs: u64,
267}
268
269impl JobProfile {
270    /// Returns why the profile is unusable, or `None` when every value is in range.
271    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    /// Whether a job of this profile ends within [`QUICK_MAX_SECS`]: a normal lease for it may
282    /// start while a benchmark still waits for other leases to end.
283    pub fn is_quick(&self) -> bool {
284        self.est_secs <= QUICK_MAX_SECS
285    }
286
287    /// Whether a job of this profile loads the machine less than an idle desktop app: a
288    /// normal lease for it may run beside a benchmark.
289    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
297/// The longest expected run time of a quick job.
298pub const QUICK_MAX_SECS: u64 = 15;
299
300/// The most cores a low-impact job may use.
301pub const LOW_IMPACT_MAX_CORES: f32 = 0.25;
302
303/// The most memory a low-impact job may use.
304pub const LOW_IMPACT_MAX_RAM_MB: u64 = 256;
305
306/// Named job profiles. Their values come from the `[classes]` section of the config.
307#[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    /// Short jobs that barely load the machine.
313    Light,
314    /// Compiles, test suites, and other CPU-bound work.
315    CpuHeavy,
316    /// Training, rendering, games, and other GPU-bound work.
317    GpuHeavy,
318    /// Jobs that load both the CPU and the GPU.
319    Mixed,
320}
321
322impl JobClass {
323    /// Every class, in declaration order.
324    pub const ALL: [Self; 4] = [Self::Light, Self::CpuHeavy, Self::GpuHeavy, Self::Mixed];
325
326    /// The name used in config files and on the wire, for example `cpu_heavy`.
327    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/// How a lease shares the machine.
338#[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    /// Runs alongside other leases as long as their reservations fit.
344    Normal,
345    /// Runs alone on a quiet machine so that measurements are not disturbed.
346    BenchmarkExclusive,
347}
348
349impl LeaseKind {
350    /// Every kind, in declaration order.
351    pub const ALL: [Self; 2] = [Self::Normal, Self::BenchmarkExclusive];
352
353    /// The name used in storage and on the wire, for example `benchmark_exclusive`.
354    pub fn as_str(self) -> &'static str {
355        match self {
356            Self::Normal => "normal",
357            Self::BenchmarkExclusive => "benchmark_exclusive",
358        }
359    }
360}
361
362/// Where a lease is in its lifecycle.
363#[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    /// Waiting for resources.
369    Queued,
370    /// Granted; its reservation counts against the machine.
371    Active,
372    /// Released by its holder.
373    Released,
374    /// Ended by the daemon because the heartbeat stopped or the holder died.
375    Expired,
376}
377
378impl LeaseState {
379    /// Every state, in declaration order.
380    pub const ALL: [Self; 4] = [Self::Queued, Self::Active, Self::Released, Self::Expired];
381
382    /// The name used in storage and on the wire, for example `queued`.
383    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/// Why a lease ended.
394///
395/// Kept apart from [`LeaseState`], whose values are fixed by the database's CHECK constraints
396/// and by older `allot-mcp` builds that reject unknown states.
397#[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    /// Its holder released it.
403    Released,
404    /// The daemon ended it because the heartbeat stopped or the holder died.
405    Expired,
406    /// The user stopped the job and its process tree.
407    Killed,
408    /// The user removed the request from the queue before it started.
409    Removed,
410}
411
412impl EndCause {
413    /// Every cause, in declaration order.
414    pub const ALL: [Self; 4] = [Self::Released, Self::Expired, Self::Killed, Self::Removed];
415
416    /// The name used in storage and on the wire, for example `killed`.
417    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    /// The state a lease that ended this way is stored in. Kills and removals end in
427    /// `Expired`: the daemon ended the lease, not its holder, and older clients drop expired
428    /// leases the same way.
429    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    /// Whether the user caused it, so the holder's session must be told once.
437    pub fn is_notice(self) -> bool {
438        matches!(self, Self::Killed | Self::Removed)
439    }
440}
441
442/// A reservation of machine resources for one job.
443#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
444#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
445pub struct Lease {
446    /// Lease ID.
447    pub id: LeaseId,
448    /// Session that owns the lease.
449    pub holder: Holder,
450    /// How the lease shares the machine.
451    pub kind: LeaseKind,
452    /// Lifecycle state.
453    pub state: LeaseState,
454    /// Class the profile was taken from, or `None` for a custom profile.
455    pub class: Option<JobClass>,
456    /// Resources reserved while the lease is active.
457    pub profile: JobProfile,
458    /// What the lease is for, usually the command that will run.
459    pub label: String,
460    /// Working directory of the command, or empty when the requester did not say.
461    #[serde(default)]
462    pub cwd: String,
463    /// When the lease was requested, in milliseconds since the Unix epoch.
464    pub requested_at_ms: i64,
465    /// When the lease became active.
466    pub granted_at_ms: Option<i64>,
467    /// When the lease was released or expired.
468    pub ended_at_ms: Option<i64>,
469    /// When the lease expires unless a heartbeat arrives first.
470    pub expires_at_ms: i64,
471    /// Why the lease ended; `None` while it is queued or active, and for leases that ended
472    /// before causes were recorded.
473    #[serde(default, skip_serializing_if = "Option::is_none")]
474    pub end_cause: Option<EndCause>,
475    /// The command the lease's holder last reported running under it; `None` until the hook
476    /// reports one.
477    #[serde(default, skip_serializing_if = "Option::is_none")]
478    pub binding: Option<LeaseBinding>,
479    /// How the lease's command is kept apart from the rest of the machine; `None` where allotd
480    /// does not report it, as on Windows.
481    #[serde(default, skip_serializing_if = "Option::is_none")]
482    pub isolation: Option<LeaseIsolation>,
483}
484
485/// How a lease's command is accounted for and stopped.
486#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
487#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
488pub struct LeaseIsolation {
489    /// Whether the command runs in its own cgroup or is followed as a process tree.
490    pub kind: IsolationKind,
491    /// Name of the systemd scope that holds the command, for example
492    /// `allot-lease-42.scope`; `None` without a cgroup.
493    pub scope: Option<String>,
494    /// Caps the OS enforces on the command.
495    pub limits: EnforcedLimits,
496}
497
498/// How a lease's processes are found and stopped.
499#[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    /// A cgroup of its own: exact usage, and a kill ends every process in it at once.
505    Cgroup,
506    /// The process tree under the command's root, followed sample by sample.
507    Tree,
508}
509
510/// Caps the OS enforces on a lease's cgroup; each is `None` when not enforced.
511#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
512#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
513pub struct EnforcedLimits {
514    /// CPU time limit in logical cores.
515    pub cpu_cores: Option<f32>,
516    /// Memory above which the OS throttles the command and reclaims its memory.
517    pub memory_high_mb: Option<u64>,
518    /// Memory at which the OS kills the command.
519    pub memory_max_mb: Option<u64>,
520}
521
522/// Whether `value` is its type's default, which such fields leave off the wire.
523pub(crate) fn is_default<T: Default + PartialEq>(value: &T) -> bool {
524    *value == T::default()
525}
526
527/// The command a lease covers, as the PreToolUse hook reported it, and the process tree it
528/// runs as once that is found. A later report for the same lease replaces it.
529#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
530#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
531pub struct LeaseBinding {
532    /// Claude Code's ID for the tool call that runs the command.
533    pub tool_use_id: String,
534    /// When the hook reported the command, in milliseconds since the Unix epoch. Processes
535    /// that started before it are never part of the command.
536    pub bound_at_ms: i64,
537    /// Root of the command's process tree; `None` until it is found.
538    pub root: Option<BoundProcess>,
539}
540
541/// One process, identified across PID reuse.
542#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
543#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
544pub struct BoundProcess {
545    /// Process ID.
546    pub pid: u32,
547    /// Start time of `pid` in seconds since the Unix epoch, as in [`Holder::pid_start_time`].
548    pub start_time: u64,
549}
550
551/// Load from processes outside the holder's session while a benchmark lease was active.
552///
553/// CPU is the summed per-process load of every other session and of processes outside all
554/// sessions. Kernel and interrupt time belongs to no process, so it is not counted: it would
555/// otherwise charge the benchmark's own system time as noise.
556#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
557#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
558pub struct NoiseReport {
559    /// Average CPU load of other processes, as a percentage of all logical processors.
560    pub avg_cpu_pct: f32,
561    /// Peak CPU load of other processes.
562    pub peak_cpu_pct: f32,
563    /// Average GPU engine load of other processes, as a percentage of one adapter.
564    pub avg_gpu_pct: f32,
565    /// Peak GPU engine load of other processes.
566    pub peak_gpu_pct: f32,
567    /// Whether the machine met the quiet limits when the lease was granted. `false` means it
568    /// was granted anyway after the longest quiet wait.
569    pub quiet_at_start: bool,
570}
571
572/// Average load of a lease holder's session over only the samples in which it was busy, so
573/// the idle time before and after the command does not water the load down.
574#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
575#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
576pub struct BusyUsage {
577    /// Average CPU load in logical cores.
578    pub cores: f32,
579    /// Average GPU engine load as a percentage of one adapter.
580    pub gpu_pct: f32,
581}
582
583/// One finished lease with what its holder's session used, kept for history-based estimates.
584#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
585#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
586pub struct JobRun {
587    /// Lease the job ran under, if the lease is still stored.
588    pub lease_id: Option<LeaseId>,
589    /// Session that ran the job; `None` for runs recorded before sessions were.
590    #[serde(default, skip_serializing_if = "Option::is_none")]
591    pub session: Option<SessionKey>,
592    /// Why the run ended; `None` for runs recorded before causes were.
593    #[serde(default, skip_serializing_if = "Option::is_none")]
594    pub end_cause: Option<EndCause>,
595    /// Normalized command plus working directory, used to find similar runs.
596    pub fingerprint: String,
597    /// The lease's label, usually the command as it was run.
598    pub command: String,
599    /// Working directory of the command.
600    pub cwd: String,
601    /// Profile the lease reserved, which may already include an earlier estimate.
602    pub declared: JobProfile,
603    /// Peak usage of the holder's session during the run.
604    pub peak: ResourceUsage,
605    /// Average usage of the holder's session during the run.
606    pub avg: ResourceUsage,
607    /// Average load while the session was busy; `None` when it never was, and for runs
608    /// recorded before this was measured.
609    #[serde(default, skip_serializing_if = "Option::is_none")]
610    pub busy: Option<BusyUsage>,
611    /// Start of the run, in milliseconds since the Unix epoch.
612    pub started_at_ms: i64,
613    /// End of the run, in milliseconds since the Unix epoch.
614    pub ended_at_ms: i64,
615    /// Background load during the run; recorded only for benchmark leases.
616    pub noise: Option<NoiseReport>,
617    /// Whether the session held another active lease during the run. Usage is measured per
618    /// session, so such a run mixes several jobs and estimates leave it out.
619    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}