Skip to main content

adk_harness/shell/
pids.rs

1//! The process groups of background shells, kept so the next start reaps what a crash left
2//! running (spec 3.1 §7.29 "Lifetime", §9.2 I70).
3//!
4//! Each record names a shell's process — the leader of its own process group — and the
5//! harness process that owns it, each with the start time the OS reports. A record whose
6//! owner no longer runs is an orphan: its group is killed only when the process with its
7//! pid has the recorded start time, or no process has that pid any more, so a reused pid is
8//! never signalled.
9
10use std::sync::Mutex;
11
12use adk_core::Result;
13use async_trait::async_trait;
14use serde::{Deserialize, Serialize};
15
16/// One background shell's process, as the registry keeps it.
17///
18/// # Example
19///
20/// ```rust
21/// use adk_harness::ShellPidRecord;
22///
23/// let record = ShellPidRecord {
24///     pid: 4242,
25///     started: "1730000000.000123".into(),
26///     owner_pid: 4000,
27///     owner_started: "1729999000.000001".into(),
28/// };
29/// assert_eq!(serde_json::to_value(&record).unwrap()["ownerPid"], 4000);
30/// ```
31#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(rename_all = "camelCase")]
33pub struct ShellPidRecord {
34    /// The shell's process id, which is also its process group id.
35    pub pid: u32,
36    /// The shell's start time as the OS reports it.
37    pub started: String,
38    /// The harness process that started the shell.
39    pub owner_pid: u32,
40    /// That process's start time.
41    pub owner_started: String,
42}
43
44/// Where the harness records the process of each running background shell (spec 3.1
45/// §7.29): `harness.db` in adk-cli (`SqliteShellPidRegistry`, feature `sqlite`), memory by
46/// default.
47///
48/// # Example
49///
50/// ```rust
51/// use adk_harness::{InMemoryShellPidRegistry, ShellPidRecord, ShellPidRegistry};
52///
53/// # futures::executor::block_on(async {
54/// let registry = InMemoryShellPidRegistry::default();
55/// let record = ShellPidRecord { pid: 7, started: "1".into(), owner_pid: 1, owner_started: "0".into() };
56/// registry.register(&record).await?;
57/// assert_eq!(registry.list().await?, vec![record.clone()]);
58/// registry.remove(&record).await?;
59/// assert!(registry.list().await?.is_empty());
60/// # Ok::<(), adk_core::AdkError>(())
61/// # }).unwrap();
62/// ```
63#[async_trait]
64pub trait ShellPidRegistry: Send + Sync {
65    /// Records a running shell's process.
66    async fn register(&self, record: &ShellPidRecord) -> Result<()>;
67
68    /// Forgets a shell's process once it has ended or been reaped.
69    async fn remove(&self, record: &ShellPidRecord) -> Result<()>;
70
71    /// Every recorded process.
72    async fn list(&self) -> Result<Vec<ShellPidRecord>>;
73}
74
75/// A [`ShellPidRegistry`] in memory: a crash forgets it, so nothing is reaped at the next
76/// start.
77#[derive(Debug, Default)]
78pub struct InMemoryShellPidRegistry {
79    records: Mutex<Vec<ShellPidRecord>>,
80}
81
82#[async_trait]
83impl ShellPidRegistry for InMemoryShellPidRegistry {
84    async fn register(&self, record: &ShellPidRecord) -> Result<()> {
85        let mut records = self.records.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
86        records.retain(|existing| existing != record);
87        records.push(record.clone());
88        Ok(())
89    }
90
91    async fn remove(&self, record: &ShellPidRecord) -> Result<()> {
92        self.records
93            .lock()
94            .unwrap_or_else(std::sync::PoisonError::into_inner)
95            .retain(|existing| existing != record);
96        Ok(())
97    }
98
99    async fn list(&self) -> Result<Vec<ShellPidRecord>> {
100        Ok(self.records.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone())
101    }
102}
103
104/// A [`ShellPidRegistry`] in SQLite, table `adk_harness_shell_pids` (feature `sqlite`).
105///
106/// It holds process ids and start times only, never a command, so it is not sealed under
107/// the store key. Call [`migrate`](Self::migrate) once before use.
108///
109/// # Example
110///
111/// ```rust,ignore
112/// let pids = adk_harness::SqliteShellPidRegistry::new(pool);
113/// pids.migrate().await?;
114/// ```
115#[cfg(feature = "sqlite")]
116#[derive(Debug, Clone)]
117pub struct SqliteShellPidRegistry {
118    pool: sqlx::SqlitePool,
119}
120
121#[cfg(feature = "sqlite")]
122impl SqliteShellPidRegistry {
123    /// A registry over `pool`.
124    pub fn new(pool: sqlx::SqlitePool) -> Self {
125        Self { pool }
126    }
127
128    /// Creates the registry's table if it does not exist.
129    ///
130    /// # Errors
131    ///
132    /// Returns the database error when the statement fails.
133    pub async fn migrate(&self) -> Result<()> {
134        sqlx::query(
135            "CREATE TABLE IF NOT EXISTS adk_harness_shell_pids (\
136                pid INTEGER NOT NULL, started TEXT NOT NULL, owner_pid INTEGER NOT NULL, \
137                owner_started TEXT NOT NULL, PRIMARY KEY (pid, started))",
138        )
139        .execute(&self.pool)
140        .await
141        .map_err(crate::fsutil::db_error)?;
142        Ok(())
143    }
144}
145
146#[cfg(feature = "sqlite")]
147#[async_trait]
148impl ShellPidRegistry for SqliteShellPidRegistry {
149    async fn register(&self, record: &ShellPidRecord) -> Result<()> {
150        sqlx::query(
151            "INSERT OR REPLACE INTO adk_harness_shell_pids \
152             (pid, started, owner_pid, owner_started) VALUES (?, ?, ?, ?)",
153        )
154        .bind(i64::from(record.pid))
155        .bind(&record.started)
156        .bind(i64::from(record.owner_pid))
157        .bind(&record.owner_started)
158        .execute(&self.pool)
159        .await
160        .map_err(crate::fsutil::db_error)?;
161        Ok(())
162    }
163
164    async fn remove(&self, record: &ShellPidRecord) -> Result<()> {
165        sqlx::query("DELETE FROM adk_harness_shell_pids WHERE pid = ? AND started = ?")
166            .bind(i64::from(record.pid))
167            .bind(&record.started)
168            .execute(&self.pool)
169            .await
170            .map_err(crate::fsutil::db_error)?;
171        Ok(())
172    }
173
174    async fn list(&self) -> Result<Vec<ShellPidRecord>> {
175        let rows: Vec<(i64, String, i64, String)> = sqlx::query_as(
176            "SELECT pid, started, owner_pid, owner_started FROM adk_harness_shell_pids",
177        )
178        .fetch_all(&self.pool)
179        .await
180        .map_err(crate::fsutil::db_error)?;
181        Ok(rows
182            .into_iter()
183            .filter_map(|(pid, started, owner_pid, owner_started)| {
184                Some(ShellPidRecord {
185                    pid: u32::try_from(pid).ok()?,
186                    started,
187                    owner_pid: u32::try_from(owner_pid).ok()?,
188                    owner_started,
189                })
190            })
191            .collect())
192    }
193}
194
195/// The start time of process `pid` as the OS reports it, or `None` when no process has
196/// that pid or the platform does not say.
197pub(crate) fn process_start(pid: u32) -> Option<String> {
198    #[cfg(target_os = "macos")]
199    {
200        let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
201        let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
202        // SAFETY: `info` is a writable `proc_bsdinfo` of `size` bytes that outlives the call;
203        // `proc_pidinfo` writes at most `size` bytes into it.
204        let written = unsafe {
205            libc::proc_pidinfo(
206                pid as libc::c_int,
207                libc::PROC_PIDTBSDINFO,
208                0,
209                std::ptr::from_mut(&mut info).cast(),
210                size,
211            )
212        };
213        (written == size).then(|| format!("{}.{:06}", info.pbi_start_tvsec, info.pbi_start_tvusec))
214    }
215    #[cfg(target_os = "linux")]
216    {
217        // Field 22 of `stat`, the start time in clock ticks since boot; the command name
218        // before it is in parentheses and may hold spaces.
219        let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
220        let after_name = &stat[stat.rfind(')')? + 1..];
221        after_name.split_whitespace().nth(19).map(str::to_string)
222    }
223    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
224    {
225        let _ = pid;
226        None
227    }
228}
229
230/// This process's pid and start time, or `None` where the platform does not report one.
231pub(crate) fn this_process() -> Option<(u32, String)> {
232    let pid = std::process::id();
233    process_start(pid).map(|started| (pid, started))
234}
235
236/// Kills the process group of every shell in `registry` whose harness process no longer
237/// runs, and forgets it; returns how many groups were signalled (spec 3.1 §7.29).
238///
239/// A group is signalled only when the process with its pid has the recorded start time, or
240/// no process has that pid any more (the leader exited and left its group behind), so a
241/// reused pid is never signalled. Records of a live harness process, this one or another,
242/// are left alone. A no-op where the OS does not report start times.
243///
244/// # Errors
245///
246/// Returns the registry's error.
247///
248/// # Example
249///
250/// ```rust
251/// use adk_harness::{InMemoryShellPidRegistry, reap_orphaned_shells};
252///
253/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
254/// let registry = InMemoryShellPidRegistry::default();
255/// assert_eq!(reap_orphaned_shells(&registry).await?, 0);
256/// # Ok::<(), adk_core::AdkError>(())
257/// # }).unwrap();
258/// ```
259pub async fn reap_orphaned_shells(registry: &dyn ShellPidRegistry) -> Result<usize> {
260    let mut killed = 0;
261    for record in registry.list().await? {
262        let owner = process_start(record.owner_pid);
263        if owner.as_deref() == Some(record.owner_started.as_str()) {
264            continue;
265        }
266        // Without start times nothing can be told apart, so nothing is signalled.
267        if this_process().is_none() {
268            continue;
269        }
270        let current = process_start(record.pid);
271        if current.is_none() || current.as_deref() == Some(record.started.as_str()) {
272            #[cfg(unix)]
273            // SAFETY: `killpg` takes a process-group id and a signal, and cannot violate
274            // memory safety; a group that no longer exists makes it fail harmlessly.
275            let signalled = unsafe { libc::killpg(record.pid as libc::pid_t, libc::SIGKILL) } == 0;
276            #[cfg(not(unix))]
277            let signalled = false;
278            if signalled {
279                killed += 1;
280                tracing::info!(
281                    process.pid = record.pid,
282                    "reaped a background shell a crash left running"
283                );
284            }
285        }
286        registry.remove(&record).await?;
287    }
288    Ok(killed)
289}
290
291#[cfg(all(test, unix))]
292mod tests {
293    use super::*;
294
295    #[test]
296    fn this_process_has_a_start_time_that_does_not_change() {
297        if cfg!(not(any(target_os = "macos", target_os = "linux"))) {
298            return;
299        }
300        let (pid, started) = this_process().expect("macOS and Linux report a start time");
301        assert_eq!(pid, std::process::id());
302        assert_eq!(process_start(pid), Some(started));
303    }
304
305    /// A record left by a harness process that no longer runs is reaped: the group of a
306    /// process with the recorded start time is killed, and one whose pid now names a
307    /// process started later is left alone.
308    #[tokio::test]
309    async fn an_orphan_is_killed_and_a_reused_pid_is_not() {
310        if cfg!(not(any(target_os = "macos", target_os = "linux"))) {
311            return;
312        }
313        let spawn = || {
314            let mut command = std::process::Command::new("sleep");
315            command.arg("30");
316            // SAFETY: `setsid` in the forked child is async-signal-safe.
317            unsafe {
318                std::os::unix::process::CommandExt::pre_exec(&mut command, || {
319                    libc::setsid();
320                    Ok(())
321                });
322            }
323            command.spawn().unwrap()
324        };
325        let mut orphan = spawn();
326        let mut reused = spawn();
327        let registry = InMemoryShellPidRegistry::default();
328        // A dead owner: no process has pid 0's start time.
329        let dead_owner = |pid: u32, started: String| ShellPidRecord {
330            pid,
331            started,
332            owner_pid: u32::MAX - 1,
333            owner_started: "never".into(),
334        };
335        registry
336            .register(&dead_owner(orphan.id(), process_start(orphan.id()).unwrap()))
337            .await
338            .unwrap();
339        registry.register(&dead_owner(reused.id(), "0.000001".into())).await.unwrap();
340
341        assert_eq!(reap_orphaned_shells(&registry).await.unwrap(), 1);
342        assert!(registry.list().await.unwrap().is_empty());
343        let status = orphan.wait().unwrap();
344        assert!(!status.success(), "the orphan was killed: {status:?}");
345        assert!(reused.try_wait().unwrap().is_none(), "a reused pid is never signalled");
346        reused.kill().unwrap();
347        reused.wait().unwrap();
348    }
349
350    #[tokio::test]
351    async fn a_live_owners_shells_are_left_alone() {
352        let Some((pid, started)) = this_process() else { return };
353        let registry = InMemoryShellPidRegistry::default();
354        let record =
355            ShellPidRecord { pid: 1, started: "x".into(), owner_pid: pid, owner_started: started };
356        registry.register(&record).await.unwrap();
357        assert_eq!(reap_orphaned_shells(&registry).await.unwrap(), 0);
358        assert_eq!(registry.list().await.unwrap(), vec![record]);
359    }
360}