Skip to main content

schedr_agent/
journal.rs

1//! The journal on disk: one file per attempt the agent started and the master hasn't
2//! acknowledged, so a restarted agent still reports a result it had and stops a task process
3//! its previous incarnation left behind (see archive/PROJECT.md, Worker lifecycle).
4//!
5//! - **Files:** `<journal_dir>/<attempt_id>.json`, each replaced atomically (a temporary file,
6//!   fsync, rename, fsync of the directory) before the message it backs is sent: `running`
7//!   before `Started` (and again with the process's identity once it is spawned), `finished`
8//!   before `Finished`. A file goes when the master acknowledges the result or decides to
9//!   forget the attempt.
10//! - **On start:** temporary files left by a crash are removed, finished results are reported
11//!   again, and the process groups of attempts that were running are stopped (SIGTERM, then
12//!   SIGKILL after a grace time); those attempts aren't reported, so the master ends them
13//!   `lost`.
14//! - **Process identity:** a process group ID and the start time of its leader (from
15//!   `/proc/<pid>/stat`), so a recycled PID isn't taken for the task. Without `/proc` the
16//!   agent warns once and nothing is stopped; once the leader is gone, nothing is stopped.
17//!
18//! - **Cleanups:** an attempt of a task with a cleanup also keeps `<attempt_id>.attempt`, what
19//!   its cleanup needs to run after a restart (the assignment and where its code is), written
20//!   before `Started`, and `<attempt_id>.handles`, its handles, a line each, on disk before
21//!   the task hears they are registered. Its record is `cleaning` from the task's end, with the
22//!   task's result: the cleanup runs again from there (see archive/PROJECT.md, Per-task cleanup).
23//!
24//! - **One agent per journal:** it holds a lock (see [`Journal::lock`]).
25//!
26//! Its operations block (fsync); the agent runs them off its event loop.
27
28use std::fs::{self, File};
29use std::io::{self, Write};
30use std::os::unix::fs::OpenOptionsExt;
31use std::path::{Path, PathBuf};
32use std::time::{Duration, Instant};
33
34use prost::Message;
35use rustix::process::{Pid, Signal, kill_process_group};
36use schedr_model::runner::CleanupHandle;
37use schedr_proto::pb;
38use serde::{Deserialize, Serialize};
39
40#[cfg(test)]
41mod tests;
42
43/// The prefix of a file being written; such files are removed on start.
44const TEMP_PREFIX: &str = ".tmp-";
45
46/// What a cleanup needs after a restart: `<attempt_id>.attempt`.
47const KEPT_EXTENSION: &str = "attempt";
48
49/// An attempt's handles, a line each: `<attempt_id>.handles`.
50const HANDLES_EXTENSION: &str = "handles";
51
52/// The lock file: one agent per journal.
53pub const LOCK_FILE: &str = ".lock";
54
55/// How often a stopped orphan is checked for being gone.
56const ORPHAN_POLL: Duration = Duration::from_millis(50);
57
58/// How long a killed orphan's group has to go (its memory freed) before the agent goes on.
59const ORPHAN_KILL_WAIT: Duration = Duration::from_secs(5);
60
61/// What identifies a task's process group across an agent restart.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
63pub struct ProcessIdentity {
64    /// The process group ID (the PID of its leader).
65    pub pgid: i32,
66    /// The leader's start time, in clock ticks since boot (field 22 of `/proc/<pid>/stat`).
67    pub start_time: u64,
68}
69
70/// What the journal knows about an attempt.
71#[derive(Debug, Clone, PartialEq)]
72pub enum JournalRecord {
73    /// Started; its process, once spawned and identified.
74    Running(Option<ProcessIdentity>),
75    /// Ended with this result, not yet acknowledged.
76    Finished(pb::Finished),
77    /// The task ended with this result and its cleanup runs, in this process once identified.
78    Cleaning(pb::Finished, Option<ProcessIdentity>),
79}
80
81/// What a task's cleanup needs to run after an agent restart.
82#[derive(Debug, Clone, PartialEq)]
83pub struct KeptAttempt {
84    /// Its assignment, the inputs inside it however they came.
85    pub assign: pb::AssignTask,
86    /// The copy of the code it ran with; `None`: the configured root.
87    pub code_dir: Option<PathBuf>,
88    /// The hash of that code.
89    pub code_hash: Option<String>,
90    /// The copies of the other DAG roots on its `sys.path`, by root.
91    pub root_copies: std::collections::BTreeMap<String, PathBuf>,
92    /// The copy of the script root its script and cleanup script came from.
93    pub script_dir: Option<PathBuf>,
94}
95
96/// A [`KeptAttempt`] as stored.
97#[derive(Serialize, Deserialize)]
98#[serde(deny_unknown_fields)]
99struct StoredAttempt {
100    /// The `AssignTask` message, protobuf-encoded, as hex.
101    assign: String,
102    code_dir: Option<PathBuf>,
103    code_hash: Option<String>,
104    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
105    root_copies: std::collections::BTreeMap<String, PathBuf>,
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    script_dir: Option<PathBuf>,
108}
109
110/// A journal file as stored.
111#[derive(Serialize, Deserialize)]
112#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
113enum Stored {
114    Running {
115        attempt_id: String,
116        process: Option<ProcessIdentity>,
117    },
118    Finished {
119        attempt_id: String,
120        /// The `Finished` message, protobuf-encoded, as hex.
121        finished: String,
122    },
123    Cleaning {
124        attempt_id: String,
125        /// The task's `Finished` message, protobuf-encoded, as hex.
126        finished: String,
127        process: Option<ProcessIdentity>,
128    },
129}
130
131/// The journal directory.
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct Journal {
134    dir: PathBuf,
135}
136
137impl Journal {
138    /// The journal in `dir` (created when first written).
139    #[must_use]
140    pub const fn new(dir: PathBuf) -> Self {
141        Self { dir }
142    }
143
144    /// Its directory.
145    #[must_use]
146    pub fn dir(&self) -> &Path {
147        &self.dir
148    }
149
150    /// Takes the journal's lock for as long as the returned file is open: one agent per
151    /// journal (another one's recovery would stop this one's tasks).
152    ///
153    /// # Errors
154    ///
155    /// An I/O error if the directory or lock file can't be created, or `WouldBlock` if another
156    /// process holds the lock.
157    pub fn lock(&self) -> io::Result<File> {
158        fs::create_dir_all(&self.dir)?;
159        let file = fs::OpenOptions::new()
160            .create(true)
161            .truncate(false)
162            .write(true)
163            .open(self.dir.join(LOCK_FILE))?;
164        rustix::fs::flock(&file, rustix::fs::FlockOperation::NonBlockingLockExclusive)?;
165        Ok(file)
166    }
167
168    /// Records `record` for an attempt, replacing what was there; it is on disk when this
169    /// returns.
170    ///
171    /// # Errors
172    ///
173    /// An I/O error if the directory or file can't be written, or `InvalidInput` for an
174    /// attempt ID that isn't a safe file name.
175    pub fn write(&self, attempt_id: &str, record: &JournalRecord) -> io::Result<()> {
176        let path = self.path(attempt_id)?;
177        let json = encoded(attempt_id, record)?;
178        self.replace(attempt_id, &path, &json)
179    }
180
181    /// Records several attempts' records, as [`Self::write`] does each, with their files
182    /// written and flushed to disk side by side and the directory flushed once (M4B.5, B184):
183    /// a burst of results costs about one flush's time, not two flushes each. On disk when this
184    /// returns, all of them; an error leaves those written before it.
185    ///
186    /// # Errors
187    ///
188    /// The first I/O error, or `InvalidInput` for an attempt ID that isn't a safe file name
189    /// (then nothing is written).
190    pub fn write_many(&self, records: &[(&str, &JournalRecord)]) -> io::Result<()> {
191        let files = records
192            .iter()
193            .map(|(attempt_id, record)| {
194                Ok((
195                    *attempt_id,
196                    self.path(attempt_id)?,
197                    encoded(attempt_id, record)?,
198                ))
199            })
200            .collect::<io::Result<Vec<_>>>()?;
201        fs::create_dir_all(&self.dir)?;
202        let written: Vec<io::Result<()>> = std::thread::scope(|scope| {
203            let threads: Vec<_> = files
204                .iter()
205                .map(|(attempt_id, _, json)| {
206                    let temp = self.dir.join(format!("{TEMP_PREFIX}{attempt_id}"));
207                    scope.spawn(move || -> io::Result<()> {
208                        let mut file = private_file().truncate(true).open(&temp)?;
209                        file.write_all(json)?;
210                        file.sync_all()
211                    })
212                })
213                .collect();
214            threads
215                .into_iter()
216                .map(|t| {
217                    t.join()
218                        .unwrap_or_else(|_| Err(io::Error::other("a write panicked")))
219                })
220                .collect()
221        });
222        for ((attempt_id, path, _), done) in files.iter().zip(written) {
223            done?;
224            fs::rename(self.dir.join(format!("{TEMP_PREFIX}{attempt_id}")), path)?;
225        }
226        self.sync_dir()
227    }
228}
229
230/// A record as its file holds it.
231fn encoded(attempt_id: &str, record: &JournalRecord) -> io::Result<Vec<u8>> {
232    {
233        let stored = match record {
234            JournalRecord::Running(process) => Stored::Running {
235                attempt_id: attempt_id.to_owned(),
236                process: *process,
237            },
238            JournalRecord::Finished(finished) => Stored::Finished {
239                attempt_id: attempt_id.to_owned(),
240                finished: to_hex(&finished.encode_to_vec()),
241            },
242            JournalRecord::Cleaning(finished, process) => Stored::Cleaning {
243                attempt_id: attempt_id.to_owned(),
244                finished: to_hex(&finished.encode_to_vec()),
245                process: *process,
246            },
247        };
248        serde_json::to_vec(&stored).map_err(io::Error::other)
249    }
250}
251
252impl Journal {
253    /// Replaces `path` with `content`, atomically; on disk when this returns.
254    fn replace(&self, attempt_id: &str, path: &Path, content: &[u8]) -> io::Result<()> {
255        fs::create_dir_all(&self.dir)?;
256        let temp = self.dir.join(format!("{TEMP_PREFIX}{attempt_id}"));
257        let mut file = private_file().truncate(true).open(&temp)?;
258        file.write_all(content)?;
259        file.sync_all()?;
260        drop(file);
261        fs::rename(&temp, path)?;
262        self.sync_dir()
263    }
264
265    /// Keeps what an attempt's cleanup needs to run after a restart; on disk when this
266    /// returns.
267    ///
268    /// # Errors
269    ///
270    /// An I/O error if it can't be written, or `InvalidInput` for an attempt ID that isn't a
271    /// safe file name.
272    pub fn keep(&self, attempt_id: &str, kept: &KeptAttempt) -> io::Result<()> {
273        let path = self.path(attempt_id)?.with_extension(KEPT_EXTENSION);
274        let stored = StoredAttempt {
275            assign: to_hex(&kept.assign.encode_to_vec()),
276            code_dir: kept.code_dir.clone(),
277            code_hash: kept.code_hash.clone(),
278            root_copies: kept.root_copies.clone(),
279            script_dir: kept.script_dir.clone(),
280        };
281        let json = serde_json::to_vec(&stored).map_err(io::Error::other)?;
282        self.replace(attempt_id, &path, &json)
283    }
284
285    /// What was kept for an attempt's cleanup; `None` if nothing was.
286    ///
287    /// # Errors
288    ///
289    /// An I/O error if it can't be read, `InvalidData` if it doesn't read as what was written,
290    /// or `InvalidInput` for an attempt ID that isn't a safe file name.
291    pub fn kept(&self, attempt_id: &str) -> io::Result<Option<KeptAttempt>> {
292        let path = self.path(attempt_id)?.with_extension(KEPT_EXTENSION);
293        let Some(bytes) = read_if_there(&path)? else {
294            return Ok(None);
295        };
296        let invalid = |message: String| io::Error::new(io::ErrorKind::InvalidData, message);
297        let stored: StoredAttempt =
298            serde_json::from_slice(&bytes).map_err(|e| invalid(e.to_string()))?;
299        let assign = from_hex(&stored.assign).ok_or_else(|| invalid("not hex".to_owned()))?;
300        Ok(Some(KeptAttempt {
301            assign: pb::AssignTask::decode(assign.as_slice())
302                .map_err(|e| invalid(e.to_string()))?,
303            code_dir: stored.code_dir,
304            code_hash: stored.code_hash,
305            root_copies: stored.root_copies,
306            script_dir: stored.script_dir,
307        }))
308    }
309
310    /// Adds a handle to an attempt's; on disk when this returns.
311    ///
312    /// # Errors
313    ///
314    /// An I/O error if it can't be written, or `InvalidInput` for an attempt ID that isn't a
315    /// safe file name.
316    pub fn add_handle(&self, attempt_id: &str, handle: &CleanupHandle) -> io::Result<()> {
317        let path = self.path(attempt_id)?.with_extension(HANDLES_EXTENSION);
318        let mut line = serde_json::to_vec(handle).map_err(io::Error::other)?;
319        line.push(b'\n');
320        fs::create_dir_all(&self.dir)?;
321        let new = !path.exists();
322        let mut file = private_file().append(true).open(&path)?;
323        file.write_all(&line)?;
324        file.sync_all()?;
325        if new {
326            self.sync_dir()?;
327        }
328        Ok(())
329    }
330
331    /// An attempt's handles, in registration order. A last line with no end, cut off by a
332    /// crash, was never acknowledged to the task, and is left out.
333    ///
334    /// # Errors
335    ///
336    /// An I/O error if they can't be read, `InvalidData` if a complete line doesn't read, or
337    /// `InvalidInput` for an attempt ID that isn't a safe file name.
338    pub fn handles(&self, attempt_id: &str) -> io::Result<Vec<CleanupHandle>> {
339        let path = self.path(attempt_id)?.with_extension(HANDLES_EXTENSION);
340        let bytes = read_if_there(&path)?.unwrap_or_default();
341        let complete = bytes
342            .iter()
343            .rposition(|byte| *byte == b'\n')
344            .map_or(&[][..], |end| &bytes[..end]);
345        if complete.is_empty() {
346            return Ok(Vec::new());
347        }
348        complete
349            .split(|byte| *byte == b'\n')
350            .map(|line| {
351                serde_json::from_slice(line)
352                    .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
353            })
354            .collect()
355    }
356
357    /// Forgets an attempt; one that isn't recorded is fine.
358    ///
359    /// # Errors
360    ///
361    /// An I/O error if the file can't be removed, or `InvalidInput` for an attempt ID that
362    /// isn't a safe file name.
363    pub fn remove(&self, attempt_id: &str) -> io::Result<()> {
364        let path = self.path(attempt_id)?;
365        // The record last: what is left of a crash here is removed on the next start.
366        for extension in [KEPT_EXTENSION, HANDLES_EXTENSION] {
367            match fs::remove_file(path.with_extension(extension)) {
368                Err(error) if error.kind() != io::ErrorKind::NotFound => return Err(error),
369                _ => {}
370            }
371        }
372        match fs::remove_file(path) {
373            Ok(()) => self.sync_dir(),
374            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
375            Err(error) => Err(error),
376        }
377    }
378
379    /// Removes temporary files left by a crash and reads every attempt recorded, by ID; a file
380    /// that doesn't read is logged and removed (it was never acted on). Only for the agent
381    /// holding the journal, before it starts writing.
382    ///
383    /// # Errors
384    ///
385    /// An I/O error if the directory can't be read or created.
386    pub fn recover(&self) -> io::Result<Vec<(String, JournalRecord)>> {
387        fs::create_dir_all(&self.dir)?;
388        self.scan(true)
389    }
390
391    /// Every attempt recorded, by ID, changing nothing: files being written or that don't
392    /// read are left out (safe while an agent writes the journal).
393    ///
394    /// # Errors
395    ///
396    /// An I/O error if the directory can't be read.
397    pub fn records(&self) -> io::Result<Vec<(String, JournalRecord)>> {
398        self.scan(false)
399    }
400
401    /// What is recorded for one attempt, changing nothing; `None` when nothing is (or the
402    /// file is being written, or doesn't read).
403    ///
404    /// # Errors
405    ///
406    /// `InvalidInput` for an attempt ID that isn't a safe file name.
407    pub fn record(&self, attempt_id: &str) -> io::Result<Option<JournalRecord>> {
408        Ok(read(&self.path(attempt_id)?, attempt_id).ok())
409    }
410
411    fn scan(&self, clean: bool) -> io::Result<Vec<(String, JournalRecord)>> {
412        let mut records = Vec::new();
413        for entry in fs::read_dir(&self.dir)? {
414            let path = entry?.path();
415            let name = path
416                .file_name()
417                .map(|n| n.to_string_lossy().into_owned())
418                .unwrap_or_default();
419            if name.starts_with(TEMP_PREFIX) {
420                if clean {
421                    remove_logged(&path, "temporary journal file");
422                }
423                continue;
424            }
425            let Some(attempt_id) = name.strip_suffix(".json") else {
426                continue;
427            };
428            match read(&path, attempt_id) {
429                Ok(record) => records.push((attempt_id.to_owned(), record)),
430                Err(error) if clean => {
431                    tracing::warn!(path = %path.display(), %error, "unreadable journal file");
432                    remove_logged(&path, "unreadable journal file");
433                }
434                Err(_) => {}
435            }
436        }
437        records.sort_by(|a, b| a.0.cmp(&b.0));
438        if clean {
439            self.remove_strays(&records)?;
440        }
441        Ok(records)
442    }
443
444    /// Removes the kept files of attempts with no record (a crash between the two).
445    fn remove_strays(&self, records: &[(String, JournalRecord)]) -> io::Result<()> {
446        for entry in fs::read_dir(&self.dir)? {
447            let path = entry?.path();
448            let extension = path.extension().and_then(|e| e.to_str());
449            let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
450            if matches!(extension, Some(KEPT_EXTENSION | HANDLES_EXTENSION))
451                && !records.iter().any(|(id, _)| id == stem)
452            {
453                remove_logged(&path, "journal file with no record");
454            }
455        }
456        Ok(())
457    }
458
459    fn path(&self, attempt_id: &str) -> io::Result<PathBuf> {
460        let safe = !attempt_id.is_empty()
461            && attempt_id
462                .bytes()
463                .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
464        if safe {
465            Ok(self.dir.join(format!("{attempt_id}.json")))
466        } else {
467            Err(io::Error::new(
468                io::ErrorKind::InvalidInput,
469                format!("attempt ID `{attempt_id}` isn't a safe file name"),
470            ))
471        }
472    }
473
474    fn sync_dir(&self) -> io::Result<()> {
475        File::open(&self.dir)?.sync_all()
476    }
477}
478
479/// A journal file being opened: only its owner reads it, what it holds being the task's own.
480fn private_file() -> fs::OpenOptions {
481    let mut options = fs::OpenOptions::new();
482    options.create(true).write(true).mode(0o600);
483    options
484}
485
486/// A file's content; `None` if it isn't there.
487fn read_if_there(path: &Path) -> io::Result<Option<Vec<u8>>> {
488    match fs::read(path) {
489        Ok(bytes) => Ok(Some(bytes)),
490        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
491        Err(error) => Err(error),
492    }
493}
494
495/// Removes a file recovery doesn't want; a failure is logged, not fatal (the records that do
496/// read must still be reported).
497fn remove_logged(path: &Path, what: &str) {
498    if let Err(error) = fs::remove_file(path) {
499        tracing::warn!(path = %path.display(), %error, "can't remove {what}");
500    }
501}
502
503fn read(path: &Path, attempt_id: &str) -> io::Result<JournalRecord> {
504    let invalid = |message: String| io::Error::new(io::ErrorKind::InvalidData, message);
505    let stored: Stored =
506        serde_json::from_slice(&fs::read(path)?).map_err(|e| invalid(e.to_string()))?;
507    let (id, record) = match stored {
508        Stored::Running {
509            attempt_id,
510            process,
511        } => (attempt_id, JournalRecord::Running(process)),
512        Stored::Finished {
513            attempt_id,
514            finished,
515        } => {
516            let bytes = from_hex(&finished).ok_or_else(|| invalid("not hex".to_owned()))?;
517            let finished =
518                pb::Finished::decode(bytes.as_slice()).map_err(|e| invalid(e.to_string()))?;
519            (attempt_id, JournalRecord::Finished(finished))
520        }
521        Stored::Cleaning {
522            attempt_id,
523            finished,
524            process,
525        } => {
526            let bytes = from_hex(&finished).ok_or_else(|| invalid("not hex".to_owned()))?;
527            let finished =
528                pb::Finished::decode(bytes.as_slice()).map_err(|e| invalid(e.to_string()))?;
529            (attempt_id, JournalRecord::Cleaning(finished, process))
530        }
531    };
532    if id == attempt_id {
533        Ok(record)
534    } else {
535        Err(invalid(format!("it is for attempt `{id}`")))
536    }
537}
538
539fn to_hex(bytes: &[u8]) -> String {
540    use std::fmt::Write as _;
541    bytes.iter().fold(String::new(), |mut hex, b| {
542        let _ = write!(hex, "{b:02x}");
543        hex
544    })
545}
546
547fn from_hex(hex: &str) -> Option<Vec<u8>> {
548    if !hex.len().is_multiple_of(2) {
549        return None;
550    }
551    (0..hex.len())
552        .step_by(2)
553        .map(|i| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok())
554        .collect()
555}
556
557/// The identity of the process group led by `pid`.
558///
559/// # Errors
560///
561/// An I/O error if `/proc/<pid>/stat` can't be read (no such process, or no `/proc`), or
562/// `InvalidData` if it doesn't parse.
563pub fn process_identity(pid: i32) -> io::Result<ProcessIdentity> {
564    let stat = fs::read_to_string(format!("/proc/{pid}/stat"))?;
565    // The command name (field 2) is in parentheses and may contain anything; the fields after
566    // its closing parenthesis start at field 3.
567    let start_time = stat
568        .rsplit_once(')')
569        .and_then(|(_, rest)| rest.split_whitespace().nth(22 - 3))
570        .and_then(|field| field.parse().ok())
571        .ok_or_else(|| {
572            io::Error::new(
573                io::ErrorKind::InvalidData,
574                format!("`/proc/{pid}/stat` has no start time"),
575            )
576        })?;
577    Ok(ProcessIdentity {
578        pgid: pid,
579        start_time,
580    })
581}
582
583/// The group a journal's `pgid` names; never group 1 (B88): signalling it is `kill(-1)`,
584/// every process the agent may signal, and no task's group is init's.
585fn orphan_group(pgid: i32) -> Option<Pid> {
586    if pgid <= 1 {
587        return None;
588    }
589    Pid::from_raw(pgid)
590}
591
592/// How stopping an orphaned process group went.
593#[derive(Debug, Clone, Copy, PartialEq, Eq)]
594pub enum Orphan {
595    /// Its leader isn't running (any more, or the PID is another process's now): left alone.
596    Gone,
597    /// It ended after SIGTERM.
598    Stopped,
599    /// It needed SIGKILL.
600    Killed,
601}
602
603/// How an orphan is waited for.
604#[derive(Debug, Clone, Copy, PartialEq, Eq)]
605pub struct OrphanWaits {
606    /// How often it is looked at (`orphan_poll`).
607    pub poll: Duration,
608    /// How long it may take to go after SIGKILL (`orphan_kill_wait`).
609    pub kill_wait: Duration,
610}
611
612impl Default for OrphanWaits {
613    /// 50 ms and 5 s.
614    fn default() -> Self {
615        Self {
616            poll: ORPHAN_POLL,
617            kill_wait: ORPHAN_KILL_WAIT,
618        }
619    }
620}
621
622/// Stops the process group `identity` names, if its leader still runs: SIGTERM, and SIGKILL
623/// if the group hasn't ended after `grace`, then waits for it to go (at most 5 s).
624///
625/// # Errors
626///
627/// An I/O error from signalling the group.
628pub async fn stop_orphan(
629    identity: ProcessIdentity,
630    grace: Duration,
631    waits: OrphanWaits,
632) -> io::Result<Orphan> {
633    if process_identity(identity.pgid).ok() != Some(identity) {
634        return Ok(Orphan::Gone);
635    }
636    let Some(group) = orphan_group(identity.pgid) else {
637        return Ok(Orphan::Gone);
638    };
639    let signal = |signal| match kill_process_group(group, signal) {
640        Ok(()) | Err(rustix::io::Errno::SRCH) => Ok(()),
641        Err(error) => Err(io::Error::from(error)),
642    };
643    signal(Signal::TERM)?;
644    if gone_within(group, grace, waits.poll).await {
645        return Ok(Orphan::Stopped);
646    }
647    signal(Signal::KILL)?;
648    if !gone_within(group, waits.kill_wait, waits.poll).await {
649        tracing::warn!(
650            pgid = identity.pgid,
651            "a killed task process group hasn't gone yet"
652        );
653    }
654    Ok(Orphan::Killed)
655}
656
657/// Whether the process group goes within `wait`.
658async fn gone_within(group: Pid, wait: Duration, poll: Duration) -> bool {
659    let deadline = Instant::now() + wait;
660    loop {
661        if !crate::process::group_running(group) {
662            return true;
663        }
664        let left = deadline.saturating_duration_since(Instant::now());
665        if left.is_zero() {
666            return false;
667        }
668        tokio::time::sleep(poll.min(left)).await;
669    }
670}