platform/process_identity.rs
1//! Pid-reuse-safe process liveness.
2//!
3//! What `assembly::discovery` (the daemon singleton lock) asks of a recorded
4//! holder: is this pid still the process that wrote it, or did the pid get
5//! recycled by something unrelated.
6
7use std::path::Path;
8use std::time::{SystemTime, UNIX_EPOCH};
9
10/// A process, identified precisely enough to answer "is this still the same
11/// process I saw before, or did its pid get recycled?" — a bare pid can't
12/// answer that on its own.
13///
14/// **Why this matters**: pid-only liveness (`kill(pid, 0) == 0`) has a
15/// latent failure mode on long-running systems — if the holder crashes and
16/// some unrelated new process happens to be assigned the same pid before
17/// the next check, pid-only liveness reports "still alive" and the lock is
18/// refused forever (until someone manually deletes the lock file). Not a
19/// theoretical risk: pid space wraps around on any system that's been
20/// running long enough. Comparing the recorded start time against the
21/// current holder of that pid closes the gap — a reused pid almost never
22/// has the exact same start time as whatever held it before.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct ProcessIdentity {
25 pub pid: u32,
26 pub started_at: i64,
27}
28
29impl ProcessIdentity {
30 pub fn current() -> Self {
31 let pid = std::process::id();
32 Self {
33 pid,
34 started_at: process_start_time(pid).unwrap_or(0),
35 }
36 }
37
38 /// Start times within this many seconds of each other count as "the
39 /// same process" — `process_start_time` samples `ps -o etime=`
40 /// (whole-second resolution), so querying the very same still-running
41 /// process twice a moment apart can legitimately drift by ~1s as the
42 /// wall clock ticks over between the two `now - elapsed` computations.
43 /// A real pid reuse lands nowhere near this close by comparison.
44 const START_TIME_TOLERANCE_SECS: i64 = 2;
45
46 /// Four-way liveness/reuse check against a *recorded* identity (e.g.
47 /// one read back from a lock file):
48 /// - `Alive` — `pid` is running and its start time still matches
49 /// (within [`START_TIME_TOLERANCE_SECS`]); the recorded holder is
50 /// genuinely still there.
51 /// - `Reused` — `pid` is running but its start time no longer matches
52 /// the recorded one — a different process now holds this pid.
53 /// - `Dead` — `pid` isn't running at all.
54 /// - `Unknown` — liveness or start time couldn't be determined at all
55 /// (unsupported platform, `ps` unavailable, or the recorded value
56 /// itself was never captured — `started_at == 0`). Distinct from
57 /// `Reused` on purpose: "can't tell" and "confirmed a different
58 /// process" call for different caller behavior (see
59 /// [`decide_stale_lock`]) — collapsing them would mean an
60 /// unverifiable lock gets silently reclaimed out from under a holder
61 /// that may well still be alive.
62 pub fn check(recorded: &ProcessIdentity) -> ProcessLiveness {
63 match pid_alive(recorded.pid) {
64 Some(false) => return ProcessLiveness::Dead,
65 None => return ProcessLiveness::Unknown,
66 Some(true) => {}
67 }
68 if recorded.started_at == 0 {
69 return ProcessLiveness::Unknown;
70 }
71 match process_start_time(recorded.pid) {
72 Some(current_start)
73 if (current_start - recorded.started_at).abs()
74 <= Self::START_TIME_TOLERANCE_SECS =>
75 {
76 ProcessLiveness::Alive
77 }
78 Some(_) => ProcessLiveness::Reused,
79 None => ProcessLiveness::Unknown,
80 }
81 }
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum ProcessLiveness {
86 Alive,
87 Reused,
88 Dead,
89 Unknown,
90}
91
92/// What a caller weighing whether to reclaim a stale lock/discovery file
93/// should do, given a [`ProcessLiveness`].
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum StaleLockDecision {
96 /// The recorded holder might still be there — confirmed alive, or
97 /// unconfirmed and therefore assumed alive out of caution. Don't touch
98 /// the existing file.
99 KeepExisting,
100 /// The recorded holder is confirmed gone (dead pid, or the pid now
101 /// belongs to someone else) — safe to overwrite.
102 Reclaim,
103}
104
105/// Runs [`ProcessIdentity::check`] against `recorded` and logs the decision
106/// via `tracing`, so call sites just branch on the result instead of each
107/// re-matching all four [`ProcessLiveness`] variants and re-writing the same
108/// log lines. `subject` names what's being checked (e.g. `"daemon.lock"`)
109/// and `path` is where it lives on disk — both go into the log for
110/// post-mortem debugging.
111pub fn decide_stale_lock(
112 recorded: &ProcessIdentity,
113 subject: &str,
114 path: &Path,
115) -> StaleLockDecision {
116 match ProcessIdentity::check(recorded) {
117 ProcessLiveness::Alive => StaleLockDecision::KeepExisting,
118 ProcessLiveness::Unknown => {
119 tracing::warn!(
120 pid = recorded.pid,
121 path = %path.display(),
122 "could not confirm whether {subject}'s recorded pid is still alive \
123 (no reliable liveness probe on this platform/environment, or its \
124 start time was never captured); conservatively treating it as still held"
125 );
126 StaleLockDecision::KeepExisting
127 }
128 ProcessLiveness::Reused => {
129 tracing::warn!(
130 stale_pid = recorded.pid,
131 path = %path.display(),
132 "{subject}'s pid was reused by an unrelated process (start time mismatch); overwriting"
133 );
134 StaleLockDecision::Reclaim
135 }
136 ProcessLiveness::Dead => {
137 tracing::info!(
138 stale_pid = recorded.pid,
139 path = %path.display(),
140 "stale {subject} from dead pid; overwriting"
141 );
142 StaleLockDecision::Reclaim
143 }
144 }
145}
146
147/// Best-effort liveness probe — `kill -0 pid` semantics on Unix.
148/// `Some(true)`/`Some(false)` are a confirmed answer; `None` means the
149/// platform has no probe wired up here (see the `cfg(not(unix))` arm) —
150/// callers must not treat that as "alive" (see [`ProcessLiveness::Unknown`]).
151#[cfg(unix)]
152#[allow(unsafe_code)]
153fn pid_alive(pid: u32) -> Option<bool> {
154 let r = unsafe { libc::kill(pid as libc::pid_t, 0) };
155 if r == 0 {
156 return Some(true);
157 }
158 let err = std::io::Error::last_os_error();
159 Some(err.raw_os_error() != Some(libc::ESRCH))
160}
161
162#[cfg(not(unix))]
163fn pid_alive(_pid: u32) -> Option<bool> {
164 None
165}
166
167/// `pid`'s process start time as Unix epoch seconds (rounded to the nearest
168/// second — see [`ProcessIdentity::check`]'s tolerance for why sub-second
169/// precision isn't needed), or `None` if it can't be determined (process
170/// gone by the time we looked, `ps` unavailable, or a read/parse failure —
171/// all treated the same by callers: "couldn't verify, can't use this for
172/// the reuse check").
173///
174/// Deliberately shells out to `ps -o etime=` rather than hand-rolling the
175/// `sysctl(KERN_PROC_PID)`/`kinfo_proc` FFI: `libc` doesn't expose
176/// `kinfo_proc`'s layout for macOS (only for the free/net/openbsd targets),
177/// so getting that struct's field offsets right would mean hand-maintaining
178/// an unsafe `#[repr(C)]` mirror of an Apple-internal struct with no
179/// compiler to check it against — a correctness risk `ps`'s stable,
180/// documented output doesn't carry.
181///
182/// `etime` (not GNU/Linux procps's `etimes` extension, which macOS's `ps`
183/// rejects outright — `ps: etimes: keyword not found`) prints elapsed time
184/// as `[[dd-]hh:]mm:ss`, a purely numeric, locale- and timezone-independent
185/// format supported by both, so one parser (`parse_elapsed`) covers both
186/// rather than two platform-specific implementations.
187///
188/// Unix-only: there's no `ps -o etime=` equivalent on other platforms.
189/// Gated with `cfg` rather than left to fail at runtime so a non-Unix build
190/// never shells out to a command that can't exist there — see the
191/// `cfg(not(unix))` arm just below.
192#[cfg(unix)]
193pub fn process_start_time(pid: u32) -> Option<i64> {
194 let output = std::process::Command::new("ps")
195 .args(["-o", "etime=", "-p", &pid.to_string()])
196 .output()
197 .ok()?;
198 if !output.status.success() {
199 return None;
200 }
201 let elapsed_secs = parse_elapsed(String::from_utf8(output.stdout).ok()?.trim())?;
202 let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs() as i64;
203 plausible(now - elapsed_secs)
204}
205
206/// A start time that could not be one is not a reading.
207///
208/// The value here is derived — `now` minus whatever `ps` said — so a `ps` this
209/// code does not understand produces a number rather than an error. One Linux
210/// host answered `441056556-16:45:20`, four hundred million days, and the
211/// subtraction dutifully placed the process's start a million years before the
212/// epoch. Taken at face value that is not a harmless oddity: every recorded
213/// identity then fails the reuse check, so instance files are deleted out from
214/// under live daemons and locks are reclaimed from processes still holding
215/// them. "Could not verify" is a state this code already has, and it is the
216/// honest one here — `None` becomes `ProcessLiveness::Unknown`, which callers
217/// treat as "leave it alone".
218///
219/// The window is deliberately loose. It is not trying to validate a start
220/// time; it is refusing an answer that is not one.
221#[cfg(unix)]
222fn plausible(start: i64) -> Option<i64> {
223 /// 2000-01-01. No process this code meets started before it.
224 const FLOOR: i64 = 946_684_800;
225 let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs() as i64;
226 // A little slack above `now` for clock adjustment between the two reads.
227 (FLOOR..=now + 60).contains(&start).then_some(start)
228}
229
230#[cfg(not(unix))]
231pub fn process_start_time(_pid: u32) -> Option<i64> {
232 None
233}
234
235/// Parses `ps -o etime=`'s `[[dd-]hh:]mm:ss` elapsed-time format into total
236/// seconds.
237#[cfg(unix)]
238fn parse_elapsed(s: &str) -> Option<i64> {
239 let (days, rest) = match s.split_once('-') {
240 Some((d, r)) => (d.parse::<i64>().ok()?, r),
241 None => (0, s),
242 };
243 let parts: Vec<&str> = rest.split(':').collect();
244 let (hours, minutes, seconds) = match parts.as_slice() {
245 [h, m, s] => (
246 h.parse::<i64>().ok()?,
247 m.parse::<i64>().ok()?,
248 s.parse::<i64>().ok()?,
249 ),
250 [m, s] => (0, m.parse::<i64>().ok()?, s.parse::<i64>().ok()?),
251 _ => return None,
252 };
253 Some(days * 86400 + hours * 3600 + minutes * 60 + seconds)
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259
260 /// A `ps` this code cannot read produces a number, not an error, and the
261 /// number is worse than nothing: every identity built on it fails the
262 /// reuse check, so live daemons lose their instance files and running
263 /// processes lose their locks.
264 #[test]
265 fn a_start_time_that_could_not_be_one_is_not_a_reading() {
266 let now = SystemTime::now()
267 .duration_since(UNIX_EPOCH)
268 .unwrap()
269 .as_secs() as i64;
270
271 assert_eq!(
272 plausible(now - 3600),
273 Some(now - 3600),
274 "an hour ago is fine"
275 );
276 assert_eq!(plausible(now), Some(now), "just now is fine");
277
278 // What the Linux host that found this actually produced.
279 assert_eq!(plausible(-38_107_284_710_668), None);
280 assert_eq!(plausible(0), None, "the epoch is not a process start time");
281 assert_eq!(plausible(now + 86_400), None, "nor is tomorrow");
282 }
283
284 /// A short-lived child process — gives tests a real, distinct, live pid
285 /// (with its own real start time) instead of reusing the test's own,
286 /// which would trip the "same pid" branch instead of the "another
287 /// process" branch these tests mean to exercise.
288 struct Child(std::process::Child);
289 impl Child {
290 fn spawn() -> Self {
291 Self(
292 std::process::Command::new("sleep")
293 .arg("5")
294 .spawn()
295 .expect("spawn a short-lived child for the test"),
296 )
297 }
298 fn pid(&self) -> u32 {
299 self.0.id()
300 }
301 }
302 impl Drop for Child {
303 fn drop(&mut self) {
304 let _ = self.0.kill();
305 let _ = self.0.wait();
306 }
307 }
308
309 #[test]
310 fn process_identity_check_reports_alive_for_the_current_process() {
311 let identity = ProcessIdentity::current();
312 assert_eq!(ProcessIdentity::check(&identity), ProcessLiveness::Alive);
313 }
314
315 #[test]
316 fn process_identity_check_reports_dead_for_an_unused_pid() {
317 let fake = ProcessIdentity {
318 pid: 999_999_999,
319 started_at: 1,
320 };
321 assert_eq!(ProcessIdentity::check(&fake), ProcessLiveness::Dead);
322 }
323
324 #[test]
325 fn process_identity_check_reports_reused_when_start_time_mismatches() {
326 let mut identity = ProcessIdentity::current();
327 identity.started_at += 1_000_000; // clearly wrong, well outside tolerance
328 assert_eq!(ProcessIdentity::check(&identity), ProcessLiveness::Reused);
329 }
330
331 /// `Alive` is the verdict for a process whose start time still matches —
332 /// which presumes the host can read one at all. Where it cannot, `check`
333 /// answers `Unknown` by design, and that is a different case with its own
334 /// test rather than a weaker version of this one.
335 #[test]
336 fn process_identity_check_reports_alive_for_a_real_child_with_matching_start_time() {
337 let child = Child::spawn();
338 let Some(recorded_start) = process_start_time(child.pid()) else {
339 eprintln!("skipping: this host cannot read process start times");
340 return;
341 };
342 let recorded = ProcessIdentity {
343 pid: child.pid(),
344 started_at: recorded_start,
345 };
346 assert_eq!(ProcessIdentity::check(&recorded), ProcessLiveness::Alive);
347 }
348
349 /// And that different case: no readable start time is "cannot verify", not
350 /// "a different process". A host whose `ps` this code cannot read must not
351 /// have its locks reclaimed and its instance files deleted.
352 #[test]
353 fn an_unreadable_start_time_is_unknown_rather_than_reused() {
354 let child = Child::spawn();
355 let recorded = ProcessIdentity {
356 pid: child.pid(),
357 started_at: 0,
358 };
359 assert_eq!(ProcessIdentity::check(&recorded), ProcessLiveness::Unknown);
360 }
361
362 #[test]
363 fn process_identity_check_reports_reused_for_a_real_pid_with_mismatched_start_time() {
364 let child = Child::spawn();
365 let recorded = ProcessIdentity {
366 pid: child.pid(),
367 started_at: 12345, // deliberately wrong — simulates reuse
368 };
369 assert_eq!(ProcessIdentity::check(&recorded), ProcessLiveness::Reused);
370 }
371
372 #[test]
373 fn process_identity_check_reports_unknown_when_recorded_start_time_was_never_captured() {
374 // `started_at == 0` is what `ProcessIdentity::current()` records when
375 // `process_start_time` itself failed to probe — an unverifiable
376 // record, not a confirmed mismatch, so this must not read as `Reused`.
377 let mut identity = ProcessIdentity::current();
378 identity.started_at = 0;
379 assert_eq!(ProcessIdentity::check(&identity), ProcessLiveness::Unknown);
380 }
381
382 #[test]
383 fn decide_stale_lock_keeps_existing_for_a_confirmed_alive_process() {
384 let identity = ProcessIdentity::current();
385 assert_eq!(
386 decide_stale_lock(&identity, "test.lock", Path::new("/tmp/test.lock")),
387 StaleLockDecision::KeepExisting
388 );
389 }
390
391 #[test]
392 fn decide_stale_lock_keeps_existing_when_liveness_is_unverifiable() {
393 let mut identity = ProcessIdentity::current();
394 identity.started_at = 0;
395 assert_eq!(
396 decide_stale_lock(&identity, "test.lock", Path::new("/tmp/test.lock")),
397 StaleLockDecision::KeepExisting
398 );
399 }
400
401 #[test]
402 fn decide_stale_lock_reclaims_a_dead_pid() {
403 let fake = ProcessIdentity {
404 pid: 999_999_999,
405 started_at: 1,
406 };
407 assert_eq!(
408 decide_stale_lock(&fake, "test.lock", Path::new("/tmp/test.lock")),
409 StaleLockDecision::Reclaim
410 );
411 }
412
413 #[test]
414 fn decide_stale_lock_reclaims_a_reused_pid() {
415 let mut identity = ProcessIdentity::current();
416 identity.started_at += 1_000_000; // clearly wrong, well outside tolerance
417 assert_eq!(
418 decide_stale_lock(&identity, "test.lock", Path::new("/tmp/test.lock")),
419 StaleLockDecision::Reclaim
420 );
421 }
422
423 #[test]
424 #[cfg(unix)]
425 fn parse_elapsed_handles_every_ps_etime_shape() {
426 assert_eq!(parse_elapsed("00:05"), Some(5));
427 assert_eq!(parse_elapsed("02:30"), Some(150));
428 assert_eq!(parse_elapsed("01:02:03"), Some(3723));
429 assert_eq!(parse_elapsed("3-01:02:03"), Some(3 * 86400 + 3723));
430 assert_eq!(parse_elapsed("not-a-time"), None);
431 assert_eq!(parse_elapsed(""), None);
432 }
433}