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