interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / spark-supervisor / src / proc_telemetry.rs

131 lines · 4454 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use std::fs;
17use std::path::Path;
18
19#[derive(Debug, Clone, Default)]
20#[allow(dead_code)]
21pub struct ProcessStats {
22 pub pid: u32,
23 pub is_alive: bool,
24 pub rss_bytes: u64,
25 pub cmdline: String,
26}
27
28/// Reads the state letter, field (3) of `/proc/<pid>/stat`. Field (2) `comm` is in
29/// parentheses and may itself contain spaces or `)`, so the state is the first token
30/// after the last `)` (proc_pid_stat(5)).
31pub fn parse_stat_state(stat: &str) -> Option<char> {
32 let rest = &stat[stat.rfind(')')? + 1..];
33 rest.split_whitespace().next()?.chars().next()
34}
35
36/// A pid counts as alive unless its state is Z (zombie: exited, not yet reaped) or
37/// X/x (dead), per proc_pid_stat(5). A zombie still has a `/proc/<pid>` directory, so
38/// directory existence alone would report an exited child as alive.
39pub fn stat_state_is_alive(state: char) -> bool {
40 !matches!(state, 'Z' | 'X' | 'x')
41}
42
43pub fn get_process_stats(pid: u32) -> ProcessStats {
44 let proc_dir = format!("/proc/{}", pid);
45 let path = Path::new(&proc_dir);
46 // Unreadable or unparsable stat (the process vanished mid-read) counts as not alive.
47 let alive = fs::read_to_string(path.join("stat"))
48 .ok()
49 .and_then(|s| parse_stat_state(&s))
50 .is_some_and(stat_state_is_alive);
51 if !alive {
52 return ProcessStats {
53 pid,
54 is_alive: false,
55 rss_bytes: 0,
56 cmdline: String::new(),
57 };
58 }
59
60 let cmdline = fs::read_to_string(path.join("cmdline"))
61 .map(|s| s.replace('\0', " ").trim().to_string())
62 .unwrap_or_default();
63
64 let mut rss_bytes = 0;
65 if let Ok(statm) = fs::read_to_string(path.join("statm")) {
66 let parts: Vec<&str> = statm.split_whitespace().collect();
67 if parts.len() >= 2 {
68 if let Ok(resident_pages) = parts[1].parse::<u64>() {
69 // Typical page size is 4096 bytes on Linux arm64/x86_64
70 rss_bytes = resident_pages * 4096;
71 }
72 }
73 }
74
75 ProcessStats {
76 pid,
77 is_alive: true,
78 rss_bytes,
79 cmdline,
80 }
81}
82
83#[cfg(test)]
84mod tests {
85 use super::*;
86 use std::time::{Duration, Instant};
87
88 #[test]
89 fn parses_state_after_last_paren() {
90 assert_eq!(parse_stat_state("123 (sleep) S 1 123 123"), Some('S'));
91 assert_eq!(parse_stat_state("123 (a) b) Z 1 123"), Some('Z'));
92 assert_eq!(parse_stat_state("123 (sleep"), None);
93 assert_eq!(parse_stat_state(""), None);
94 }
95
96 #[test]
97 fn zombie_and_dead_are_not_alive() {
98 for s in ['Z', 'X', 'x'] {
99 assert!(!stat_state_is_alive(s), "{s}");
100 }
101 for s in ['R', 'S', 'D', 'T', 't'] {
102 assert!(stat_state_is_alive(s), "{s}");
103 }
104 }
105
106 #[test]
107 fn own_process_is_alive_missing_pid_is_not() {
108 assert!(get_process_stats(std::process::id()).is_alive);
109 assert!(!get_process_stats(u32::MAX).is_alive);
110 }
111
112 #[test]
113 fn unreaped_child_zombie_is_not_alive() {
114 let mut child = std::process::Command::new("true").spawn().unwrap();
115 let pid = child.id();
116 let stat = format!("/proc/{pid}/stat");
117 let deadline = Instant::now() + Duration::from_secs(5);
118 // Not reaped yet: wait for the kernel to show it as a zombie.
119 loop {
120 let s = fs::read_to_string(&stat).expect("zombie keeps its /proc entry");
121 if parse_stat_state(&s) == Some('Z') {
122 break;
123 }
124 assert!(Instant::now() < deadline, "never became a zombie: {s}");
125 std::thread::sleep(Duration::from_millis(1));
126 }
127 assert!(Path::new(&format!("/proc/{pid}")).exists());
128 assert!(!get_process_stats(pid).is_alive);
129 child.wait().unwrap();
130 }
131}