Skip to main content

hawdb_qos/
resource.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#![forbid(unsafe_code)]
16
17use crate::{StorageDeviceProfile, StorageMediaKind};
18#[cfg(any(target_os = "linux", test))]
19use hawdb_cgroup::{LinuxCgroupSnapshot, LinuxCgroupValue, LinuxCgroupVersion};
20use std::num::NonZeroUsize;
21use sysinfo::System;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct RuntimeResourceBudget {
25    pub host_parallelism: NonZeroUsize,
26    pub cgroup_quota_parallelism: Option<NonZeroUsize>,
27    pub cpuset_parallelism: Option<NonZeroUsize>,
28    pub effective_parallelism: NonZeroUsize,
29    pub foreground_parallelism: NonZeroUsize,
30    pub background_parallelism: NonZeroUsize,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub struct IoConcurrencyBudget {
35    pub foreground_depth: NonZeroUsize,
36    pub background_depth: NonZeroUsize,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
40pub enum RuntimeMemoryPressure {
41    Normal,
42    Elevated,
43    Critical,
44    #[default]
45    Unknown,
46}
47
48impl RuntimeMemoryPressure {
49    pub const fn as_str(self) -> &'static str {
50        match self {
51            Self::Normal => "normal",
52            Self::Elevated => "elevated",
53            Self::Critical => "critical",
54            Self::Unknown => "unknown",
55        }
56    }
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub struct RuntimeMemorySnapshot {
61    pub host_total_bytes: Option<u64>,
62    pub host_available_bytes: Option<u64>,
63    pub cgroup_limit_bytes: Option<u64>,
64    pub cgroup_high_bytes: Option<u64>,
65    pub cgroup_current_bytes: Option<u64>,
66    pub effective_limit_bytes: Option<u64>,
67    pub effective_available_bytes: Option<u64>,
68    pub pressure: RuntimeMemoryPressure,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub struct RuntimeResourceSnapshot {
73    pub cpu: RuntimeResourceBudget,
74    pub memory: RuntimeMemorySnapshot,
75}
76
77#[derive(Debug)]
78pub(crate) struct RuntimeResourceDetector {
79    system: Option<System>,
80    #[cfg(test)]
81    scripted: Option<ScriptedHostResources>,
82}
83
84/// Test-only host whose samples a test controls and counts.
85#[cfg(test)]
86#[derive(Debug, Clone)]
87pub(crate) struct ScriptedHostResources {
88    current: std::sync::Arc<std::sync::Mutex<RuntimeResourceSnapshot>>,
89    samples: std::sync::Arc<std::sync::atomic::AtomicU64>,
90}
91
92#[cfg(test)]
93impl ScriptedHostResources {
94    pub(crate) fn new(initial: RuntimeResourceSnapshot) -> Self {
95        Self {
96            current: std::sync::Arc::new(std::sync::Mutex::new(initial)),
97            samples: std::sync::Arc::default(),
98        }
99    }
100
101    pub(crate) fn set(&self, resources: RuntimeResourceSnapshot) {
102        *self.current.lock().unwrap() = resources;
103    }
104
105    pub(crate) fn samples(&self) -> u64 {
106        self.samples.load(std::sync::atomic::Ordering::SeqCst)
107    }
108
109    pub(crate) fn detector(&self) -> RuntimeResourceDetector {
110        RuntimeResourceDetector {
111            system: None,
112            scripted: Some(self.clone()),
113        }
114    }
115}
116
117impl RuntimeResourceDetector {
118    pub(crate) fn new() -> Self {
119        Self {
120            system: None,
121            #[cfg(test)]
122            scripted: None,
123        }
124    }
125
126    pub(crate) fn detect(&mut self) -> RuntimeResourceSnapshot {
127        #[cfg(test)]
128        if let Some(scripted) = &self.scripted {
129            scripted
130                .samples
131                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
132            return *scripted.current.lock().unwrap();
133        }
134        let host_parallelism = std::thread::available_parallelism().unwrap_or(NonZeroUsize::MIN);
135        let (host_total_bytes, host_available_bytes) =
136            detect_host_memory(&mut self.system, System::new);
137
138        #[cfg(target_os = "linux")]
139        {
140            let cgroup = LinuxCgroupSnapshot::detect();
141            resource_snapshot_from_cgroup(
142                host_parallelism,
143                host_total_bytes,
144                host_available_bytes,
145                &cgroup,
146            )
147        }
148
149        #[cfg(not(target_os = "linux"))]
150        RuntimeResourceSnapshot::from_parts(
151            RuntimeResourceBudget::from_limits(host_parallelism, None, None),
152            RuntimeMemorySnapshot::from_limits(
153                host_total_bytes,
154                host_available_bytes,
155                None,
156                None,
157                None,
158            ),
159        )
160    }
161}
162
163impl RuntimeResourceBudget {
164    pub fn detect() -> Self {
165        let host = std::thread::available_parallelism().unwrap_or(NonZeroUsize::MIN);
166        #[cfg(target_os = "linux")]
167        let (quota, cpuset) = linux_cgroup_cpu_limits();
168        #[cfg(not(target_os = "linux"))]
169        let (quota, cpuset) = (None, None);
170        Self::from_limits(host, quota, cpuset)
171    }
172
173    pub fn from_limits(
174        host_parallelism: NonZeroUsize,
175        cgroup_quota_parallelism: Option<NonZeroUsize>,
176        cpuset_parallelism: Option<NonZeroUsize>,
177    ) -> Self {
178        let effective = [
179            Some(host_parallelism),
180            cgroup_quota_parallelism,
181            cpuset_parallelism,
182        ]
183        .into_iter()
184        .flatten()
185        .min()
186        .unwrap_or(NonZeroUsize::MIN);
187        let background = NonZeroUsize::new((effective.get() / 4).max(1))
188            .expect("background parallelism is always non-zero");
189        Self {
190            host_parallelism,
191            cgroup_quota_parallelism,
192            cpuset_parallelism,
193            effective_parallelism: effective,
194            foreground_parallelism: effective,
195            background_parallelism: background,
196        }
197    }
198}
199
200impl RuntimeMemorySnapshot {
201    pub fn detect() -> Self {
202        let mut system = None;
203        let (host_total_bytes, host_available_bytes) = detect_host_memory(&mut system, System::new);
204
205        #[cfg(target_os = "linux")]
206        let (cgroup_limit_bytes, cgroup_high_bytes, cgroup_current_bytes) =
207            linux_cgroup_memory_limits();
208        #[cfg(not(target_os = "linux"))]
209        let (cgroup_limit_bytes, cgroup_high_bytes, cgroup_current_bytes) = (None, None, None);
210
211        Self::from_limits(
212            host_total_bytes,
213            host_available_bytes,
214            cgroup_limit_bytes,
215            cgroup_high_bytes,
216            cgroup_current_bytes,
217        )
218    }
219
220    pub fn from_limits(
221        host_total_bytes: Option<u64>,
222        host_available_bytes: Option<u64>,
223        cgroup_limit_bytes: Option<u64>,
224        cgroup_high_bytes: Option<u64>,
225        cgroup_current_bytes: Option<u64>,
226    ) -> Self {
227        let cgroup_effective_limit_bytes = [cgroup_limit_bytes, cgroup_high_bytes]
228            .into_iter()
229            .flatten()
230            .min();
231        let effective_limit_bytes = [host_total_bytes, cgroup_effective_limit_bytes]
232            .into_iter()
233            .flatten()
234            .min();
235        let cgroup_available_bytes = cgroup_effective_limit_bytes
236            .zip(cgroup_current_bytes)
237            .map(|(limit, current)| limit.saturating_sub(current));
238        let effective_available_bytes = [host_available_bytes, cgroup_available_bytes]
239            .into_iter()
240            .flatten()
241            .min();
242        let pressure = memory_pressure(
243            effective_limit_bytes,
244            effective_available_bytes,
245            cgroup_high_bytes,
246            cgroup_current_bytes,
247        );
248        Self {
249            host_total_bytes,
250            host_available_bytes,
251            cgroup_limit_bytes,
252            cgroup_high_bytes,
253            cgroup_current_bytes,
254            effective_limit_bytes,
255            effective_available_bytes,
256            pressure,
257        }
258    }
259}
260
261impl RuntimeResourceSnapshot {
262    pub fn detect() -> Self {
263        RuntimeResourceDetector::new().detect()
264    }
265
266    pub const fn from_parts(cpu: RuntimeResourceBudget, memory: RuntimeMemorySnapshot) -> Self {
267        Self { cpu, memory }
268    }
269}
270
271#[cfg(any(target_os = "linux", test))]
272fn resource_snapshot_from_cgroup(
273    host_parallelism: NonZeroUsize,
274    host_total_bytes: Option<u64>,
275    host_available_bytes: Option<u64>,
276    cgroup: &LinuxCgroupSnapshot,
277) -> RuntimeResourceSnapshot {
278    let (cgroup_quota_parallelism, cpuset_parallelism) = cgroup_cpu_limits_from(cgroup);
279    let (cgroup_limit_bytes, cgroup_high_bytes, cgroup_current_bytes) =
280        cgroup_memory_limits_from(cgroup);
281    RuntimeResourceSnapshot::from_parts(
282        RuntimeResourceBudget::from_limits(
283            host_parallelism,
284            cgroup_quota_parallelism,
285            cpuset_parallelism,
286        ),
287        RuntimeMemorySnapshot::from_limits(
288            host_total_bytes,
289            host_available_bytes,
290            cgroup_limit_bytes,
291            cgroup_high_bytes,
292            cgroup_current_bytes,
293        ),
294    )
295}
296
297impl IoConcurrencyBudget {
298    pub fn shared_host() -> Self {
299        Self::shared_host_for_device(StorageDeviceProfile::default())
300    }
301
302    pub fn shared_host_for_device(device: StorageDeviceProfile) -> Self {
303        let foreground = match device.media_kind {
304            StorageMediaKind::Rotational => 2,
305            StorageMediaKind::NonRotational => device
306                .queue_depth_hint
307                .map(NonZeroUsize::get)
308                .unwrap_or(12)
309                .clamp(4, 32),
310            StorageMediaKind::Memory => 8,
311            StorageMediaKind::Network | StorageMediaKind::Virtual | StorageMediaKind::Unknown => 4,
312        };
313        let background = (foreground / 4).clamp(1, 4);
314        Self::new(foreground, background)
315    }
316
317    pub fn mobile_embedded() -> Self {
318        Self::mobile_embedded_for_device(StorageDeviceProfile::default())
319    }
320
321    pub fn mobile_embedded_for_device(device: StorageDeviceProfile) -> Self {
322        let foreground = match device.media_kind {
323            StorageMediaKind::Rotational
324            | StorageMediaKind::Network
325            | StorageMediaKind::Virtual => 1,
326            StorageMediaKind::NonRotational | StorageMediaKind::Memory => device
327                .queue_depth_hint
328                .map(NonZeroUsize::get)
329                .unwrap_or(4)
330                .clamp(1, 4),
331            StorageMediaKind::Unknown => 2,
332        };
333        Self::new(foreground, 1)
334    }
335
336    pub fn new(foreground_depth: usize, background_depth: usize) -> Self {
337        Self {
338            foreground_depth: NonZeroUsize::new(foreground_depth.max(1))
339                .expect("foreground I/O depth is always non-zero"),
340            background_depth: NonZeroUsize::new(background_depth.max(1))
341                .expect("background I/O depth is always non-zero"),
342        }
343    }
344}
345
346#[cfg(target_os = "linux")]
347fn linux_cgroup_cpu_limits() -> (Option<NonZeroUsize>, Option<NonZeroUsize>) {
348    cgroup_cpu_limits_from(&LinuxCgroupSnapshot::detect())
349}
350
351#[cfg(any(target_os = "linux", test))]
352fn cgroup_cpu_limits_from(
353    snapshot: &LinuxCgroupSnapshot,
354) -> (Option<NonZeroUsize>, Option<NonZeroUsize>) {
355    if !cgroup_limits_are_sensed(snapshot.version) {
356        return (None, None);
357    }
358    (
359        admitted_cpu_limit(snapshot.cpu_quota_parallelism),
360        admitted_cpu_limit(snapshot.cpuset_parallelism),
361    )
362}
363
364/// Whether the sensed cgroup hierarchy carries limits this crate reads.
365///
366/// Cgroup v1 and hybrid hierarchies are deliberately not parsed. Their
367/// `V1Unsupported` marker means "limits may exist but HawDB does not read
368/// them", not "sensing failed": treating it as a failure would derive a
369/// zero memory capacity and permanently reject every query on such hosts.
370/// Host totals govern instead, and any v1-enforced limit remains the
371/// kernel's to enforce. `Unknown` (unreadable procfs, unresolvable v2
372/// mount) and per-file `Invalid` values stay fail-closed.
373#[cfg(any(target_os = "linux", test))]
374const fn cgroup_limits_are_sensed(version: LinuxCgroupVersion) -> bool {
375    !matches!(version, LinuxCgroupVersion::V1Unsupported)
376}
377
378#[cfg(any(target_os = "linux", test))]
379fn admitted_cpu_limit(value: LinuxCgroupValue<NonZeroUsize>) -> Option<NonZeroUsize> {
380    match value {
381        LinuxCgroupValue::Value(value) => Some(value),
382        LinuxCgroupValue::Invalid => Some(NonZeroUsize::MIN),
383        LinuxCgroupValue::Absent | LinuxCgroupValue::Unlimited => None,
384    }
385}
386
387#[cfg(target_os = "linux")]
388fn linux_cgroup_memory_limits() -> (Option<u64>, Option<u64>, Option<u64>) {
389    cgroup_memory_limits_from(&LinuxCgroupSnapshot::detect())
390}
391
392#[cfg(any(target_os = "linux", test))]
393fn cgroup_memory_limits_from(
394    snapshot: &LinuxCgroupSnapshot,
395) -> (Option<u64>, Option<u64>, Option<u64>) {
396    if !cgroup_limits_are_sensed(snapshot.version) {
397        return (None, None, None);
398    }
399    (
400        admitted_memory_limit(snapshot.memory_limit_bytes),
401        admitted_memory_limit(snapshot.memory_high_bytes),
402        admitted_memory_current(snapshot.memory_current_bytes),
403    )
404}
405
406#[cfg(any(target_os = "linux", test))]
407fn admitted_memory_limit(value: LinuxCgroupValue<u64>) -> Option<u64> {
408    match value {
409        LinuxCgroupValue::Value(value) => Some(value),
410        LinuxCgroupValue::Invalid => Some(0),
411        LinuxCgroupValue::Absent | LinuxCgroupValue::Unlimited => None,
412    }
413}
414
415#[cfg(any(target_os = "linux", test))]
416fn admitted_memory_current(value: LinuxCgroupValue<u64>) -> Option<u64> {
417    match value {
418        LinuxCgroupValue::Value(value) => Some(value),
419        LinuxCgroupValue::Invalid => Some(u64::MAX),
420        LinuxCgroupValue::Absent | LinuxCgroupValue::Unlimited => None,
421    }
422}
423
424fn detect_host_memory(
425    system: &mut Option<System>,
426    initialize: impl FnOnce() -> Result<System, sysinfo::Error>,
427) -> (Option<u64>, Option<u64>) {
428    // sysinfo initialization can fail, including on unsupported targets. Keep
429    // host readings unknown and retain independent cgroup limits in that case.
430    // A later refresh can recover; a successful detector remains cached.
431    if system.is_none() {
432        *system = initialize().ok();
433    }
434    let Some(system) = system.as_mut() else {
435        return (None, None);
436    };
437    system.refresh_memory();
438    host_memory_values(system.total_memory(), system.available_memory())
439}
440
441fn host_memory_values(total_bytes: u64, available_bytes: u64) -> (Option<u64>, Option<u64>) {
442    // A detected total makes zero availability meaningful. Only two zero
443    // readings retain sysinfo's unavailable/unsupported fallback.
444    (
445        (total_bytes > 0).then_some(total_bytes),
446        (total_bytes > 0 || available_bytes > 0).then_some(available_bytes),
447    )
448}
449
450fn memory_pressure(
451    effective_limit_bytes: Option<u64>,
452    effective_available_bytes: Option<u64>,
453    cgroup_high_bytes: Option<u64>,
454    cgroup_current_bytes: Option<u64>,
455) -> RuntimeMemoryPressure {
456    if cgroup_high_bytes
457        .zip(cgroup_current_bytes)
458        .is_some_and(|(high, current)| current >= high)
459    {
460        return RuntimeMemoryPressure::Critical;
461    }
462    let Some((limit, available)) = effective_limit_bytes.zip(effective_available_bytes) else {
463        return RuntimeMemoryPressure::Unknown;
464    };
465    if limit == 0 || u128::from(available) * 100 <= u128::from(limit) * 10 {
466        RuntimeMemoryPressure::Critical
467    } else if u128::from(available) * 100 <= u128::from(limit) * 25 {
468        RuntimeMemoryPressure::Elevated
469    } else {
470        RuntimeMemoryPressure::Normal
471    }
472}
473
474#[cfg(test)]
475mod tests {
476    use super::*;
477    use crate::{
478        RuntimeAdmissionCode, RuntimeGovernor, RuntimeGovernorConfig, RuntimeWorkKind,
479        RuntimeWorkPriority, RuntimeWorkRequest,
480    };
481
482    #[test]
483    fn failed_host_initialization_retains_unknown_and_cgroup_budgets() {
484        for error in [
485            sysinfo::Error::Unsupported,
486            sysinfo::Error::Io(std::io::ErrorKind::PermissionDenied.into()),
487            sysinfo::Error::Other("host initialization failed".into()),
488        ] {
489            let mut system = None;
490            let (total, available) = detect_host_memory(&mut system, || Err(error));
491            assert_eq!((total, available), (None, None));
492            assert!(system.is_none());
493            let resources = RuntimeResourceSnapshot::from_parts(
494                RuntimeResourceBudget::from_limits(NonZeroUsize::MIN, None, None),
495                RuntimeMemorySnapshot::from_limits(total, available, None, None, None),
496            );
497            assert_eq!(resources.memory, RuntimeMemorySnapshot::default());
498            let config = RuntimeGovernorConfig::shared_host();
499            let governor = RuntimeGovernor::new(config, resources, IoConcurrencyBudget::new(4, 1));
500            assert_eq!(
501                governor.snapshot().limits.memory_budget_bytes,
502                config.fallback_memory_budget_bytes
503            );
504
505            let cgroup = LinuxCgroupSnapshot {
506                version: LinuxCgroupVersion::V2,
507                memory_limit_bytes: LinuxCgroupValue::Value(4 << 30),
508                memory_high_bytes: LinuxCgroupValue::Value(3 << 30),
509                memory_current_bytes: LinuxCgroupValue::Value(3 << 30),
510                ..LinuxCgroupSnapshot::host()
511            };
512            let constrained =
513                resource_snapshot_from_cgroup(NonZeroUsize::MIN, total, available, &cgroup);
514            assert_eq!(constrained.memory.effective_limit_bytes, Some(3 << 30));
515            assert_eq!(constrained.memory.effective_available_bytes, Some(0));
516            assert_eq!(constrained.memory.pressure, RuntimeMemoryPressure::Critical);
517        }
518    }
519
520    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
521    #[test]
522    fn host_initialization_recovers_and_reuses_the_successful_detector() {
523        let mut system = None;
524        assert_eq!(
525            detect_host_memory(&mut system, || Err(sysinfo::Error::Unsupported)),
526            (None, None)
527        );
528        let (total, _) = detect_host_memory(&mut system, System::new);
529        assert!(
530            system.is_some(),
531            "the native system detector must initialize"
532        );
533        let (cached_total, _) = detect_host_memory(&mut system, || {
534            panic!("a successful detector must be reused")
535        });
536        assert_eq!(cached_total, total);
537    }
538
539    #[test]
540    fn host_memory_values_distinguish_exhausted_from_unknown() {
541        for (total, available, expected) in [
542            (0, 0, (None, None)),
543            (0, 1, (None, Some(1))),
544            (1, 0, (Some(1), Some(0))),
545            (1, 1, (Some(1), Some(1))),
546            (u64::MAX, 0, (Some(u64::MAX), Some(0))),
547            (u64::MAX, u64::MAX, (Some(u64::MAX), Some(u64::MAX))),
548        ] {
549            assert_eq!(host_memory_values(total, available), expected);
550        }
551    }
552
553    fn sampled_host_resources(total: u64, available: u64) -> RuntimeResourceSnapshot {
554        let (total, available) = host_memory_values(total, available);
555        RuntimeResourceSnapshot::from_parts(
556            RuntimeResourceBudget::from_limits(NonZeroUsize::new(8).unwrap(), None, None),
557            RuntimeMemorySnapshot::from_limits(total, available, None, None, None),
558        )
559    }
560
561    #[test]
562    fn zero_host_headroom_gates_real_governor_admission() {
563        let governor = RuntimeGovernor::new(
564            RuntimeGovernorConfig::shared_host(),
565            sampled_host_resources(8 << 30, 0),
566            IoConcurrencyBudget::new(4, 1),
567        );
568        let error = governor
569            .try_admit(RuntimeWorkRequest::blocking_cpu(
570                RuntimeWorkPriority::Foreground,
571                1,
572            ))
573            .unwrap_err();
574        assert_eq!(error.code, RuntimeAdmissionCode::MemorySaturated);
575        assert_eq!(error.available, 0);
576        assert!(error.is_retryable());
577        let snapshot = governor.snapshot();
578        assert_eq!(
579            snapshot.resources.memory.pressure,
580            RuntimeMemoryPressure::Critical
581        );
582        assert_eq!(snapshot.resources.memory.effective_available_bytes, Some(0));
583        assert_eq!(snapshot.limits.memory_capacity_bytes, 2 << 30);
584        assert_eq!(snapshot.limits.memory_budget_bytes, 0);
585        assert_eq!(snapshot.admitted_memory_bytes, 0);
586    }
587
588    #[test]
589    fn host_headroom_and_cgroup_limits_compose_at_admission() {
590        let cgroup = LinuxCgroupSnapshot {
591            version: LinuxCgroupVersion::V2,
592            memory_limit_bytes: LinuxCgroupValue::Value(4 << 30),
593            memory_high_bytes: LinuxCgroupValue::Value(3 << 30),
594            memory_current_bytes: LinuxCgroupValue::Value(2 << 30),
595            ..LinuxCgroupSnapshot::host()
596        };
597        let cases = [
598            (LinuxCgroupSnapshot::host(), None, 2 << 30),
599            (
600                LinuxCgroupSnapshot::fail_closed(LinuxCgroupVersion::V1Unsupported),
601                None,
602                2 << 30,
603            ),
604            (cgroup, Some(1 << 30), 768 << 20),
605            (
606                LinuxCgroupSnapshot {
607                    memory_current_bytes: LinuxCgroupValue::Value(3 << 30),
608                    ..cgroup
609                },
610                Some(0),
611                768 << 20,
612            ),
613            (
614                LinuxCgroupSnapshot {
615                    memory_limit_bytes: LinuxCgroupValue::Unlimited,
616                    memory_high_bytes: LinuxCgroupValue::Unlimited,
617                    ..cgroup
618                },
619                None,
620                2 << 30,
621            ),
622            (
623                LinuxCgroupSnapshot::fail_closed(LinuxCgroupVersion::Unknown),
624                Some(0),
625                0,
626            ),
627            (
628                LinuxCgroupSnapshot {
629                    memory_current_bytes: LinuxCgroupValue::Invalid,
630                    ..cgroup
631                },
632                Some(0),
633                768 << 20,
634            ),
635        ];
636        for (cgroup, cgroup_available, capacity) in cases {
637            for available in [0, 4, 4 << 30] {
638                let (host_total, host_available) = host_memory_values(8 << 30, available);
639                let resources = resource_snapshot_from_cgroup(
640                    NonZeroUsize::new(8).unwrap(),
641                    host_total,
642                    host_available,
643                    &cgroup,
644                );
645                let expected_available = available.min(cgroup_available.unwrap_or(available));
646                let budget = expected_available / 4;
647                assert_eq!(
648                    resources.memory.effective_available_bytes,
649                    Some(expected_available)
650                );
651                let governor = RuntimeGovernor::new(
652                    RuntimeGovernorConfig::shared_host(),
653                    resources,
654                    IoConcurrencyBudget::new(4, 1),
655                );
656                assert_eq!(governor.snapshot().limits.memory_capacity_bytes, capacity);
657                assert_eq!(governor.snapshot().limits.memory_budget_bytes, budget);
658                if budget > 0 {
659                    let permit = governor
660                        .try_admit(RuntimeWorkRequest::blocking_cpu(
661                            RuntimeWorkPriority::Foreground,
662                            budget,
663                        ))
664                        .unwrap();
665                    drop(permit);
666                } else {
667                    assert_eq!(resources.memory.pressure, RuntimeMemoryPressure::Critical);
668                    let error = governor
669                        .try_admit(RuntimeWorkRequest::blocking_cpu(
670                            RuntimeWorkPriority::Background,
671                            0,
672                        ))
673                        .unwrap_err();
674                    assert_eq!(error.code, RuntimeAdmissionCode::MemoryPressure);
675                    assert!(error.is_retryable());
676                }
677                for requested in [budget + 1, capacity + 1] {
678                    let error = governor
679                        .try_admit(RuntimeWorkRequest::blocking_cpu(
680                            RuntimeWorkPriority::Foreground,
681                            requested,
682                        ))
683                        .unwrap_err();
684                    assert_eq!(error.code, RuntimeAdmissionCode::MemorySaturated);
685                    assert_eq!(error.is_retryable(), requested <= capacity);
686                }
687                assert_eq!(governor.snapshot().admitted_memory_bytes, 0);
688            }
689        }
690    }
691
692    #[test]
693    fn unknown_host_readings_retain_the_fallback_budget() {
694        let config = RuntimeGovernorConfig::shared_host();
695        let resources = sampled_host_resources(0, 0);
696        assert_eq!(resources.memory, RuntimeMemorySnapshot::default());
697        let governor = RuntimeGovernor::new(config, resources, IoConcurrencyBudget::new(4, 1));
698        assert_eq!(
699            governor.snapshot().limits.memory_budget_bytes,
700            config.fallback_memory_budget_bytes
701        );
702        let permit = governor
703            .try_admit(RuntimeWorkRequest::blocking_cpu(
704                RuntimeWorkPriority::Foreground,
705                1,
706            ))
707            .unwrap();
708        drop(permit);
709    }
710
711    #[test]
712    fn host_headroom_refresh_preserves_permits_and_recovers_admission() {
713        let healthy = sampled_host_resources(8 << 30, 4 << 30);
714        let exhausted = sampled_host_resources(8 << 30, 0);
715        let governor = RuntimeGovernor::new(
716            RuntimeGovernorConfig::shared_host(),
717            healthy,
718            IoConcurrencyBudget::new(4, 1),
719        );
720        let request = RuntimeWorkRequest::blocking_cpu(RuntimeWorkPriority::Foreground, 128 << 20);
721        let permit = governor.try_admit(request).unwrap();
722        assert!(governor.update_resources(exhausted));
723        let snapshot = governor.snapshot();
724        assert_eq!(snapshot.admitted_memory_bytes, request.memory_bytes);
725        assert_eq!(snapshot.limits.memory_budget_bytes, request.memory_bytes);
726        assert_eq!(snapshot.limits.memory_capacity_bytes, 2 << 30);
727        assert_eq!(snapshot.active_foreground_tasks, 1);
728        let error = governor.try_admit(request).unwrap_err();
729        assert_eq!(error.code, RuntimeAdmissionCode::MemorySaturated);
730        assert!(error.is_retryable());
731
732        drop(permit);
733        assert!(governor.update_resources(exhausted));
734        assert!(!governor.update_resources(exhausted));
735        assert_eq!(governor.snapshot().admitted_memory_bytes, 0);
736        assert_eq!(governor.snapshot().limits.memory_budget_bytes, 0);
737        assert!(governor.try_admit(request).unwrap_err().is_retryable());
738
739        assert!(governor.update_resources(healthy));
740        assert_eq!(governor.snapshot().limits.memory_budget_bytes, 1 << 30);
741        let permit = governor.try_admit(request).unwrap();
742        drop(permit);
743        assert_eq!(governor.snapshot().active_foreground_tasks, 0);
744    }
745
746    #[test]
747    fn effective_budget_uses_the_smallest_cpu_limit() {
748        let budget = RuntimeResourceBudget::from_limits(
749            NonZeroUsize::new(16).unwrap(),
750            NonZeroUsize::new(6),
751            NonZeroUsize::new(4),
752        );
753        assert_eq!(budget.effective_parallelism.get(), 4);
754        assert_eq!(budget.foreground_parallelism.get(), 4);
755        assert_eq!(budget.background_parallelism.get(), 1);
756    }
757
758    #[test]
759    fn v1_cgroup_snapshot_falls_back_to_host_limits() {
760        let snapshot = LinuxCgroupSnapshot::fail_closed(LinuxCgroupVersion::V1Unsupported);
761        assert_eq!(cgroup_cpu_limits_from(&snapshot), (None, None));
762        assert_eq!(cgroup_memory_limits_from(&snapshot), (None, None, None));
763
764        let memory =
765            RuntimeMemorySnapshot::from_limits(Some(16 << 30), Some(8 << 30), None, None, None);
766        assert_eq!(memory.effective_limit_bytes, Some(16 << 30));
767        assert_eq!(memory.effective_available_bytes, Some(8 << 30));
768    }
769
770    #[test]
771    fn unknown_cgroup_snapshot_remains_fail_closed() {
772        let snapshot = LinuxCgroupSnapshot::fail_closed(LinuxCgroupVersion::Unknown);
773        assert_eq!(
774            cgroup_cpu_limits_from(&snapshot),
775            (Some(NonZeroUsize::MIN), Some(NonZeroUsize::MIN))
776        );
777        assert_eq!(
778            cgroup_memory_limits_from(&snapshot),
779            (Some(0), Some(0), Some(u64::MAX))
780        );
781    }
782
783    #[test]
784    fn invalid_cgroup_values_fail_closed_at_admission_boundary() {
785        assert_eq!(
786            admitted_cpu_limit(LinuxCgroupValue::Invalid),
787            Some(NonZeroUsize::MIN)
788        );
789        assert_eq!(admitted_memory_limit(LinuxCgroupValue::Invalid), Some(0));
790        assert_eq!(
791            admitted_memory_current(LinuxCgroupValue::Invalid),
792            Some(u64::MAX)
793        );
794
795        let memory = RuntimeMemorySnapshot::from_limits(
796            Some(16 << 30),
797            Some(8 << 30),
798            admitted_memory_limit(LinuxCgroupValue::Invalid),
799            None,
800            admitted_memory_current(LinuxCgroupValue::Invalid),
801        );
802        assert_eq!(memory.effective_limit_bytes, Some(0));
803        assert_eq!(memory.effective_available_bytes, Some(0));
804        assert_eq!(memory.pressure, RuntimeMemoryPressure::Critical);
805    }
806
807    #[test]
808    fn resource_snapshot_derives_cpu_and_memory_from_one_cgroup_sample() {
809        let cgroup = LinuxCgroupSnapshot {
810            version: LinuxCgroupVersion::V2,
811            cpu_quota_parallelism: LinuxCgroupValue::Value(NonZeroUsize::new(6).unwrap()),
812            cpuset_parallelism: LinuxCgroupValue::Value(NonZeroUsize::new(4).unwrap()),
813            memory_limit_bytes: LinuxCgroupValue::Value(4 << 30),
814            memory_high_bytes: LinuxCgroupValue::Value(3 << 30),
815            memory_current_bytes: LinuxCgroupValue::Value(2 << 30),
816        };
817        let snapshot = resource_snapshot_from_cgroup(
818            NonZeroUsize::new(16).unwrap(),
819            Some(16 << 30),
820            Some(8 << 30),
821            &cgroup,
822        );
823
824        assert_eq!(snapshot.cpu.cgroup_quota_parallelism.unwrap().get(), 6);
825        assert_eq!(snapshot.cpu.cpuset_parallelism.unwrap().get(), 4);
826        assert_eq!(snapshot.cpu.effective_parallelism.get(), 4);
827        assert_eq!(snapshot.memory.cgroup_limit_bytes, Some(4 << 30));
828        assert_eq!(snapshot.memory.cgroup_high_bytes, Some(3 << 30));
829        assert_eq!(snapshot.memory.cgroup_current_bytes, Some(2 << 30));
830        assert_eq!(snapshot.memory.effective_limit_bytes, Some(3 << 30));
831        assert_eq!(snapshot.memory.effective_available_bytes, Some(1 << 30));
832    }
833
834    #[test]
835    fn memory_snapshot_uses_cgroup_headroom_and_high_watermark() {
836        let snapshot = RuntimeMemorySnapshot::from_limits(
837            Some(16 << 30),
838            Some(8 << 30),
839            Some(4 << 30),
840            Some(3 << 30),
841            Some(2 << 30),
842        );
843        assert_eq!(snapshot.effective_limit_bytes, Some(3 << 30));
844        assert_eq!(snapshot.effective_available_bytes, Some(1 << 30));
845        assert_eq!(snapshot.pressure, RuntimeMemoryPressure::Normal);
846
847        let pressured = RuntimeMemorySnapshot::from_limits(
848            Some(16 << 30),
849            Some(8 << 30),
850            Some(4 << 30),
851            Some(3 << 30),
852            Some(3 << 30),
853        );
854        assert_eq!(pressured.pressure, RuntimeMemoryPressure::Critical);
855    }
856
857    #[test]
858    fn platform_memory_detection_has_internally_consistent_limits() {
859        let snapshot = RuntimeMemorySnapshot::detect();
860        if let (Some(limit), Some(available)) = (
861            snapshot.effective_limit_bytes,
862            snapshot.effective_available_bytes,
863        ) {
864            assert!(available <= limit);
865        }
866    }
867
868    #[test]
869    fn shared_host_io_budget_uses_device_evidence_instead_of_cpu_count() {
870        let device = StorageDeviceProfile::host_provided(
871            StorageMediaKind::NonRotational,
872            NonZeroUsize::new(12),
873        );
874        let io = IoConcurrencyBudget::shared_host_for_device(device);
875        assert_eq!(io.foreground_depth.get(), 12);
876        assert_eq!(io.background_depth.get(), 3);
877
878        let default_ssd =
879            StorageDeviceProfile::host_provided(StorageMediaKind::NonRotational, None);
880        let io = IoConcurrencyBudget::shared_host_for_device(default_ssd);
881        assert_eq!(io.foreground_depth.get(), 12);
882        assert_eq!(io.background_depth.get(), 3);
883    }
884
885    #[test]
886    fn shared_host_ssd_io_budget_preserves_explicit_hint_bounds() {
887        for (hint, foreground, background) in [(1, 4, 1), (8, 8, 2), (16, 16, 4), (64, 32, 4)] {
888            let device = StorageDeviceProfile::host_provided(
889                StorageMediaKind::NonRotational,
890                NonZeroUsize::new(hint),
891            );
892            let io = IoConcurrencyBudget::shared_host_for_device(device);
893            assert_eq!(io, IoConcurrencyBudget::new(foreground, background));
894        }
895    }
896
897    #[test]
898    fn shared_host_ssd_io_admission_enforces_and_refunds_each_priority_budget() {
899        let device = StorageDeviceProfile::host_provided(StorageMediaKind::NonRotational, None);
900        let governor = RuntimeGovernor::new(
901            RuntimeGovernorConfig::shared_host(),
902            sampled_host_resources(8 << 30, 8 << 30),
903            IoConcurrencyBudget::shared_host_for_device(device),
904        );
905        let mut foreground =
906            RuntimeWorkRequest::new(RuntimeWorkPriority::Foreground, RuntimeWorkKind::Io);
907        foreground.io_slots = 12;
908        let mut background =
909            RuntimeWorkRequest::new(RuntimeWorkPriority::Background, RuntimeWorkKind::Io);
910        background.io_slots = 3;
911        let foreground_permit = governor.try_admit(foreground).unwrap();
912        let background_permit = governor.try_admit(background).unwrap();
913        let snapshot = governor.snapshot();
914        assert_eq!(snapshot.active_foreground_io_slots, 12);
915        assert_eq!(snapshot.active_background_io_slots, 3);
916
917        for mut request in [foreground, background] {
918            request.io_slots = 1;
919            let error = governor.try_admit(request).unwrap_err();
920            assert_eq!(error.code, RuntimeAdmissionCode::IoSaturated);
921            assert_eq!(error.requested, 1);
922            assert_eq!(error.available, 0);
923            assert!(error.is_retryable());
924        }
925
926        drop(background_permit);
927        assert_eq!(governor.snapshot().active_background_io_slots, 0);
928        assert_eq!(governor.snapshot().active_foreground_io_slots, 12);
929        drop(governor.try_admit(background).unwrap());
930        drop(foreground_permit);
931        drop(governor.try_admit(foreground).unwrap());
932        let snapshot = governor.snapshot();
933        assert_eq!(snapshot.active_foreground_io_slots, 0);
934        assert_eq!(snapshot.active_background_io_slots, 0);
935    }
936
937    #[test]
938    fn shared_host_non_ssd_io_defaults_stay_conservative() {
939        for (kind, foreground, background) in [
940            (StorageMediaKind::Rotational, 2, 1),
941            (StorageMediaKind::Memory, 8, 2),
942            (StorageMediaKind::Network, 4, 1),
943            (StorageMediaKind::Virtual, 4, 1),
944            (StorageMediaKind::Unknown, 4, 1),
945        ] {
946            let io = IoConcurrencyBudget::shared_host_for_device(
947                StorageDeviceProfile::host_provided(kind, None),
948            );
949            assert_eq!(io, IoConcurrencyBudget::new(foreground, background));
950        }
951    }
952
953    #[test]
954    fn mobile_io_budget_stays_conservative() {
955        let device = StorageDeviceProfile::host_provided(
956            StorageMediaKind::NonRotational,
957            NonZeroUsize::new(32),
958        );
959        let io = IoConcurrencyBudget::mobile_embedded_for_device(device);
960        assert_eq!(io.foreground_depth.get(), 4);
961        assert_eq!(io.background_depth.get(), 1);
962    }
963
964    #[test]
965    fn unknown_device_budget_uses_conservative_defaults() {
966        assert_eq!(
967            IoConcurrencyBudget::shared_host(),
968            IoConcurrencyBudget::shared_host_for_device(StorageDeviceProfile::default())
969        );
970        assert_eq!(
971            IoConcurrencyBudget::mobile_embedded(),
972            IoConcurrencyBudget::mobile_embedded_for_device(StorageDeviceProfile::default())
973        );
974    }
975}