Skip to main content

schedr_agent/
fork.rs

1//! The fork servers, agent side (see archive/PROJECT.md, How Python tasks are started: the fork
2//! server): started with the worker, two per interpreter (one preloading the configured
3//! libraries, a bare one), each restarted with backoff when it dies; a Python task or a parse
4//! job asks the preloaded one to fork its runner, then the bare one, and is spawned when
5//! neither can (a task with `preload=False` asks only the bare one, one with
6//! `fresh_process=True` neither).
7//!
8//! A forked runner is not the agent's child: its **shim** (forked by the fork server) is its
9//! parent and reports on a status socket the agent passes with the request,
10//! `process_started` (the PID, once the process group exists) and `process_exited`. The shim
11//! reaps the process only when the agent closes that socket ([`GroupHold`]), so its PID and
12//! group can't be reused while the agent may still signal them.
13//!
14//! The thin operating-system layer under [`crate::launch`], exercised by the integration tests
15//! (`tests/fork.rs`); the backoff is unit-tested.
16
17use std::io::{self, IoSlice};
18use std::mem::MaybeUninit;
19use std::os::fd::{AsFd, OwnedFd};
20use std::sync::Arc;
21use std::time::{Duration, Instant};
22
23use prometheus_client::metrics::counter::Counter;
24use prometheus_client::metrics::family::Family;
25use prometheus_client::metrics::gauge::Gauge;
26use rustix::net::{SendAncillaryBuffer, SendAncillaryMessage, SendFlags};
27use rustix::process::{Pid, kill_process_group};
28use schedr_model::runner::{
29    AgentMessage, ForkRequest, ForkServerRequest, MAX_MESSAGE_SIZE, RunnerMessage, RunnerMode,
30};
31use schedr_proto::pb;
32use tokio::io::AsyncWriteExt;
33use tokio::net::UnixStream;
34use tokio::net::unix::pipe;
35use tokio::sync::{Mutex, watch};
36use tokio::task::JoinHandle;
37
38use crate::attempt::WorkerSetup;
39use crate::channel::{ChannelError, Messages, read_message};
40use crate::launch::{LaunchError, start_runner};
41use crate::metrics::{ForkFallbackLabels, ForkServerLabels};
42use crate::output::TailBuffer;
43use crate::process::{OsProcess, ProcessSpec, collect, open_log};
44use crate::status::Termination;
45use crate::supervise::{Process, Signal};
46use crate::usage::Ended;
47
48#[cfg(test)]
49mod tests;
50
51/// How long a fork server may take to preload its libraries and answer.
52pub const PRELOAD_TIMEOUT: Duration = Duration::from_secs(300);
53
54/// How long a fork server may take to answer a `fork` request.
55pub const FORK_ANSWER_TIMEOUT: Duration = Duration::from_secs(30);
56
57/// The first wait before restarting a fork server that died or couldn't start.
58pub const BACKOFF_FIRST: Duration = Duration::from_secs(1);
59
60/// The longest wait before a restart.
61pub const BACKOFF_MAX: Duration = Duration::from_secs(300);
62
63/// How long a fork server must have been up for the backoff to start again from
64/// [`BACKOFF_FIRST`].
65pub const BACKOFF_RESET_AFTER: Duration = Duration::from_secs(600);
66
67/// Why a fork server came up disabled.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum Cause {
70    /// A preloaded library failed to import: maybe something not ready yet, so retried for
71    /// `[worker] fork_server_import_retry` (decisions 19A, 20A).
72    Import,
73    /// Threads after preloading, or a version mismatch: the same on every start until the
74    /// image changes, so never retried.
75    Lasting,
76}
77
78/// Whether a fork server disabled for `cause`, failing for `failing_for` since its first
79/// failure, is started again: a failing import within `window` (long enough for what isn't
80/// ready at a pod's start; a failure still there after it is lasting: a missing package, a
81/// typo).
82#[must_use]
83pub fn retried(cause: Cause, failing_for: Duration, window: Duration) -> bool {
84    cause == Cause::Import && failing_for < window
85}
86
87/// How a fork server's restarts are spaced.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub struct ForkBackoff {
90    /// The first wait (`fork_backoff_first`).
91    pub first: Duration,
92    /// The longest (`fork_backoff_max`).
93    pub max: Duration,
94    /// A server up for this long starts them over (`fork_backoff_reset_after`).
95    pub reset_after: Duration,
96}
97
98impl Default for ForkBackoff {
99    /// [`BACKOFF_FIRST`], [`BACKOFF_MAX`], [`BACKOFF_RESET_AFTER`].
100    fn default() -> Self {
101        Self {
102            first: BACKOFF_FIRST,
103            max: BACKOFF_MAX,
104            reset_after: BACKOFF_RESET_AFTER,
105        }
106    }
107}
108
109impl ForkBackoff {
110    /// The wait before the next restart: `previous` doubled up to `max`, or `first` again after
111    /// a server that was up for `reset_after`.
112    #[must_use]
113    pub fn next(&self, previous: Duration, up_for: Option<Duration>) -> Duration {
114        if up_for.is_some_and(|up| up >= self.reset_after) {
115            self.first
116        } else {
117            (previous * 2).min(self.max)
118        }
119    }
120}
121
122/// Which of an interpreter's two fork servers.
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum Kind {
125    /// It preloads the configured libraries.
126    Preloaded,
127    /// It preloads nothing (for tasks whose libraries don't survive the preloaded one).
128    Bare,
129}
130
131impl Kind {
132    /// The metric label.
133    #[must_use]
134    pub const fn label(self) -> &'static str {
135        match self {
136            Self::Preloaded => "preloaded",
137            Self::Bare => "bare",
138        }
139    }
140}
141
142/// Why a task wasn't forked by one fork server (the metric's `reason`).
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub enum Fallback {
145    /// The fork server is disabled (a failing preload, threads, a version mismatch).
146    Disabled,
147    /// The fork server isn't running (starting, or waiting to restart).
148    Down,
149    /// It answered `fork_failed`.
150    ForkFailed,
151    /// The shim ended (or said nothing in time) before reporting the process.
152    ShimDied,
153}
154
155impl Fallback {
156    /// The metric label.
157    #[must_use]
158    pub const fn label(self) -> &'static str {
159        match self {
160            Self::Disabled => "disabled",
161            Self::Down => "down",
162            Self::ForkFailed => "fork_failed",
163            Self::ShimDied => "shim_died",
164        }
165    }
166}
167
168/// Where the fork servers' states and fallbacks are counted.
169#[derive(Debug, Clone, Default)]
170pub struct ForkMetrics {
171    /// Fork servers by interpreter, kind and state (1 for the current state).
172    pub servers: Family<ForkServerLabels, Gauge>,
173    /// Python tasks that weren't forked by a fork server, by interpreter and reason.
174    pub fallbacks: Family<ForkFallbackLabels, Counter>,
175}
176
177/// A fork server's state.
178#[derive(Debug)]
179enum State {
180    /// Starting, or waiting to restart.
181    Down,
182    /// Taking requests on its control socket. `asking`: a request was sent and its answer not
183    /// read yet; still set when the next request comes, that answer was abandoned (its reader
184    /// was dropped), and the socket's answers no longer pair with requests.
185    Up {
186        control: UnixStream,
187        next_id: u64,
188        asking: bool,
189    },
190    /// Not used again until the worker restarts.
191    Disabled(String),
192}
193
194impl State {
195    const fn label(&self) -> &'static str {
196        match self {
197            Self::Down => "down",
198            Self::Up { .. } => "up",
199            Self::Disabled(_) => "disabled",
200        }
201    }
202}
203
204/// One fork server: its state, shared by its supervisor and the tasks asking it to fork.
205#[derive(Debug)]
206struct Server {
207    kind: Kind,
208    interpreter: String,
209    /// Its process group while it is up (0: none): whose memory the heartbeat reports
210    /// (decision 463).
211    group: std::sync::atomic::AtomicI32,
212    state: Mutex<State>,
213    metrics: ForkMetrics,
214    board: Arc<WarningBoard>,
215}
216
217/// The disabled fork servers, as the worker's warnings (sent to the master).
218#[derive(Debug)]
219struct WarningBoard {
220    interpreter: String,
221    /// Whether the bare server is the only one (no preload list).
222    bare_alone: bool,
223    /// Why each disabled server is, by kind.
224    reasons: std::sync::Mutex<std::collections::BTreeMap<&'static str, String>>,
225    warnings: watch::Sender<Vec<pb::WorkerWarning>>,
226}
227
228impl WarningBoard {
229    /// Records `kind`'s state, publishing the warnings if they changed.
230    fn record(&self, kind: Kind, disabled: Option<&str>) {
231        let mut reasons = self
232            .reasons
233            .lock()
234            .unwrap_or_else(std::sync::PoisonError::into_inner);
235        let changed = match disabled {
236            Some(reason) => {
237                reasons.insert(kind.label(), reason.to_owned()).as_deref() != Some(reason)
238            }
239            None => reasons.remove(kind.label()).is_some(),
240        };
241        if changed {
242            let warnings = reasons
243                .iter()
244                .rev()
245                .map(|(label, reason)| self.warning(label, reason, &reasons))
246                .collect();
247            self.warnings.send_replace(warnings);
248        }
249    }
250
251    /// The warning for server `label`, disabled for `reason`; what it means for tasks depends
252    /// on whether the other server is disabled too (`disabled`).
253    fn warning(
254        &self,
255        label: &str,
256        reason: &str,
257        disabled: &std::collections::BTreeMap<&'static str, String>,
258    ) -> pb::WorkerWarning {
259        let other = if label == "preloaded" {
260            "bare"
261        } else {
262            "preloaded"
263        };
264        let then = if self.bare_alone || disabled.contains_key(other) {
265            "tasks are spawned"
266        } else if label == "preloaded" {
267            "tasks are forked by the bare fork server, or spawned"
268        } else {
269            "tasks the preloaded fork server can't fork are spawned"
270        };
271        pb::WorkerWarning {
272            kind: FORK_SERVER_DISABLED.to_owned(),
273            interpreter: self.interpreter.clone(),
274            message: format!("the {label} fork server is disabled: {reason}; {then}"),
275        }
276    }
277}
278
279/// The worker warning's kind for a disabled fork server.
280pub const FORK_SERVER_DISABLED: &str = "fork_server_disabled";
281
282impl Server {
283    /// Moves to `state`, keeping the gauge's one-hot labels in step.
284    fn set(&self, current: &mut State, state: State) {
285        for label in ["down", "up", "disabled"] {
286            let value = i64::from(label == state.label());
287            self.metrics
288                .servers
289                .get_or_create(&ForkServerLabels {
290                    interpreter: self.interpreter.clone(),
291                    kind: self.kind.label().to_owned(),
292                    state: label.to_owned(),
293                })
294                .set(value);
295        }
296        let disabled = match &state {
297            State::Disabled(reason) => Some(reason.as_str()),
298            _ => None,
299        };
300        self.board.record(self.kind, disabled);
301        *current = state;
302    }
303}
304
305/// An interpreter's fork servers, preloaded first (cheap to clone; clones share them).
306#[derive(Debug, Clone)]
307pub struct ForkServers {
308    servers: Arc<Vec<Server>>,
309    /// The servers' memory together, as last measured (decision 463).
310    memory: Arc<std::sync::atomic::AtomicU64>,
311    warnings: watch::Receiver<Vec<pb::WorkerWarning>>,
312    /// How long a server may take to answer a request.
313    answer_timeout: Duration,
314}
315
316/// An interpreter's fork server settings (`[interpreters.<name>]` with `fork_server = true`).
317#[derive(Debug, Clone, PartialEq, Eq)]
318pub struct ForkConfig {
319    /// The interpreter's name.
320    pub interpreter: String,
321    /// The libraries the preloaded fork server imports.
322    pub preload: Vec<String>,
323    /// How long a failing import is retried (`[worker] fork_server_import_retry`).
324    pub import_retry: Duration,
325}
326
327/// How to start an interpreter's fork servers.
328#[derive(Debug, Clone)]
329pub struct ForkSetup {
330    /// The interpreter's name (the metrics' label).
331    pub interpreter: String,
332    /// The fork server's process: the interpreter, `-m schedr.runner fork_server`, its
333    /// environment and directory; `log_file` is a template, each kind writes
334    /// `fork-server-<kind>.log` next to it.
335    pub process: ProcessSpec,
336    /// The libraries the preloaded one imports; none: only the bare one is started.
337    pub preload: Vec<String>,
338    /// How long a failing import is retried (`[worker] fork_server_import_retry`).
339    pub import_retry: Duration,
340    /// How long what it does may take.
341    pub timeouts: crate::attempt::WorkerTimeouts,
342    /// How often its servers' memory is measured (the watchdog's interval, decision 463).
343    pub memory_interval: Duration,
344}
345
346impl ForkServers {
347    /// The DAG interpreter's fork servers for a worker set up as `setup`, started; `None`
348    /// without `fork_server = true`, and off Linux (forking is unsafe on macOS: a warning
349    /// says it is ignored, and tasks are spawned).
350    #[must_use]
351    pub fn for_worker(setup: &WorkerSetup, metrics: &ForkMetrics) -> Option<Self> {
352        let config = setup.fork_server.as_ref()?;
353        if !cfg!(target_os = "linux") {
354            tracing::warn!(
355                interpreter = config.interpreter,
356                "fork_server = true is ignored: fork servers run on Linux only; tasks are spawned"
357            );
358            return None;
359        }
360        let process = ProcessSpec {
361            program: setup.python.clone(),
362            args: vec![
363                // Not the working directory first: a root's file can't shadow what the runner imports (B178).
364                "-P".to_owned(),
365                "-m".to_owned(),
366                "schedr.runner".to_owned(),
367                "fork_server".to_owned(),
368            ],
369            // As a task's: a forked one keeps the `sys.path` this `PYTHONPATH` gives.
370            env: setup
371                .agent_env
372                .iter()
373                .filter(|(name, _)| crate::env::is_allowed(name) || setup.pass_env.contains(name))
374                .map(|(k, v)| (k.clone(), v.clone()))
375                .collect(),
376            working_dir: setup.log_dir.clone(),
377            log_file: setup.log_dir.join("fork-server.log"),
378            max_output_size: 64 * 1024,
379            mask: crate::mask::Mask::default(),
380            start_timeout: setup.timeouts.runner_start,
381            output_drain: setup.timeouts.output_drain,
382        };
383        let setup = ForkSetup {
384            interpreter: config.interpreter.clone(),
385            process,
386            preload: config.preload.clone(),
387            import_retry: config.import_retry,
388            memory_interval: setup.memory.interval,
389            timeouts: setup.timeouts,
390        };
391        Some(Self::start(&setup, metrics))
392    }
393
394    /// Starts the fork servers in the background (each restarted with backoff while the
395    /// returned value lives in any clone).
396    #[must_use]
397    pub fn start(setup: &ForkSetup, metrics: &ForkMetrics) -> Self {
398        let mut kinds = vec![
399            (Kind::Preloaded, setup.preload.clone()),
400            (Kind::Bare, vec![]),
401        ];
402        if setup.preload.is_empty() {
403            kinds.remove(0);
404        }
405        let (warnings, watching) = watch::channel(Vec::new());
406        let board = Arc::new(WarningBoard {
407            interpreter: setup.interpreter.clone(),
408            bare_alone: kinds.len() == 1,
409            reasons: std::sync::Mutex::default(),
410            warnings,
411        });
412        let servers: Vec<Server> = kinds
413            .iter()
414            .map(|(kind, _)| Server {
415                kind: *kind,
416                interpreter: setup.interpreter.clone(),
417                group: std::sync::atomic::AtomicI32::new(0),
418                state: Mutex::new(State::Down),
419                metrics: metrics.clone(),
420                board: Arc::clone(&board),
421            })
422            .collect();
423        for server in &servers {
424            // Scraped as down from the start, not missing until it first starts.
425            server.set(&mut State::Down, State::Down);
426        }
427        let servers = Arc::new(servers);
428        for (index, (kind, preload)) in kinds.into_iter().enumerate() {
429            let mut process = setup.process.clone();
430            process.log_file = process
431                .log_file
432                .with_file_name(format!("fork-server-{}.log", kind.label()));
433            let timeouts = setup.timeouts;
434            let retry = setup.import_retry;
435            tokio::spawn(keep_up(
436                Arc::downgrade(&servers),
437                index,
438                process,
439                preload,
440                retry,
441                timeouts.fork_backoff,
442                timeouts.fork_preload,
443            ));
444        }
445        let memory = Arc::default();
446        tokio::spawn(measure(
447            Arc::downgrade(&servers),
448            Arc::clone(&memory),
449            setup.memory_interval,
450        ));
451        Self {
452            servers,
453            memory,
454            warnings: watching,
455            answer_timeout: setup.timeouts.fork_answer,
456        }
457    }
458
459    /// The servers' memory together (PSS), as last measured; 0 before the first measure.
460    #[must_use]
461    pub fn memory(&self) -> u64 {
462        self.memory.load(std::sync::atomic::Ordering::Relaxed)
463    }
464
465    /// Waits until each server takes requests or something is wrong with one, for at most
466    /// `within`, and says what is wrong: for a one-off that wants to fork, where a worker lets
467    /// its first tasks spawn.
468    pub async fn settled(&self, within: Duration) -> Vec<String> {
469        let mut warnings = self.warnings();
470        let _ = tokio::time::timeout(within, async {
471            loop {
472                if !warnings.borrow_and_update().is_empty() || self.all_settled().await {
473                    return;
474                }
475                let _ = tokio::time::timeout(Duration::from_millis(20), warnings.changed()).await;
476            }
477        })
478        .await;
479        warnings
480            .borrow()
481            .iter()
482            .map(|warning| warning.message.clone())
483            .collect()
484    }
485
486    async fn all_settled(&self) -> bool {
487        for server in self.servers.iter() {
488            if matches!(*server.state.lock().await, State::Down) {
489                return false;
490            }
491        }
492        true
493    }
494
495    /// The worker's warnings about these fork servers (one per disabled server), as they
496    /// change.
497    #[must_use]
498    pub fn warnings(&self) -> watch::Receiver<Vec<pb::WorkerWarning>> {
499        self.warnings.clone()
500    }
501
502    /// The disabled fork servers and why (for the worker's warnings).
503    pub async fn disabled(&self) -> Vec<(Kind, String)> {
504        let mut found = Vec::new();
505        for server in self.servers.iter() {
506            if let State::Disabled(reason) = &*server.state.lock().await {
507                found.push((server.kind, reason.clone()));
508            }
509        }
510        found
511    }
512
513    /// Forks a runner in `mode` for `spec` (its environment, directory, log file and output
514    /// limit): from the preloaded server (unless `preload` is off: `@task(preload=False)`),
515    /// else the bare one. Each one that couldn't is counted; one skipped by choice isn't.
516    ///
517    /// # Errors
518    ///
519    /// The last server's [`Fallback`] when none forked it: the caller spawns it.
520    pub async fn fork(
521        &self,
522        spec: &ProcessSpec,
523        mode: RunnerMode,
524        preload: bool,
525    ) -> Result<Forked, Fallback> {
526        let mut last = Fallback::Down;
527        let tried = self
528            .servers
529            .iter()
530            .filter(|server| preload || server.kind == Kind::Bare);
531        for server in tried {
532            match fork_on(server, spec, mode, self.answer_timeout).await {
533                Ok(forked) => return Ok(forked),
534                Err(fallback) => {
535                    server
536                        .metrics
537                        .fallbacks
538                        .get_or_create(&ForkFallbackLabels {
539                            interpreter: server.interpreter.clone(),
540                            reason: fallback.label().to_owned(),
541                        })
542                        .inc();
543                    last = fallback;
544                }
545            }
546        }
547        Err(last)
548    }
549}
550
551/// Measures the servers that are up every `every` into `memory`, until they are gone: the
552/// processes of each one's group (PSS; its shims too, a forked task leading a group of its own).
553/// A measure that can't be read (a PSS missing, Grok's review of M5.1h) keeps the last one.
554async fn measure(
555    servers: std::sync::Weak<Vec<Server>>,
556    memory: Arc<std::sync::atomic::AtomicU64>,
557    every: Duration,
558) {
559    let mut tick = tokio::time::interval(every);
560    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
561    loop {
562        tick.tick().await;
563        let Some(all) = servers.upgrade() else {
564            return;
565        };
566        let groups: Vec<i32> = all
567            .iter()
568            .map(|server| server.group.load(std::sync::atomic::Ordering::Relaxed))
569            .filter(|group| *group > 0)
570            .collect();
571        drop(all);
572        let measured = tokio::task::spawn_blocking(move || {
573            servers_memory(std::path::Path::new("/proc"), &groups)
574        })
575        .await
576        .ok()
577        .flatten();
578        if let Some(total) = measured {
579            memory.store(total, std::sync::atomic::Ordering::Relaxed);
580        }
581    }
582}
583
584/// The memory of the processes in `groups` together (PSS); `None` when one's can't be read.
585#[must_use]
586pub fn servers_memory(proc_root: &std::path::Path, groups: &[i32]) -> Option<u64> {
587    groups
588        .iter()
589        .map(|group| crate::memory::group_memory(proc_root, *group, false))
590        .sum()
591}
592
593/// Keeps fork server `index` running while its [`ForkServers`] lives: starts it, restarts it
594/// with backoff when it dies or can't start, retries a failing import for
595/// `import_retry`, and stops for good once it is disabled otherwise.
596async fn keep_up(
597    servers: std::sync::Weak<Vec<Server>>,
598    index: usize,
599    process: ProcessSpec,
600    preload: Vec<String>,
601    import_retry: Duration,
602    spacing: ForkBackoff,
603    preload_timeout: Duration,
604) {
605    let mut backoff = spacing.first / 2;
606    // Since when its preload has been failing, and the reason last logged.
607    let mut failing: Option<(Instant, String)> = None;
608    loop {
609        let up_for = match start_server(&process, &preload, preload_timeout).await {
610            Ok(Started::Ready(mut os, control)) => {
611                {
612                    let Some(all) = servers.upgrade() else {
613                        return;
614                    };
615                    let server = &all[index];
616                    server
617                        .group
618                        .store(os.id(), std::sync::atomic::Ordering::Relaxed);
619                    let mut state = server.state.lock().await;
620                    server.set(
621                        &mut state,
622                        State::Up {
623                            control,
624                            next_id: 1,
625                            asking: false,
626                        },
627                    );
628                    tracing::info!(kind = server.kind.label(), "fork server up");
629                }
630                failing = None;
631                let up_at = Instant::now();
632                let ended = os.wait().await;
633                let Some(all) = servers.upgrade() else {
634                    return;
635                };
636                let server = &all[index];
637                server.group.store(0, std::sync::atomic::Ordering::Relaxed);
638                let mut state = server.state.lock().await;
639                if matches!(*state, State::Disabled(_)) {
640                    return;
641                }
642                tracing::warn!(kind = server.kind.label(), ?ended, "fork server ended");
643                server.set(&mut state, State::Down);
644                Some(up_at.elapsed())
645            }
646            Ok(Started::Disabled(reason, cause)) => {
647                let Some(all) = servers.upgrade() else {
648                    return;
649                };
650                let server = &all[index];
651                let kind = server.kind.label();
652                let since = failing
653                    .as_ref()
654                    .map_or_else(Instant::now, |(since, _)| *since);
655                let again = retried(cause, since.elapsed(), import_retry);
656                if !again {
657                    let gave_up = (cause == Cause::Import).then(|| since.elapsed().as_secs() / 60);
658                    tracing::warn!(kind, reason, ?gave_up, "fork server disabled until restart");
659                } else if failing.as_ref().is_none_or(|(_, said)| *said != reason) {
660                    tracing::warn!(kind, reason, "fork server disabled; retrying");
661                }
662                let mut state = server.state.lock().await;
663                server.set(&mut state, State::Disabled(reason.clone()));
664                if !again {
665                    return;
666                }
667                failing = Some((since, reason));
668                None
669            }
670            Err(error) => {
671                let Some(all) = servers.upgrade() else {
672                    return;
673                };
674                let server = &all[index];
675                tracing::warn!(kind = server.kind.label(), %error, "can't start the fork server");
676                let mut state = server.state.lock().await;
677                server.set(&mut state, State::Down);
678                None
679            }
680        };
681        backoff = spacing.next(backoff, up_for);
682        tokio::time::sleep(backoff).await;
683        // No one wants it any more: starting it would make its folders anew.
684        if servers.strong_count() == 0 {
685            return;
686        }
687    }
688}
689
690/// How starting a fork server went.
691enum Started {
692    /// It preloaded and is single-threaded.
693    Ready(Box<OsProcess>, UnixStream),
694    /// It can't be used: why, and whether that may pass.
695    Disabled(String, Cause),
696}
697
698/// Starts a fork server and has it preload `preload`.
699async fn start_server(
700    process: &ProcessSpec,
701    preload: &[String],
702    preload_timeout: Duration,
703) -> Result<Started, LaunchError> {
704    // Its directory and log go in the worker's log directory, which tasks create on their
705    // first run: a fork server starting before any task needs it now.
706    for dir in [
707        Some(process.working_dir.as_path()),
708        process.log_file.parent(),
709    ]
710    .into_iter()
711    .flatten()
712    {
713        tokio::fs::create_dir_all(dir)
714            .await
715            .map_err(|source| LaunchError::Start {
716                what: format!("the fork server's directory {}", dir.display()),
717                source,
718            })?;
719    }
720    let runner = match start_runner(process, RunnerMode::ForkServer, |_| {}).await {
721        Ok(runner) => runner,
722        Err(LaunchError::Channel(ChannelError::Refused(reason))) => {
723            return Ok(Started::Disabled(reason, Cause::Lasting));
724        }
725        Err(error) => return Err(error),
726    };
727    let (os, mut control) = (runner.process, runner.stream);
728    let request = AgentMessage::ForkServer(ForkServerRequest {
729        preload: preload.to_vec(),
730    });
731    crate::channel::write_message(&mut control, &request).await?;
732    let answer = tokio::time::timeout(preload_timeout, read_message(&mut control)).await;
733    match answer {
734        Ok(Ok(RunnerMessage::ForkServerReady)) => Ok(Started::Ready(Box::new(os), control)),
735        Ok(Ok(RunnerMessage::ForkServerDisabled { reason, threads })) => {
736            let cause = if threads.is_empty() {
737                Cause::Import
738            } else {
739                Cause::Lasting
740            };
741            Ok(Started::Disabled(reason, cause))
742        }
743        Ok(Ok(other)) => Err(ChannelError::Unexpected {
744            expected: "fork_server_ready",
745            got: format!("{other:?}"),
746        }
747        .into()),
748        Ok(Err(error)) => Err(error.into()),
749        Err(_) => Err(LaunchError::NoHello(preload_timeout)),
750    }
751}
752
753/// A runner forked from a fork server, with the agent's ends of its sockets.
754#[derive(Debug)]
755pub struct Forked {
756    /// The process (supervised like a spawned one).
757    pub process: ForkedProcess,
758    /// The agent's end of the runner's channel (it says hello on it next).
759    pub stream: UnixStream,
760    /// A copy of the status socket, holding the ended process: the caller drops it once
761    /// nothing signals the group any more, whatever happened to `process` meanwhile.
762    pub hold: GroupHold,
763}
764
765/// Asks `server` to fork a runner.
766async fn fork_on(
767    server: &Server,
768    spec: &ProcessSpec,
769    mode: RunnerMode,
770    answer_timeout: Duration,
771) -> Result<Forked, Fallback> {
772    let io = |_| Fallback::ForkFailed;
773    let (ours, theirs) = std::os::unix::net::UnixStream::pair().map_err(io)?;
774    let (status, status_theirs) = std::os::unix::net::UnixStream::pair().map_err(io)?;
775    let (stdout, stdout_theirs) = std::io::pipe().map_err(io)?;
776    let (stderr, stderr_theirs) = std::io::pipe().map_err(io)?;
777    let log = open_log(spec).await.map_err(io)?;
778    {
779        let mut state = server.state.lock().await;
780        let (control, id) = match &mut *state {
781            State::Up { asking: true, .. } => {
782                return Err(out_of_step(
783                    server,
784                    &mut state,
785                    "an earlier answer was abandoned",
786                ));
787            }
788            State::Up {
789                control,
790                next_id,
791                asking,
792            } => {
793                let id = *next_id;
794                *next_id += 1;
795                *asking = true;
796                (control, id)
797            }
798            State::Down => return Err(Fallback::Down),
799            State::Disabled(_) => return Err(Fallback::Disabled),
800        };
801        let request = AgentMessage::Fork(ForkRequest {
802            id,
803            mode,
804            env: spec.env.clone(),
805            cwd: spec.working_dir.to_string_lossy().into_owned(),
806        });
807        let fds = [
808            OwnedFd::from(theirs),
809            OwnedFd::from(stdout_theirs),
810            OwnedFd::from(stderr_theirs),
811            OwnedFd::from(status_theirs),
812        ];
813        if send_with_fds(control, &request, &fds).await.is_err() {
814            return Err(out_of_step(
815                server,
816                &mut state,
817                "the request couldn't be sent",
818            ));
819        }
820        let answer = tokio::time::timeout(answer_timeout, read_message(control)).await;
821        if let State::Up { asking, .. } = &mut *state {
822            *asking = false;
823        }
824        answered(server, &mut state, id, answer)?;
825        // Our copies of the process's ends go here: closed, so only the process holds them.
826        drop(fds);
827    }
828    let hold = GroupHold {
829        _open: OwnedFd::from(status.try_clone().map_err(io)?),
830    };
831    let mut status = tokio_stream(status).map_err(io)?;
832    let started = tokio::time::timeout(spec.start_timeout, read_message(&mut status)).await;
833    let Ok(Ok(RunnerMessage::ProcessStarted { pid })) = started else {
834        return Err(Fallback::ShimDied);
835    };
836    let group = Pid::from_raw(pid).ok_or(Fallback::ShimDied)?;
837    let limit = spec.max_output_size;
838    let stdout = pipe::Receiver::from_owned_fd(OwnedFd::from(stdout)).map_err(io)?;
839    let stderr = pipe::Receiver::from_owned_fd(OwnedFd::from(stderr)).map_err(io)?;
840    Ok(Forked {
841        process: ForkedProcess {
842            group,
843            status: Some(status.into()),
844            ended: None,
845            usage: Ended::default(),
846            stdout: Some(tokio::spawn(collect(
847                stdout,
848                Arc::clone(&log),
849                limit,
850                spec.mask.clone(),
851            ))),
852            stderr: Some(tokio::spawn(collect(stderr, log, limit, spec.mask.clone()))),
853        },
854        stream: tokio_stream(ours).map_err(io)?,
855        hold,
856    })
857}
858
859fn tokio_stream(stream: std::os::unix::net::UnixStream) -> io::Result<UnixStream> {
860    stream.set_nonblocking(true)?;
861    UnixStream::from_std(stream)
862}
863
864/// What a fork server's answer to request `id` means: forked, a fallback, or the server let
865/// go (disabled, or out of step).
866fn answered(
867    server: &Server,
868    state: &mut State,
869    id: u64,
870    answer: Result<Result<RunnerMessage, ChannelError>, tokio::time::error::Elapsed>,
871) -> Result<(), Fallback> {
872    match answer {
873        Ok(Ok(RunnerMessage::Forked { id: forked })) if forked == id => Ok(()),
874        Ok(Ok(RunnerMessage::ForkFailed { id: failed, reason })) if failed == id => {
875            tracing::warn!(kind = server.kind.label(), reason, "fork failed");
876            Err(Fallback::ForkFailed)
877        }
878        Ok(Ok(RunnerMessage::ForkServerDisabled { reason, .. })) => {
879            tracing::warn!(kind = server.kind.label(), reason, "fork server disabled");
880            // Dropping its control socket ends it; its supervisor stops for good.
881            server.set(state, State::Disabled(reason));
882            Err(Fallback::Disabled)
883        }
884        Ok(Ok(other)) => {
885            let why = format!("an answer that isn't this request's: {other:?}");
886            Err(out_of_step(server, state, &why))
887        }
888        Ok(Err(error)) => {
889            let why = format!("reading the answer: {error}");
890            Err(out_of_step(server, state, &why))
891        }
892        Err(_) => Err(out_of_step(server, state, "no answer in time")),
893    }
894}
895
896/// A fork server whose control socket no longer pairs answers with requests (an answer
897/// abandoned, late, or not this request's; or a request half sent): it is let go as down.
898/// Dropping the socket ends it, and its supervisor restarts it with backoff.
899fn out_of_step(server: &Server, state: &mut State, why: &str) -> Fallback {
900    tracing::warn!(
901        kind = server.kind.label(),
902        why,
903        "fork server out of step; restarting it"
904    );
905    server.set(state, State::Down);
906    Fallback::Down
907}
908
909/// No `SIGPIPE` for a fork server that is gone: `MSG_NOSIGNAL` is Linux's (where the fork
910/// server runs); elsewhere Rust's runtime ignores `SIGPIPE` already.
911#[cfg(target_os = "linux")]
912const SEND_FLAGS: SendFlags = SendFlags::NOSIGNAL;
913#[cfg(not(target_os = "linux"))]
914const SEND_FLAGS: SendFlags = SendFlags::empty();
915
916/// Sends `message` with `fds` on its first bytes (`SCM_RIGHTS`), in the channel's framing.
917async fn send_with_fds(
918    stream: &mut UnixStream,
919    message: &AgentMessage,
920    fds: &[OwnedFd],
921) -> Result<(), ChannelError> {
922    let body = serde_json::to_vec(message)?;
923    let size = u32::try_from(body.len())
924        .ok()
925        .filter(|size| *size <= MAX_MESSAGE_SIZE)
926        .ok_or(ChannelError::TooLarge(body.len() as u64))?;
927    let header = size.to_be_bytes();
928    let borrowed: Vec<_> = fds.iter().map(AsFd::as_fd).collect();
929    let mut sent = 0;
930    while sent == 0 {
931        stream.writable().await?;
932        let result = stream.try_io(tokio::io::Interest::WRITABLE, || {
933            let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(4))];
934            let mut control = SendAncillaryBuffer::new(&mut space);
935            control.push(SendAncillaryMessage::ScmRights(&borrowed));
936            rustix::net::sendmsg(&*stream, &[IoSlice::new(&header)], &mut control, SEND_FLAGS)
937                .map_err(io::Error::from)
938        });
939        match result {
940            Ok(n) => sent = n,
941            Err(error) if error.kind() == io::ErrorKind::WouldBlock => {}
942            Err(error) => return Err(error.into()),
943        }
944    }
945    // The descriptors went with the first bytes; the rest is plain.
946    stream.write_all(&header[sent..]).await?;
947    stream.write_all(&body).await?;
948    Ok(())
949}
950
951/// A copy of the agent's end of a forked process's status socket: while any copy is open, the
952/// shim keeps the ended process unreaped, so its PID and group stay its own. Dropped once
953/// nothing may signal the group any more (after the memory watchdog stopped), on every path.
954#[derive(Debug)]
955pub struct GroupHold {
956    _open: OwnedFd,
957}
958
959/// A forked runner process: its group, its shim's status socket, and its output.
960#[derive(Debug)]
961pub struct ForkedProcess {
962    group: Pid,
963    status: Option<Messages<UnixStream>>,
964    ended: Option<Termination>,
965    usage: Ended,
966    /// Taken by [`ForkedProcess::output`].
967    stdout: Option<JoinHandle<io::Result<TailBuffer>>>,
968    stderr: Option<JoinHandle<io::Result<TailBuffer>>>,
969}
970
971impl ForkedProcess {
972    /// Its process ID, which is also its process group's ID.
973    #[must_use]
974    pub fn id(&self) -> i32 {
975        self.group.as_raw_nonzero().get()
976    }
977
978    /// The captured stdout and stderr, once both pipes are closed.
979    ///
980    /// # Errors
981    ///
982    /// Returns an I/O error from reading a pipe or writing the log file.
983    pub async fn output(mut self) -> io::Result<(TailBuffer, TailBuffer)> {
984        let taken = (self.stdout.take(), self.stderr.take());
985        let (Some(stdout), Some(stderr)) = taken else {
986            return Err(io::Error::other("the output was taken already"));
987        };
988        let stdout = stdout.await.map_err(io::Error::other)??;
989        let stderr = stderr.await.map_err(io::Error::other)??;
990        Ok((stdout, stderr))
991    }
992}
993
994impl Drop for ForkedProcess {
995    /// A process dropped before its end was seen is killed, as a spawned one is
996    /// (`kill_on_drop`): a dropped attempt or parse job must not leave it running unwatched.
997    /// Its PID is still its own: the caller's [`GroupHold`] outlives it.
998    fn drop(&mut self) {
999        if self.ended.is_none() {
1000            let _ = kill_process_group(self.group, rustix::process::Signal::KILL);
1001        }
1002    }
1003}
1004
1005impl Process for ForkedProcess {
1006    async fn wait(&mut self) -> io::Result<Termination> {
1007        if let Some(ended) = self.ended {
1008            return Ok(ended);
1009        }
1010        let Some(status) = &mut self.status else {
1011            return Ok(Termination::Unknown);
1012        };
1013        let ended = loop {
1014            // Cancel-safe: `wait` is called again after a stop or deadline won (B57).
1015            match status.next().await {
1016                Ok(RunnerMessage::ProcessExited {
1017                    code,
1018                    signal,
1019                    core_dumped,
1020                    usage,
1021                }) => {
1022                    self.usage = Ended { usage, core_dumped };
1023                    break match (code, signal) {
1024                        (Some(code), _) => Termination::Exited(code),
1025                        (None, Some(signal)) => Termination::Signaled(signal),
1026                        (None, None) => Termination::Unknown,
1027                    };
1028                }
1029                Ok(_) => {}
1030                Err(_) => {
1031                    // The shim is gone: no one will report or reap the process. Stop
1032                    // whatever is left of its group.
1033                    let _ = kill_process_group(self.group, rustix::process::Signal::KILL);
1034                    break Termination::Unknown;
1035                }
1036            }
1037        };
1038        self.ended = Some(ended);
1039        Ok(ended)
1040    }
1041
1042    fn signal(&mut self, signal: Signal) -> io::Result<()> {
1043        let sig = match signal {
1044            Signal::Term => rustix::process::Signal::TERM,
1045            Signal::Kill => rustix::process::Signal::KILL,
1046        };
1047        match kill_process_group(self.group, sig) {
1048            Ok(()) | Err(rustix::io::Errno::SRCH) => Ok(()),
1049            Err(e) => Err(e.into()),
1050        }
1051    }
1052
1053    fn group_alive(&self) -> bool {
1054        crate::process::group_running(self.group)
1055    }
1056
1057    fn ended(&self) -> Ended {
1058        self.usage
1059    }
1060}