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    /// The minimum of a class or preset that names none: half the cores, but at least one
282    /// core, or all of them when there are fewer. `light` (1 core) never shrinks.
283    pub fn default_min_cores(&self) -> f32 {
284        (self.cores / 2.0).max(self.cores.min(1.0))
285    }
286
287    /// Returns why `min_cores` cannot be the fewest cores this profile starts with, or `None`
288    /// when `0 < min_cores <= cores`.
289    pub fn min_cores_reason(&self, min_cores: f32) -> Option<&'static str> {
290        if !(min_cores.is_finite() && min_cores > 0.0) {
291            Some("min_cores must be a finite number above 0")
292        } else if min_cores > self.cores {
293            Some("min_cores must be at most cores")
294        } else {
295            None
296        }
297    }
298
299    /// Whether a job of this profile ends within [`QUICK_MAX_SECS`]: a normal lease for it may
300    /// start while a benchmark still waits for other leases to end.
301    pub fn is_quick(&self) -> bool {
302        self.est_secs <= QUICK_MAX_SECS
303    }
304
305    /// Whether a job of this profile loads the machine less than an idle desktop app: a
306    /// normal lease for it may run beside a benchmark.
307    pub fn is_low_impact(&self) -> bool {
308        self.cores <= LOW_IMPACT_MAX_CORES
309            && self.ram_mb <= LOW_IMPACT_MAX_RAM_MB
310            && self.gpu_pct == 0.0
311            && self.vram_mb == 0
312    }
313}
314
315/// The longest expected run time of a quick job.
316pub const QUICK_MAX_SECS: u64 = 15;
317
318/// The most cores a low-impact job may use.
319pub const LOW_IMPACT_MAX_CORES: f32 = 0.25;
320
321/// The most memory a low-impact job may use.
322pub const LOW_IMPACT_MAX_RAM_MB: u64 = 256;
323
324/// Named job profiles. Their values come from the `[classes]` section of the config.
325#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
326#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
327#[serde(rename_all = "snake_case")]
328#[non_exhaustive]
329pub enum JobClass {
330    /// Short jobs that barely load the machine.
331    Light,
332    /// Compiles, test suites, and other CPU-bound work.
333    CpuHeavy,
334    /// Training, rendering, games, and other GPU-bound work.
335    GpuHeavy,
336    /// Jobs that load both the CPU and the GPU.
337    Mixed,
338}
339
340impl JobClass {
341    /// Every class, in declaration order.
342    pub const ALL: [Self; 4] = [Self::Light, Self::CpuHeavy, Self::GpuHeavy, Self::Mixed];
343
344    /// The name used in config files and on the wire, for example `cpu_heavy`.
345    pub fn as_str(self) -> &'static str {
346        match self {
347            Self::Light => "light",
348            Self::CpuHeavy => "cpu_heavy",
349            Self::GpuHeavy => "gpu_heavy",
350            Self::Mixed => "mixed",
351        }
352    }
353}
354
355/// How a lease shares the machine.
356#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
357#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
358#[serde(rename_all = "snake_case")]
359#[non_exhaustive]
360pub enum LeaseKind {
361    /// Runs alongside other leases as long as their reservations fit.
362    Normal,
363    /// Runs alone on a quiet machine so that measurements are not disturbed.
364    BenchmarkExclusive,
365}
366
367impl LeaseKind {
368    /// Every kind, in declaration order.
369    pub const ALL: [Self; 2] = [Self::Normal, Self::BenchmarkExclusive];
370
371    /// The name used in storage and on the wire, for example `benchmark_exclusive`.
372    pub fn as_str(self) -> &'static str {
373        match self {
374            Self::Normal => "normal",
375            Self::BenchmarkExclusive => "benchmark_exclusive",
376        }
377    }
378}
379
380/// Where a lease is in its lifecycle.
381#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
382#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
383#[serde(rename_all = "snake_case")]
384#[non_exhaustive]
385pub enum LeaseState {
386    /// Waiting for resources.
387    Queued,
388    /// Granted; its reservation counts against the machine.
389    Active,
390    /// Released by its holder.
391    Released,
392    /// Ended by the daemon because the heartbeat stopped or the holder died.
393    Expired,
394}
395
396impl LeaseState {
397    /// Every state, in declaration order.
398    pub const ALL: [Self; 4] = [Self::Queued, Self::Active, Self::Released, Self::Expired];
399
400    /// The name used in storage and on the wire, for example `queued`.
401    pub fn as_str(self) -> &'static str {
402        match self {
403            Self::Queued => "queued",
404            Self::Active => "active",
405            Self::Released => "released",
406            Self::Expired => "expired",
407        }
408    }
409}
410
411/// Why a lease ended.
412///
413/// Kept apart from [`LeaseState`], whose values are fixed by the database's CHECK constraints
414/// and by older `allot-mcp` builds that reject unknown states.
415#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
416#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
417#[serde(rename_all = "snake_case")]
418#[non_exhaustive]
419pub enum EndCause {
420    /// Its holder released it.
421    Released,
422    /// The daemon ended it because the heartbeat stopped or the holder died.
423    Expired,
424    /// The user stopped the job and its process tree.
425    Killed,
426    /// The user removed the request from the queue before it started.
427    Removed,
428}
429
430impl EndCause {
431    /// Every cause, in declaration order.
432    pub const ALL: [Self; 4] = [Self::Released, Self::Expired, Self::Killed, Self::Removed];
433
434    /// The name used in storage and on the wire, for example `killed`.
435    pub fn as_str(self) -> &'static str {
436        match self {
437            Self::Released => "released",
438            Self::Expired => "expired",
439            Self::Killed => "killed",
440            Self::Removed => "removed",
441        }
442    }
443
444    /// The state a lease that ended this way is stored in. Kills and removals end in
445    /// `Expired`: the daemon ended the lease, not its holder, and older clients drop expired
446    /// leases the same way.
447    pub fn ended_state(self) -> LeaseState {
448        match self {
449            Self::Released => LeaseState::Released,
450            Self::Expired | Self::Killed | Self::Removed => LeaseState::Expired,
451        }
452    }
453
454    /// Whether the user caused it, so the holder's session must be told once.
455    pub fn is_notice(self) -> bool {
456        matches!(self, Self::Killed | Self::Removed)
457    }
458}
459
460/// A reservation of machine resources for one job.
461#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
462#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
463pub struct Lease {
464    /// Lease ID.
465    pub id: LeaseId,
466    /// Session that owns the lease.
467    pub holder: Holder,
468    /// How the lease shares the machine.
469    pub kind: LeaseKind,
470    /// Lifecycle state.
471    pub state: LeaseState,
472    /// Class the profile was taken from, or `None` for a custom profile.
473    pub class: Option<JobClass>,
474    /// Resources reserved while the lease is active. Its cores are what the lease was granted,
475    /// which is fewer than `asked_cores` when the grant shrank to fit.
476    pub profile: JobProfile,
477    /// Cores the request asked for, after history raised them; `None` for leases from before
478    /// minimums were recorded, which asked for `profile.cores`.
479    #[serde(default, skip_serializing_if = "Option::is_none")]
480    pub asked_cores: Option<f32>,
481    /// The fewest cores the lease may start with; `None` for leases from before minimums were
482    /// recorded, which may not shrink.
483    #[serde(default, skip_serializing_if = "Option::is_none")]
484    pub min_cores: Option<f32>,
485    /// What the lease is for, usually the command that will run.
486    pub label: String,
487    /// Working directory of the command, or empty when the requester did not say.
488    #[serde(default)]
489    pub cwd: String,
490    /// When the lease was requested, in milliseconds since the Unix epoch.
491    pub requested_at_ms: i64,
492    /// When the lease became active.
493    pub granted_at_ms: Option<i64>,
494    /// When the lease was released or expired.
495    pub ended_at_ms: Option<i64>,
496    /// When the lease expires unless a heartbeat arrives first.
497    pub expires_at_ms: i64,
498    /// Why the lease ended; `None` while it is queued or active, and for leases that ended
499    /// before causes were recorded.
500    #[serde(default, skip_serializing_if = "Option::is_none")]
501    pub end_cause: Option<EndCause>,
502    /// The command the lease's holder last reported running under it; `None` until the hook
503    /// reports one.
504    #[serde(default, skip_serializing_if = "Option::is_none")]
505    pub binding: Option<LeaseBinding>,
506    /// How the lease's command is kept apart from the rest of the machine; `None` where allotd
507    /// does not report it, as on Windows.
508    #[serde(default, skip_serializing_if = "Option::is_none")]
509    pub isolation: Option<LeaseIsolation>,
510}
511
512impl Lease {
513    /// The profile the lease asked for: its reservation with the cores it asked for, which
514    /// differ only when the grant shrank it to fit.
515    pub fn asked_profile(&self) -> JobProfile {
516        JobProfile {
517            cores: self.asked_cores.unwrap_or(self.profile.cores),
518            ..self.profile
519        }
520    }
521}
522
523/// How a lease's command is accounted for and stopped.
524#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
525#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
526pub struct LeaseIsolation {
527    /// Whether the command runs in its own cgroup or is followed as a process tree.
528    pub kind: IsolationKind,
529    /// Name of the systemd scope that holds the command, for example
530    /// `allot-lease-42.scope`; `None` without a cgroup.
531    pub scope: Option<String>,
532    /// Caps the OS enforces on the command.
533    pub limits: EnforcedLimits,
534}
535
536/// How a lease's processes are found and stopped.
537#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
538#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
539#[serde(rename_all = "snake_case")]
540#[non_exhaustive]
541pub enum IsolationKind {
542    /// A cgroup of its own: exact usage, and a kill ends every process in it at once.
543    Cgroup,
544    /// The process tree under the command's root, followed sample by sample.
545    Tree,
546}
547
548/// Caps the OS enforces on a lease's cgroup; each is `None` when not enforced.
549#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
550#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
551pub struct EnforcedLimits {
552    /// CPU time limit in logical cores.
553    pub cpu_cores: Option<f32>,
554    /// Memory above which the OS throttles the command and reclaims its memory.
555    pub memory_high_mb: Option<u64>,
556    /// Memory at which the OS kills the command.
557    pub memory_max_mb: Option<u64>,
558}
559
560/// Whether `value` is its type's default, which such fields leave off the wire.
561pub(crate) fn is_default<T: Default + PartialEq>(value: &T) -> bool {
562    *value == T::default()
563}
564
565/// The command a lease covers, as the PreToolUse hook reported it, and the process tree it
566/// runs as once that is found. A later report for the same lease replaces it.
567#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
568#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
569pub struct LeaseBinding {
570    /// Claude Code's ID for the tool call that runs the command.
571    pub tool_use_id: String,
572    /// When the hook reported the command, in milliseconds since the Unix epoch. Processes
573    /// that started before it are never part of the command.
574    pub bound_at_ms: i64,
575    /// Root of the command's process tree; `None` until it is found.
576    pub root: Option<BoundProcess>,
577}
578
579/// One process, identified across PID reuse.
580#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
581#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
582pub struct BoundProcess {
583    /// Process ID.
584    pub pid: u32,
585    /// Start time of `pid` in seconds since the Unix epoch, as in [`Holder::pid_start_time`].
586    pub start_time: u64,
587}
588
589/// Load from processes outside the holder's session while a benchmark lease was active.
590///
591/// CPU is the summed per-process load of every other session and of processes outside all
592/// sessions. Kernel and interrupt time belongs to no process, so it is not counted: it would
593/// otherwise charge the benchmark's own system time as noise.
594#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
595#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
596pub struct NoiseReport {
597    /// Average CPU load of other processes, as a percentage of all logical processors.
598    pub avg_cpu_pct: f32,
599    /// Peak CPU load of other processes.
600    pub peak_cpu_pct: f32,
601    /// Average GPU engine load of other processes, as a percentage of one adapter.
602    pub avg_gpu_pct: f32,
603    /// Peak GPU engine load of other processes.
604    pub peak_gpu_pct: f32,
605    /// Whether the machine met the quiet limits when the lease was granted. `false` means it
606    /// was granted anyway after the longest quiet wait.
607    pub quiet_at_start: bool,
608}
609
610/// Average load of a lease holder's session over only the samples in which it was busy, so
611/// the idle time before and after the command does not water the load down.
612#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
613#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
614pub struct BusyUsage {
615    /// Average CPU load in logical cores.
616    pub cores: f32,
617    /// Average GPU engine load as a percentage of one adapter.
618    pub gpu_pct: f32,
619}
620
621/// One finished lease with what its holder's session used, kept for history-based estimates.
622#[cfg_attr(any(feature = "schema", test), derive(schemars::JsonSchema))]
623#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
624pub struct JobRun {
625    /// Lease the job ran under, if the lease is still stored.
626    pub lease_id: Option<LeaseId>,
627    /// Session that ran the job; `None` for runs recorded before sessions were.
628    #[serde(default, skip_serializing_if = "Option::is_none")]
629    pub session: Option<SessionKey>,
630    /// Why the run ended; `None` for runs recorded before causes were.
631    #[serde(default, skip_serializing_if = "Option::is_none")]
632    pub end_cause: Option<EndCause>,
633    /// Normalized command plus working directory, used to find similar runs.
634    pub fingerprint: String,
635    /// The lease's label, usually the command as it was run.
636    pub command: String,
637    /// Working directory of the command.
638    pub cwd: String,
639    /// Profile the lease reserved, which may already include an earlier estimate.
640    pub declared: JobProfile,
641    /// Peak usage of the holder's session during the run.
642    pub peak: ResourceUsage,
643    /// Average usage of the holder's session during the run.
644    pub avg: ResourceUsage,
645    /// Average load while the session was busy; `None` when it never was, and for runs
646    /// recorded before this was measured.
647    #[serde(default, skip_serializing_if = "Option::is_none")]
648    pub busy: Option<BusyUsage>,
649    /// Start of the run, in milliseconds since the Unix epoch.
650    pub started_at_ms: i64,
651    /// End of the run, in milliseconds since the Unix epoch.
652    pub ended_at_ms: i64,
653    /// Background load during the run; recorded only for benchmark leases.
654    pub noise: Option<NoiseReport>,
655    /// Whether the session held another active lease during the run. Usage is measured per
656    /// session, so such a run mixes several jobs and estimates leave it out.
657    pub overlapped: bool,
658}
659
660#[cfg(test)]
661mod tests {
662    use super::*;
663    use crate::test_support::{assert_json_round_trip, sample_lease, sample_snapshot};
664
665    fn profile_with(cores: f32, gpu_pct: f32) -> JobProfile {
666        JobProfile {
667            cores,
668            ram_mb: 1024,
669            gpu_pct,
670            vram_mb: 0,
671            est_secs: 60,
672        }
673    }
674
675    #[test]
676    fn test_snapshot_json_round_trip_preserves_every_field() {
677        assert_json_round_trip(&sample_snapshot());
678    }
679
680    #[test]
681    fn test_lease_json_round_trip_preserves_every_field() {
682        assert_json_round_trip(&sample_lease());
683    }
684
685    #[test]
686    fn test_lease_json_uses_snake_case_enums_and_bare_ids() {
687        let value = serde_json::to_value(sample_lease()).unwrap();
688        assert_eq!(value["id"], 7);
689        assert_eq!(value["holder"]["session"], "3f2a9c1e-session");
690        assert_eq!(value["kind"], "benchmark_exclusive");
691        assert_eq!(value["state"], "active");
692        assert_eq!(value["class"], "cpu_heavy");
693    }
694
695    #[test]
696    fn test_enum_as_str_matches_serde_name() {
697        for class in JobClass::ALL {
698            assert_eq!(serde_json::to_value(class).unwrap(), class.as_str());
699        }
700        for kind in LeaseKind::ALL {
701            assert_eq!(serde_json::to_value(kind).unwrap(), kind.as_str());
702        }
703        for state in LeaseState::ALL {
704            assert_eq!(serde_json::to_value(state).unwrap(), state.as_str());
705        }
706        for cause in EndCause::ALL {
707            assert_eq!(serde_json::to_value(cause).unwrap(), cause.as_str());
708        }
709    }
710
711    #[test]
712    fn test_lease_with_end_cause_round_trips_and_writes_snake_case() {
713        let lease = Lease {
714            state: LeaseState::Released,
715            ended_at_ms: Some(1_793_000_090_000),
716            end_cause: Some(EndCause::Killed),
717            ..sample_lease()
718        };
719        assert_json_round_trip(&lease);
720        assert_eq!(serde_json::to_value(&lease).unwrap()["end_cause"], "killed");
721    }
722
723    #[test]
724    fn test_lease_without_end_cause_omits_the_field() {
725        let value = serde_json::to_value(sample_lease()).unwrap();
726        assert!(value.get("end_cause").is_none());
727        assert!(value.get("binding").is_none());
728    }
729
730    #[test]
731    fn test_lease_with_asked_and_min_cores_round_trips_and_omits_them_when_unknown() {
732        let lease = Lease {
733            asked_cores: Some(8.0),
734            min_cores: Some(4.0),
735            ..sample_lease()
736        };
737        assert_json_round_trip(&lease);
738        let value = serde_json::to_value(&lease).unwrap();
739        assert_eq!(value["asked_cores"], 8.0);
740        assert_eq!(value["min_cores"], 4.0);
741        let unknown = serde_json::to_value(sample_lease()).unwrap();
742        assert!(unknown.get("asked_cores").is_none());
743        assert!(unknown.get("min_cores").is_none());
744    }
745
746    #[test]
747    fn test_lease_with_binding_round_trips_with_and_without_root() {
748        let pending = LeaseBinding {
749            tool_use_id: "toolu_01AbC".into(),
750            bound_at_ms: 1_793_000_013_000,
751            root: None,
752        };
753        let bound = LeaseBinding {
754            root: Some(BoundProcess {
755                pid: 30_112,
756                start_time: 1_793_000_013,
757            }),
758            ..pending.clone()
759        };
760        for binding in [pending, bound] {
761            assert_json_round_trip(&Lease {
762                binding: Some(binding),
763                ..sample_lease()
764            });
765        }
766    }
767
768    #[test]
769    fn test_v0_1_shapes_decode_without_new_fields() {
770        let mut lease = serde_json::to_value(sample_lease()).unwrap();
771        lease.as_object_mut().unwrap().remove("end_cause");
772        let lease: Lease = serde_json::from_value(lease).unwrap();
773        assert_eq!(lease.end_cause, None);
774        assert_eq!(lease.binding, None);
775        assert_eq!(lease.isolation, None);
776        assert_eq!((lease.asked_cores, lease.min_cores), (None, None));
777
778        let mut snapshot = serde_json::to_value(sample_snapshot()).unwrap();
779        snapshot.as_object_mut().unwrap().remove("drives");
780        snapshot["sessions"][0]["processes"][0]
781            .as_object_mut()
782            .unwrap()
783            .remove("exe");
784        let snapshot: Snapshot = serde_json::from_value(snapshot).unwrap();
785        assert!(snapshot.drives.is_empty());
786        assert_eq!(snapshot.sessions[0].processes[0].exe, None);
787    }
788
789    #[test]
790    fn test_windows_adapter_and_lease_omit_every_cross_platform_field() {
791        let snapshot = serde_json::to_value(sample_snapshot()).unwrap();
792        let gpu = snapshot["gpus"][0].as_object().unwrap();
793        for field in ["unified_memory", "source", "process_load", "process_memory"] {
794            assert!(gpu.get(field).is_none(), "{field}");
795        }
796        let lease = serde_json::to_value(sample_lease()).unwrap();
797        assert!(lease.get("isolation").is_none());
798    }
799
800    #[test]
801    fn test_adapter_from_an_older_allotd_is_a_windows_adapter() {
802        let mut value = serde_json::to_value(&sample_snapshot().gpus[0]).unwrap();
803        let object = value.as_object_mut().unwrap();
804        for field in ["unified_memory", "source", "process_load", "process_memory"] {
805            object.remove(field);
806        }
807        let gpu: GpuAdapter = serde_json::from_value(value).unwrap();
808        assert!(!gpu.unified_memory);
809        assert_eq!(gpu.source, GpuSource::Pdh);
810        assert_eq!(gpu.process_load, Accuracy::Exact);
811        assert_eq!(gpu.process_memory, Accuracy::Exact);
812    }
813
814    #[test]
815    fn test_unified_adapter_round_trips_and_writes_snake_case() {
816        let gpu = GpuAdapter {
817            name: "Apple M3 Max".into(),
818            luid: "4294969310".into(),
819            dedicated_used_mb: 9_216,
820            dedicated_total_mb: None,
821            shared_used_mb: 0,
822            unified_memory: true,
823            source: GpuSource::Iokit,
824            process_load: Accuracy::Estimated,
825            process_memory: Accuracy::Unavailable,
826            ..sample_snapshot().gpus[0].clone()
827        };
828        assert_json_round_trip(&gpu);
829        let value = serde_json::to_value(&gpu).unwrap();
830        assert_eq!(value["unified_memory"], true);
831        assert_eq!(value["source"], "iokit");
832        assert_eq!(value["process_load"], "estimated");
833        assert_eq!(value["process_memory"], "unavailable");
834        let fdinfo = serde_json::to_value(GpuSource::DrmFdinfo).unwrap();
835        assert_eq!(fdinfo, "drm_fdinfo");
836    }
837
838    #[test]
839    fn test_lease_with_isolation_round_trips_for_cgroup_and_tree() {
840        let cgroup = LeaseIsolation {
841            kind: IsolationKind::Cgroup,
842            scope: Some("allot-lease-7.scope".into()),
843            limits: EnforcedLimits {
844                cpu_cores: Some(8.0),
845                memory_high_mb: Some(4096),
846                memory_max_mb: Some(6144),
847            },
848        };
849        let tree = LeaseIsolation {
850            kind: IsolationKind::Tree,
851            scope: None,
852            limits: EnforcedLimits::default(),
853        };
854        for isolation in [cgroup, tree] {
855            assert_json_round_trip(&Lease {
856                isolation: Some(isolation),
857                ..sample_lease()
858            });
859        }
860        let value = serde_json::to_value(Lease {
861            isolation: Some(LeaseIsolation {
862                kind: IsolationKind::Tree,
863                scope: None,
864                limits: EnforcedLimits::default(),
865            }),
866            ..sample_lease()
867        })
868        .unwrap();
869        assert_eq!(value["isolation"]["kind"], "tree");
870        assert!(value["isolation"]["scope"].is_null());
871        assert!(value["isolation"]["limits"]["memory_max_mb"].is_null());
872    }
873
874    #[test]
875    fn test_snapshot_without_drives_and_exe_omits_both_fields() {
876        let mut snapshot = sample_snapshot();
877        snapshot.drives.clear();
878        snapshot.sessions[0].processes[0].exe = None;
879        let value = serde_json::to_value(snapshot).unwrap();
880        assert!(value.get("drives").is_none());
881        assert!(value["sessions"][0]["processes"][0].get("exe").is_none());
882    }
883
884    #[test]
885    fn test_gpu_engines_busiest_reads_the_picked_window_of_the_busiest_group() {
886        let rolling = |avg_1s, avg_10s| Rolling {
887            avg_1s,
888            avg_10s,
889            avg_60s: 0.0,
890        };
891        let engines = GpuEngines {
892            three_d_pct: rolling(12.0, 40.0),
893            compute_pct: rolling(55.5, 20.0),
894            copy_pct: rolling(1.0, 1.0),
895            video_pct: rolling(0.0, 0.0),
896        };
897        assert_eq!(engines.busiest(|load| load.avg_1s), 55.5);
898        assert_eq!(engines.busiest(|load| load.avg_10s), 40.0);
899        assert_eq!(GpuEngines::default().busiest(|load| load.avg_1s), 0.0);
900    }
901
902    #[test]
903    fn test_resource_usage_add_assign_sums_every_field() {
904        let mut total = ResourceUsage {
905            cores: 1.5,
906            ram_mb: 100,
907            gpu_pct: 10.0,
908            vram_mb: 64,
909        };
910        total += ResourceUsage {
911            cores: 2.25,
912            ram_mb: 50,
913            gpu_pct: 5.5,
914            vram_mb: 0,
915        };
916        assert_eq!(
917            total,
918            ResourceUsage {
919                cores: 3.75,
920                ram_mb: 150,
921                gpu_pct: 15.5,
922                vram_mb: 64,
923            }
924        );
925    }
926
927    #[test]
928    fn test_noise_report_json_round_trip_preserves_every_field() {
929        assert_json_round_trip(&NoiseReport {
930            avg_cpu_pct: 2.5,
931            peak_cpu_pct: 9.0,
932            avg_gpu_pct: 0.5,
933            peak_gpu_pct: 3.25,
934            quiet_at_start: false,
935        });
936    }
937
938    #[test]
939    fn test_lease_without_cwd_field_deserializes_with_empty_cwd() {
940        let mut value = serde_json::to_value(sample_lease()).unwrap();
941        value.as_object_mut().unwrap().remove("cwd");
942        let lease: Lease = serde_json::from_value(value).unwrap();
943        assert_eq!(lease.cwd, "");
944    }
945
946    #[test]
947    fn test_job_run_json_round_trip_preserves_every_field() {
948        let usage = ResourceUsage {
949            cores: 6.5,
950            ram_mb: 2800,
951            gpu_pct: 0.0,
952            vram_mb: 0,
953        };
954        assert_json_round_trip(&JobRun {
955            lease_id: Some(LeaseId(3)),
956            session: Some(SessionKey("3f2a9c1e-session".into())),
957            end_cause: Some(EndCause::Killed),
958            fingerprint: r"cargo build -p allotd|e:\work\app".into(),
959            command: "cargo build -p allotd 2>&1".into(),
960            cwd: r"E:\work\app".into(),
961            declared: profile_with(8.0, 0.0),
962            peak: usage,
963            avg: usage,
964            busy: Some(BusyUsage {
965                cores: 7.25,
966                gpu_pct: 0.0,
967            }),
968            started_at_ms: 1_793_000_000_000,
969            ended_at_ms: 1_793_000_095_000,
970            noise: None,
971            overlapped: true,
972        });
973    }
974
975    #[test]
976    fn test_job_profile_invalid_reason_in_range_is_none() {
977        assert_eq!(profile_with(0.0, 0.0).invalid_reason(), None);
978        assert_eq!(profile_with(16.0, 100.0).invalid_reason(), None);
979    }
980
981    #[test]
982    fn test_job_profile_invalid_reason_out_of_range_names_field() {
983        assert!(
984            profile_with(-1.0, 0.0)
985                .invalid_reason()
986                .unwrap()
987                .contains("cores")
988        );
989        assert!(
990            profile_with(f32::NAN, 0.0)
991                .invalid_reason()
992                .unwrap()
993                .contains("cores")
994        );
995        assert!(
996            profile_with(1.0, 101.0)
997                .invalid_reason()
998                .unwrap()
999                .contains("gpu_pct")
1000        );
1001        assert!(
1002            profile_with(1.0, f32::NAN)
1003                .invalid_reason()
1004                .unwrap()
1005                .contains("gpu_pct")
1006        );
1007    }
1008}