Skip to main content

aither_sandbox/
job_registry.rs

1//! Background job registry for tracking and managing background terminal tasks.
2//!
3//! Uses an internal command channel to avoid shared locks.
4
5use std::collections::HashMap;
6use std::fmt::Write as _;
7use std::path::PathBuf;
8use std::time::{Duration, Instant};
9
10use aither_core::{IdLease, WeakIdLease};
11use async_channel::{Receiver, Sender, WeakSender};
12use futures_lite::io::AsyncWriteExt;
13
14use crate::interpreter::Interpreter;
15use crate::memory::MemoryDomain;
16use crate::output_policy::OutputPolicy;
17use crate::policy::SandboxMode;
18#[cfg(unix)]
19use crate::process_tree::KillTreeError;
20use crate::process_tree::{JobTree, ProcessScanner};
21use crate::terminal::TimeoutKill;
22
23/// Information about a running or completed background job.
24#[derive(Debug, Clone)]
25pub struct JobInfo {
26    /// Process ID.
27    pub pid: u32,
28    /// Stable task identifier exposed to the model.
29    pub task_id: String,
30    /// Stateless execution key that owns this job.
31    pub execution_key: String,
32    /// The script that was executed.
33    pub script: String,
34    /// The interpreter of `script`.
35    pub interpreter: Interpreter,
36    /// The permission mode used.
37    pub mode: SandboxMode,
38    /// When the job was started.
39    pub started_at: Instant,
40    /// Current status of the job.
41    pub status: JobStatus,
42    /// Path to output file.
43    pub output_path: Option<PathBuf>,
44    /// Where the job runs.
45    pub place: JobPlace,
46    /// The bound the job was started under: it is killed once this long has
47    /// passed since it started. `None` when nothing bounds it.
48    pub timeout: Option<Duration>,
49}
50
51impl JobInfo {
52    /// How long until the job's `timeout` bound kills it, zero once passed;
53    /// `None` when nothing bounds it.
54    #[must_use]
55    pub fn remaining(&self) -> Option<Duration> {
56        self.timeout
57            .map(|timeout| timeout.saturating_sub(self.started_at.elapsed()))
58    }
59}
60
61/// Status of a background job.
62///
63/// Every finished status carries its [`Delivery`]: the transition that
64/// finishes a job also records that its completion is owed to the agent.
65/// The registry forgets a job once its completion was taken and nothing
66/// watches it, so a [`Delivery::Taken`] job reads only while it is watched
67/// or, taken by a waiter, until its own flow settles it.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub enum JobStatus {
70    /// Job is currently running.
71    Running,
72    /// Job completed successfully.
73    Completed {
74        /// Exit code of the process.
75        exit_code: i32,
76        /// Whether the agent has taken the job's completion.
77        delivery: Delivery,
78    },
79    /// Job failed with an error.
80    Failed {
81        /// Error message.
82        error: String,
83        /// Whether the agent has taken the job's completion.
84        delivery: Delivery,
85    },
86    /// Job was killed.
87    Killed {
88        /// Why it was killed.
89        cause: KillCause,
90        /// Whether the agent has taken the job's completion.
91        delivery: Delivery,
92    },
93}
94
95/// Why a job was killed.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum KillCause {
98    /// A request ended it: `terminal_kill`, or the shutdown of its terminal.
99    User,
100    /// Its `timeout` bound passed.
101    Timeout(TimeoutKill),
102    /// Its home environment's memory ran out of room for the agent's jobs
103    /// (see [`MemoryDomain`]), and the agent left it running past the
104    /// response window that followed the final warning.
105    MemoryRunaway {
106        /// The tree's physical footprint when it was killed.
107        footprint_bytes: u64,
108        /// The memory of the domain it ran in: the machine's physical memory,
109        /// or the container's limit.
110        capacity_bytes: u64,
111        /// The domain it ran in.
112        domain: MemoryDomain,
113    },
114}
115
116/// Where a job runs, which decides what is watched of it.
117///
118/// Only the home environment is watched: the machine the embedder runs on,
119/// and the container the agent works in when it has one. The memory and the
120/// disk of a remote execution environment are never judged and its jobs are
121/// never killed for them.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
123pub enum JobPlace {
124    /// A process of the machine the embedder runs on.
125    Host,
126    /// A process inside the container the agent works in.
127    Container,
128    /// A process on a remote host over SSH.
129    Remote,
130}
131
132impl JobStatus {
133    /// How far a finished job's completion got; `None` while it runs.
134    #[must_use]
135    pub const fn delivery(&self) -> Option<Delivery> {
136        match self {
137            Self::Running => None,
138            Self::Completed { delivery, .. }
139            | Self::Failed { delivery, .. }
140            | Self::Killed { delivery, .. } => Some(*delivery),
141        }
142    }
143
144    /// Why a killed job was killed; `None` for a job that was not.
145    #[must_use]
146    pub const fn kill_cause(&self) -> Option<KillCause> {
147        match self {
148            Self::Killed { cause, .. } => Some(*cause),
149            Self::Running | Self::Completed { .. } | Self::Failed { .. } => None,
150        }
151    }
152
153    /// Whether the job finished and its agent has yet to take the
154    /// completion: the agent still owes its session a turn for it.
155    #[must_use]
156    pub const fn completion_pending(&self) -> bool {
157        matches!(self.delivery(), Some(Delivery::Pending))
158    }
159}
160
161/// Why bytes were not written to a job's stdin.
162#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
163pub enum JobInputError {
164    /// The registry holds no job of that name.
165    #[error("unknown task_id: {task_id}")]
166    UnknownTask {
167        /// The task named.
168        task_id: String,
169    },
170    /// The job no longer runs.
171    #[error("task {task_id} is not running; current status: {status:?}")]
172    NotRunning {
173        /// The job.
174        task_id: String,
175        /// How it ended.
176        status: JobStatus,
177    },
178    /// The job's stdin is the null device, not a pipe: it was started in the
179    /// foreground, and a job promoted past the foreground window keeps the
180    /// stdin it started with.
181    #[error("task {task_id} reads no input: it started in the foreground, with no stdin pipe")]
182    NoStdin {
183        /// The job.
184        task_id: String,
185    },
186    /// The job's stdin pipe is closed.
187    #[error("terminal input channel closed for task {task_id}")]
188    Closed {
189        /// The job.
190        task_id: String,
191    },
192}
193
194/// Whether a finished job's completion has reached its agent.
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum Delivery {
197    /// The completion is on its way to the agent, which has not taken it.
198    Pending,
199    /// The agent took the completion: its [`PendingCompletion`] was dropped.
200    Taken,
201}
202
203/// A finished job's completion on its way to the agent.
204///
205/// The job reads [`Delivery::Pending`] in its registry for as long as this
206/// lives; dropping it is the agent taking the completion, which marks the
207/// job [`Delivery::Taken`] and lets the registry forget it, so its task id
208/// goes back to the allocator. The registry hands out one per job, through
209/// [`JobRegistry::owe_completion`].
210#[must_use = "dropping it marks the completion taken"]
211pub struct PendingCompletion {
212    tx: Sender<JobCommand>,
213    /// Keeps the word naming this job until the registry hears of the take.
214    task_id: Option<IdLease>,
215}
216
217impl std::fmt::Debug for PendingCompletion {
218    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
219        f.debug_struct("PendingCompletion")
220            .field("task_id", &self.task_id)
221            .finish_non_exhaustive()
222    }
223}
224
225impl PendingCompletion {
226    /// Takes the completion as dropping it does, returning once the registry
227    /// recorded the take: a job it then forgets reads as unknown to every
228    /// later request.
229    pub async fn take(mut self) {
230        // Only `take` and `drop` empty it, each consuming the completion.
231        let Some(task_id) = self.task_id.take() else {
232            return;
233        };
234        let (reply_tx, reply_rx) = async_channel::bounded(1);
235        // A closed registry has no reader left to tell.
236        if self
237            .tx
238            .send(
239                JobRequest::TakeCompletion {
240                    task_id,
241                    reply: reply_tx,
242                }
243                .into(),
244            )
245            .await
246            .is_ok()
247        {
248            let _ = reply_rx.recv().await;
249        }
250    }
251}
252
253impl Drop for PendingCompletion {
254    fn drop(&mut self) {
255        if let Some(task_id) = self.task_id.take() {
256            // A closed registry has no reader left to tell.
257            let _ = self
258                .tx
259                .try_send(StateCommand::TakeCompletion { task_id }.into());
260        }
261    }
262}
263
264/// Keeps a job in its registry, finished or not, while something reads it
265/// by its task id; the registry forgets a finished job only once every
266/// watch of it dropped. [`JobRegistry::watch`] hands them out.
267pub struct JobWatch {
268    tx: Sender<JobCommand>,
269    /// Keeps the word naming this job; the unwatch it sends keeps a clone
270    /// until the registry hears of it.
271    task_id: IdLease,
272}
273
274impl std::fmt::Debug for JobWatch {
275    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276        f.debug_struct("JobWatch")
277            .field("task_id", &self.task_id)
278            .finish_non_exhaustive()
279    }
280}
281
282impl Drop for JobWatch {
283    fn drop(&mut self) {
284        let task_id = self.task_id.clone();
285        let _ = self.tx.try_send(StateCommand::Unwatch { task_id }.into());
286    }
287}
288
289/// What [`JobRegistry::owe_completion`] settled for a job.
290#[derive(Debug)]
291pub struct OwedCompletion {
292    /// The job as it ended. A job whose completion a waiter took is
293    /// forgotten as it settles when nothing watches it, so this is the one
294    /// read of it its flow is sure of.
295    pub info: JobInfo,
296    /// Keeps the completion pending until the agent takes it; `None` when a
297    /// waiter ([`JobRegistry::wait_taking`]) already took it, so nothing is
298    /// owed.
299    pub pending: Option<PendingCompletion>,
300}
301
302impl JobRead {
303    /// The delta, or `None` for an unchanged read.
304    #[must_use]
305    pub fn into_delta(self) -> Option<JobDelta> {
306        match self {
307            Self::Delta(delta) => Some(delta),
308            Self::Unchanged { .. } => None,
309        }
310    }
311}
312
313/// Incremental read result for a background terminal buffer.
314#[derive(Debug, Clone, PartialEq, Eq)]
315pub struct JobDelta {
316    /// Stable task identifier exposed to the model.
317    pub task_id: String,
318    /// Cursor the caller should pass on the next read.
319    pub cursor: usize,
320    /// Total bytes currently buffered for this task.
321    pub total_bytes: usize,
322    /// Newly read bytes from the terminal buffer.
323    pub bytes: Vec<u8>,
324    /// Current task status at the time of the read.
325    pub status: JobStatus,
326}
327
328/// What a read of a job's output returned.
329///
330/// A read that would return what the job's last read returned is a poll:
331/// only more output, or the job's end, can tell the reader something new, so
332/// it comes back as [`Self::Unchanged`] for the reader's wording to say so.
333#[derive(Debug, Clone, PartialEq, Eq)]
334pub enum JobRead {
335    /// Output past the cursor, or the same cursor with a changed status.
336    Delta(JobDelta),
337    /// Nothing changed since this job's last read.
338    Unchanged {
339        /// The job whose output did not change.
340        task_id: String,
341    },
342}
343
344/// Why a tool refused a read of a job's output: nothing changed since the
345/// job's last read. The refusal a tool returns as `Refused<UnchangedRead>`.
346#[derive(Debug, Clone, PartialEq, Eq)]
347pub struct UnchangedRead {
348    /// The job whose output did not change.
349    pub task_id: String,
350}
351
352/// Sender used by the registry to push bytes into a running process stdin.
353pub type TerminalInputSender = Sender<Vec<u8>>;
354
355/// One of a job's two output streams.
356#[derive(Debug, Clone, Copy, PartialEq, Eq)]
357pub enum TerminalStream {
358    Stdout,
359    Stderr,
360}
361
362#[derive(Debug)]
363#[allow(clippy::struct_excessive_bools)]
364struct JobState {
365    info: JobInfo,
366    /// Keeps the job's task id leased while the registry keeps the job.
367    task_id: IdLease,
368    terminal_buffer: Vec<u8>,
369    /// Complete lines only, each from one stream, in the order they
370    /// completed: what the `monitor` pump reads.
371    line_buffer: Vec<u8>,
372    stdout_partial: Vec<u8>,
373    stderr_partial: Vec<u8>,
374    stdout_buffer: Vec<u8>,
375    stderr_buffer: Vec<u8>,
376    stdout_closed: bool,
377    stderr_closed: bool,
378    input_tx: Option<TerminalInputSender>,
379    kill_switch: Option<Sender<()>>,
380    process_tree: Option<JobTree>,
381    /// Why the kill in flight was asked for: the first of overlapping kills.
382    kill_cause: Option<KillCause>,
383    /// How many kills of the job run outside the registry; an ending the
384    /// job's own flow reports meanwhile waits in `deferred_end`.
385    kills_in_flight: usize,
386    deferred_end: Option<Ending>,
387    /// Callers parked until the last kill in flight records its outcome.
388    settled_waiters: Vec<SettledWaiter>,
389    /// Callers parked until the job ends.
390    ended_waiters: Vec<Sender<Option<JobInfo>>>,
391    output_redirect: Option<async_fs::File>,
392    finished_at: Option<Instant>,
393    /// Whether the job's [`PendingCompletion`] was handed out.
394    completion_owed: bool,
395    /// Whether a waiter took the completion before it was handed out: the
396    /// job then reads [`Delivery::Taken`] the moment it ends and owes
397    /// nothing.
398    claimed: bool,
399    /// How many [`JobWatch`]es of the job live.
400    watchers: usize,
401}
402
403/// A caller waiting for a job's kills in flight to record their outcome.
404#[derive(Debug)]
405enum SettledWaiter {
406    /// `get_by_task_id_settled`.
407    Read(Sender<Option<JobInfo>>),
408    /// `owe_completion`.
409    Owe {
410        ending: Result<i32, String>,
411        reply: Sender<Option<OwedCompletion>>,
412    },
413}
414
415/// State mutations sent to the registry service; none expect a reply.
416enum StateCommand {
417    Register {
418        pid: u32,
419        task_id: IdLease,
420        execution_key: String,
421        script: String,
422        interpreter: Interpreter,
423        mode: SandboxMode,
424        output_path: Option<PathBuf>,
425        process_tree: Option<JobTree>,
426        place: JobPlace,
427    },
428    Bound {
429        task_id: IdLease,
430        timeout: Duration,
431    },
432    /// The process of task `task_id` is about to start: its output can be
433    /// appended to from here on, ahead of the job's registration.
434    Launching {
435        task_id: IdLease,
436    },
437    /// The launch of task `task_id` ended; a job that never registered is
438    /// forgotten and what waited for it is released.
439    Abandon {
440        task_id: IdLease,
441    },
442    AttachTerminalInput {
443        task_id: IdLease,
444        input_tx: TerminalInputSender,
445    },
446    AttachKillSwitch {
447        task_id: IdLease,
448        kill_tx: Sender<()>,
449    },
450    AppendTerminalOutput {
451        task_id: IdLease,
452        stream: TerminalStream,
453        chunk: Vec<u8>,
454    },
455    CloseTerminalStream {
456        task_id: IdLease,
457        stream: TerminalStream,
458    },
459    Complete {
460        task_id: IdLease,
461        exit_code: i32,
462        output_path: Option<PathBuf>,
463    },
464    Fail {
465        task_id: IdLease,
466        error: String,
467        output_path: Option<PathBuf>,
468    },
469    /// The agent took the completion of task `task_id`.
470    TakeCompletion {
471        task_id: IdLease,
472    },
473    /// A [`JobWatch`] of task `task_id` dropped.
474    Unwatch {
475        task_id: IdLease,
476    },
477}
478
479/// Registry queries and job-control requests, each answered on `reply`.
480enum JobRequest {
481    List {
482        reply: Sender<Vec<JobInfo>>,
483    },
484    GetByTaskId {
485        task_id: String,
486        reply: Sender<Option<JobInfo>>,
487    },
488    GetByTaskIdSettled {
489        task_id: String,
490        reply: Sender<Option<JobInfo>>,
491    },
492    /// Appends `chunk` to the stdout of task `task_id`, replying once it is
493    /// in, with whether it went in: a task not registered yet gets it when
494    /// it registers, one that no longer runs or was forgotten gets nothing.
495    AppendTaskStdout {
496        task_id: IdLease,
497        chunk: Vec<u8>,
498        reply: Sender<bool>,
499    },
500    /// The lease of the job `task_id` names, whether registered or still
501    /// launching, held weakly.
502    Lease {
503        task_id: String,
504        reply: Sender<Option<WeakIdLease>>,
505    },
506    OweCompletion {
507        task_id: String,
508        ending: Result<i32, String>,
509        reply: Sender<Option<OwedCompletion>>,
510    },
511    BeginKillByTaskId {
512        task_id: String,
513        cause: KillCause,
514        reply: Sender<KillPlan>,
515    },
516    BeginKillByExecutionKey {
517        execution_key: String,
518        cause: KillCause,
519        reply: Sender<Vec<(String, KillPlan)>>,
520    },
521    EndKill {
522        task_id: String,
523        killed: bool,
524        reply: Sender<bool>,
525    },
526    InputTerminal {
527        task_id: String,
528        bytes: Vec<u8>,
529        reply: Sender<Result<(), JobInputError>>,
530    },
531    StartOutputRedirect {
532        task_id: String,
533        output_path: PathBuf,
534        reply: Sender<Result<Vec<u8>, String>>,
535    },
536    TerminalOutput {
537        task_id: String,
538        reply: Sender<Option<(Vec<u8>, Vec<u8>)>>,
539    },
540    ReadJobDelta {
541        task_id: String,
542        cursor: usize,
543        max_bytes: usize,
544        /// Whether this read is a model read of the merged terminal buffer,
545        /// tracked by the unchanged-read refusal; a monitor pump's reads are
546        /// not, and read the complete-line buffer instead.
547        tracked: bool,
548        reply: Sender<Result<JobRead, String>>,
549    },
550    WaitEnded {
551        task_id: String,
552        /// Whether the waiter takes the job's completion.
553        claim: bool,
554        reply: Sender<Option<JobInfo>>,
555    },
556    TerminalStreamsClosed {
557        task_id: String,
558        reply: Sender<bool>,
559    },
560    FormatRunning {
561        reply: Sender<String>,
562    },
563    HasRunning {
564        reply: Sender<bool>,
565    },
566    Watch {
567        task_id: String,
568        reply: Sender<Option<JobWatch>>,
569    },
570    /// [`PendingCompletion::take`].
571    TakeCompletion {
572        task_id: IdLease,
573        reply: Sender<()>,
574    },
575}
576
577/// How the registry's caller kills a job: the kill itself runs outside the
578/// registry's state actor, which would otherwise stall every other job's
579/// output, listing and kills meanwhile.
580enum KillPlan {
581    /// The registry decided at once.
582    Done(bool),
583    /// Kill the job's whole process tree.
584    Tree(JobTree),
585    /// Kill the process group led by this pid.
586    Group(u32),
587}
588
589/// How a job's own flow ended it while a kill of it was running.
590#[derive(Debug)]
591enum Ending {
592    Complete {
593        exit_code: i32,
594        output_path: Option<PathBuf>,
595    },
596    Fail {
597        error: String,
598        output_path: Option<PathBuf>,
599    },
600}
601
602/// Message delivered to the registry service.
603enum JobCommand {
604    State(StateCommand),
605    Request(JobRequest),
606}
607
608impl From<StateCommand> for JobCommand {
609    fn from(command: StateCommand) -> Self {
610        Self::State(command)
611    }
612}
613
614impl From<JobRequest> for JobCommand {
615    fn from(request: JobRequest) -> Self {
616        Self::Request(request)
617    }
618}
619
620/// Registry handle for tracking background jobs.
621///
622/// Cloning keeps a sender to the same registry service.
623#[derive(Clone, Debug)]
624pub struct JobRegistry {
625    tx: Sender<JobCommand>,
626    /// The tree scanner — kept for the other unixes and the tests; on Linux
627    /// the supervisor owns each tree.
628    #[cfg_attr(target_os = "linux", allow(dead_code))]
629    scanner: ProcessScanner,
630}
631
632/// Background service that owns the job registry state.
633#[derive(Debug)]
634pub struct JobRegistryService {
635    rx: Receiver<JobCommand>,
636    /// What each [`PendingCompletion`] reports back on; weak, so the service
637    /// still ends with the last handle.
638    tx: WeakSender<JobCommand>,
639    /// How much of a script a job listing shows.
640    policy: OutputPolicy,
641}
642
643/// Creates a registry handle and its background service; job listings are
644/// cut at the `job_preview_bytes` of `policy`.
645#[must_use]
646pub fn job_registry_channel(policy: OutputPolicy) -> (JobRegistry, JobRegistryService) {
647    let (tx, rx) = async_channel::unbounded();
648    let weak = tx.downgrade();
649    (
650        JobRegistry {
651            tx,
652            scanner: ProcessScanner::default(),
653        },
654        JobRegistryService {
655            rx,
656            tx: weak,
657            policy,
658        },
659    )
660}
661
662impl JobRegistry {
663    async fn send_command(&self, command: impl Into<JobCommand>) {
664        self.tx
665            .send(command.into())
666            .await
667            .expect("job registry service unavailable");
668    }
669
670    async fn recv_reply<T>(reply_rx: Receiver<T>) -> T {
671        reply_rx
672            .recv()
673            .await
674            .expect("job registry response dropped")
675    }
676
677    /// Registers a new running job under `task_id`, the word its model
678    /// addresses it by.
679    ///
680    /// The registry holds the lease for as long as it keeps the job: until
681    /// the job finished, its agent took the completion
682    /// ([`Self::owe_completion`]) and nothing watches it, or until the
683    /// registry drops. The job is identified by `task_id` alone: `pid` is
684    /// data of the job, which another job may share once the operating
685    /// system reuses it.
686    pub async fn register(
687        &self,
688        pid: u32,
689        task_id: &IdLease,
690        execution_key: &str,
691        script: &str,
692        mode: SandboxMode,
693        output_path: Option<PathBuf>,
694    ) {
695        self.register_with_tree(
696            pid,
697            task_id,
698            execution_key,
699            script,
700            Interpreter::Shell,
701            mode,
702            output_path,
703            None,
704            JobPlace::Host,
705        )
706        .await;
707    }
708
709    /// Registers a new running job like [`Self::register`], for a job that
710    /// runs at `place` instead of on this machine, with `script` in
711    /// `interpreter`.
712    #[allow(clippy::too_many_arguments)]
713    pub async fn register_at(
714        &self,
715        place: JobPlace,
716        pid: u32,
717        task_id: &IdLease,
718        execution_key: &str,
719        script: &str,
720        interpreter: Interpreter,
721        mode: SandboxMode,
722    ) {
723        self.register_with_tree(
724            pid,
725            task_id,
726            execution_key,
727            script,
728            interpreter,
729            mode,
730            None,
731            None,
732            place,
733        )
734        .await;
735    }
736
737    /// Registers a new running job whose process tree was started with
738    /// the sandbox that spawned it: the tree is part of the job from its
739    /// first moment, so a kill never finds a job without it.
740    #[allow(clippy::too_many_arguments)]
741    pub(crate) async fn register_with_tree(
742        &self,
743        pid: u32,
744        task_id: &IdLease,
745        execution_key: &str,
746        script: &str,
747        interpreter: Interpreter,
748        mode: SandboxMode,
749        output_path: Option<PathBuf>,
750        process_tree: Option<JobTree>,
751        place: JobPlace,
752    ) {
753        self.send_command(StateCommand::Register {
754            place,
755            pid,
756            task_id: task_id.clone(),
757            execution_key: execution_key.to_string(),
758            script: script.to_string(),
759            interpreter,
760            mode,
761            output_path,
762            process_tree,
763        })
764        .await;
765    }
766
767    /// Records that the job of task `task_id` runs under a `timeout` bound,
768    /// reported as [`JobInfo::timeout`]. Called before the job registers: it
769    /// is applied when it does.
770    pub async fn bound_by_timeout(&self, task_id: &IdLease, timeout: Duration) {
771        self.send_command(StateCommand::Bound {
772            task_id: task_id.clone(),
773            timeout,
774        })
775        .await;
776    }
777
778    /// Attaches a stdin input channel to a running job. A job with no channel
779    /// attached reads no input: [`JobInputError::NoStdin`].
780    pub async fn attach_terminal_input(&self, task_id: &IdLease, input_tx: TerminalInputSender) {
781        self.send_command(StateCommand::AttachTerminalInput {
782            task_id: task_id.clone(),
783            input_tx,
784        })
785        .await;
786    }
787
788    /// Attaches a kill switch used by runtimes without host-visible PIDs.
789    pub async fn attach_kill_switch(&self, task_id: &IdLease, kill_tx: Sender<()>) {
790        self.send_command(StateCommand::AttachKillSwitch {
791            task_id: task_id.clone(),
792            kill_tx,
793        })
794        .await;
795    }
796
797    /// The process-table scanner the registry's local jobs share, for the
798    /// sandbox that starts their trees' watch right after the spawn, while the
799    /// children's lineage can still be read.
800    #[cfg_attr(target_os = "linux", allow(dead_code))]
801    pub(crate) fn scanner(&self) -> ProcessScanner {
802        self.scanner.clone()
803    }
804
805    /// Appends stdout bytes for a running job.
806    pub async fn append_stdout(&self, task_id: &IdLease, chunk: Vec<u8>) {
807        self.append_output(task_id.clone(), TerminalStream::Stdout, chunk)
808            .await;
809    }
810
811    /// Appends stderr bytes for a running job.
812    pub async fn append_stderr(&self, task_id: &IdLease, chunk: Vec<u8>) {
813        self.append_output(task_id.clone(), TerminalStream::Stderr, chunk)
814            .await;
815    }
816
817    /// Appends bytes to `stream` of a running job. `task_id` goes with them:
818    /// the registry drops it once they are in, so a sender holding the job's
819    /// lease only weakly keeps nothing leased once its sends are recorded.
820    pub(crate) async fn append_output(
821        &self,
822        task_id: IdLease,
823        stream: TerminalStream,
824        chunk: Vec<u8>,
825    ) {
826        self.send_command(StateCommand::AppendTerminalOutput {
827            task_id,
828            stream,
829            chunk,
830        })
831        .await;
832    }
833
834    /// Appends stdout bytes to task `task_id`, returning once they are in its
835    /// output, and whether they went in. A task whose job is not registered
836    /// yet (its process may already be running a command) gets them as it
837    /// registers, ahead of anything the process wrote later; one the
838    /// registry already forgot, or whose job no longer runs, drops them and
839    /// answers `false`.
840    ///
841    /// `task_id` is the job's own lease, which the bytes hold until they are
842    /// in: its word cannot name a later job while they are on their way.
843    pub async fn append_task_stdout(&self, task_id: &IdLease, chunk: Vec<u8>) -> bool {
844        let (reply_tx, reply_rx) = async_channel::bounded(1);
845        self.send_command(JobRequest::AppendTaskStdout {
846            task_id: task_id.clone(),
847            chunk,
848            reply: reply_tx,
849        })
850        .await;
851        Self::recv_reply(reply_rx).await
852    }
853
854    /// The lease of the job `task_id` names, held weakly, while the job is
855    /// registered or its process is starting.
856    pub(crate) async fn task_lease(&self, task_id: &str) -> Option<WeakIdLease> {
857        let (reply_tx, reply_rx) = async_channel::bounded(1);
858        self.send_command(JobRequest::Lease {
859            task_id: task_id.to_string(),
860            reply: reply_tx,
861        })
862        .await;
863        Self::recv_reply(reply_rx).await
864    }
865
866    /// Records that the process of task `task_id` is about to start, so its
867    /// output takes appends from before its job registers.
868    pub(crate) async fn launching(&self, task_id: &IdLease) {
869        self.send_command(StateCommand::Launching {
870            task_id: task_id.clone(),
871        })
872        .await;
873    }
874
875    /// Records that the launch of task `task_id` ended. A process that never
876    /// started leaves no job: what waited to be appended to it is released
877    /// and the task takes no more.
878    pub(crate) async fn abandon_launch(&self, task_id: &IdLease) {
879        self.send_command(StateCommand::Abandon {
880            task_id: task_id.clone(),
881        })
882        .await;
883    }
884
885    /// Marks stdout stream closed.
886    pub async fn close_stdout(&self, task_id: &IdLease) {
887        self.close_output(task_id.clone(), TerminalStream::Stdout)
888            .await;
889    }
890
891    /// Marks stderr stream closed.
892    pub async fn close_stderr(&self, task_id: &IdLease) {
893        self.close_output(task_id.clone(), TerminalStream::Stderr)
894            .await;
895    }
896
897    /// Marks `stream` of a job closed, `task_id` going with the close as it
898    /// does with [`Self::append_output`].
899    pub(crate) async fn close_output(&self, task_id: IdLease, stream: TerminalStream) {
900        self.send_command(StateCommand::CloseTerminalStream { task_id, stream })
901            .await;
902    }
903
904    /// Sends bytes to a running task terminal stdin.
905    ///
906    /// # Errors
907    /// Returns an error when the task does not exist, no longer runs, has no
908    /// stdin channel attached or its channel closed.
909    pub async fn terminal_input(&self, task_id: &str, bytes: Vec<u8>) -> Result<(), JobInputError> {
910        let (reply_tx, reply_rx) = async_channel::bounded(1);
911        self.send_command(JobRequest::InputTerminal {
912            task_id: task_id.to_string(),
913            bytes,
914            reply: reply_tx,
915        })
916        .await;
917        Self::recv_reply(reply_rx).await
918    }
919
920    /// Starts continuous output redirection for a task and returns current snapshot bytes.
921    ///
922    /// # Errors
923    /// Returns an error when the task does not exist or output cannot be redirected.
924    pub async fn start_output_redirect(
925        &self,
926        task_id: &str,
927        output_path: PathBuf,
928    ) -> Result<Vec<u8>, String> {
929        let (reply_tx, reply_rx) = async_channel::bounded(1);
930        self.send_command(JobRequest::StartOutputRedirect {
931            task_id: task_id.to_string(),
932            output_path,
933            reply: reply_tx,
934        })
935        .await;
936        Self::recv_reply(reply_rx).await
937    }
938
939    /// Returns true when both stdout/stderr streams are closed for task
940    /// `task_id`.
941    pub async fn terminal_streams_closed(&self, task_id: &str) -> bool {
942        let (reply_tx, reply_rx) = async_channel::bounded(1);
943        self.send_command(JobRequest::TerminalStreamsClosed {
944            task_id: task_id.to_string(),
945            reply: reply_tx,
946        })
947        .await;
948        Self::recv_reply(reply_rx).await
949    }
950
951    /// Returns collected stdout/stderr buffers for task `task_id`.
952    pub async fn terminal_output(&self, task_id: &str) -> Option<(Vec<u8>, Vec<u8>)> {
953        let (reply_tx, reply_rx) = async_channel::bounded(1);
954        self.send_command(JobRequest::TerminalOutput {
955            task_id: task_id.to_string(),
956            reply: reply_tx,
957        })
958        .await;
959        Self::recv_reply(reply_rx).await
960    }
961
962    /// Returns terminal output added since the provided cursor.
963    ///
964    /// # Errors
965    /// An error when the task id is unknown.
966    pub async fn terminal_read(
967        &self,
968        task_id: &str,
969        cursor: usize,
970        max_bytes: usize,
971    ) -> Result<JobRead, String> {
972        let (reply_tx, reply_rx) = async_channel::bounded(1);
973        self.send_command(JobRequest::ReadJobDelta {
974            task_id: task_id.to_string(),
975            cursor,
976            max_bytes,
977            tracked: true,
978            reply: reply_tx,
979        })
980        .await;
981        Self::recv_reply(reply_rx).await
982    }
983
984    /// Returns terminal output added since the provided cursor, without
985    /// touching the unchanged-read tracker: the caller is the `monitor`
986    /// pump, whose own cadence is not the model polling.
987    ///
988    /// # Errors
989    /// Returns an error when the task id is unknown.
990    pub async fn monitor_read(
991        &self,
992        task_id: &str,
993        cursor: usize,
994        max_bytes: usize,
995    ) -> Result<JobDelta, String> {
996        let (reply_tx, reply_rx) = async_channel::bounded(1);
997        self.send_command(JobRequest::ReadJobDelta {
998            task_id: task_id.to_string(),
999            cursor,
1000            max_bytes,
1001            tracked: false,
1002            reply: reply_tx,
1003        })
1004        .await;
1005        match Self::recv_reply(reply_rx).await? {
1006            JobRead::Delta(delta) => Ok(delta),
1007            JobRead::Unchanged { task_id } => {
1008                unreachable!("an untracked read of {task_id} is never unchanged")
1009            }
1010        }
1011    }
1012
1013    /// Waits until the job ends and returns how: its status, and the real
1014    /// ending of a job whose kill was in flight. `None` for a task the
1015    /// registry does not hold.
1016    pub async fn wait_ended(&self, task_id: &str) -> Option<JobInfo> {
1017        self.wait(task_id, false).await
1018    }
1019
1020    /// Waits until the job ends, as [`Self::wait_ended`] does, and takes its
1021    /// completion: nothing is owed to the agent for a job its waiter read, so
1022    /// the job's [`OwedCompletion`] carries no [`PendingCompletion`]. A
1023    /// completion already handed out stays with its holder.
1024    pub async fn wait_taking(&self, task_id: &str) -> Option<JobInfo> {
1025        self.wait(task_id, true).await
1026    }
1027
1028    async fn wait(&self, task_id: &str, claim: bool) -> Option<JobInfo> {
1029        let (reply_tx, reply_rx) = async_channel::bounded(1);
1030        self.send_command(JobRequest::WaitEnded {
1031            task_id: task_id.to_string(),
1032            claim,
1033            reply: reply_tx,
1034        })
1035        .await;
1036        Self::recv_reply(reply_rx).await
1037    }
1038
1039    /// Marks a job as completed.
1040    pub async fn complete(&self, task_id: &IdLease, exit_code: i32, output_path: Option<PathBuf>) {
1041        self.send_command(StateCommand::Complete {
1042            task_id: task_id.clone(),
1043            exit_code,
1044            output_path,
1045        })
1046        .await;
1047    }
1048
1049    /// Marks a job as failed.
1050    pub async fn fail(&self, task_id: &IdLease, error: &str, output_path: Option<PathBuf>) {
1051        self.send_command(StateCommand::Fail {
1052            task_id: task_id.clone(),
1053            error: error.to_string(),
1054            output_path,
1055        })
1056        .await;
1057    }
1058
1059    /// Lists all jobs.
1060    pub async fn list(&self) -> Vec<JobInfo> {
1061        let (reply_tx, reply_rx) = async_channel::bounded(1);
1062        self.send_command(JobRequest::List { reply: reply_tx })
1063            .await;
1064        Self::recv_reply(reply_rx).await
1065    }
1066
1067    /// Gets information about a specific job by its task ID.
1068    pub async fn get_by_task_id(&self, task_id: &str) -> Option<JobInfo> {
1069        let (reply_tx, reply_rx) = async_channel::bounded(1);
1070        self.send_command(JobRequest::GetByTaskId {
1071            task_id: task_id.to_string(),
1072            reply: reply_tx,
1073        })
1074        .await;
1075        Self::recv_reply(reply_rx).await
1076    }
1077
1078    /// Gets information about a job by its task ID once no kill of it is in
1079    /// flight. A job whose process has exited from a kill's signal still reads
1080    /// `Running` until the kill records its outcome; this waits for that
1081    /// outcome, so the status it returns is the job's real ending.
1082    pub async fn get_by_task_id_settled(&self, task_id: &str) -> Option<JobInfo> {
1083        let (reply_tx, reply_rx) = async_channel::bounded(1);
1084        self.send_command(JobRequest::GetByTaskIdSettled {
1085            task_id: task_id.to_string(),
1086            reply: reply_tx,
1087        })
1088        .await;
1089        Self::recv_reply(reply_rx).await
1090    }
1091
1092    /// Settles how task `task_id` ended and hands out the completion it owes
1093    /// its agent; its flow calls this once, after the job's process is done,
1094    /// and sends the returned [`PendingCompletion`] with the completed task.
1095    ///
1096    /// Waits for any kill of the job in flight, as
1097    /// [`Self::get_by_task_id_settled`] does. A job the registry still reads
1098    /// as running ends with `ending` — `Ok(exit_code)` or `Err(error)` — so
1099    /// no completion leaves a job running. `None` for a task the registry
1100    /// never registered. A job whose completion a waiter took
1101    /// ([`Self::wait_taking`]) is forgotten here when nothing watches it.
1102    ///
1103    /// # Panics
1104    ///
1105    /// The registry panics when the job's completion was already handed out.
1106    pub async fn owe_completion(
1107        &self,
1108        task_id: &str,
1109        ending: Result<i32, String>,
1110    ) -> Option<OwedCompletion> {
1111        let (reply_tx, reply_rx) = async_channel::bounded(1);
1112        self.send_command(JobRequest::OweCompletion {
1113            task_id: task_id.to_string(),
1114            ending,
1115            reply: reply_tx,
1116        })
1117        .await;
1118        Self::recv_reply(reply_rx).await
1119    }
1120
1121    /// Kills a running job whose `timeout` bound passed; the job reads
1122    /// [`KillCause::Timeout`].
1123    pub async fn kill_timed_out(&self, task_id: &str, kill: TimeoutKill) -> bool {
1124        self.kill_for(task_id, KillCause::Timeout(kill)).await
1125    }
1126
1127    /// Kills a running job whose process tree holds `footprint_bytes` of a
1128    /// `domain` with `capacity_bytes`; the job reads
1129    /// [`KillCause::MemoryRunaway`].
1130    pub async fn kill_runaway(
1131        &self,
1132        task_id: &str,
1133        footprint_bytes: u64,
1134        capacity_bytes: u64,
1135        domain: MemoryDomain,
1136    ) -> bool {
1137        self.kill_for(
1138            task_id,
1139            KillCause::MemoryRunaway {
1140                footprint_bytes,
1141                capacity_bytes,
1142                domain,
1143            },
1144        )
1145        .await
1146    }
1147
1148    async fn kill_for(&self, task_id: &str, cause: KillCause) -> bool {
1149        let (reply_tx, reply_rx) = async_channel::bounded(1);
1150        self.send_command(JobRequest::BeginKillByTaskId {
1151            task_id: task_id.to_string(),
1152            cause,
1153            reply: reply_tx,
1154        })
1155        .await;
1156        let plan = Self::recv_reply(reply_rx).await;
1157        self.finish_kill(task_id, plan).await
1158    }
1159
1160    /// Kills a running job by its task ID.
1161    pub async fn kill_by_task_id(&self, task_id: &str) -> bool {
1162        self.kill_for(task_id, KillCause::User).await
1163    }
1164
1165    /// Kills every job that is still running in this registry.
1166    pub async fn kill_running(&self) -> usize {
1167        let jobs = self.list().await;
1168        futures::future::join_all(
1169            jobs.into_iter()
1170                .filter(|job| job.status == JobStatus::Running)
1171                .map(|job| async move { self.kill_by_task_id(&job.task_id).await }),
1172        )
1173        .await
1174        .into_iter()
1175        .filter(|killed| *killed)
1176        .count()
1177    }
1178
1179    /// Kills all running jobs owned by an execution key.
1180    pub async fn kill_by_execution_key(&self, execution_key: &str) -> usize {
1181        let (reply_tx, reply_rx) = async_channel::bounded(1);
1182        self.send_command(JobRequest::BeginKillByExecutionKey {
1183            execution_key: execution_key.to_string(),
1184            cause: KillCause::User,
1185            reply: reply_tx,
1186        })
1187        .await;
1188        let plans = Self::recv_reply(reply_rx).await;
1189        futures::future::join_all(
1190            plans
1191                .into_iter()
1192                .map(|(task_id, plan)| async move { self.finish_kill(&task_id, plan).await }),
1193        )
1194        .await
1195        .into_iter()
1196        .filter(|killed| *killed)
1197        .count()
1198    }
1199
1200    /// Runs the kill a [`KillPlan`] describes and records its outcome.
1201    async fn finish_kill(&self, task_id: &str, plan: KillPlan) -> bool {
1202        let killed = match plan {
1203            KillPlan::Done(killed) => return killed,
1204            KillPlan::Tree(tree) => match tree.kill().await {
1205                Ok(()) => true,
1206                #[cfg(unix)]
1207                Err(KillTreeError::Ended) => {
1208                    tracing::debug!(task_id, "the job ended before the kill reached it");
1209                    false
1210                }
1211                Err(error) => {
1212                    tracing::warn!(task_id, error = %error, "failed to kill job");
1213                    false
1214                }
1215            },
1216            KillPlan::Group(group) => match crate::process_tree::kill_process_tree(group).await {
1217                Ok(()) => true,
1218                Err(error) => {
1219                    tracing::warn!(task_id, error = %error, "failed to kill job");
1220                    false
1221                }
1222            },
1223        };
1224        let (reply_tx, reply_rx) = async_channel::bounded(1);
1225        self.send_command(JobRequest::EndKill {
1226            task_id: task_id.to_string(),
1227            killed,
1228            reply: reply_tx,
1229        })
1230        .await;
1231        Self::recv_reply(reply_rx).await
1232    }
1233
1234    /// Formats only RUNNING jobs for compression preservation.
1235    pub async fn format_running_jobs(&self) -> String {
1236        let (reply_tx, reply_rx) = async_channel::bounded(1);
1237        self.send_command(JobRequest::FormatRunning { reply: reply_tx })
1238            .await;
1239        Self::recv_reply(reply_rx).await
1240    }
1241
1242    /// Returns true if there are any running jobs.
1243    pub async fn has_running(&self) -> bool {
1244        let (reply_tx, reply_rx) = async_channel::bounded(1);
1245        self.send_command(JobRequest::HasRunning { reply: reply_tx })
1246            .await;
1247        Self::recv_reply(reply_rx).await
1248    }
1249
1250    /// Keeps task `task_id` in the registry, and its word naming it, until
1251    /// the returned watch drops; `None` for a task the registry does not
1252    /// hold.
1253    pub(crate) async fn watch(&self, task_id: &str) -> Option<JobWatch> {
1254        let (reply_tx, reply_rx) = async_channel::bounded(1);
1255        self.send_command(JobRequest::Watch {
1256            task_id: task_id.to_string(),
1257            reply: reply_tx,
1258        })
1259        .await;
1260        Self::recv_reply(reply_rx).await
1261    }
1262}
1263
1264/// Stdout appends for tasks the registry holds no job for: those whose job is
1265/// not registered yet wait for it, those whose job it already forgot are
1266/// dropped.
1267///
1268/// Both refer to their job's lease weakly. The sender of an append holds the
1269/// lease until it is answered, so while one waits its word names that job
1270/// alone; once the lease ends, what waited for it goes with it, and a later
1271/// job leasing the same word never receives it.
1272#[derive(Default)]
1273struct ParkedOutput {
1274    /// Appends waiting for their job to register, by its task id.
1275    by_task: HashMap<String, Parked>,
1276    /// Forgotten jobs whose lease something still holds, such as the job's
1277    /// flow or a progress report on its way.
1278    forgotten: Vec<WeakIdLease>,
1279    /// `timeout` bounds of jobs not registered yet, by task id.
1280    bounds: HashMap<String, (WeakIdLease, Duration)>,
1281    /// Jobs whose process is starting and not registered yet, by task id.
1282    launching: HashMap<String, WeakIdLease>,
1283}
1284
1285/// The appends waiting for one job, in arrival order.
1286struct Parked {
1287    lease: WeakIdLease,
1288    appends: Vec<ParkedAppend>,
1289}
1290
1291/// One parked append: its bytes and the reply that releases its sender.
1292type ParkedAppend = (Vec<u8>, Sender<bool>);
1293
1294impl ParkedOutput {
1295    /// Records that the process of task `task_id` is starting.
1296    fn launching(&mut self, task_id: &IdLease) {
1297        self.prune();
1298        self.launching
1299            .insert(task_id.to_string(), task_id.downgrade());
1300    }
1301
1302    /// The lease of task `task_id` while its process starts.
1303    fn launching_lease(&mut self, task_id: &str) -> Option<WeakIdLease> {
1304        self.prune();
1305        self.launching.get(task_id).cloned()
1306    }
1307
1308    /// Ends the launch of task `task_id` that never registered: what waited
1309    /// for its job is handed back to be released, and later appends are
1310    /// dropped.
1311    fn abandon(&mut self, task_id: &IdLease) -> Vec<ParkedAppend> {
1312        self.launching.remove(task_id.as_str());
1313        let waiting = self.take(task_id);
1314        self.forgot(task_id);
1315        waiting
1316    }
1317
1318    /// Parks an append to task `task_id`, whose job is not registered. Hands
1319    /// back the reply when the registry already forgot that job, for the
1320    /// sender to be released without its bytes going anywhere.
1321    fn park(
1322        &mut self,
1323        task_id: &IdLease,
1324        chunk: Vec<u8>,
1325        reply: Sender<bool>,
1326    ) -> Option<Sender<bool>> {
1327        self.prune();
1328        if self
1329            .forgotten
1330            .iter()
1331            .any(|forgotten| forgotten.refers_to(task_id))
1332        {
1333            return Some(reply);
1334        }
1335        let parked = self
1336            .by_task
1337            .entry(task_id.to_string())
1338            .or_insert_with(|| Parked {
1339                lease: task_id.downgrade(),
1340                appends: Vec::new(),
1341            });
1342        assert!(
1343            parked.lease.refers_to(task_id),
1344            "two live leases share the task id '{task_id}'"
1345        );
1346        parked.appends.push((chunk, reply));
1347        None
1348    }
1349
1350    /// Takes the appends waiting for task `task_id`, which is registering, in
1351    /// arrival order.
1352    fn take(&mut self, task_id: &IdLease) -> Vec<ParkedAppend> {
1353        self.prune();
1354        self.by_task
1355            .remove(task_id.as_str())
1356            .map(|parked| {
1357                assert!(
1358                    parked.lease.refers_to(task_id),
1359                    "two live leases share the task id '{task_id}'"
1360                );
1361                parked.appends
1362            })
1363            .unwrap_or_default()
1364    }
1365
1366    /// Holds the `timeout` bound of task `task_id`, whose job registers next.
1367    fn bound(&mut self, task_id: &IdLease, timeout: Duration) {
1368        self.prune();
1369        self.bounds
1370            .insert(task_id.to_string(), (task_id.downgrade(), timeout));
1371    }
1372
1373    /// Takes the `timeout` bound held for task `task_id`, which is registering.
1374    fn take_bound(&mut self, task_id: &IdLease) -> Option<Duration> {
1375        self.prune();
1376        self.bounds
1377            .remove(task_id.as_str())
1378            .map(|(lease, timeout)| {
1379                assert!(
1380                    lease.refers_to(task_id),
1381                    "two live leases share the task id '{task_id}'"
1382                );
1383                timeout
1384            })
1385    }
1386
1387    /// Records that the registry forgot the job of task `task_id`, so what is
1388    /// still sent to it is dropped instead of waiting for it.
1389    fn forgot(&mut self, task_id: &IdLease) {
1390        self.prune();
1391        self.forgotten.push(task_id.downgrade());
1392    }
1393
1394    /// Drops what refers to a lease that ended: no sender of an append to it
1395    /// is left, and its word may name another job.
1396    fn prune(&mut self) {
1397        self.by_task
1398            .retain(|_, parked| parked.lease.upgrade().is_some());
1399        self.forgotten
1400            .retain(|forgotten| forgotten.upgrade().is_some());
1401        self.bounds
1402            .retain(|_, (lease, _)| lease.upgrade().is_some());
1403        self.launching.retain(|_, lease| lease.upgrade().is_some());
1404    }
1405}
1406
1407/// Per-session read tracking behind the unchanged-read refusal: what each
1408/// task's last `terminal_read` returned with.
1409#[derive(Default)]
1410struct ReadTracker {
1411    /// Task id → the `(cursor, total_bytes, status)` its last read returned.
1412    delta_reads: HashMap<String, (usize, usize, JobStatus)>,
1413}
1414
1415/// The jobs the registry holds, by the task id each leases: the lease keeps
1416/// the word unique among the jobs that live, while a pid is the operating
1417/// system's to hand out again as soon as its process ends.
1418type Jobs = HashMap<String, JobState>;
1419
1420impl JobRegistryService {
1421    /// Runs the registry service loop until all senders are dropped.
1422    pub async fn serve(self) {
1423        let mut jobs = Jobs::new();
1424        let mut reads = ReadTracker::default();
1425        let mut parked = ParkedOutput::default();
1426
1427        while let Ok(command) = self.rx.recv().await {
1428            match command {
1429                JobCommand::State(command) => {
1430                    handle_state_command(&mut jobs, &mut reads, &mut parked, command).await;
1431                }
1432                JobCommand::Request(request) => {
1433                    let preview = self.policy.get().job_preview_bytes;
1434                    handle_job_request(
1435                        &mut jobs,
1436                        &mut reads,
1437                        &mut parked,
1438                        &self.tx,
1439                        preview,
1440                        request,
1441                    )
1442                    .await;
1443                }
1444            }
1445        }
1446    }
1447}
1448
1449async fn handle_state_command(
1450    jobs: &mut Jobs,
1451    reads: &mut ReadTracker,
1452    parked: &mut ParkedOutput,
1453    command: StateCommand,
1454) {
1455    match command {
1456        StateCommand::Register {
1457            pid,
1458            task_id,
1459            execution_key,
1460            script,
1461            interpreter,
1462            mode,
1463            output_path,
1464            process_tree,
1465            place,
1466        } => {
1467            parked.launching.remove(task_id.as_str());
1468            let waiting = parked.take(&task_id);
1469            let timeout = parked.take_bound(&task_id);
1470            let key = task_id.to_string();
1471            register_job(
1472                jobs,
1473                pid,
1474                task_id,
1475                execution_key,
1476                script,
1477                interpreter,
1478                mode,
1479                output_path,
1480                place,
1481                timeout,
1482            );
1483            if let Some(job) = jobs.get_mut(&key) {
1484                job.process_tree = process_tree;
1485            }
1486            for (chunk, reply) in waiting {
1487                append_terminal_output(jobs, &key, TerminalStream::Stdout, chunk).await;
1488                let _ = reply.send(true).await;
1489            }
1490        }
1491        StateCommand::Bound { task_id, timeout } => parked.bound(&task_id, timeout),
1492        StateCommand::Launching { task_id } => parked.launching(&task_id),
1493        StateCommand::Abandon { task_id } => {
1494            if !jobs.contains_key(task_id.as_str()) {
1495                for (_, reply) in parked.abandon(&task_id) {
1496                    let _ = reply.send(false).await;
1497                }
1498            }
1499        }
1500        StateCommand::AttachTerminalInput { task_id, input_tx } => {
1501            // A job that already finished takes no input: the sender drops here.
1502            if let Some(job) = jobs
1503                .get_mut(task_id.as_str())
1504                .filter(|job| matches!(job.info.status, JobStatus::Running))
1505            {
1506                job.input_tx = Some(input_tx);
1507            }
1508        }
1509        StateCommand::AttachKillSwitch { task_id, kill_tx } => {
1510            if let Some(job) = jobs.get_mut(task_id.as_str()) {
1511                job.kill_switch = Some(kill_tx);
1512            }
1513        }
1514        StateCommand::AppendTerminalOutput {
1515            task_id,
1516            stream,
1517            chunk,
1518        } => {
1519            append_terminal_output(jobs, &task_id, stream, chunk).await;
1520        }
1521        StateCommand::CloseTerminalStream { task_id, stream } => {
1522            close_terminal_stream(jobs, &task_id, stream);
1523        }
1524        StateCommand::Complete {
1525            task_id,
1526            exit_code,
1527            output_path,
1528        } => complete_job(jobs, &task_id, exit_code, output_path).await,
1529        StateCommand::Fail {
1530            task_id,
1531            error,
1532            output_path,
1533        } => fail_job(jobs, &task_id, error, output_path).await,
1534        StateCommand::TakeCompletion { task_id } => {
1535            take_completion(jobs, reads, parked, &task_id);
1536        }
1537        StateCommand::Unwatch { task_id } => {
1538            if let Some(job) = jobs.get_mut(task_id.as_str()) {
1539                job.watchers -= 1;
1540                forget_if_done(jobs, reads, parked, &task_id);
1541            }
1542        }
1543    }
1544}
1545
1546/// Forgets job `task_id` once nothing can address it any more: it finished,
1547/// its own flow settled its completion, its agent took it and nothing
1548/// watches it. Its task id then goes back to the allocator once nothing else
1549/// holds it, a later read of it answers as for any unknown task, and
1550/// progress still reported to it is dropped.
1551fn forget_if_done(
1552    jobs: &mut Jobs,
1553    reads: &mut ReadTracker,
1554    parked: &mut ParkedOutput,
1555    task_id: &str,
1556) {
1557    let job = &jobs[task_id];
1558    // A waiter's claim reads the job taken before its flow settles it; the
1559    // flow still reads the job's output after that.
1560    if job.completion_owed
1561        && job.info.status.delivery() == Some(Delivery::Taken)
1562        && job.watchers == 0
1563    {
1564        let job = jobs.remove(task_id).expect("the job is registered");
1565        reads.delta_reads.remove(task_id);
1566        parked.forgot(&job.task_id);
1567        tracing::debug!(task_id, pid = %job.info.pid, "forgot finished job");
1568    }
1569}
1570
1571#[allow(clippy::too_many_lines)]
1572async fn handle_job_request(
1573    jobs: &mut Jobs,
1574    reads: &mut ReadTracker,
1575    parked: &mut ParkedOutput,
1576    tx: &WeakSender<JobCommand>,
1577    script_preview_bytes: usize,
1578    request: JobRequest,
1579) {
1580    match request {
1581        JobRequest::AppendTaskStdout {
1582            task_id,
1583            chunk,
1584            reply,
1585        } => {
1586            if let Some(job) = jobs.get(task_id.as_str()) {
1587                assert!(
1588                    job.task_id.same_lease(&task_id),
1589                    "two live leases share the task id '{task_id}'"
1590                );
1591                let running = matches!(job.info.status, JobStatus::Running);
1592                if running {
1593                    append_terminal_output(jobs, &task_id, TerminalStream::Stdout, chunk).await;
1594                }
1595                let _ = reply.send(running).await;
1596            } else if let Some(reply) = parked.park(&task_id, chunk, reply) {
1597                let _ = reply.send(false).await;
1598            }
1599        }
1600        JobRequest::Lease { task_id, reply } => {
1601            let lease = jobs
1602                .get(&task_id)
1603                .map(|job| job.task_id.downgrade())
1604                .or_else(|| parked.launching_lease(&task_id));
1605            let _ = reply.send(lease).await;
1606        }
1607        JobRequest::List { reply } => {
1608            let items = jobs.values().map(|state| state.info.clone()).collect();
1609            let _ = reply.send(items).await;
1610        }
1611        JobRequest::GetByTaskId { task_id, reply } => {
1612            let item = jobs.get(&task_id).map(|state| state.info.clone());
1613            let _ = reply.send(item).await;
1614        }
1615        JobRequest::GetByTaskIdSettled { task_id, reply } => {
1616            get_settled_by_task_id(jobs, &task_id, reply).await;
1617        }
1618        JobRequest::OweCompletion {
1619            task_id,
1620            ending,
1621            reply,
1622        } => owe_settled_completion(jobs, reads, parked, &task_id, ending, reply, tx).await,
1623        JobRequest::BeginKillByTaskId {
1624            task_id,
1625            cause,
1626            reply,
1627        } => {
1628            let plan = begin_kill(jobs, &task_id, cause).await;
1629            let _ = reply.send(plan).await;
1630        }
1631        JobRequest::BeginKillByExecutionKey {
1632            execution_key,
1633            cause,
1634            reply,
1635        } => {
1636            let plans = begin_kill_by_execution_key(jobs, &execution_key, cause).await;
1637            let _ = reply.send(plans).await;
1638        }
1639        JobRequest::EndKill {
1640            task_id,
1641            killed,
1642            reply,
1643        } => {
1644            let result = end_kill(jobs, &task_id, killed).await;
1645            release_settled_waiters(jobs, reads, parked, &task_id, tx).await;
1646            let _ = reply.send(result).await;
1647        }
1648        JobRequest::InputTerminal {
1649            task_id,
1650            bytes,
1651            reply,
1652        } => {
1653            let result = input_terminal(jobs, &task_id, bytes).await;
1654            let _ = reply.send(result).await;
1655        }
1656        JobRequest::StartOutputRedirect {
1657            task_id,
1658            output_path,
1659            reply,
1660        } => {
1661            let result = redirect_task_output(jobs, &task_id, output_path).await;
1662            let _ = reply.send(result).await;
1663        }
1664        JobRequest::TerminalOutput { task_id, reply } => {
1665            send_terminal_output(jobs, &task_id, reply).await;
1666        }
1667        JobRequest::ReadJobDelta {
1668            task_id,
1669            cursor,
1670            max_bytes,
1671            tracked,
1672            reply,
1673        } => {
1674            let result = read_terminal_delta(jobs, &task_id, cursor, max_bytes, !tracked)
1675                .map(|delta| tracked_delta(reads, &task_id, delta, tracked));
1676            let _ = reply.send(result).await;
1677        }
1678        JobRequest::WaitEnded {
1679            task_id,
1680            claim,
1681            reply,
1682        } => {
1683            wait_for_end(jobs, &task_id, claim, reply).await;
1684        }
1685        JobRequest::TerminalStreamsClosed { task_id, reply } => {
1686            let closed = jobs
1687                .get(&task_id)
1688                .is_some_and(|job| job.stdout_closed && job.stderr_closed);
1689            let _ = reply.send(closed).await;
1690        }
1691        JobRequest::FormatRunning { reply } => {
1692            let _ = reply
1693                .send(format_running_jobs(jobs, script_preview_bytes))
1694                .await;
1695        }
1696        JobRequest::HasRunning { reply } => {
1697            let _ = reply.send(has_running_job(jobs)).await;
1698        }
1699        JobRequest::TakeCompletion { task_id, reply } => {
1700            take_completion(jobs, reads, parked, &task_id);
1701            let _ = reply.send(()).await;
1702        }
1703        JobRequest::Watch { task_id, reply } => {
1704            let watch = jobs.get_mut(&task_id).map(|job| {
1705                job.watchers += 1;
1706                JobWatch {
1707                    tx: tx
1708                        .upgrade()
1709                        .expect("a request arrives through a live registry handle"),
1710                    task_id: job.task_id.clone(),
1711                }
1712            });
1713            let _ = reply.send(watch).await;
1714        }
1715    }
1716}
1717
1718async fn send_terminal_output(
1719    jobs: &Jobs,
1720    task_id: &str,
1721    reply: Sender<Option<(Vec<u8>, Vec<u8>)>>,
1722) {
1723    let output = jobs
1724        .get(task_id)
1725        .map(|job| (job.stdout_buffer.clone(), job.stderr_buffer.clone()));
1726    let _ = reply.send(output).await;
1727}
1728
1729fn has_running_job(jobs: &Jobs) -> bool {
1730    jobs.values()
1731        .any(|job| matches!(job.info.status, JobStatus::Running))
1732}
1733
1734#[allow(clippy::too_many_arguments)]
1735fn register_job(
1736    jobs: &mut Jobs,
1737    pid: u32,
1738    task_id: IdLease,
1739    execution_key: String,
1740    script: String,
1741    interpreter: Interpreter,
1742    mode: SandboxMode,
1743    output_path: Option<PathBuf>,
1744    place: JobPlace,
1745    timeout: Option<Duration>,
1746) {
1747    let info = JobInfo {
1748        timeout,
1749        place,
1750        pid,
1751        task_id: task_id.to_string(),
1752        execution_key,
1753        script,
1754        interpreter,
1755        mode,
1756        started_at: Instant::now(),
1757        status: JobStatus::Running,
1758        output_path,
1759    };
1760    let key = task_id.to_string();
1761    let replaced = jobs.insert(key.clone(), JobState::new(info, task_id));
1762    assert!(
1763        replaced.is_none(),
1764        "two live leases share the task id '{key}'"
1765    );
1766    tracing::debug!(task_id = %key, pid = %pid, "registered background job");
1767}
1768
1769impl JobState {
1770    const fn new(info: JobInfo, task_id: IdLease) -> Self {
1771        Self {
1772            info,
1773            task_id,
1774            terminal_buffer: Vec::new(),
1775            line_buffer: Vec::new(),
1776            stdout_partial: Vec::new(),
1777            stderr_partial: Vec::new(),
1778            stdout_buffer: Vec::new(),
1779            stderr_buffer: Vec::new(),
1780            stdout_closed: false,
1781            stderr_closed: false,
1782            input_tx: None,
1783            kill_switch: None,
1784            process_tree: None,
1785            kill_cause: None,
1786            kills_in_flight: 0,
1787            deferred_end: None,
1788            settled_waiters: Vec::new(),
1789            ended_waiters: Vec::new(),
1790            output_redirect: None,
1791            finished_at: None,
1792            completion_owed: false,
1793            claimed: false,
1794            watchers: 0,
1795        }
1796    }
1797}
1798
1799/// How a job ended, before the registry records it.
1800enum JobEnd {
1801    Completed { exit_code: i32 },
1802    Failed { error: String },
1803    Killed(KillCause),
1804}
1805
1806/// Records how `job` ended: the one transition out of
1807/// [`JobStatus::Running`]. The same step marks its completion
1808/// [`Delivery::Pending`], so no reader ever sees the job finished with
1809/// nothing owed to its agent, or [`Delivery::Taken`] when a waiter claimed
1810/// it, so none sees a turn owed for a job its waiter read.
1811fn finish(job: &mut JobState, end: JobEnd) {
1812    assert!(
1813        matches!(job.info.status, JobStatus::Running),
1814        "job {} ended twice: it already reads {:?}",
1815        job.info.task_id,
1816        job.info.status
1817    );
1818    let delivery = if job.claimed {
1819        Delivery::Taken
1820    } else {
1821        Delivery::Pending
1822    };
1823    job.info.status = match end {
1824        JobEnd::Completed { exit_code } => JobStatus::Completed {
1825            exit_code,
1826            delivery,
1827        },
1828        JobEnd::Failed { error } => JobStatus::Failed { error, delivery },
1829        JobEnd::Killed(cause) => JobStatus::Killed { cause, delivery },
1830    };
1831    job.finished_at = Some(Instant::now());
1832    for waiter in std::mem::take(&mut job.ended_waiters) {
1833        // A waiter that stopped waiting dropped its receiver.
1834        let _ = waiter.try_send(Some(job.info.clone()));
1835    }
1836    job.kill_switch = None;
1837    // Dropping the last sender ends the stdin writer thread blocked on it.
1838    job.input_tx = None;
1839}
1840
1841/// Marks the completion of task `task_id` taken, the agent having dropped
1842/// its [`PendingCompletion`], and forgets the job when nothing watches it.
1843fn take_completion(
1844    jobs: &mut Jobs,
1845    reads: &mut ReadTracker,
1846    parked: &mut ParkedOutput,
1847    task_id: &str,
1848) {
1849    if let Some(job) = jobs.get_mut(task_id) {
1850        mark_taken(job);
1851        forget_if_done(jobs, reads, parked, task_id);
1852    }
1853}
1854
1855fn mark_taken(job: &mut JobState) {
1856    let task_id = &job.info.task_id;
1857    let delivery = match &mut job.info.status {
1858        JobStatus::Running => panic!("job {task_id}'s completion was taken while it runs"),
1859        JobStatus::Completed { delivery, .. }
1860        | JobStatus::Failed { delivery, .. }
1861        | JobStatus::Killed { delivery, .. } => delivery,
1862    };
1863    assert_eq!(
1864        *delivery,
1865        Delivery::Pending,
1866        "job {task_id}'s completion was taken twice"
1867    );
1868    *delivery = Delivery::Taken;
1869}
1870
1871/// Hands out the completion of task `task_id`, or parks the request while a
1872/// kill of it is in flight. A job a waiter claimed is then forgotten when
1873/// nothing watches it.
1874async fn owe_settled_completion(
1875    jobs: &mut Jobs,
1876    reads: &mut ReadTracker,
1877    parked: &mut ParkedOutput,
1878    task_id: &str,
1879    ending: Result<i32, String>,
1880    reply: Sender<Option<OwedCompletion>>,
1881    tx: &WeakSender<JobCommand>,
1882) {
1883    let Some(job) = jobs.get_mut(task_id) else {
1884        let _ = reply.send(None).await;
1885        return;
1886    };
1887    if job.kills_in_flight > 0 {
1888        job.settled_waiters
1889            .push(SettledWaiter::Owe { ending, reply });
1890        return;
1891    }
1892    let owed = owe_completion(jobs, task_id, ending, tx).await;
1893    forget_if_done(jobs, reads, parked, task_id);
1894    let _ = reply.send(Some(owed)).await;
1895}
1896
1897/// Hands out the completion of job `task_id`, no kill of which is in flight;
1898/// a job still running ends with `ending` first.
1899async fn owe_completion(
1900    jobs: &mut Jobs,
1901    task_id: &str,
1902    ending: Result<i32, String>,
1903    tx: &WeakSender<JobCommand>,
1904) -> OwedCompletion {
1905    if matches!(jobs[task_id].info.status, JobStatus::Running) {
1906        match ending {
1907            Ok(exit_code) => complete_job(jobs, task_id, exit_code, None).await,
1908            Err(error) => fail_job(jobs, task_id, error, None).await,
1909        }
1910    }
1911    let job = jobs.get_mut(task_id).expect("the job is registered");
1912    assert!(
1913        !job.completion_owed,
1914        "job {task_id}'s completion was handed out twice"
1915    );
1916    // A waiter that claimed the job took its completion when it ended.
1917    let delivery = if job.claimed {
1918        Delivery::Taken
1919    } else {
1920        Delivery::Pending
1921    };
1922    assert_eq!(
1923        job.info.status.delivery(),
1924        Some(delivery),
1925        "job {task_id} owes a completion it never recorded: {:?}",
1926        job.info.status
1927    );
1928    job.completion_owed = true;
1929    let info = job.info.clone();
1930    if job.claimed {
1931        // A waiter read the job: nothing is owed to the agent.
1932        return OwedCompletion {
1933            info,
1934            pending: None,
1935        };
1936    }
1937    OwedCompletion {
1938        info,
1939        pending: Some(PendingCompletion {
1940            tx: tx
1941                .upgrade()
1942                .expect("a request arrives through a live registry handle"),
1943            task_id: Some(job.task_id.clone()),
1944        }),
1945    }
1946}
1947
1948async fn append_terminal_output(
1949    jobs: &mut Jobs,
1950    task_id: &str,
1951    stream: TerminalStream,
1952    chunk: Vec<u8>,
1953) {
1954    if chunk.is_empty() {
1955        return;
1956    }
1957    if let Some(job) = jobs.get_mut(task_id) {
1958        job.terminal_buffer.extend_from_slice(&chunk);
1959        if let Some(file) = job.output_redirect.as_mut()
1960            && let Err(error) = file.write_all(&chunk).await
1961        {
1962            // A redirect the model started after the job ended fails the
1963            // write alone; the job keeps the ending it already recorded.
1964            if matches!(job.info.status, JobStatus::Running) {
1965                mark_job_failed(
1966                    job,
1967                    format!(
1968                        "failed to append redirected output for task {}: {error}",
1969                        job.info.task_id
1970                    ),
1971                );
1972            }
1973            tracing::error!(
1974                task_id,
1975                error = %error,
1976                "failed to append redirected output"
1977            );
1978        }
1979        let (buffer, partial) = match stream {
1980            TerminalStream::Stdout => (&mut job.stdout_buffer, &mut job.stdout_partial),
1981            TerminalStream::Stderr => (&mut job.stderr_buffer, &mut job.stderr_partial),
1982        };
1983        buffer.extend_from_slice(&chunk);
1984        partial.extend_from_slice(&chunk);
1985        // Each stream completes its own lines; a line reaches the line
1986        // buffer whole, so one stream never interrupts the other's.
1987        if let Some(last_newline) = partial.iter().rposition(|byte| *byte == b'\n') {
1988            job.line_buffer.extend(partial.drain(..=last_newline));
1989        }
1990    }
1991}
1992
1993fn close_terminal_stream(jobs: &mut Jobs, task_id: &str, stream: TerminalStream) {
1994    if let Some(job) = jobs.get_mut(task_id) {
1995        match stream {
1996            TerminalStream::Stdout => job.stdout_closed = true,
1997            TerminalStream::Stderr => job.stderr_closed = true,
1998        }
1999    }
2000}
2001
2002async fn complete_job(
2003    jobs: &mut Jobs,
2004    task_id: &str,
2005    exit_code: i32,
2006    output_path: Option<PathBuf>,
2007) {
2008    if let Some(job) = jobs.get_mut(task_id) {
2009        if !matches!(job.info.status, JobStatus::Running) {
2010            tracing::debug!(
2011                task_id,
2012                status = ?job.info.status,
2013                "ignoring complete for non-running job"
2014            );
2015            return;
2016        }
2017        if job.kills_in_flight > 0 {
2018            job.deferred_end = Some(Ending::Complete {
2019                exit_code,
2020                output_path,
2021            });
2022            return;
2023        }
2024        if let Err(error) = finalize_output_redirect(job).await {
2025            tracing::error!(
2026                task_id,
2027                error = %error,
2028                "failed to flush redirected output on complete"
2029            );
2030            mark_job_failed(job, error);
2031            return;
2032        }
2033        finish(job, JobEnd::Completed { exit_code });
2034        if output_path.is_some() {
2035            job.info.output_path = output_path;
2036        }
2037        tracing::debug!(task_id, exit_code = %exit_code, "job completed");
2038    }
2039}
2040
2041async fn fail_job(jobs: &mut Jobs, task_id: &str, error: String, output_path: Option<PathBuf>) {
2042    if let Some(job) = jobs.get_mut(task_id) {
2043        if !matches!(job.info.status, JobStatus::Running) {
2044            tracing::debug!(
2045                task_id,
2046                status = ?job.info.status,
2047                "ignoring fail for non-running job"
2048            );
2049            return;
2050        }
2051        if job.kills_in_flight > 0 {
2052            job.deferred_end = Some(Ending::Fail { error, output_path });
2053            return;
2054        }
2055        let status_error = if let Err(finalize_error) = finalize_output_redirect(job).await {
2056            format!("{error}; additionally failed to flush redirected output: {finalize_error}")
2057        } else {
2058            error
2059        };
2060        mark_job_failed(job, status_error);
2061        if output_path.is_some() {
2062            job.info.output_path = output_path;
2063        }
2064        tracing::debug!(task_id, "job failed");
2065    }
2066}
2067
2068async fn begin_kill_by_execution_key(
2069    jobs: &mut Jobs,
2070    execution_key: &str,
2071    cause: KillCause,
2072) -> Vec<(String, KillPlan)> {
2073    let task_ids: Vec<String> = jobs
2074        .iter()
2075        .filter(|(_, state)| {
2076            state.info.execution_key == execution_key
2077                && matches!(state.info.status, JobStatus::Running)
2078        })
2079        .map(|(task_id, _)| task_id.clone())
2080        .collect();
2081
2082    let mut plans = Vec::with_capacity(task_ids.len());
2083    for task_id in task_ids {
2084        let plan = begin_kill(jobs, &task_id, cause).await;
2085        plans.push((task_id, plan));
2086    }
2087    plans
2088}
2089
2090async fn input_terminal(jobs: &Jobs, task_id: &str, bytes: Vec<u8>) -> Result<(), JobInputError> {
2091    let Some(job) = jobs.get(task_id) else {
2092        return Err(JobInputError::UnknownTask {
2093            task_id: task_id.to_owned(),
2094        });
2095    };
2096    if !matches!(job.info.status, JobStatus::Running) {
2097        return Err(JobInputError::NotRunning {
2098            task_id: task_id.to_owned(),
2099            status: job.info.status.clone(),
2100        });
2101    }
2102    // A job with a stdin pipe has its channel attached before its start is
2103    // reported, so a running job without one was started without a pipe.
2104    let Some(tx) = &job.input_tx else {
2105        return Err(JobInputError::NoStdin {
2106            task_id: task_id.to_owned(),
2107        });
2108    };
2109    tx.send(bytes).await.map_err(|_| JobInputError::Closed {
2110        task_id: task_id.to_owned(),
2111    })
2112}
2113
2114async fn redirect_task_output(
2115    jobs: &mut Jobs,
2116    task_id: &str,
2117    output_path: PathBuf,
2118) -> Result<Vec<u8>, String> {
2119    let Some(job) = jobs.get_mut(task_id) else {
2120        return Err(format!("unknown task_id: {task_id}"));
2121    };
2122    start_output_redirect(job, output_path).await
2123}
2124
2125/// A read returning what the last read of this task returned is a poll:
2126/// nothing new arrived. Refuse it so the agent waits for the completion
2127/// event instead. Untracked reads — the `monitor` pump's own cadence —
2128/// neither refuse nor update the tracker.
2129fn tracked_delta(
2130    reads: &mut ReadTracker,
2131    task_id: &str,
2132    delta: JobDelta,
2133    tracked: bool,
2134) -> JobRead {
2135    let returned = (delta.cursor, delta.total_bytes, delta.status.clone());
2136    if !tracked {
2137        return JobRead::Delta(delta);
2138    }
2139    if reads.delta_reads.get(task_id) == Some(&returned) {
2140        JobRead::Unchanged {
2141            task_id: task_id.to_string(),
2142        }
2143    } else {
2144        reads.delta_reads.insert(task_id.to_string(), returned);
2145        JobRead::Delta(delta)
2146    }
2147}
2148
2149/// Answers a wait for a job's end at once when it ended, or parks it until
2150/// [`finish`] records the ending.
2151async fn wait_for_end(jobs: &mut Jobs, task_id: &str, claim: bool, reply: Sender<Option<JobInfo>>) {
2152    match jobs.get_mut(task_id) {
2153        Some(job) if matches!(job.info.status, JobStatus::Running) => {
2154            job.claimed |= claim && !job.completion_owed;
2155            job.ended_waiters.push(reply);
2156        }
2157        Some(job) => {
2158            // Its flow has yet to settle the completion: the claim takes it
2159            // now, so no reader sees a turn owed for it meanwhile.
2160            if claim && !job.completion_owed && !job.claimed {
2161                job.claimed = true;
2162                mark_taken(job);
2163            }
2164            let _ = reply.send(Some(job.info.clone())).await;
2165        }
2166        None => {
2167            let _ = reply.send(None).await;
2168        }
2169    }
2170}
2171
2172fn read_terminal_delta(
2173    jobs: &Jobs,
2174    task_id: &str,
2175    cursor: usize,
2176    max_bytes: usize,
2177    lines: bool,
2178) -> Result<JobDelta, String> {
2179    jobs.get(task_id).map_or_else(
2180        || Err(format!("unknown task_id: {task_id}")),
2181        |job| terminal_read(job, cursor, max_bytes, lines),
2182    )
2183}
2184
2185async fn start_output_redirect(
2186    job: &mut JobState,
2187    output_path: PathBuf,
2188) -> Result<Vec<u8>, String> {
2189    if let Some(existing) = job.info.output_path.as_ref() {
2190        if existing != &output_path {
2191            return Err(format!(
2192                "task {} already redirects output to {}",
2193                job.info.task_id,
2194                existing.display()
2195            ));
2196        }
2197        return Ok(job.terminal_buffer.clone());
2198    }
2199
2200    let mut file = async_fs::OpenOptions::new()
2201        .create(true)
2202        .truncate(true)
2203        .write(true)
2204        .open(&output_path)
2205        .await
2206        .map_err(|error| {
2207            format!(
2208                "failed to open output redirect file {}: {error}",
2209                output_path.display()
2210            )
2211        })?;
2212
2213    file.write_all(&job.terminal_buffer)
2214        .await
2215        .map_err(|error| {
2216            format!(
2217                "failed to write initial output redirect snapshot for task {}: {error}",
2218                job.info.task_id
2219            )
2220        })?;
2221    file.flush().await.map_err(|error| {
2222        format!(
2223            "failed to flush initial output redirect snapshot for task {}: {error}",
2224            job.info.task_id
2225        )
2226    })?;
2227
2228    job.info.output_path = Some(output_path);
2229    job.output_redirect = Some(file);
2230    Ok(job.terminal_buffer.clone())
2231}
2232
2233fn mark_job_failed(job: &mut JobState, error: String) {
2234    finish(job, JobEnd::Failed { error });
2235}
2236
2237async fn finalize_output_redirect(job: &mut JobState) -> Result<(), String> {
2238    if let Some(mut file) = job.output_redirect.take()
2239        && let Err(error) = file.flush().await
2240    {
2241        return Err(format!(
2242            "failed to flush redirected output for task {}: {error}",
2243            job.info.task_id
2244        ));
2245    }
2246    Ok(())
2247}
2248
2249/// Starts killing a job: decides at once what needs no process signal, and
2250/// otherwise hands back what the caller must kill outside the registry.
2251async fn begin_kill(jobs: &mut Jobs, task_id: &str, cause: KillCause) -> KillPlan {
2252    let Some(job) = jobs.get_mut(task_id) else {
2253        return KillPlan::Done(false);
2254    };
2255    if !matches!(job.info.status, JobStatus::Running) {
2256        tracing::warn!(task_id, "cannot kill non-running job");
2257        return KillPlan::Done(false);
2258    }
2259
2260    if let Some(kill_switch) = job.kill_switch.take() {
2261        if kill_switch.send(()).await.is_err() {
2262            tracing::warn!(task_id, "failed to signal runtime kill switch");
2263            return KillPlan::Done(false);
2264        }
2265        if let Err(error) = finalize_output_redirect(job).await {
2266            tracing::warn!(
2267                task_id,
2268                error = %error,
2269                "failed to flush redirected output after kill switch signal"
2270            );
2271        }
2272        finish(job, JobEnd::Killed(cause));
2273        job.stdout_closed = true;
2274        job.stderr_closed = true;
2275        tracing::info!(task_id, "killed job via runtime kill switch");
2276        return KillPlan::Done(true);
2277    }
2278
2279    if job.kills_in_flight == 0 {
2280        job.kill_cause = Some(cause);
2281    }
2282    job.kills_in_flight += 1;
2283    let group = job.info.pid;
2284    job.process_tree
2285        .as_ref()
2286        .map_or(KillPlan::Group(group), |tree| KillPlan::Tree(tree.clone()))
2287}
2288
2289/// Records the outcome of a kill that ran outside the registry. A job whose
2290/// own flow ended it meanwhile takes that ending only when the kill failed.
2291async fn end_kill(jobs: &mut Jobs, task_id: &str, killed: bool) -> bool {
2292    let Some(job) = jobs.get_mut(task_id) else {
2293        return false;
2294    };
2295    job.kills_in_flight = job.kills_in_flight.saturating_sub(1);
2296    if killed {
2297        job.deferred_end = None;
2298        if matches!(job.info.status, JobStatus::Running) {
2299            if let Err(error) = finalize_output_redirect(job).await {
2300                tracing::warn!(
2301                    task_id,
2302                    error = %error,
2303                    "failed to flush redirected output after kill"
2304                );
2305            }
2306            let cause = job
2307                .kill_cause
2308                .expect("a kill in flight was asked for with a cause");
2309            finish(job, JobEnd::Killed(cause));
2310            job.stdout_closed = true;
2311            job.stderr_closed = true;
2312            tracing::info!(task_id, ?cause, "killed job");
2313        }
2314        return true;
2315    }
2316    // While another kill of the job still runs, `complete_job` and `fail_job`
2317    // defer the ending again.
2318    match job.deferred_end.take() {
2319        Some(Ending::Complete {
2320            exit_code,
2321            output_path,
2322        }) => complete_job(jobs, task_id, exit_code, output_path).await,
2323        Some(Ending::Fail { error, output_path }) => {
2324            fail_job(jobs, task_id, error, output_path).await;
2325        }
2326        None => {}
2327    }
2328    false
2329}
2330
2331/// Answers a settled read at once, or parks it while a kill of the job runs.
2332async fn get_settled_by_task_id(jobs: &mut Jobs, task_id: &str, reply: Sender<Option<JobInfo>>) {
2333    match jobs.get_mut(task_id) {
2334        Some(job) if job.kills_in_flight > 0 => {
2335            job.settled_waiters.push(SettledWaiter::Read(reply));
2336        }
2337        Some(job) => {
2338            let _ = reply.send(Some(job.info.clone())).await;
2339        }
2340        None => {
2341            let _ = reply.send(None).await;
2342        }
2343    }
2344}
2345
2346/// Answers the callers parked on a job once its last kill in flight ended,
2347/// then forgets a job a waiter claimed whose completion they settled when
2348/// nothing watches it.
2349async fn release_settled_waiters(
2350    jobs: &mut Jobs,
2351    reads: &mut ReadTracker,
2352    parked: &mut ParkedOutput,
2353    task_id: &str,
2354    tx: &WeakSender<JobCommand>,
2355) {
2356    let Some(job) = jobs.get_mut(task_id) else {
2357        return;
2358    };
2359    if job.kills_in_flight > 0 {
2360        return;
2361    }
2362    for waiter in std::mem::take(&mut job.settled_waiters) {
2363        match waiter {
2364            SettledWaiter::Read(reply) => {
2365                let _ = reply.send(Some(jobs[task_id].info.clone())).await;
2366            }
2367            SettledWaiter::Owe { ending, reply } => {
2368                let owed = owe_completion(jobs, task_id, ending, tx).await;
2369                let _ = reply.send(Some(owed)).await;
2370            }
2371        }
2372    }
2373    forget_if_done(jobs, reads, parked, task_id);
2374}
2375
2376/// The start of `script`, cut at a character boundary at or below `limit`
2377/// bytes.
2378fn script_preview(script: &str, limit: usize) -> String {
2379    if script.len() <= limit {
2380        return script.to_string();
2381    }
2382    let end = (0..=limit)
2383        .rev()
2384        .find(|index| script.is_char_boundary(*index))
2385        .unwrap_or(0);
2386    format!("{}...", &script[..end])
2387}
2388
2389fn format_running_jobs(jobs: &Jobs, script_preview_bytes: usize) -> String {
2390    let running: Vec<_> = jobs
2391        .values()
2392        .filter(|job| matches!(job.info.status, JobStatus::Running))
2393        .collect();
2394
2395    if running.is_empty() {
2396        return String::new();
2397    }
2398
2399    let mut output = String::new();
2400    for job in running {
2401        let script_preview = script_preview(&job.info.script, script_preview_bytes);
2402
2403        let output_path = job
2404            .info
2405            .output_path
2406            .as_ref()
2407            .map_or_else(|| "(no output)".to_string(), |p| p.display().to_string());
2408
2409        let _ = writeln!(
2410            output,
2411            "  - task {} (pid {}): `{}` -> {}",
2412            job.info.task_id, job.info.pid, script_preview, output_path
2413        );
2414    }
2415
2416    output
2417}
2418
2419fn terminal_read(
2420    job: &JobState,
2421    cursor: usize,
2422    max_bytes: usize,
2423    lines: bool,
2424) -> Result<JobDelta, String> {
2425    let buffer = if lines {
2426        &job.line_buffer
2427    } else {
2428        &job.terminal_buffer
2429    };
2430    let total_bytes = buffer.len();
2431    if cursor > total_bytes {
2432        return Err(format!(
2433            "cursor {cursor} exceeds terminal buffer size {total_bytes} for task {}",
2434            job.info.task_id
2435        ));
2436    }
2437    let end = total_bytes.min(cursor.saturating_add(max_bytes));
2438    Ok(JobDelta {
2439        task_id: job.info.task_id.clone(),
2440        cursor: end,
2441        total_bytes,
2442        bytes: buffer[cursor..end].to_vec(),
2443        status: job.info.status.clone(),
2444    })
2445}
2446
2447#[cfg(test)]
2448mod tests {
2449    use super::*;
2450    use crate::test_ids::lease;
2451    use executor_core::Executor;
2452    use executor_core::Task;
2453    use executor_core::tokio::TokioGlobal;
2454    use tempfile::tempdir;
2455
2456    fn spawn_registry() -> JobRegistry {
2457        let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
2458        TokioGlobal
2459            .spawn(async move { service.serve().await })
2460            .detach();
2461        registry
2462    }
2463
2464    /// A bound recorded before the job registers is reported once it does; a
2465    /// job nothing bounded reports none.
2466    #[tokio::test]
2467    async fn a_job_reports_the_timeout_it_runs_under() {
2468        let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
2469        tokio::spawn(service.serve());
2470        let bounded = crate::test_ids::lease("bounded");
2471        let free = crate::test_ids::lease("free");
2472
2473        registry
2474            .bound_by_timeout(&bounded, Duration::from_secs(600))
2475            .await;
2476        registry
2477            .register(1, &bounded, "exec", "run", SandboxMode::Sandboxed, None)
2478            .await;
2479        registry
2480            .register(2, &free, "exec", "run", SandboxMode::Sandboxed, None)
2481            .await;
2482
2483        let info = registry
2484            .get_by_task_id("bounded")
2485            .await
2486            .expect("job exists");
2487        assert_eq!(info.timeout, Some(Duration::from_secs(600)));
2488        let remaining = info.remaining().expect("the job is bounded");
2489        assert!(remaining > Duration::from_secs(590), "{remaining:?}");
2490        let info = registry.get_by_task_id("free").await.expect("job exists");
2491        assert_eq!(info.timeout, None);
2492        assert_eq!(info.remaining(), None);
2493    }
2494
2495    /// A job's task id stays leased while the registry keeps the job, past
2496    /// its end, and is released once the registry forgets it: when its
2497    /// completion is taken and nothing watches it, or with the registry.
2498    #[tokio::test]
2499    async fn a_job_keeps_its_task_id_leased_until_the_registry_forgets_it() {
2500        let ids = crate::test_ids::RecordingIds::default();
2501        let allocator = ids.allocator();
2502        let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
2503        let served = tokio::spawn(service.serve());
2504
2505        let first = allocator.lease().unwrap();
2506        registry
2507            .register(1, &first, "exec", "run", SandboxMode::Sandboxed, None)
2508            .await;
2509        let second = allocator.lease().unwrap();
2510        registry
2511            .register(2, &second, "exec", "run", SandboxMode::Sandboxed, None)
2512            .await;
2513        registry.complete(&first, 0, None).await;
2514        drop((first, second));
2515        assert!(registry.get_by_task_id("alfa").await.is_some());
2516        assert!(ids.released().is_empty(), "the registry holds both");
2517
2518        drop(registry.owe_completion("alfa", Ok(0)).await.unwrap());
2519        // The registry serves commands in order, so this list sees the job
2520        // forgotten.
2521        assert_eq!(registry.list().await.len(), 1);
2522        assert_eq!(ids.released(), ["alfa"]);
2523
2524        drop(registry);
2525        served.await.expect("the service ends with its last handle");
2526        let mut released = ids.released();
2527        released.sort();
2528        assert_eq!(released, ["alfa", "bravo"]);
2529    }
2530
2531    /// A job whose pid the operating system reused is a job of its own: the
2532    /// finished job it shares the pid with, its completion still untaken,
2533    /// keeps its output, its completion and its place in the registry.
2534    #[tokio::test]
2535    async fn a_job_sharing_a_held_jobs_pid_does_not_replace_it() {
2536        let registry = spawn_registry();
2537        let (old, new) = (lease("old"), lease("new"));
2538        registry
2539            .register(4242, &old, "exec", "first", SandboxMode::Sandboxed, None)
2540            .await;
2541        registry.append_stdout(&old, b"old output\n".to_vec()).await;
2542        registry.complete(&old, 3, None).await;
2543
2544        registry
2545            .register(4242, &new, "exec", "second", SandboxMode::Sandboxed, None)
2546            .await;
2547        registry.append_stdout(&new, b"new output\n".to_vec()).await;
2548
2549        let mut jobs = registry.list().await;
2550        jobs.sort_by(|a, b| a.task_id.cmp(&b.task_id));
2551        assert_eq!(
2552            jobs.iter()
2553                .map(|job| (job.task_id.as_str(), job.pid))
2554                .collect::<Vec<_>>(),
2555            [("new", 4242), ("old", 4242)]
2556        );
2557        assert_eq!(
2558            registry.get_by_task_id("old").await.unwrap().status,
2559            JobStatus::Completed {
2560                exit_code: 3,
2561                delivery: Delivery::Pending
2562            }
2563        );
2564        assert_eq!(
2565            registry.get_by_task_id("new").await.unwrap().status,
2566            JobStatus::Running
2567        );
2568        let (stdout, _) = registry.terminal_output("old").await.unwrap();
2569        assert_eq!(stdout, b"old output\n");
2570        let (stdout, _) = registry.terminal_output("new").await.unwrap();
2571        assert_eq!(stdout, b"new output\n");
2572        let read = registry
2573            .terminal_read("old", 0, 1024)
2574            .await
2575            .unwrap()
2576            .into_delta()
2577            .unwrap();
2578        assert_eq!(read.bytes, b"old output\n");
2579
2580        let owed = registry
2581            .owe_completion("old", Ok(3))
2582            .await
2583            .expect("the first job is still registered");
2584        assert!(owed.pending.is_some(), "its completion is still takeable");
2585        drop(owed);
2586        assert!(registry.get_by_task_id("old").await.is_none());
2587        assert_eq!(
2588            registry.get_by_task_id("new").await.unwrap().status,
2589            JobStatus::Running,
2590            "the second job is untouched"
2591        );
2592    }
2593
2594    /// A waiter that takes a job's completion leaves nothing owed from the
2595    /// moment the job ended, though the job's flow settles it later: a job
2596    /// that ended before the wait and one that ends during it both read
2597    /// taken, and the job stays readable until its flow settled and its
2598    /// watch dropped.
2599    #[tokio::test]
2600    async fn a_claiming_wait_reads_the_job_taken_before_its_flow_settles() {
2601        let registry = spawn_registry();
2602        let (ended, ending) = (lease("ended"), lease("ending"));
2603        registry
2604            .register(1, &ended, "exec", "run", SandboxMode::Sandboxed, None)
2605            .await;
2606        registry
2607            .register(2, &ending, "exec", "run", SandboxMode::Sandboxed, None)
2608            .await;
2609        let ended_watch = registry.watch("ended").await.expect("ended is held");
2610        let ending_watch = registry.watch("ending").await.expect("ending is held");
2611
2612        registry.complete(&ended, 0, None).await;
2613        let taken = JobStatus::Completed {
2614            exit_code: 0,
2615            delivery: Delivery::Taken,
2616        };
2617        assert_eq!(registry.wait_taking("ended").await.unwrap().status, taken);
2618        assert_eq!(
2619            registry.get_by_task_id("ended").await.unwrap().status,
2620            taken
2621        );
2622
2623        // The first poll queues the wait ahead of the ending, and the
2624        // registry serves its commands in order.
2625        let mut waiting = std::pin::pin!(registry.wait_taking("ending"));
2626        assert!(
2627            futures_lite::future::poll_once(waiting.as_mut())
2628                .await
2629                .is_none()
2630        );
2631        registry.complete(&ending, 0, None).await;
2632        assert_eq!(waiting.await.unwrap().status, taken);
2633        assert_eq!(
2634            registry.get_by_task_id("ending").await.unwrap().status,
2635            taken
2636        );
2637        assert!(
2638            !registry
2639                .list()
2640                .await
2641                .iter()
2642                .any(|job| job.status.completion_pending()),
2643            "no turn is owed for a job its waiter read"
2644        );
2645
2646        // The watch dropping before the flow settles leaves the job readable
2647        // to the flow.
2648        drop(ended_watch);
2649        assert!(registry.terminal_output("ended").await.is_some());
2650        for task_id in ["ended", "ending"] {
2651            let owed = registry.owe_completion(task_id, Ok(0)).await.unwrap();
2652            assert!(owed.pending.is_none(), "{task_id} owes nothing");
2653        }
2654        drop(ending_watch);
2655        assert!(registry.get_by_task_id("ending").await.is_none());
2656    }
2657
2658    /// A job its waiter claimed, whose watch dropped before its flow settled
2659    /// it, is forgotten as the flow settles it: the flow still reads it as it
2660    /// ended, and its id goes back to the allocator.
2661    #[tokio::test]
2662    async fn a_claimed_job_unwatched_before_its_flow_settles_is_forgotten_as_it_settles() {
2663        let ids = aither_core::AnyIdAllocator::new(aither_core::WordAllocator::new(["river"]));
2664        let registry = spawn_registry();
2665        let task_id = ids.lease().expect("river is free");
2666        registry
2667            .register(1, &task_id, "exec", "run", SandboxMode::Sandboxed, None)
2668            .await;
2669        let watch = registry.watch("river").await.expect("river is held");
2670
2671        let mut waiting = std::pin::pin!(registry.wait_taking("river"));
2672        assert!(
2673            futures_lite::future::poll_once(waiting.as_mut())
2674                .await
2675                .is_none()
2676        );
2677        registry.complete(&task_id, 0, None).await;
2678        let taken = JobStatus::Completed {
2679            exit_code: 0,
2680            delivery: Delivery::Taken,
2681        };
2682        assert_eq!(waiting.await.unwrap().status, taken);
2683        drop(watch);
2684        assert!(
2685            registry.terminal_output("river").await.is_some(),
2686            "the flow still reads the job it has yet to settle"
2687        );
2688
2689        let owed = registry.owe_completion("river", Ok(0)).await.unwrap();
2690        assert!(owed.pending.is_none(), "the waiter took the completion");
2691        assert_eq!(owed.info.status, taken);
2692        drop(task_id);
2693        assert!(registry.list().await.is_empty(), "the job is forgotten");
2694        assert_eq!(&*ids.lease().expect("river is free again"), "river");
2695    }
2696
2697    /// Once its completion is taken and nothing watches it, a finished job
2698    /// leaves the registry: its id goes back to the allocator, every read of
2699    /// it answers as for an unknown task, and a job that leases the word
2700    /// again starts with no read history.
2701    #[tokio::test]
2702    async fn a_taken_completion_forgets_the_job_and_releases_its_id() {
2703        let ids = aither_core::AnyIdAllocator::new(aither_core::WordAllocator::new(["river"]));
2704        let registry = spawn_registry();
2705        let river = ids.lease().unwrap();
2706        registry
2707            .register(1, &river, "exec", "run", SandboxMode::Sandboxed, None)
2708            .await;
2709        registry.append_stdout(&river, b"done\n".to_vec()).await;
2710        registry.complete(&river, 0, None).await;
2711        drop(river);
2712        registry
2713            .terminal_read("river", 0, 1024)
2714            .await
2715            .expect("a finished job reads until delivered");
2716        assert!(ids.lease().is_err(), "the registry holds river");
2717
2718        // A watch keeps the job past the take, reading it taken.
2719        let watch = registry.watch("river").await.expect("river is held");
2720        let owed = registry.owe_completion("river", Ok(0)).await.unwrap();
2721        drop(owed);
2722        assert_eq!(
2723            registry.get_by_task_id("river").await.unwrap().status,
2724            JobStatus::Completed {
2725                exit_code: 0,
2726                delivery: Delivery::Taken
2727            }
2728        );
2729        assert!(ids.lease().is_err(), "the watch holds river");
2730
2731        drop(watch);
2732        assert!(registry.list().await.is_empty(), "the job is forgotten");
2733        assert!(registry.get_by_task_id("river").await.is_none());
2734        assert!(registry.terminal_read("river", 0, 1024).await.is_err());
2735        assert!(!registry.kill_by_task_id("river").await);
2736        assert!(
2737            registry
2738                .terminal_input("river", b"x".to_vec())
2739                .await
2740                .is_err()
2741        );
2742
2743        // The word names a new job, whose first read is not refused as a
2744        // repeat of the old job's last one.
2745        let again = ids.lease().expect("river went back to the allocator");
2746        registry
2747            .register(2, &again, "exec", "run", SandboxMode::Sandboxed, None)
2748            .await;
2749        registry.append_stdout(&again, b"done\n".to_vec()).await;
2750        registry.complete(&again, 0, None).await;
2751        registry
2752            .terminal_read("river", 0, 1024)
2753            .await
2754            .expect("a new job under a reused word reads afresh");
2755    }
2756
2757    #[tokio::test]
2758    async fn task_output_appended_before_registration_lands_first_and_in_order() {
2759        let registry = spawn_registry();
2760        let early = lease("early");
2761        let appends = {
2762            let registry = registry.clone();
2763            let early = early.clone();
2764            tokio::spawn(async move {
2765                registry.append_task_stdout(&early, b"one\n".to_vec()).await;
2766                registry.append_task_stdout(&early, b"two\n".to_vec()).await;
2767            })
2768        };
2769        // The appends are parked: the job does not exist, and their sender
2770        // is still waiting for it.
2771        tokio::task::yield_now().await;
2772        assert!(!appends.is_finished());
2773        assert!(registry.get_by_task_id("early").await.is_none());
2774
2775        registry
2776            .register(9, &early, "exec-e", "run", SandboxMode::Sandboxed, None)
2777            .await;
2778        appends.await.expect("appends are released by registration");
2779        registry.append_stdout(&early, b"three\n".to_vec()).await;
2780
2781        let (stdout, _) = registry.terminal_output("early").await.expect("job exists");
2782        assert_eq!(stdout, b"one\ntwo\nthree\n");
2783    }
2784
2785    /// Parked progress refers to its job's lease weakly: it never keeps the
2786    /// word leased, and once the lease ends it goes with it, so a later job
2787    /// leasing the same word starts with none of it.
2788    #[tokio::test]
2789    async fn parked_output_never_reaches_a_later_job_under_the_same_word() {
2790        let ids = aither_core::AnyIdAllocator::new(aither_core::WordAllocator::new(["river"]));
2791        let registry = spawn_registry();
2792        let first = ids.lease().unwrap();
2793        let reporter = {
2794            let registry = registry.clone();
2795            let first = first.clone();
2796            tokio::spawn(async move {
2797                registry
2798                    .append_task_stdout(&first, b"stale\n".to_vec())
2799                    .await;
2800            })
2801        };
2802        tokio::task::yield_now().await;
2803        assert!(!reporter.is_finished(), "the report is parked");
2804        drop(first);
2805        assert!(ids.lease().is_err(), "the waiting reporter holds river");
2806
2807        // The first job never registers; its reporter goes away.
2808        reporter.abort();
2809        assert!(reporter.await.unwrap_err().is_cancelled());
2810        let second = ids.lease().expect("parked output holds no lease");
2811        registry
2812            .register(2, &second, "exec", "run", SandboxMode::Sandboxed, None)
2813            .await;
2814        registry
2815            .append_task_stdout(&second, b"fresh\n".to_vec())
2816            .await;
2817
2818        let (stdout, _) = registry.terminal_output("river").await.expect("job exists");
2819        assert_eq!(stdout, b"fresh\n");
2820    }
2821
2822    /// Progress a command reports after its job was forgotten is dropped:
2823    /// its sender is released at once, and the word goes back to the
2824    /// allocator when the command lets go of it.
2825    #[tokio::test]
2826    async fn output_for_a_forgotten_job_is_dropped() {
2827        let ids = aither_core::AnyIdAllocator::new(aither_core::WordAllocator::new(["river"]));
2828        let registry = spawn_registry();
2829        let river = ids.lease().unwrap();
2830        registry
2831            .register(1, &river, "exec", "run", SandboxMode::Sandboxed, None)
2832            .await;
2833        registry.complete(&river, 0, None).await;
2834        drop(registry.owe_completion("river", Ok(0)).await.unwrap());
2835        assert!(registry.list().await.is_empty(), "the job is forgotten");
2836
2837        // Answered at once, not parked for a registration that never comes.
2838        tokio::time::timeout(
2839            std::time::Duration::from_secs(5),
2840            registry.append_task_stdout(&river, b"late\n".to_vec()),
2841        )
2842        .await
2843        .expect("a report to a forgotten job is answered");
2844        assert!(registry.get_by_task_id("river").await.is_none());
2845        drop(river);
2846        let again = ids.lease().expect("nothing kept river");
2847        registry
2848            .register(2, &again, "exec", "run", SandboxMode::Sandboxed, None)
2849            .await;
2850        let (stdout, _) = registry.terminal_output("river").await.expect("job exists");
2851        assert!(stdout.is_empty(), "the late report reached no job");
2852    }
2853
2854    #[tokio::test]
2855    async fn unchanged_terminal_read_is_refused_then_succeeds_after_new_output() {
2856        let registry = spawn_registry();
2857        registry
2858            .register(
2859                7,
2860                &lease("alpha"),
2861                "exec-a",
2862                "run",
2863                SandboxMode::Sandboxed,
2864                None,
2865            )
2866            .await;
2867        registry
2868            .append_stdout(&lease("alpha"), b"one".to_vec())
2869            .await;
2870
2871        let first = registry
2872            .terminal_read("alpha", 0, 1024)
2873            .await
2874            .expect("first read succeeds")
2875            .into_delta()
2876            .expect("the first read is a delta");
2877        let second = registry.terminal_read("alpha", first.cursor, 1024).await;
2878        assert!(
2879            matches!(
2880                &second,
2881                Ok(JobRead::Unchanged { task_id }) if task_id == "alpha"
2882            ),
2883            "an unchanged repeat read is reported as a poll: {second:?}"
2884        );
2885
2886        registry
2887            .append_stdout(&lease("alpha"), b"two".to_vec())
2888            .await;
2889        let third = registry
2890            .terminal_read("alpha", first.cursor, 1024)
2891            .await
2892            .expect("read succeeds once output changed")
2893            .into_delta()
2894            .expect("changed output reads as a delta");
2895        assert_eq!(third.bytes, b"two");
2896    }
2897
2898    #[tokio::test]
2899    async fn test_job_registry_lifecycle() {
2900        let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
2901        TokioGlobal
2902            .spawn(async move { service.serve().await })
2903            .detach();
2904
2905        registry
2906            .register(
2907                12345,
2908                &lease("amber"),
2909                "exec-test",
2910                "sleep 10",
2911                SandboxMode::Sandboxed,
2912                Some(PathBuf::from("outputs/12345.txt")),
2913            )
2914            .await;
2915
2916        let jobs = registry.list().await;
2917        assert_eq!(jobs.len(), 1);
2918        assert_eq!(jobs[0].pid, 12345);
2919        assert_eq!(jobs[0].task_id, "amber");
2920        assert_eq!(jobs[0].execution_key, "exec-test");
2921        assert!(matches!(jobs[0].status, JobStatus::Running));
2922
2923        registry.complete(&lease("amber"), 0, None).await;
2924        let job = registry.get_by_task_id("amber").await.unwrap();
2925        assert_eq!(
2926            job.status,
2927            JobStatus::Completed {
2928                exit_code: 0,
2929                delivery: Delivery::Pending
2930            }
2931        );
2932    }
2933
2934    #[tokio::test]
2935    async fn test_format_running_jobs() {
2936        let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
2937        TokioGlobal
2938            .spawn(async move { service.serve().await })
2939            .detach();
2940
2941        registry
2942            .register(
2943                1,
2944                &lease("alpha"),
2945                "exec-a",
2946                "echo hello",
2947                SandboxMode::Sandboxed,
2948                None,
2949            )
2950            .await;
2951        registry
2952            .register(
2953                2,
2954                &lease("beta"),
2955                "exec-b",
2956                "sleep 5",
2957                SandboxMode::Sandboxed,
2958                None,
2959            )
2960            .await;
2961        registry.complete(&lease("beta"), 0, None).await;
2962
2963        let running = registry.format_running_jobs().await;
2964        assert!(running.contains("task alpha"));
2965        assert!(!running.contains("task beta"));
2966    }
2967
2968    #[tokio::test]
2969    async fn test_output_redirect_streams_full_output() {
2970        let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
2971        TokioGlobal
2972            .spawn(async move { service.serve().await })
2973            .detach();
2974
2975        let temp = tempdir().unwrap();
2976        let redirect_path = temp.path().join("stream.log");
2977
2978        registry
2979            .register(
2980                101,
2981                &lease("stream"),
2982                "exec-stream",
2983                "printf one",
2984                SandboxMode::Sandboxed,
2985                None,
2986            )
2987            .await;
2988
2989        registry
2990            .append_stdout(&lease("stream"), b"line1\nline2\n".to_vec())
2991            .await;
2992        let snapshot = registry
2993            .start_output_redirect("stream", redirect_path.clone())
2994            .await
2995            .unwrap();
2996        assert_eq!(String::from_utf8_lossy(&snapshot), "line1\nline2\n");
2997
2998        registry
2999            .append_stderr(&lease("stream"), b"line3\n".to_vec())
3000            .await;
3001        registry.complete(&lease("stream"), 0, None).await;
3002        let job = registry.get_by_task_id("stream").await.unwrap();
3003        assert!(matches!(
3004            job.status,
3005            JobStatus::Completed { exit_code: 0, .. }
3006        ));
3007
3008        let redirected = async_fs::read(&redirect_path).await.unwrap();
3009        assert_eq!(
3010            String::from_utf8_lossy(&redirected),
3011            "line1\nline2\nline3\n"
3012        );
3013    }
3014
3015    #[tokio::test]
3016    async fn test_read_terminal_delta_reads_incrementally() {
3017        let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
3018        TokioGlobal
3019            .spawn(async move { service.serve().await })
3020            .detach();
3021
3022        registry
3023            .register(
3024                202,
3025                &lease("delta"),
3026                "exec-delta",
3027                "tail -f log",
3028                SandboxMode::Sandboxed,
3029                None,
3030            )
3031            .await;
3032        registry
3033            .append_stdout(&lease("delta"), b"hello ".to_vec())
3034            .await;
3035        registry
3036            .append_stderr(&lease("delta"), b"world".to_vec())
3037            .await;
3038
3039        let first = registry
3040            .terminal_read("delta", 0, 6)
3041            .await
3042            .unwrap()
3043            .into_delta()
3044            .unwrap();
3045        assert_eq!(String::from_utf8_lossy(&first.bytes), "hello ");
3046        assert_eq!(first.cursor, 6);
3047        assert_eq!(first.total_bytes, 11);
3048        assert!(matches!(first.status, JobStatus::Running));
3049
3050        let second = registry
3051            .terminal_read("delta", first.cursor, 32)
3052            .await
3053            .unwrap()
3054            .into_delta()
3055            .unwrap();
3056        assert_eq!(String::from_utf8_lossy(&second.bytes), "world");
3057        assert_eq!(second.cursor, 11);
3058        assert_eq!(second.total_bytes, 11);
3059    }
3060
3061    /// The rotation case: tail writes `tail: ` on stderr, the new file's line
3062    /// arrives on stdout, then the rest of the notice on stderr. The monitor
3063    /// reads whole lines, while the merged terminal buffer stays in arrival
3064    /// order.
3065    #[tokio::test]
3066    async fn monitor_reads_whole_lines_when_partial_writes_interleave() {
3067        let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
3068        TokioGlobal
3069            .spawn(async move { service.serve().await })
3070            .detach();
3071        registry
3072            .register(
3073                203,
3074                &lease("lines"),
3075                "exec-lines",
3076                "tail -F f",
3077                SandboxMode::Sandboxed,
3078                None,
3079            )
3080            .await;
3081        let lines = lease("lines");
3082        registry.append_stderr(&lines, b"tail: ".to_vec()).await;
3083        registry.append_stdout(&lines, b"rotated\n".to_vec()).await;
3084        registry
3085            .append_stderr(&lines, b"'f' has been replaced\n".to_vec())
3086            .await;
3087        registry.append_stdout(&lines, b"unfinished".to_vec()).await;
3088
3089        let lines = registry.monitor_read("lines", 0, usize::MAX).await.unwrap();
3090        assert_eq!(
3091            String::from_utf8_lossy(&lines.bytes),
3092            "rotated\ntail: 'f' has been replaced\n"
3093        );
3094        let merged = registry
3095            .terminal_read("lines", 0, usize::MAX)
3096            .await
3097            .unwrap()
3098            .into_delta()
3099            .unwrap();
3100        assert_eq!(
3101            String::from_utf8_lossy(&merged.bytes),
3102            "tail: rotated\n'f' has been replaced\nunfinished"
3103        );
3104    }
3105
3106    #[tokio::test]
3107    async fn test_kill_by_execution_key_no_match() {
3108        let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
3109        TokioGlobal
3110            .spawn(async move { service.serve().await })
3111            .detach();
3112
3113        registry
3114            .register(
3115                1,
3116                &lease("alpha"),
3117                "exec-a",
3118                "echo hello",
3119                SandboxMode::Sandboxed,
3120                None,
3121            )
3122            .await;
3123        registry.complete(&lease("alpha"), 0, None).await;
3124
3125        let killed = registry.kill_by_execution_key("exec-b").await;
3126        assert_eq!(killed, 0);
3127    }
3128
3129    #[tokio::test]
3130    async fn test_kill_switch_path_marks_job_killed() {
3131        let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
3132        TokioGlobal
3133            .spawn(async move { service.serve().await })
3134            .detach();
3135
3136        registry
3137            .register(
3138                555,
3139                &lease("switch"),
3140                "exec-kill-switch",
3141                "sleep 10",
3142                SandboxMode::Sandboxed,
3143                None,
3144            )
3145            .await;
3146        let (kill_tx, kill_rx) = async_channel::bounded::<()>(1);
3147        registry.attach_kill_switch(&lease("switch"), kill_tx).await;
3148
3149        assert!(registry.kill_by_task_id("switch").await);
3150        assert!(kill_rx.recv().await.is_ok());
3151        let job = registry
3152            .get_by_task_id("switch")
3153            .await
3154            .expect("job should exist");
3155        assert!(matches!(job.status, JobStatus::Killed { .. }));
3156    }
3157
3158    #[tokio::test]
3159    async fn a_finished_job_releases_its_input_sender_and_refuses_input() {
3160        let registry = spawn_registry();
3161        registry
3162            .register(
3163                557,
3164                &lease("input"),
3165                "exec-input",
3166                "cat",
3167                SandboxMode::Sandboxed,
3168                None,
3169            )
3170            .await;
3171        let (input_tx, input_rx) = async_channel::unbounded::<Vec<u8>>();
3172        registry
3173            .attach_terminal_input(&lease("input"), input_tx)
3174            .await;
3175        registry
3176            .terminal_input("input", b"x".to_vec())
3177            .await
3178            .expect("a running job takes input");
3179        assert_eq!(input_rx.recv().await.expect("input arrives"), b"x");
3180
3181        registry.complete(&lease("input"), 0, None).await;
3182
3183        // The registry handles commands in order, so this reply follows the
3184        // completion.
3185        let error = registry
3186            .terminal_input("input", b"y".to_vec())
3187            .await
3188            .expect_err("a finished job refuses input");
3189        assert!(matches!(error, JobInputError::NotRunning { .. }), "{error}");
3190        assert!(input_rx.is_closed(), "the registry must drop its sender");
3191    }
3192
3193    #[tokio::test]
3194    async fn test_complete_does_not_override_killed_status() {
3195        let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
3196        TokioGlobal
3197            .spawn(async move { service.serve().await })
3198            .detach();
3199
3200        registry
3201            .register(
3202                556,
3203                &lease("finished"),
3204                "exec-killed-complete",
3205                "sleep 10",
3206                SandboxMode::Sandboxed,
3207                None,
3208            )
3209            .await;
3210        let (kill_tx, _kill_rx) = async_channel::bounded::<()>(1);
3211        registry
3212            .attach_kill_switch(&lease("finished"), kill_tx)
3213            .await;
3214        assert!(registry.kill_by_task_id("finished").await);
3215
3216        registry.complete(&lease("finished"), 0, None).await;
3217        let job = registry
3218            .get_by_task_id("finished")
3219            .await
3220            .expect("job should exist");
3221        assert!(matches!(job.status, JobStatus::Killed { .. }));
3222    }
3223
3224    /// A script longer than the preview, with a multibyte character across
3225    /// the cut, is listed instead of panicking inside the registry.
3226    #[tokio::test]
3227    async fn test_format_running_jobs_cuts_a_multibyte_script_at_a_boundary() {
3228        let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
3229        TokioGlobal
3230            .spawn(async move { service.serve().await })
3231            .detach();
3232
3233        // Three bytes per character: byte 50 lies inside the 17th.
3234        let script = "日".repeat(30);
3235        let preview_bytes = crate::output_policy::fixture::LIMITS.job_preview_bytes;
3236        assert!(!script.is_char_boundary(preview_bytes));
3237        registry
3238            .register(
3239                1,
3240                &lease("cjk"),
3241                "exec-cjk",
3242                &script,
3243                SandboxMode::Sandboxed,
3244                None,
3245            )
3246            .await;
3247
3248        let running = registry.format_running_jobs().await;
3249        assert!(
3250            running.contains(&format!("`{}...`", "日".repeat(16))),
3251            "{running}"
3252        );
3253        assert_eq!(script_preview("short", 50), "short");
3254        assert_eq!(script_preview(&"x".repeat(50), 50), "x".repeat(50));
3255        assert_eq!(
3256            script_preview(&"x".repeat(51), 50),
3257            format!("{}...", "x".repeat(50))
3258        );
3259        assert_eq!(script_preview("abcdef", 3), "abc...");
3260    }
3261
3262    fn running_job(pid: u32) -> Jobs {
3263        let mut jobs = Jobs::new();
3264        register_job(
3265            &mut jobs,
3266            pid,
3267            lease("task"),
3268            "exec".to_string(),
3269            "true".to_string(),
3270            Interpreter::Shell,
3271            SandboxMode::Sandboxed,
3272            None,
3273            JobPlace::Host,
3274            None,
3275        );
3276        jobs
3277    }
3278
3279    /// Two kills of one job overlap: the first to end must not release an
3280    /// ending the job's own flow reported while the second still runs.
3281    #[tokio::test]
3282    async fn overlapping_kills_hold_the_deferred_ending_until_the_last_ends() {
3283        let mut jobs = running_job(7);
3284        let user = KillCause::User;
3285        assert!(matches!(
3286            begin_kill(&mut jobs, "task", user).await,
3287            KillPlan::Group(7)
3288        ));
3289        assert!(matches!(
3290            begin_kill(&mut jobs, "task", user).await,
3291            KillPlan::Group(7)
3292        ));
3293        complete_job(&mut jobs, "task", 0, None).await;
3294        assert_eq!(
3295            jobs["task"].info.status,
3296            JobStatus::Running,
3297            "the ending waits"
3298        );
3299
3300        assert!(!end_kill(&mut jobs, "task", false).await);
3301        assert_eq!(
3302            jobs["task"].info.status,
3303            JobStatus::Running,
3304            "the other kill still runs"
3305        );
3306        assert!(!end_kill(&mut jobs, "task", false).await);
3307        assert_eq!(
3308            jobs["task"].info.status,
3309            JobStatus::Completed {
3310                exit_code: 0,
3311                delivery: Delivery::Pending
3312            },
3313            "the last kill to fail releases the ending"
3314        );
3315    }
3316
3317    /// A kill that succeeds wins over an ending reported while it ran.
3318    #[tokio::test]
3319    async fn a_successful_kill_wins_over_a_deferred_ending() {
3320        let mut jobs = running_job(8);
3321        assert!(matches!(
3322            begin_kill(&mut jobs, "task", KillCause::User).await,
3323            KillPlan::Group(8)
3324        ));
3325        complete_job(&mut jobs, "task", 0, None).await;
3326        assert!(end_kill(&mut jobs, "task", true).await);
3327        assert_eq!(
3328            jobs["task"].info.status,
3329            JobStatus::Killed {
3330                cause: KillCause::User,
3331                delivery: Delivery::Pending
3332            }
3333        );
3334    }
3335
3336    /// A job whose process exited from a kill's signal reads as running until
3337    /// the kill records its outcome; the settled read waits for it.
3338    #[tokio::test]
3339    async fn the_settled_read_waits_for_a_kill_in_flight() {
3340        let (registry, service) = job_registry_channel(crate::output_policy::fixture::policy());
3341        TokioGlobal
3342            .spawn(async move { service.serve().await })
3343            .detach();
3344        registry
3345            .register(
3346                557,
3347                &lease("settled"),
3348                "exec-settled",
3349                "sleep 10",
3350                SandboxMode::Sandboxed,
3351                None,
3352            )
3353            .await;
3354        let (reply_tx, reply_rx) = async_channel::bounded(1);
3355        registry
3356            .send_command(JobRequest::BeginKillByTaskId {
3357                task_id: "settled".to_string(),
3358                cause: KillCause::User,
3359                reply: reply_tx,
3360            })
3361            .await;
3362        let plan = JobRegistry::recv_reply(reply_rx).await;
3363        assert!(matches!(plan, KillPlan::Group(557)));
3364        // The killed process exits and its flow reports completion while the
3365        // kill has not returned.
3366        registry.complete(&lease("settled"), 137, None).await;
3367        let running = registry.get_by_task_id("settled").await;
3368        assert!(matches!(
3369            running.expect("job should exist").status,
3370            JobStatus::Running
3371        ));
3372
3373        let waiting = {
3374            let registry = registry.clone();
3375            tokio::spawn(async move { registry.get_by_task_id_settled("settled").await })
3376        };
3377        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
3378        assert!(!waiting.is_finished(), "the kill is still in flight");
3379
3380        let (reply_tx, reply_rx) = async_channel::bounded(1);
3381        registry
3382            .send_command(JobRequest::EndKill {
3383                task_id: "settled".to_string(),
3384                killed: true,
3385                reply: reply_tx,
3386            })
3387            .await;
3388        assert!(JobRegistry::recv_reply(reply_rx).await);
3389        let job = waiting.await.unwrap().expect("job should exist");
3390        assert!(matches!(job.status, JobStatus::Killed { .. }));
3391    }
3392
3393    /// What a host reading the registry can tell: whether the session still
3394    /// owes its agent a turn.
3395    fn host_sees_owed_turn(jobs: &[JobInfo]) -> bool {
3396        jobs.iter()
3397            .any(|job| job.status == JobStatus::Running || job.status.completion_pending())
3398    }
3399
3400    #[tokio::test]
3401    async fn a_job_reads_its_completion_pending_from_the_transition_that_finishes_it() {
3402        let registry = spawn_registry();
3403        registry
3404            .register(
3405                9,
3406                &lease("owed"),
3407                "exec",
3408                "run",
3409                SandboxMode::Sandboxed,
3410                None,
3411            )
3412            .await;
3413        // The registry serves its commands in order, so this list sees the
3414        // state the finishing transition left, before anything else runs.
3415        registry.complete(&lease("owed"), 0, None).await;
3416        let jobs = registry.list().await;
3417        assert!(
3418            host_sees_owed_turn(&jobs),
3419            "a finished job whose completion was never delivered reads as done: {jobs:?}"
3420        );
3421
3422        // The job's flow hands the completion out; the agent holds it.
3423        let owed = registry
3424            .owe_completion("owed", Ok(0))
3425            .await
3426            .expect("the job is registered");
3427        assert_eq!(owed.info.status.kill_cause(), None);
3428        let jobs = registry.list().await;
3429        assert!(host_sees_owed_turn(&jobs), "{jobs:?}");
3430
3431        // The agent takes it, and the registry forgets the job.
3432        drop(owed);
3433        let jobs = registry.list().await;
3434        assert!(jobs.is_empty(), "{jobs:?}");
3435        assert!(!host_sees_owed_turn(&jobs));
3436    }
3437
3438    #[tokio::test]
3439    async fn a_completion_owed_by_a_job_still_running_ends_it_pending() {
3440        let registry = spawn_registry();
3441        registry
3442            .register(
3443                10,
3444                &lease("lost"),
3445                "exec",
3446                "run",
3447                SandboxMode::Sandboxed,
3448                None,
3449            )
3450            .await;
3451        // The flow failed without the registry recording how.
3452        let owed = registry
3453            .owe_completion("lost", Err("output could not be saved".to_string()))
3454            .await
3455            .expect("the job is registered");
3456        assert_eq!(owed.info.status.kill_cause(), None);
3457        let job = registry
3458            .get_by_task_id("lost")
3459            .await
3460            .expect("job should exist");
3461        assert_eq!(
3462            job.status,
3463            JobStatus::Failed {
3464                error: "output could not be saved".to_string(),
3465                delivery: Delivery::Pending
3466            }
3467        );
3468        assert!(
3469            registry
3470                .owe_completion("task-never-registered", Ok(0))
3471                .await
3472                .is_none()
3473        );
3474    }
3475
3476    #[tokio::test]
3477    async fn a_completion_owed_during_a_kill_waits_for_its_outcome() {
3478        let registry = spawn_registry();
3479        registry
3480            .register(
3481                11,
3482                &lease("kill"),
3483                "exec",
3484                "run",
3485                SandboxMode::Sandboxed,
3486                None,
3487            )
3488            .await;
3489        let (reply_tx, reply_rx) = async_channel::bounded(1);
3490        registry
3491            .send_command(JobRequest::BeginKillByTaskId {
3492                task_id: "kill".to_string(),
3493                cause: KillCause::User,
3494                reply: reply_tx,
3495            })
3496            .await;
3497        assert!(matches!(
3498            JobRegistry::recv_reply(reply_rx).await,
3499            KillPlan::Group(11)
3500        ));
3501        let (reply_tx, owed) = async_channel::bounded(1);
3502        registry
3503            .send_command(JobRequest::OweCompletion {
3504                task_id: "kill".to_string(),
3505                ending: Ok(137),
3506                reply: reply_tx,
3507            })
3508            .await;
3509        // Served after the request above: the owed completion is parked.
3510        assert_eq!(
3511            registry
3512                .get_by_task_id("kill")
3513                .await
3514                .expect("job should exist")
3515                .status,
3516            JobStatus::Running
3517        );
3518        assert!(owed.is_empty(), "the kill is still in flight");
3519
3520        let (reply_tx, reply_rx) = async_channel::bounded(1);
3521        registry
3522            .send_command(JobRequest::EndKill {
3523                task_id: "kill".to_string(),
3524                killed: true,
3525                reply: reply_tx,
3526            })
3527            .await;
3528        assert!(JobRegistry::recv_reply(reply_rx).await);
3529        let owed = JobRegistry::recv_reply(owed)
3530            .await
3531            .expect("the job is registered");
3532        assert_eq!(owed.info.status.kill_cause(), Some(KillCause::User));
3533        assert_eq!(
3534            registry
3535                .get_by_task_id("kill")
3536                .await
3537                .expect("job should exist")
3538                .status,
3539            JobStatus::Killed {
3540                cause: KillCause::User,
3541                delivery: Delivery::Pending
3542            }
3543        );
3544    }
3545
3546    #[tokio::test]
3547    #[should_panic(expected = "handed out twice")]
3548    async fn a_completion_is_handed_out_once() {
3549        let (tx, _rx) = async_channel::unbounded();
3550        let weak = tx.downgrade();
3551        let mut jobs = Jobs::new();
3552        register_job(
3553            &mut jobs,
3554            12,
3555            lease("twice"),
3556            "exec".to_string(),
3557            "run".to_string(),
3558            Interpreter::Shell,
3559            SandboxMode::Sandboxed,
3560            None,
3561            JobPlace::Host,
3562            None,
3563        );
3564        let _first = owe_completion(&mut jobs, "twice", Ok(0), &weak).await;
3565        let _second = owe_completion(&mut jobs, "twice", Ok(0), &weak).await;
3566    }
3567}