Skip to main content

schedr_agent/
launch.rs

1//! Starting real processes for attempts and parse jobs: the runner with its end of a fresh
2//! socket pair, commands as they are, each supervised (timeout, cancel, SIGTERM then SIGKILL).
3//!
4//! A runner gets its channel to the agent as an **inherited, already connected socket**
5//! (`SCHEDR_AGENT_FD`), not a path to connect to: no socket file, no directory, no path-length
6//! limit, and no other process can connect (see archive/PROJECT.md, Rust/Python integration).
7//!
8//! The thin operating-system layer under [`crate::agent`], like [`crate::process`]: exercised
9//! by the integration tests (`tests/runner.rs`); the decisions around it are unit-tested in
10//! [`crate::attempt`], [`crate::parse`] and [`crate::supervise`].
11
12use std::os::fd::{AsRawFd, OwnedFd};
13use std::sync::{Arc, PoisonError};
14use std::time::{Duration, Instant};
15
16use prometheus_client::metrics::counter::Counter;
17use schedr_model::SecretName;
18use schedr_model::ctx::CTX_FD_ENV;
19use schedr_model::runner::{AgentMessage, ParseRequest, RunnerMessage, RunnerMode, TaskRequest};
20use tokio::net::UnixStream;
21
22use crate::attempt::{Ran, StartTimes};
23use crate::channel::{ChannelError, accept_runner, read_message, write_message};
24use crate::ctx::CtxInfo;
25use crate::fork::{ForkServers, Forked, ForkedProcess, GroupHold};
26use crate::handles::{AttemptHandles, HandleError};
27use crate::memory::{GroupWatch, MemoryWatch, SharedSeen, over_budget_message, watch_group};
28use crate::output::TailBuffer;
29use crate::parse::{ParseRunner, ParseSession};
30use crate::process::{OsProcess, ProcessSpec, spawn, spawn_passing};
31use crate::secrets::{AttemptSecrets, ConnectionError, SecretError};
32use crate::status::{StopReason, Termination};
33use crate::supervise::{Limits, Process, Signal, Stops, Supervised, supervise};
34
35/// The environment variable with the runner's descriptor of its socket to the agent.
36pub const FD_ENV: &str = "SCHEDR_AGENT_FD";
37
38/// How long a started runner has to say hello, unless `[worker] runner_start_timeout` says.
39pub const RUNNER_START_TIMEOUT: Duration = Duration::from_secs(30);
40
41/// The version runners must have (the same `schedr` package as the agent).
42pub const AGENT_VERSION: &str = env!("CARGO_PKG_VERSION");
43
44/// Why a process couldn't be started or talked to.
45#[derive(Debug, thiserror::Error)]
46pub enum LaunchError {
47    /// Starting it, its socket or its log file failed.
48    #[error("can't start {what}: {source}")]
49    Start {
50        /// What was being started.
51        what: String,
52        /// The error.
53        source: std::io::Error,
54    },
55    /// The runner didn't say hello in time.
56    #[error("the runner didn't say hello within {0:?}")]
57    NoHello(Duration),
58    /// The runner connected in another mode than it was started in.
59    #[error("the runner said it is in {got:?} mode, expected {expected:?}")]
60    WrongMode {
61        /// The mode it was started in.
62        expected: RunnerMode,
63        /// The mode it said.
64        got: RunnerMode,
65    },
66    /// Talking to the runner failed.
67    #[error(transparent)]
68    Channel(#[from] ChannelError),
69    /// Waiting for or signalling the process failed.
70    #[error("supervising the process: {0}")]
71    Supervise(std::io::Error),
72}
73
74/// A runner that connected and said hello.
75#[derive(Debug)]
76pub struct Runner {
77    /// Its process.
78    pub process: OsProcess,
79    /// Its socket.
80    pub stream: UnixStream,
81    /// From starting its process to its hello.
82    pub hello_after: Duration,
83}
84
85/// Starts the runner described by `spec` in `mode`, handing it its end of a new socket pair,
86/// and completes the handshake; `spawned` gets its process ID as soon as it runs.
87///
88/// # Errors
89///
90/// [`LaunchError`] if it can't be started, doesn't say hello in time, or is in another mode or
91/// version (it was refused then).
92pub async fn start_runner(
93    spec: &ProcessSpec,
94    mode: RunnerMode,
95    spawned: impl FnOnce(i32),
96) -> Result<Runner, LaunchError> {
97    let (process, mut stream, starting) = spawn_runner(spec, spawned).await?;
98    match handshake(&mut stream, mode, spec.start_timeout, None).await {
99        Handshake::Said(Ok(())) => Ok(Runner {
100            process,
101            stream,
102            hello_after: starting.elapsed(),
103        }),
104        Handshake::Said(Err(error)) => {
105            abandon(process, spec.output_drain).await;
106            Err(error)
107        }
108        // Without stops, the handshake isn't cut short.
109        Handshake::Stopped(_) => unreachable!("a handshake without stops isn't stopped"),
110    }
111}
112
113/// Starts the runner described by `spec`, handing it its end of a new socket pair; `spawned`
114/// gets its process ID as soon as it runs. Returns the process, the agent's end of the
115/// socket, and when it was started.
116async fn spawn_runner(
117    spec: &ProcessSpec,
118    spawned: impl FnOnce(i32),
119) -> Result<(OsProcess, UnixStream, Instant), LaunchError> {
120    let start = |what: &str, source| LaunchError::Start {
121        what: what.to_owned(),
122        source,
123    };
124    let (ours, theirs) =
125        std::os::unix::net::UnixStream::pair().map_err(|e| start("the runner's socket", e))?;
126    let mut spec = spec.clone();
127    spec.env
128        .insert(FD_ENV.to_owned(), theirs.as_raw_fd().to_string());
129    let starting = Instant::now();
130    let process = spawn_passing(&spec, Some(OwnedFd::from(theirs)))
131        .await
132        .map_err(|e| start("the runner", e))?;
133    spawned(process.id());
134    ours.set_nonblocking(true)
135        .map_err(|e| start("the runner's socket", e))?;
136    let stream = UnixStream::from_std(ours).map_err(|e| start("the runner's socket", e))?;
137    Ok((process, stream, starting))
138}
139
140/// How a runner's handshake ended.
141enum Handshake {
142    /// It said hello in `mode` (`Ok`), or didn't in time, or said something else.
143    Said(Result<(), LaunchError>),
144    /// A reason to stop the attempt came first (B56): its cancel, or its deadline passing.
145    Stopped(StopReason),
146}
147
148/// Waits for the runner's hello in `mode`, for at most `timeout`. With
149/// `stops`, an attempt's reasons to stop and its deadline (`None` for none) are raced
150/// against it: the first to come ends the wait.
151async fn handshake(
152    stream: &mut UnixStream,
153    mode: RunnerMode,
154    timeout: Duration,
155    stops: Option<(&mut Stops, Option<tokio::time::Instant>)>,
156) -> Handshake {
157    let hello = async {
158        match tokio::time::timeout(timeout, accept_runner(stream, AGENT_VERSION)).await {
159            Ok(Ok(said)) if said == mode => Ok(()),
160            Ok(Ok(said)) => Err(LaunchError::WrongMode {
161                expected: mode,
162                got: said,
163            }),
164            Ok(Err(error)) => Err(error.into()),
165            Err(_) => Err(LaunchError::NoHello(timeout)),
166        }
167    };
168    match unless_stopped(hello, stops).await {
169        Ok(said) => Handshake::Said(said),
170        Err(reason) => Handshake::Stopped(reason),
171    }
172}
173
174/// `work`'s result, unless a reason in `stops` or their deadline comes first (reasons first,
175/// as in `supervise`); `work` is then dropped. Without `stops`, `work` alone.
176pub(crate) async fn unless_stopped<T>(
177    work: impl Future<Output = T>,
178    stops: Option<(&mut Stops, Option<tokio::time::Instant>)>,
179) -> Result<T, StopReason> {
180    let Some((stops, deadline)) = stops else {
181        return Ok(work.await);
182    };
183    let deadline = async {
184        match deadline {
185            Some(deadline) => tokio::time::sleep_until(deadline).await,
186            None => std::future::pending().await,
187        }
188    };
189    tokio::select! {
190        biased;
191        reason = stops.next_reason() => Err(reason),
192        () = deadline => Err(StopReason::TimedOut),
193        done = work => Ok(done),
194    }
195}
196
197/// How long a stopped runner's output may take to reach its log. A process it started in a
198/// session of its own outlives the kill and can hold the pipes open; the log is then left
199/// as it is rather than waiting forever.
200pub const OUTPUT_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
201
202/// Stops a runner (one that failed to start, or a finished parse session) and waits until
203/// what it printed is in its log (the caller may show it), for at most
204/// `output_drain`.
205async fn abandon(mut process: OsProcess, output_drain: Duration) {
206    let _ = process.signal(Signal::Kill);
207    let _ = process.wait().await;
208    let _ = tokio::time::timeout(output_drain, process.output()).await;
209}
210
211/// A task's runner process: spawned, or forked from a fork server.
212#[derive(Debug)]
213pub enum TaskProcess {
214    /// A child of the agent.
215    Spawned(OsProcess),
216    /// A child of a fork server's shim.
217    Forked(ForkedProcess),
218}
219
220impl TaskProcess {
221    /// The captured stdout and stderr, once both pipes are closed.
222    ///
223    /// # Errors
224    ///
225    /// Returns an I/O error from reading a pipe or writing the log file.
226    pub async fn output(self) -> std::io::Result<(TailBuffer, TailBuffer)> {
227        match self {
228            Self::Spawned(process) => process.output().await,
229            Self::Forked(process) => process.output().await,
230        }
231    }
232}
233
234impl Process for TaskProcess {
235    async fn wait(&mut self) -> std::io::Result<Termination> {
236        match self {
237            Self::Spawned(process) => process.wait().await,
238            Self::Forked(process) => process.wait().await,
239        }
240    }
241
242    fn signal(&mut self, signal: Signal) -> std::io::Result<()> {
243        match self {
244            Self::Spawned(process) => process.signal(signal),
245            Self::Forked(process) => process.signal(signal),
246        }
247    }
248
249    fn group_alive(&self) -> bool {
250        match self {
251            Self::Spawned(process) => process.group_alive(),
252            Self::Forked(process) => process.group_alive(),
253        }
254    }
255
256    fn ended(&self) -> crate::usage::Ended {
257        match self {
258            Self::Spawned(process) => process.ended(),
259            Self::Forked(process) => process.ended(),
260        }
261    }
262}
263
264/// A task's runner as its start left it.
265enum Start {
266    /// It said hello: its process, its socket, and how long it took.
267    Ready(TaskProcess, UnixStream, Duration),
268    /// A reason to stop the attempt came first (B56): the process still runs, for
269    /// `supervise` to stop.
270    Stopped(TaskProcess, StopReason),
271    /// A reason to stop came while waiting for a fork server: no runner was started.
272    NotStarted(StopReason),
273}
274
275/// Starts a Python task's runner, forked by `forks` if they can (from the preloaded server
276/// only with `preload`), else spawned, and completes the handshake, unless a reason in `stops`
277/// or their deadline comes first (an attempt's; a parse runner has none); `spawned` gets its process ID (and whether it was forked) as
278/// soon as it runs, and `hold` a forked one's [`GroupHold`]. A forked runner that fails the
279/// handshake isn't spawned again: it ran.
280async fn start_task_runner(
281    spec: &ProcessSpec,
282    mode: RunnerMode,
283    forks: Option<&ForkServers>,
284    preload: bool,
285    hold: &mut Option<GroupHold>,
286    stops: Option<(&mut Stops, Option<tokio::time::Instant>)>,
287    spawned: impl FnOnce(i32, bool),
288) -> Result<Start, LaunchError> {
289    let starting = Instant::now();
290    let mut stops = stops;
291    // Waiting for a fork server (another runner's fork may hold it) is part of the start
292    // too (B56): a fork abandoned midway is the fork server's to recover from (out of step,
293    // restarted), and its runner, its channel closed, ends.
294    let forked = match forks {
295        Some(forks) => {
296            let again = stops
297                .as_mut()
298                .map(|(stops, deadline)| (&mut **stops, *deadline));
299            match unless_stopped(forks.fork(spec, mode, preload), again).await {
300                Ok(forked) => forked.ok(),
301                Err(reason) => return Ok(Start::NotStarted(reason)),
302            }
303        }
304        None => None,
305    };
306    let (mut process, mut stream) = if let Some(Forked {
307        process,
308        stream,
309        hold: held,
310    }) = forked
311    {
312        *hold = Some(held);
313        spawned(process.id(), true);
314        (TaskProcess::Forked(process), stream)
315    } else {
316        let (process, stream, _) = spawn_runner(spec, |pid| spawned(pid, false)).await?;
317        (TaskProcess::Spawned(process), stream)
318    };
319    let error = match handshake(&mut stream, mode, spec.start_timeout, stops).await {
320        Handshake::Said(Ok(())) => return Ok(Start::Ready(process, stream, starting.elapsed())),
321        Handshake::Stopped(reason) => return Ok(Start::Stopped(process, reason)),
322        Handshake::Said(Err(error)) => error,
323    };
324    let _ = process.signal(Signal::Kill);
325    let _ = process.wait().await;
326    let _ = tokio::time::timeout(spec.output_drain, process.output()).await;
327    Err(error)
328}
329
330/// A Python task to run: the runner's request, and the attempt's secrets (it may read one
331/// under a declared prefix while it runs).
332#[derive(Debug)]
333pub struct PythonTask {
334    /// The request.
335    pub request: TaskRequest,
336    /// The attempt's secrets; none for a task without any.
337    pub secrets: Option<Arc<AttemptSecrets>>,
338    /// The attempt's cleanup handles; none outside an attempt.
339    pub handles: Option<Arc<AttemptHandles>>,
340    /// Where a trigger's events go; none for anything else.
341    pub events: Option<crate::watchers::EventSink>,
342    /// What it calls schedr's REST API with; none: it can't.
343    pub api: Option<crate::api::ApiCaller>,
344}
345
346impl From<TaskRequest> for PythonTask {
347    fn from(request: TaskRequest) -> Self {
348        Self {
349            request,
350            secrets: None,
351            handles: None,
352            events: None,
353            api: None,
354        }
355    }
356}
357
358/// Sends the task request and serves the runner until its result: its import time, and the
359/// secrets it reads (`task_ctx.secret`). Returns the result (`None` if the channel broke)
360/// and how long the import took, if it said.
361async fn task_conversation(
362    stream: &mut UnixStream,
363    request: TaskRequest,
364    (secrets, handles, api): (
365        Option<&AttemptSecrets>,
366        Option<&AttemptHandles>,
367        Option<&crate::api::ApiCaller>,
368    ),
369) -> (Option<RunnerMessage>, Option<Duration>) {
370    let request = AgentMessage::Task(Box::new(request));
371    if write_message(stream, &request).await.is_err() {
372        return (None, None);
373    }
374    let sent = Instant::now();
375    let mut import = None;
376    loop {
377        let message: Result<RunnerMessage, ChannelError> = read_message(stream).await;
378        match message {
379            // The first one counts; a repeat isn't the result.
380            Ok(RunnerMessage::TaskImported) => {
381                import.get_or_insert_with(|| sent.elapsed());
382            }
383            // Served in turn: the runner waits for each answer.
384            Ok(RunnerMessage::SecretGet { secret }) => {
385                let answer = secret_answer(secrets, &secret).await;
386                if write_message(stream, &answer).await.is_err() {
387                    return (None, import);
388                }
389            }
390            Ok(RunnerMessage::HandleAdd { handle }) => {
391                let added = match handles {
392                    Some(handles) => handles.add(handle).await,
393                    None => Err(HandleError::NoCleanup),
394                };
395                let answer = added.map_or_else(
396                    |error| AgentMessage::HandleRefused {
397                        message: error.to_string(),
398                    },
399                    |()| AgentMessage::HandleAdded,
400                );
401                if write_message(stream, &answer).await.is_err() {
402                    return (None, import);
403                }
404            }
405            Ok(RunnerMessage::ConnectionGet { name }) => {
406                let answer = connection_answer(secrets, &name).await;
407                if write_message(stream, &answer).await.is_err() {
408                    return (None, import);
409                }
410            }
411            Ok(RunnerMessage::ApiCall {
412                method,
413                path,
414                body,
415                idempotency_key,
416            }) => {
417                let request = crate::api::ApiRequest {
418                    method,
419                    path,
420                    body,
421                    idempotency_key,
422                    masked: false,
423                }
424                .masked_by(secrets);
425                let answer = crate::api::runner_answer(api, request).await;
426                if write_message(stream, &answer).await.is_err() {
427                    return (None, import);
428                }
429            }
430            message => return (message.ok(), import),
431        }
432    }
433}
434
435/// Runs a Python task: starts the runner (forked by `forks` when there are any and they can,
436/// unless the task asks for a fresh process; only by the bare server with `preload` off),
437/// sends the request, and waits for its result while supervising the process; `spawned` gets
438/// the runner's process ID, and whether it was forked, as soon as it runs. A forked process's
439/// [`GroupHold`] goes to `hold`, on every path (the caller drops it after its watchdog).
440///
441/// # Errors
442///
443/// [`LaunchError`] if the runner can't be started or supervised; a runner that dies or sends
444/// nothing still gives a [`Ran`] (without a result).
445pub async fn run_python(
446    process: &ProcessSpec,
447    task: impl Into<PythonTask>,
448    limits: Limits,
449    mut stop: Stops,
450    forks: Option<&ForkServers>,
451    hold: &mut Option<GroupHold>,
452    spawned: impl FnOnce(i32, bool),
453) -> Result<Ran, LaunchError> {
454    let output_drain = process.output_drain;
455    let PythonTask {
456        request,
457        secrets,
458        handles,
459        events: _,
460        api,
461    } = task.into();
462    let started = Instant::now();
463    // The remaining timeout includes the runner's start (B56, B160).
464    let deadline = limits
465        .timeout
466        .map(|timeout| tokio::time::Instant::from_std(started) + timeout);
467    // The task's own choice: never forked (`fresh_process`), or not from the preloaded server.
468    // A hard memory cap is set by `schedr task-exec` before the runner starts: spawned too.
469    let settings = &request.task.settings;
470    let forks = forks.filter(|_| !settings.fresh_process && !settings.hard_memory_limit);
471    let preload = settings.preload;
472    let stops = Some((&mut stop, deadline));
473    let start = start_task_runner(
474        process,
475        RunnerMode::Task,
476        forks,
477        preload,
478        hold,
479        stops,
480        spawned,
481    );
482    let (mut process, mut stream, hello_after) = match start.await? {
483        Start::Ready(process, stream, hello_after) => (process, stream, hello_after),
484        // Cancelled or timed out before its hello: stopped as a running task is, the reason
485        // given back for `supervise` to take first; no request was sent, so no result.
486        Start::NotStarted(reason) => {
487            let supervised = Supervised {
488                termination: Termination::Unknown,
489                stopped: Some(reason),
490                killed: false,
491            };
492            return Ok(Ran::with_no_process(supervised, None, started.elapsed()));
493        }
494        Start::Stopped(mut process, reason) => {
495            let forked = matches!(process, TaskProcess::Forked(_));
496            stop.give_back(reason);
497            let supervised = supervise(&mut process, limits, stop)
498                .await
499                .map_err(LaunchError::Supervise)?;
500            let ended = process.ended();
501            // A process it started in a session of its own may hold the pipes open.
502            let _ = tokio::time::timeout(output_drain, process.output()).await;
503            return Ok(Ran {
504                supervised,
505                runner_result: None,
506                output: None,
507                duration: started.elapsed(),
508                start: None,
509                forked,
510                ended,
511                moved_to: None,
512                host_lost: None,
513                struck: false,
514            });
515        }
516    };
517    let limits = Limits {
518        timeout: deadline
519            .map(|deadline| deadline.saturating_duration_since(tokio::time::Instant::now())),
520        ..limits
521    };
522    let forked = matches!(process, TaskProcess::Forked(_));
523    // Sent while supervised: a runner that doesn't read is stopped on time all the same (B56).
524    let answers = (secrets.as_deref(), handles.as_deref(), api.as_ref());
525    let result = task_conversation(&mut stream, request, answers);
526    let ((runner_result, import), supervised) = {
527        // Boxed: the attempt's future stays small.
528        let mut result = Box::pin(result);
529        let mut supervised = Box::pin(supervise(&mut process, limits, stop));
530        // Once the process has ended, its result is in the socket already: a conversation still
531        // waiting (on a slow secret storage) is given up after a moment, not awaited.
532        tokio::select! {
533            conversation = &mut result => (conversation, supervised.await),
534            supervised = &mut supervised => {
535                let conversation = tokio::time::timeout(output_drain, result)
536                    .await
537                    .unwrap_or((None, None));
538                (conversation, supervised)
539            }
540        }
541    };
542    let supervised = supervised.map_err(LaunchError::Supervise)?;
543    let ended = process.ended();
544    let _ = process.output().await;
545    Ok(Ran {
546        supervised,
547        runner_result,
548        output: None,
549        duration: started.elapsed(),
550        start: Some(StartTimes {
551            runner: hello_after,
552            import,
553        }),
554        forked,
555        ended,
556        moved_to: None,
557        host_lost: None,
558        struck: false,
559    })
560}
561
562/// Runs a command process under supervision, keeping the tails of its output; `spawned` gets
563/// its process ID as soon as it runs. With `ctx`, the process (and every process it starts)
564/// gets a context channel (`SCHEDR_CTX_FD`, see [`crate::ctx`]), served until it ends.
565///
566/// # Errors
567///
568/// [`LaunchError`] if it can't be started or supervised.
569pub async fn run_command(
570    spec: &ProcessSpec,
571    ctx: Option<CtxInfo>,
572    limits: Limits,
573    stop: Stops,
574    spawned: impl FnOnce(i32),
575) -> Result<Ran, LaunchError> {
576    let started = Instant::now();
577    let start = |source| LaunchError::Start {
578        what: spec.program.display().to_string(),
579        source,
580    };
581    let (mut process, _serving) = match ctx {
582        Some(info) => {
583            let (ours, theirs) = crate::ctx::channel().map_err(start)?;
584            let mut spec = spec.clone();
585            spec.env
586                .insert(CTX_FD_ENV.to_owned(), theirs.as_raw_fd().to_string());
587            let serving = crate::ctx::serve(ours, info);
588            let process = spawn_passing(&spec, Some(theirs)).await.map_err(start)?;
589            (process, Some(serving))
590        }
591        None => (spawn(spec).await.map_err(start)?, None),
592    };
593    spawned(process.id());
594    // The timeout counts from here, as a runner's does: a slow start is part of the attempt.
595    let limits = Limits {
596        timeout: limits
597            .timeout
598            .map(|timeout| timeout.saturating_sub(started.elapsed())),
599        ..limits
600    };
601    let supervised = supervise(&mut process, limits, stop)
602        .await
603        .map_err(LaunchError::Supervise)?;
604    let ended = process.ended();
605    let output = process.output().await.map_err(LaunchError::Supervise)?;
606    Ok(Ran {
607        supervised,
608        runner_result: None,
609        output: Some(output),
610        start: None,
611        duration: started.elapsed(),
612        forked: false,
613        ended,
614        moved_to: None,
615        host_lost: None,
616        struck: false,
617    })
618}
619
620/// Starts runners in parse mode for one root (see [`crate::parse::parse_files`]).
621#[derive(Debug, Clone)]
622pub struct ProcessParseRunner {
623    /// The runner process (interpreter, `-m schedr.runner parse`, environment, log file).
624    pub process: ProcessSpec,
625    /// How the memory watchdog watches it (each runner, like a task).
626    pub memory: MemoryWatch,
627    /// Where the watchdog's kills are counted.
628    pub kills: Counter,
629    /// The DAG interpreter's fork servers: a parse job forks from them like a task (a fresh
630    /// child per job), spawned when they can't.
631    pub forks: Option<ForkServers>,
632}
633
634/// A parse runner that connected and got its request.
635#[derive(Debug)]
636pub struct ProcessParseSession {
637    process: TaskProcess,
638    stream: UnixStream,
639    /// The watchdog, killing the runner's group over its budget (stops when dropped).
640    watching: Option<GroupWatch>,
641    /// A forked runner's hold, let go after the watchdog (see [`GroupHold`]).
642    hold: Option<GroupHold>,
643    seen: SharedSeen,
644    budget: Option<u64>,
645    output_drain: Duration,
646}
647
648impl ParseSession for ProcessParseSession {
649    async fn next(&mut self) -> Result<RunnerMessage, ChannelError> {
650        let message = read_message(&mut self.stream).await;
651        let over = self
652            .seen
653            .lock()
654            .unwrap_or_else(PoisonError::into_inner)
655            .over;
656        match (message, over, self.budget) {
657            (Err(_), Some(used), Some(budget)) => {
658                Err(ChannelError::OverMemory(over_budget_message(budget, used)))
659            }
660            (message, _, _) => message,
661        }
662    }
663
664    async fn send(&mut self, message: AgentMessage) -> Result<(), ChannelError> {
665        write_message(&mut self.stream, &message).await
666    }
667
668    async fn stop(self) {
669        let Self {
670            mut process,
671            watching,
672            hold,
673            output_drain,
674            ..
675        } = self;
676        let _ = process.signal(Signal::Kill);
677        let _ = process.wait().await;
678        let _ = tokio::time::timeout(output_drain, process.output()).await;
679        // The watchdog stops first; then the hold goes, and a fork server's shim reaps it.
680        drop(watching);
681        drop(hold);
682    }
683}
684
685impl ParseRunner for ProcessParseRunner {
686    type Session = ProcessParseSession;
687
688    async fn start(&self, request: ParseRequest) -> Result<ProcessParseSession, ChannelError> {
689        let seen = SharedSeen::default();
690        // Declared before the watch, so it is dropped after it on any path (locals go in
691        // reverse order), a cancelled start included.
692        let mut hold = None;
693        let mut watching = None;
694        let forks = self.forks.as_ref();
695        let started = start_task_runner(
696            &self.process,
697            RunnerMode::Parse,
698            forks,
699            true,
700            &mut hold,
701            None,
702            |pgid, forked| {
703                // Told through `seen`, read when the runner's connection breaks (no one listens
704                // to its reason).
705                watching = Some(watch_group(
706                    self.memory.clone(),
707                    pgid,
708                    seen.clone(),
709                    Stops::new().0,
710                    self.kills.clone(),
711                    forked,
712                ));
713            },
714        )
715        .await;
716        let (process, stream) = match started {
717            Ok(Start::Ready(process, stream, _)) => (process, stream),
718            // Without stops, the handshake isn't cut short.
719            Ok(Start::Stopped(..) | Start::NotStarted(_)) => {
720                unreachable!("a parse runner's start has no stops")
721            }
722            Err(error) => {
723                drop(watching);
724                drop(hold);
725                return Err(match error {
726                    LaunchError::Channel(channel) => channel,
727                    other => ChannelError::Io(std::io::Error::other(other.to_string())),
728                });
729            }
730        };
731        let mut session = ProcessParseSession {
732            process,
733            stream,
734            watching,
735            hold,
736            seen,
737            budget: self.memory.budget,
738            output_drain: self.process.output_drain,
739        };
740        if let Err(error) = write_message(&mut session.stream, &AgentMessage::Parse(request)).await
741        {
742            session.stop().await;
743            return Err(error);
744        }
745        Ok(session)
746    }
747}
748
749/// The answer to a running Python task's `ConnectionGet` (decision 174).
750pub(crate) async fn connection_answer(
751    secrets: Option<&AttemptSecrets>,
752    name: &str,
753) -> AgentMessage {
754    let opened = match secrets {
755        Some(secrets) => secrets.connection(name).await,
756        None => Err(ConnectionError::NotFound(format!(
757            "connection `{name}`: no connections are known for this task"
758        ))),
759    };
760    match opened {
761        Ok(values) => AgentMessage::Connection { values },
762        Err(error) => AgentMessage::ConnectionFailed {
763            kind: error.kind().to_owned(),
764            message: error.to_string(),
765        },
766    }
767}
768
769/// The answer to a running Python task's `SecretGet`.
770pub(crate) async fn secret_answer(
771    secrets: Option<&AttemptSecrets>,
772    secret: &SecretName,
773) -> AgentMessage {
774    let read = match secrets {
775        Some(secrets) => secrets.read(secret).await,
776        None => Err(SecretError::Denied(format!(
777            "`{secret}` isn't declared in the task's `secrets=`"
778        ))),
779    };
780    match read {
781        Ok(value) => AgentMessage::Secret { value },
782        Err(error) => AgentMessage::SecretFailed {
783            kind: error.kind().to_owned(),
784            message: error.to_string(),
785        },
786    }
787}