Skip to main content

schedr_agent/
agent.rs

1//! The worker agent's main loop: one control stream to the master, attempts and parse jobs,
2//! heartbeats and code watching (see archive/PROJECT.md, Worker lifecycle and Task assignment).
3//!
4//! - **Connecting:** the agent waits for each root's first content hash (it settles too),
5//!   registers with them and with the attempts it still runs or hasn't had acknowledged, then
6//!   follows the master's decisions for those (continue, ack, kill).
7//! - **Assignments:** a free slot, an assignment that reads and the task's code on this worker
8//!   at the hash the master expects, or a rejection with the reason; then `Started`, the
9//!   attempt runs, and `Finished` (naming the code it ran) is sent until the master
10//!   acknowledges it.
11//! - **Parse jobs** parse a root's `.py` files and upload the result, if the root still has the
12//!   job's hash (otherwise a newer hash was or will be reported).
13//! - **The connection drops:** attempts keep running, and the agent connects again with
14//!   backoff (up to 30 s).
15//! - **Shutdown** (SIGTERM): the agent drains (see [`crate::drain`]): it says `Draining` (again
16//!   after any reconnect), rejects new assignments, gives the running attempts until the
17//!   termination grace period ends, interrupts the rest, and deregisters once the master has
18//!   their results. A second request interrupts at once.
19//! - **The journal** on disk backs `Started` and `Finished` (see [`crate::journal`]): an
20//!   attempt that can't be recorded is rejected, and on start the agent reports the results
21//!   its previous incarnation had and stops the processes it left running. Without `/proc`
22//!   it warns once and leaves them.
23//!
24//! The work itself goes through an [`Executor`]: processes in production
25//! ([`ProcessExecutor`]), something simpler in tests.
26
27use std::collections::{BTreeMap, BTreeSet};
28use std::path::{Path, PathBuf};
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Arc, PoisonError};
31use std::time::{Duration, Instant};
32
33use jiff::Timestamp;
34use schedr_model::TaskKind;
35use schedr_model::beat::Beat;
36use schedr_model::connection::Registry;
37use schedr_model::runner::{
38    CleanupHandle, DAG_FILE_MISSING, ErrorSummary, ParseRequest, ParsedFile,
39};
40use schedr_model::task::{CleanupRun, TaskCleanup, default_outcomes};
41use schedr_proto::PROTOCOL_VERSION;
42use schedr_proto::convert::attempt_status_from_proto;
43use schedr_proto::convert::{parse_upload_parts, parsed_file_to_proto};
44use schedr_proto::pb::master_client::MasterClient;
45use schedr_proto::pb::{self, master_message, worker_message};
46use tokio::sync::{mpsc, oneshot, watch};
47
48use crate::api::ApiCaller;
49use tokio_stream::wrappers::UnboundedReceiverStream;
50use tonic::transport::Channel;
51
52use crate::attempt::{
53    AttemptSpec, CleanupGate, Gate, NotRun, Pass, Plan, Ran, WorkerSetup, failed_before_start,
54    finished, plan, plan_at, use_cleanup_script, with_resource_value,
55};
56use crate::connection_jobs::ConnectionJob;
57use crate::ctx::CtxInfo;
58use crate::drain::{Drain, DrainPeriods, DrainStep};
59use crate::fork::ForkServers;
60use crate::handles::{AttemptHandles, HandleSink};
61use crate::journal::{
62    Journal, JournalRecord, KeptAttempt, Orphan, ProcessIdentity, process_identity, stop_orphan,
63};
64use crate::launch::{AGENT_VERSION, ProcessParseRunner, PythonTask, run_command, run_python};
65use crate::mask::Mask;
66use crate::master_time::{Local, MasterTime, SharedOutbox};
67use crate::memory::{MemorySeen, SharedSeen, over_budget_message, watch_group};
68use crate::metrics::AgentMetrics;
69use crate::process::ProcessSpec;
70use crate::resource::AttemptResource;
71use crate::secrets::{AttemptSecrets, SecretStores};
72use crate::status::StopReason;
73use crate::supervise::{Limits, StopSender, Stops};
74use crate::watch::{Poll, RootWatcher};
75
76#[cfg(test)]
77mod tests;
78
79/// The error kind of an attempt whose process couldn't be started.
80pub const START_FAILED: &str = "start_failed";
81
82/// The longest wait between attempts to reach the master.
83pub const MAX_BACKOFF: Duration = Duration::from_secs(30);
84
85/// How long a process left running by a previous incarnation has between SIGTERM and SIGKILL.
86pub const ORPHAN_GRACE: Duration = Duration::from_secs(10);
87
88/// The first wait after the master connection drops; it doubles up to [`MAX_BACKOFF`], and
89/// starts again here after a session in which the master registered the worker.
90pub const FIRST_BACKOFF: Duration = Duration::from_millis(200);
91
92/// The longest wait between two tries to reach the master: `max`, but at most half the
93/// master's worker lease once it has told it (B168), so a worker still alive reaches a master
94/// back from a restart before that master's lease on it runs out; else the master would take
95/// it for lost and move its cleanups with only the handles it got (a handle registered while
96/// the master was away left behind).
97#[must_use]
98pub fn reconnect_cap(max: Duration, lease: Option<Duration>) -> Duration {
99    lease.map_or(max, |lease| max.min(lease / 2))
100}
101
102/// A backoff with jitter: between half of `backoff` and all of it, picked by `seed` (so many
103/// workers losing the master at once don't come back in lockstep).
104#[must_use]
105pub fn jittered(backoff: Duration, seed: u32) -> Duration {
106    let fraction = 0.5 + 0.5 * f64::from(seed) / f64::from(u32::MAX);
107    backoff.mul_f64(fraction)
108}
109
110/// The agent's configuration.
111#[derive(Debug, Clone)]
112pub struct AgentSettings {
113    /// The worker's ID (stable across restarts).
114    pub worker_id: String,
115    /// The queues it serves (none: `default`).
116    pub queues: Vec<String>,
117    /// Its task slots.
118    pub slots: u32,
119    /// Its slots for wait steps (`[watchers] slots`).
120    pub watcher_slots: u32,
121    /// How tasks run here (roots, interpreter, environment, logs).
122    pub setup: WorkerSetup,
123    /// How often roots are scanned.
124    pub poll_interval: Duration,
125    /// How long a changed root must stay unchanged before it is hashed.
126    pub settle_time: Duration,
127    /// Where the journal is kept (see [`crate::journal`]).
128    pub journal_dir: PathBuf,
129    /// Where each root's code is copied, a folder per root (decision 102): parse jobs and
130    /// tasks import from the copy of the hash they are for.
131    pub code_dir: PathBuf,
132    /// How long the running attempts get when the agent is asked to stop (the pod's
133    /// `terminationGracePeriodSeconds`), and how the end of that time is split.
134    pub drain: DrainPeriods,
135    /// Where the webserver reaches this worker's log endpoint (e.g.
136    /// `https://w-0.schedr-worker.etl.svc.cluster.local:8081`), sent in `Register`.
137    pub log_endpoint: String,
138    /// The worker as a node of its deployment, sent in `Register` for the Deployments page.
139    pub node: NodeIdentity,
140    /// Its secret storages (names sent in `Register`).
141    pub secrets: Arc<SecretStores>,
142}
143
144/// A worker as a node of its deployment (decisions 121-123).
145#[derive(Debug, Clone, Default, PartialEq, Eq)]
146pub struct NodeIdentity {
147    /// The process it runs in (shared with a master in standalone).
148    pub process_id: String,
149    /// Its effective configuration as JSON, masked (no secret in clear: it leaves the
150    /// process).
151    pub config_json: String,
152}
153
154/// Told the identity of an attempt's process once it is spawned, and whether it was forked
155/// from a fork server: the task's, then each try of its cleanup's.
156pub type Spawned = Arc<dyn Fn(ProcessIdentity, bool) + Send + Sync>;
157
158/// Told a task's result when its process has ended and its cleanup starts (decision 229).
159pub type TaskEnded = Box<dyn FnOnce(pb::Finished) + Send>;
160
161/// What an attempt's processes share: the task's and each try of its cleanup.
162#[derive(Clone, Copy)]
163struct Shared<'a> {
164    secrets: &'a Arc<AttemptSecrets>,
165    handles: &'a Arc<AttemptHandles>,
166    /// Set when a process starts.
167    started: &'a AtomicBool,
168    /// Told each process.
169    spawned: &'a Spawned,
170}
171
172/// The copies of the other roots a parse sees (decision 102).
173#[derive(Debug, Clone, Default, PartialEq, Eq)]
174pub struct ParseCode {
175    /// The script roots, for a `ScriptOperator`'s declaration (decision 293).
176    pub scripts: BTreeMap<String, crate::jobs::ScriptRoot>,
177    /// The other DAG roots' copies, on `sys.path` in place of their configured paths.
178    pub roots: BTreeMap<String, PathBuf>,
179}
180
181/// Runs attempts and parse jobs.
182pub trait Executor: Clone + Send + Sync + 'static {
183    /// Runs a planned attempt until it ends or `stop` says why to stop it (a later reason
184    /// may hurry a stop under way, see [`crate::supervise::supervise`]), telling `spawned` its
185    /// process, and `ended` the task's result before its cleanup starts; returns its
186    /// `Finished`.
187    fn run(
188        &self,
189        spec: AttemptSpec,
190        plan: Plan,
191        stop: Stops,
192        spawned: Spawned,
193        ended: TaskEnded,
194    ) -> impl Future<Output = pb::Finished> + Send;
195
196    /// Runs the cleanup of an attempt an earlier agent left, whose task ended as `ended`, with
197    /// the `handles` the journal kept; returns `ended` with the cleanup's result.
198    fn cleanup(
199        &self,
200        spec: AttemptSpec,
201        ended: pb::Finished,
202        handles: Vec<CleanupHandle>,
203        spawned: Spawned,
204    ) -> impl Future<Output = pb::Finished> + Send;
205
206    /// What is wrong with the worker now, as it changes (sent to the master); none by default.
207    fn warnings(&self) -> watch::Receiver<Vec<pb::WorkerWarning>> {
208        watch::channel(Vec::new()).1
209    }
210
211    /// The worker's newest copy of each DAG root: what runs may move to it.
212    fn code_changed(&self, _copies: BTreeMap<String, PathBuf>) {}
213
214    /// Folders of code copies in use besides the attempts' own.
215    fn code_in_use(&self) -> Vec<String> {
216        Vec::new()
217    }
218
219    /// The wait step hosts as last looked at, for the heartbeat: it can't wait.
220    fn watcher_hosts(&self) -> Vec<pb::WatcherHost> {
221        Vec::new()
222    }
223
224    /// Its fork servers' memory together and its running tasks', largest first, as last
225    /// measured, for the heartbeat (decision 463): it can't wait.
226    fn memory_parts(&self) -> (u64, Vec<schedr_model::usage::TaskMemory>) {
227        (0, Vec::new())
228    }
229
230    /// Parses `files` of the root `root` in `dir`, with the other roots' copies `code`.
231    fn parse(
232        &self,
233        root: String,
234        dir: PathBuf,
235        files: Vec<String>,
236        code: ParseCode,
237    ) -> impl Future<Output = Result<Vec<ParsedFile>, String>> + Send;
238
239    /// Checks a root's connections, or tests one (`schedr connections check` / `test`); a
240    /// report for each. An executor without secrets says it can't.
241    /// A test tells `spawned` its process, as an attempt does (the journal records it, so
242    /// a worker killed meanwhile stops it when it starts again).
243    fn connection_job(
244        &self,
245        job: ConnectionJob,
246        spawned: Spawned,
247    ) -> impl Future<Output = Vec<schedr_model::commands::ConnectionReport>> + Send {
248        drop(spawned);
249        async move {
250            job.registry
251                .connections
252                .keys()
253                .chain(job.registry.refused.keys())
254                .map(|name| {
255                    crate::connection_jobs::failed(
256                        name,
257                        "this worker can't check connections".to_owned(),
258                    )
259                })
260                .collect()
261        }
262    }
263}
264
265/// Warned once when `/proc` is missing, so a crash leaves task processes running.
266pub(crate) const NO_PROC_WARNING: &str = "no /proc: orphaned tasks aren't stopped after a crash";
267
268/// Set once [`NO_PROC_WARNING`] has been logged in this process.
269static NO_PROC_SAID: AtomicBool = AtomicBool::new(false);
270
271/// How to report that a task's process couldn't be identified.
272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub(crate) enum IdentityWarning {
274    /// `/proc` is not a directory. Logged once per process, as [`NO_PROC_WARNING`].
275    NoProc,
276    /// Any other failure. Logged for this task.
277    ThisTask,
278}
279
280/// What to log when [`process_identity`] failed.
281///
282/// `proc_present` is whether `/proc` is a directory. When it isn't, the failure is that
283/// `/proc` is absent (macOS): [`IdentityWarning::NoProc`] the first time (`said` flips), then
284/// nothing. When it is, every failure is [`IdentityWarning::ThisTask`] — a process that has
285/// already exited is `NotFound` too, and that still warns per task. `said` is the
286/// process-wide flag in the agent; a test passes its own.
287#[must_use]
288pub(crate) fn identity_warning(proc_present: bool, said: &AtomicBool) -> Option<IdentityWarning> {
289    if proc_present {
290        Some(IdentityWarning::ThisTask)
291    } else if said.swap(true, Ordering::Relaxed) {
292        None
293    } else {
294        Some(IdentityWarning::NoProc)
295    }
296}
297
298/// Logs [`identity_warning`] for this process (`/proc` as it is on this machine).
299fn warn_unidentified(pid: i32, error: &std::io::Error) {
300    match identity_warning(Path::new("/proc").is_dir(), &NO_PROC_SAID) {
301        Some(IdentityWarning::NoProc) => tracing::warn!("{}", NO_PROC_WARNING),
302        Some(IdentityWarning::ThisTask) => {
303            tracing::warn!(pid, %error, "can't identify the task's process");
304        }
305        None => {}
306    }
307}
308
309/// Runs attempts and parse jobs as processes.
310#[derive(Debug, Clone)]
311pub struct ProcessExecutor {
312    /// How tasks run here.
313    pub setup: WorkerSetup,
314    /// How long one file may take to import, and how many are parsed at once.
315    pub parse: crate::parse::ParseLimits,
316    /// Where the watchdog's kills are counted.
317    pub metrics: AgentMetrics,
318    /// From an interrupted task's SIGTERM to its SIGKILL (`[worker] drain_terminate_period`).
319    pub drain_terminate_period: Duration,
320    /// The DAG interpreter's fork servers, when it has them (`fork_server = true`, Linux).
321    pub forks: Option<ForkServers>,
322    /// The hosts running this worker's wait steps.
323    pub watchers: crate::watchers::WatcherHosts,
324    /// The worker's secret storages.
325    pub secrets: Arc<SecretStores>,
326    /// Its running tasks' memory, for the heartbeat (decision 463).
327    pub running_memory: crate::memory::RunningMemory,
328}
329
330impl Executor for ProcessExecutor {
331    fn code_changed(&self, copies: BTreeMap<String, PathBuf>) {
332        self.watchers.code_changed(&copies);
333    }
334
335    fn code_in_use(&self) -> Vec<String> {
336        self.watchers.code_in_use()
337    }
338
339    fn watcher_hosts(&self) -> Vec<pb::WatcherHost> {
340        self.watchers.reports()
341    }
342
343    fn memory_parts(&self) -> (u64, Vec<schedr_model::usage::TaskMemory>) {
344        (
345            self.forks.as_ref().map_or(0, ForkServers::memory),
346            self.running_memory.now(),
347        )
348    }
349
350    fn warnings(&self) -> watch::Receiver<Vec<pb::WorkerWarning>> {
351        self.forks
352            .as_ref()
353            .map_or_else(|| watch::channel(Vec::new()).1, ForkServers::warnings)
354    }
355
356    async fn run(
357        &self,
358        spec: AttemptSpec,
359        plan: Plan,
360        stop: Stops,
361        spawned: Spawned,
362        ended: TaskEnded,
363    ) -> pb::Finished {
364        let connection_dir = self.setup.connection_dir.join(&spec.attempt_id);
365        let has_cleanup = spec.task.cleanup.is_some();
366        // Boxed: the attempt's future is large, and every caller would hold it.
367        let mut finished = Box::pin(self.run_attempt(spec, plan, stop, spawned, ended)).await;
368        // Its process never started: nothing to clean up after (decision 216).
369        if has_cleanup && finished.cleanup.is_none() {
370            finished.cleanup = Some(pb::CleanupResult {
371                status: pb::CleanupStatus::NotNeeded.into(),
372                ..pb::CleanupResult::default()
373            });
374        }
375        // Its connections' files go with it (decision 190): whichever way it ended.
376        remove_connection_files(&connection_dir).await;
377        finished
378    }
379
380    async fn cleanup(
381        &self,
382        mut spec: AttemptSpec,
383        mut ended: pb::Finished,
384        handles: Vec<CleanupHandle>,
385        spawned: Spawned,
386    ) -> pb::Finished {
387        let connection_dir = self.setup.connection_dir.join(&spec.attempt_id);
388        let result = Box::pin(self.kept_cleanup(&mut spec, handles, &spawned)).await;
389        ended.cleanup = Some(result);
390        remove_connection_files(&connection_dir).await;
391        ended
392    }
393
394    async fn connection_job(
395        &self,
396        job: ConnectionJob,
397        spawned: Spawned,
398    ) -> Vec<schedr_model::commands::ConnectionReport> {
399        use crate::connection_jobs::{failed, out_of_time};
400        // Read fresh: a secret just fixed is what the check or test sees.
401        let secrets = Arc::new(self.secrets.uncached());
402        let Some((name, _)) = job.test.clone() else {
403            let check = crate::connection_jobs::check(&secrets, &job.registry);
404            return match tokio::time::timeout_at(job.deadline, check).await {
405                Ok(reports) => reports,
406                Err(_) => job
407                    .registry
408                    .names()
409                    .map(|name| failed(name, out_of_time("check")))
410                    .collect(),
411            };
412        };
413        // What is left of its time once its turn came; all of it, secrets read included.
414        let left = job
415            .deadline
416            .saturating_duration_since(tokio::time::Instant::now());
417        let mut spec =
418            match crate::connection_jobs::test_spec(&job, &name, left, job.attempt_id.clone()) {
419                Ok(spec) => spec,
420                Err(why) => return vec![failed(&name, why)],
421            };
422        spec.stand_in_secrets();
423        // At the copy of the code the job was sent for, as a task's (decision 102).
424        let planned = match &spec.code_dir {
425            Some(dir) => plan_at(&spec, &self.setup, dir),
426            None => crate::attempt::plan(&spec, &self.setup),
427        };
428        let plan = match planned {
429            Ok(plan) => plan,
430            Err(NotRun::Rejected { detail, .. }) => return vec![failed(&name, detail)],
431            Err(NotRun::Failed { message, .. }) => return vec![failed(&name, message)],
432        };
433        let started = Instant::now();
434        let log = self.setup.log_file(&spec.attempt_id);
435        let (stop, stops) = Stops::new();
436        let fresh = Self {
437            secrets,
438            ..self.clone()
439        };
440        let run = fresh.run(spec, plan, stops, spawned, Box::new(|_| {}));
441        tokio::pin!(run);
442        // The job's deadline also covers planning and waiting for its turn; the attempt's
443        // timeout covers its secret reads and process together.
444        let finished = tokio::select! {
445            finished = &mut run => finished,
446            () = tokio::time::sleep_until(job.deadline) => {
447                let _ = stop.send(StopReason::TimedOut);
448                run.await
449            }
450        };
451        // No task's: nothing serves it.
452        let _ = tokio::fs::remove_file(&log).await;
453        vec![crate::connection_jobs::test_report(
454            &name,
455            &finished,
456            started.elapsed(),
457        )]
458    }
459
460    async fn parse(
461        &self,
462        root: String,
463        dir: PathBuf,
464        files: Vec<String>,
465        code: ParseCode,
466    ) -> Result<Vec<ParsedFile>, String> {
467        self.parse_files(root, dir, files, code).await
468    }
469}
470
471impl ProcessExecutor {
472    async fn run_attempt(
473        &self,
474        mut spec: AttemptSpec,
475        mut plan: Plan,
476        stop: Stops,
477        spawned: Spawned,
478        ended: TaskEnded,
479    ) -> pb::Finished {
480        let fetching = Instant::now();
481        let _ = tokio::fs::create_dir_all(&self.setup.log_dir).await;
482        let timeout = spec.timeout();
483        let mut stop = stop;
484        // A slow storage gives way to a cancel, a drain's interrupt or the timeout: nothing
485        // has started, so nothing needs stopping.
486        let fetched = tokio::select! {
487            fetched = self.fetch_secrets(&mut spec, &mut plan) => Ok(fetched),
488            reason = stop.next_reason() => Err(reason),
489            () = sleep_for(timeout) => Err(StopReason::TimedOut),
490        };
491        let secrets = match fetched {
492            Ok(Ok(secrets)) => secrets,
493            Ok(Err(finished)) => return *finished,
494            Err(reason) => return stopped_before_start(&spec, reason, fetching.elapsed()),
495        };
496        let elapsed = fetching.elapsed();
497        let timeout = timeout.map(|timeout| timeout.saturating_sub(elapsed));
498        // Fetching may finish in the same poll as its deadline: do not start a process
499        // with no time left, whichever branch of the select won.
500        if timeout.is_some_and(|left| left.is_zero()) {
501            return stopped_before_start(&spec, StopReason::TimedOut, elapsed);
502        }
503        let python = matches!(plan, Plan::Python { .. });
504        let mut handles =
505            AttemptHandles::new(spec.task.cleanup.as_ref(), Arc::clone(&secrets.mask));
506        if let Some(journal) = &spec.journal {
507            handles = handles.journaled(journal.clone(), spec.attempt_id.clone());
508        }
509        if let Some(sink) = &spec.handle_sink {
510            handles = handles.forwarded(sink.clone());
511        }
512        let handles = Arc::new(handles);
513        let started = AtomicBool::new(false);
514        let shared = Shared {
515            secrets: &secrets,
516            handles: &handles,
517            started: &started,
518            spawned: &spawned,
519        };
520        let mut finished = self.run_planned(&spec, plan, timeout, stop, shared).await;
521        ended_with_secrets(&mut finished, &secrets, python);
522        if let Some(cleanup) = &spec.task.cleanup
523            && started.load(Ordering::SeqCst)
524        {
525            ended(finished.clone());
526            // Dropped, the attempt is no longer this worker's: what it reports here is ignored.
527            let pass = match spec.cleanup_gate.clone() {
528                Some(gate) => gate.passes().await,
529                None => Some(Pass::All),
530            };
531            if let Some(pass) = pass {
532                if let Pass::From(from) = pass {
533                    handles.skip(from);
534                }
535                let mut result = self.run_cleanup(&spec, cleanup, shared).await;
536                result.rest = matches!(pass, Pass::From(_));
537                finished.cleanup = Some(result);
538            }
539        }
540        let log = self.setup.log_file(&spec.attempt_id);
541        // Read on demand while it ran: too short to mask, warned now.
542        let short = too_short_lines(&secrets, self.secrets.min_mask_length);
543        append_log(&log, &(short + &masked_lines(&secrets))).await;
544        finished
545    }
546
547    /// Fetches the secrets the attempt needs, then plans it again with their values (it was
548    /// planned with stand-ins). A failure ends it: nothing runs with a missing secret.
549    async fn fetch_secrets(
550        &self,
551        spec: &mut AttemptSpec,
552        plan: &mut Plan,
553    ) -> Result<Arc<AttemptSecrets>, Box<pb::Finished>> {
554        let needed = spec.needed_secrets();
555        let fail = |kind: &str, message: &str| {
556            Box::new(failed_before_start(&spec.attempt_id, kind, message))
557        };
558        let secrets = AttemptSecrets::fetch(
559            Arc::clone(&self.secrets),
560            &needed,
561            spec.task.secrets.clone(),
562        )
563        .await
564        .map_err(|e| fail(e.kind(), &e.to_string()))?
565        .with_connections(Arc::clone(&spec.connections), spec.task.connections.clone())
566        .with_connection_dir(self.setup.connection_dir.join(&spec.attempt_id));
567        secrets
568            .open_declared()
569            .await
570            .map_err(|e| fail(e.kind(), &e.to_string()))?;
571        if needed.is_empty() && spec.task.secrets.is_empty() && !secrets.has_connections() {
572            // Nothing to fetch or mask; kept to remember a read refused as undeclared, the
573            // attempt's error kind if it then fails (decision 168).
574            return Ok(Arc::new(secrets));
575        }
576        if let TaskKind::Command { connection_env, .. } = &spec.task.kind {
577            spec.connection_env = command_connections(&secrets, connection_env)
578                .await
579                .map_err(|(kind, message)| fail(kind, &message))?;
580        }
581        spec.secrets = secrets.fetched();
582        spec.mask = Mask(Some(Arc::clone(&secrets.mask)));
583        let planned = match &spec.code_dir {
584            Some(dir) => plan_at(spec, &self.setup, dir),
585            None => crate::attempt::plan(spec, &self.setup),
586        };
587        *plan = planned.map_err(|not_run| match not_run {
588            NotRun::Failed { kind, message } => fail(&kind, &message),
589            // Started already: what can't run now fails.
590            NotRun::Rejected { detail, .. } => fail(DAG_FILE_MISSING, &detail),
591        })?;
592        let short = too_short_lines(&secrets, self.secrets.min_mask_length);
593        append_log(&self.setup.log_file(&spec.attempt_id), &short).await;
594        Ok(Arc::new(secrets))
595    }
596
597    /// The cleanup of an attempt an earlier agent left: with its kept code (a missing copy is
598    /// a failed cleanup) and its secrets fetched again.
599    async fn kept_cleanup(
600        &self,
601        spec: &mut AttemptSpec,
602        handles: Vec<CleanupHandle>,
603        spawned: &Spawned,
604    ) -> pb::CleanupResult {
605        let failed = |kind: &str, summary: Vec<u8>| pb::CleanupResult {
606            status: pb::CleanupStatus::Failed.into(),
607            error_kind: kind.to_owned(),
608            error_summary_json: summary,
609            ..pb::CleanupResult::default()
610        };
611        let Some(cleanup) = spec.task.cleanup.clone() else {
612            return pb::CleanupResult {
613                status: pb::CleanupStatus::NotNeeded.into(),
614                ..pb::CleanupResult::default()
615            };
616        };
617        // Only the cleanup runs: what the task itself needed doesn't matter here.
618        use_cleanup_script(&mut spec.task);
619        if let Some(dir) = [&spec.code_dir, &spec.script_dir]
620            .into_iter()
621            .flatten()
622            .find(|dir| !dir.exists())
623        {
624            let message = format!("the attempt's code is gone from `{}`", dir.display());
625            let summary = ErrorSummary::json("CodeGone", &message).into_bytes();
626            return failed(DAG_FILE_MISSING, summary);
627        }
628        let _ = tokio::fs::create_dir_all(&self.setup.log_dir).await;
629        spec.stand_in_secrets();
630        let planned = match &spec.code_dir {
631            Some(dir) => plan_at(spec, &self.setup, dir),
632            None => crate::attempt::plan(spec, &self.setup),
633        };
634        let mut plan = match planned {
635            Ok(plan) => plan,
636            Err(NotRun::Failed { kind, message }) => {
637                return failed(
638                    &kind,
639                    ErrorSummary::json("CleanupNotRun", &message).into_bytes(),
640                );
641            }
642            Err(NotRun::Rejected { detail, .. }) => {
643                let summary = ErrorSummary::json("CleanupNotRun", &detail).into_bytes();
644                return failed(DAG_FILE_MISSING, summary);
645            }
646        };
647        // A slow storage can't hold the slot for ever: this is the cleanup's time.
648        let timeout = cleanup
649            .timeout_ms
650            .map_or(self.setup.timeouts.cleanup, Duration::from_millis);
651        let secrets = match tokio::time::timeout(timeout, self.fetch_secrets(spec, &mut plan)).await
652        {
653            Ok(Ok(secrets)) => secrets,
654            Ok(Err(finished)) => return failed(&finished.error_kind, finished.error_summary_json),
655            Err(_) => {
656                let message = "the cleanup's secrets weren't read within its timeout";
657                let summary = ErrorSummary::json("CleanupNotRun", message).into_bytes();
658                return failed("timed_out", summary);
659            }
660        };
661        let handles = Arc::new(AttemptHandles::restored(handles, Arc::clone(&secrets.mask)));
662        let started = AtomicBool::new(true);
663        let shared = Shared {
664            secrets: &secrets,
665            handles: &handles,
666            started: &started,
667            spawned,
668        };
669        self.run_cleanup(spec, &cleanup, shared).await
670    }
671
672    /// Runs the attempt's cleanup, in a fresh process each try, with the same budget and
673    /// watchdog as the task. Nothing stops it but its own timeout: a cancel doesn't (decision
674    /// 219). The slot stays taken through its tries and delays.
675    async fn run_cleanup(
676        &self,
677        spec: &AttemptSpec,
678        cleanup: &TaskCleanup,
679        shared: Shared<'_>,
680    ) -> pb::CleanupResult {
681        shared.handles.close();
682        let mut spec = spec.clone();
683        spec.task.outcomes = default_outcomes();
684        match (&mut spec.task.kind, &cleanup.run) {
685            (
686                TaskKind::Command {
687                    command, resource, ..
688                },
689                CleanupRun::Command(line),
690            ) => {
691                command.clone_from(line);
692                // A setup's own cleanup (for a setup failing halfway) reports no value.
693                *resource = None;
694            }
695            (TaskKind::Script { .. }, CleanupRun::Script { .. }) => {
696                use_cleanup_script(&mut spec.task);
697            }
698            (TaskKind::Python { .. }, CleanupRun::Python) => {
699                spec.cleanup_handles = Some(shared.handles.list());
700            }
701            // Refused when the DAG is stored; run as it is, it would run the task again.
702            _ => {
703                let message = "the task's cleanup doesn't match its kind";
704                return pb::CleanupResult {
705                    status: pb::CleanupStatus::Failed.into(),
706                    error_kind: "invalid_cleanup".to_owned(),
707                    error_summary_json: ErrorSummary::json("InvalidCleanup", message).into_bytes(),
708                    ..pb::CleanupResult::default()
709                };
710            }
711        }
712        let log = self.setup.log_file(&spec.attempt_id);
713        let timeout = cleanup
714            .timeout_ms
715            .map_or(self.setup.timeouts.cleanup, Duration::from_millis);
716        let mut result = pb::CleanupResult::default();
717        for try_number in 1..=cleanup.retries.saturating_add(1) {
718            if try_number > 1 {
719                tokio::time::sleep(Duration::from_millis(cleanup.retry_delay_ms)).await;
720            }
721            append_log(&log, &format!("cleanup: try {try_number}\n")).await;
722            let planned = match &spec.code_dir {
723                Some(dir) => plan_at(&spec, &self.setup, dir),
724                None => crate::attempt::plan(&spec, &self.setup),
725            };
726            let (_sender, stops) = Stops::new();
727            let mut ended = match planned {
728                Ok(plan) => {
729                    let python = matches!(plan, Plan::Python { .. });
730                    let mut ended = self
731                        .run_planned(&spec, plan, Some(timeout), stops, shared)
732                        .await;
733                    ended_with_secrets(&mut ended, shared.secrets, python);
734                    ended
735                }
736                Err(NotRun::Failed { kind, message }) => {
737                    failed_before_start(&spec.attempt_id, &kind, &message)
738                }
739                Err(NotRun::Rejected { detail, .. }) => {
740                    failed_before_start(&spec.attempt_id, DAG_FILE_MISSING, &detail)
741                }
742            };
743            result.tries = try_number;
744            result.duration_ms += ended.duration_ms.unwrap_or(0);
745            if ended.status == i32::from(pb::AttemptStatus::Success) {
746                result.status = pb::CleanupStatus::Ok.into();
747                result.error_kind.clear();
748                result.error_summary_json.clear();
749                return result;
750            }
751            result.status = pb::CleanupStatus::Failed.into();
752            result.error_kind = std::mem::take(&mut ended.error_kind);
753            result.error_summary_json = std::mem::take(&mut ended.error_summary_json);
754        }
755        result
756    }
757
758    /// Where `spec`'s watchdog records what it sees, and the task counted in the heartbeat's
759    /// memory with it while the second value lives (decision 463).
760    fn watched(&self, spec: &AttemptSpec) -> (SharedSeen, crate::memory::Watched) {
761        let seen = SharedSeen::default();
762        let watched = self.running_memory.watch(
763            schedr_model::usage::TaskMemory {
764                attempt_id: spec.attempt_id.clone(),
765                dag_id: spec.run.dag_id.clone(),
766                run_id: spec.run.run_id.clone(),
767                task_id: spec.task.id.to_string(),
768                map_index: spec.run.map_index,
769                bytes: 0,
770            },
771            seen.clone(),
772        );
773        (seen, watched)
774    }
775
776    /// A command task's context channel: its run, secrets, handles, resource and API.
777    fn command_ctx(
778        &self,
779        spec: &AttemptSpec,
780        (secrets, handles): (&Arc<AttemptSecrets>, &Arc<AttemptHandles>),
781        resource: Option<&Arc<AttemptResource>>,
782    ) -> CtxInfo {
783        let mut ctx = CtxInfo::of(&spec.run, AGENT_VERSION);
784        ctx.max_connections = self.setup.timeouts.task_connections_open;
785        (ctx.secrets, ctx.handles) = (Some(Arc::clone(secrets)), Some(Arc::clone(handles)));
786        ctx.resource = resource.cloned();
787        ctx.api.clone_from(&spec.api);
788        ctx
789    }
790
791    async fn run_planned(
792        &self,
793        spec: &AttemptSpec,
794        plan: Plan,
795        timeout: Option<Duration>,
796        stop: Stops,
797        shared: Shared<'_>,
798    ) -> pb::Finished {
799        let Shared {
800            secrets,
801            handles,
802            started,
803            spawned: shared_spawned,
804        } = shared;
805        let limits = Limits {
806            timeout,
807            grace: spec.cancel_grace,
808            interrupt_grace: self.drain_terminate_period,
809            poll: self.setup.timeouts.stop_poll,
810        };
811        let (seen, _reported) = self.watched(spec);
812        let memory = self.setup.memory.for_task(spec.task.settings.memory_bytes);
813        // The watchdog's kill is one more reason to stop, in the same channel.
814        let oom = stop.sender();
815        // Declared before the watch, so it is dropped after it on any path (locals go in
816        // reverse order), a dropped attempt included.
817        let mut hold = None;
818        let mut watching = None;
819        let spawned = |pid, forked| {
820            started.store(true, Ordering::SeqCst);
821            // The task's process leads its own group; watched from its first moment.
822            watching = Some(watch_group(
823                memory.clone(),
824                pid,
825                seen.clone(),
826                oom,
827                self.metrics.watchdog_kills.clone(),
828                forked,
829            ));
830            match process_identity(pid) {
831                Ok(identity) => shared_spawned(identity, forked),
832                Err(error) => warn_unidentified(pid, &error),
833            }
834        };
835        let resource =
836            AttemptResource::of(&spec.task, &spec.inputs, Arc::clone(&secrets.mask)).map(Arc::new);
837        let python_task = |request| PythonTask {
838            request,
839            secrets: Some(Arc::clone(secrets)),
840            handles: Some(Arc::clone(handles)),
841            events: None,
842            api: spec.api.clone(),
843        };
844        let ran = match plan {
845            // In a process shared with other wait steps: no budget of its own (the host's).
846            Plan::Python { process, request }
847                if matches!(request.task.kind, schedr_model::TaskKind::Sensor { .. }) =>
848            {
849                let mut task = python_task(*request);
850                task.events = spec.trigger.as_ref().map(|(_, sink)| sink.clone());
851                crate::watchers::run_watcher(
852                    &self.watchers,
853                    &self.setup,
854                    &process,
855                    task,
856                    limits,
857                    stop,
858                    |pid| {
859                        started.store(true, Ordering::SeqCst);
860                        match process_identity(pid) {
861                            Ok(identity) => shared_spawned(identity, false),
862                            Err(error) => warn_unidentified(pid, &error),
863                        }
864                    },
865                )
866                .await
867            }
868            Plan::Python { process, request } => {
869                let forks = self.forks.as_ref();
870                let task = python_task(*request);
871                run_python(&process, task, limits, stop, forks, &mut hold, spawned).await
872            }
873            Plan::Command(process) => {
874                let ctx = self.command_ctx(spec, (secrets, handles), resource.as_ref());
875                run_command(&process, Some(ctx), limits, stop, |pid| spawned(pid, false)).await
876            }
877        };
878        // The watchdog stops first; then a forked process's hold goes, and its shim reaps it:
879        // nothing signals its group after that.
880        drop(watching);
881        drop(hold);
882        if let Ok(Ran {
883            start: Some(start),
884            forked,
885            ..
886        }) = &ran
887        {
888            self.metrics
889                .task_started(if *forked { "fork" } else { "spawn" }, start);
890        }
891        let mut finished = match ran {
892            Ok(ran) => finished(&spec.attempt_id, &spec.task, &ran),
893            Err(error) => failed_before_start(&spec.attempt_id, START_FAILED, &error.to_string()),
894        };
895        if let Some(outcome) = resource.as_ref().and_then(|r| r.outcome()) {
896            with_resource_value(&mut finished, outcome);
897        }
898        let seen = *seen.lock().unwrap_or_else(PoisonError::into_inner);
899        with_memory(&mut finished, seen, memory.budget);
900        finished
901    }
902
903    async fn parse_files(
904        &self,
905        root: String,
906        dir: PathBuf,
907        files: Vec<String>,
908        code: ParseCode,
909    ) -> Result<Vec<ParsedFile>, String> {
910        // A library in the root is shipped and hashed, never loaded here (decision 305).
911        let searched = dir.clone();
912        let files =
913            tokio::task::spawn_blocking(move || crate::scan::split_dag_files(&searched, files).0)
914                .await
915                .map_err(|e| e.to_string())?;
916        if files.is_empty() {
917            return Ok(Vec::new());
918        }
919        let _ = tokio::fs::create_dir_all(&self.setup.log_dir).await;
920        let runner = ProcessParseRunner {
921            process: ProcessSpec {
922                program: self.setup.python.clone(),
923                args: vec![
924                    // Not the working directory first: a root's file can't shadow what the runner imports (B178).
925                    "-P".to_owned(),
926                    "-m".to_owned(),
927                    "schedr.runner".to_owned(),
928                    "parse".to_owned(),
929                ],
930                env: self
931                    .setup
932                    .agent_env
933                    .iter()
934                    // As a task's (`PYTHONPATH` changes what imports find).
935                    .filter(|(name, _)| {
936                        crate::env::is_allowed(name) || self.setup.pass_env.contains(name)
937                    })
938                    .map(|(k, v)| (k.clone(), v.clone()))
939                    .collect(),
940                working_dir: dir.clone(),
941                log_file: self.setup.log_dir.join(format!("parse-{root}.log")),
942                max_output_size: 64 * 1024,
943                mask: crate::mask::Mask::default(),
944                start_timeout: self.setup.timeouts.runner_start,
945                output_drain: self.setup.timeouts.output_drain,
946            },
947            memory: self.setup.memory.clone(),
948            kills: self.metrics.watchdog_kills.clone(),
949            forks: self.forks.clone(),
950        };
951        let mut copies = code.roots;
952        copies.insert(root.clone(), dir.clone());
953        let request = ParseRequest {
954            sys_path: self.setup.sys_path_at(&copies),
955            root,
956            root_dir: dir.to_string_lossy().into_owned(),
957            files,
958        };
959        crate::parse::parse_files_with(&runner, request, self.parse, &code.scripts)
960            .await
961            .map_err(|e| e.to_string())
962    }
963}
964
965/// The code an attempt started on, unless it says itself which it ended on: a moved poke
966/// (decision 335).
967fn with_code_hash(finished: &mut pb::Finished, started_on: String) {
968    if finished.code_hash.is_empty() {
969        finished.code_hash = started_on;
970    }
971}
972
973/// Adds what the watchdog saw to an attempt's `Finished`: its peak memory, and for one killed
974/// over its budget the error summary saying so.
975pub fn with_memory(finished: &mut pb::Finished, seen: MemorySeen, budget: Option<u64>) {
976    finished.peak_memory_bytes = seen.peak;
977    if let (Some(used), Some(budget)) = (seen.over, budget)
978        && finished.status == i32::from(pb::AttemptStatus::OomKilled)
979    {
980        finished.error_summary_json =
981            ErrorSummary::json(MEMORY_EXCEPTION, &over_budget_message(budget, used)).into_bytes();
982    }
983}
984
985/// How often the agent's loop beats at least (liveness, see [`Agent::beat`]).
986pub const ALIVE_INTERVAL: Duration = Duration::from_secs(5);
987
988/// The most heartbeats between two sends of an unacknowledged result: the gap doubles from
989/// one (B41), so a long stall of the master queues a few copies of each result, not one a
990/// heartbeat.
991pub const MAX_RESEND_GAP: u32 = 32;
992
993/// The largest running tasks a heartbeat names (decision 463): what a node's panel lists; the
994/// rest are in `tasks_bytes`.
995pub const LARGEST_TASKS: usize = 5;
996
997/// How many times a result is sent again over one session before the agent gives the session
998/// up and reconnects: its registration's journal then settles the result (acknowledged, or
999/// sent again on `Continue`), and no session queues more copies of a result than this.
1000pub const MAX_RESENDS: u32 = 8;
1001
1002/// The exception named in the error summary of an attempt killed over its memory budget.
1003pub const MEMORY_EXCEPTION: &str = "MemoryBudgetExceeded";
1004
1005/// Why a session with the master ended.
1006#[derive(Debug, Clone, PartialEq, Eq)]
1007pub enum SessionEnd {
1008    /// The agent is stopping.
1009    Stopped,
1010    /// The connection failed or the master ended it; connect again.
1011    Lost(String),
1012}
1013
1014/// Something happened in the background.
1015/// The most results kept in the journal as one group (M4B.5): each a thread writing its file
1016/// meanwhile.
1017pub const RESULTS_PER_GROUP: usize = 32;
1018
1019/// The next message from the master: one read ahead while gathering a burst first.
1020async fn next_inbound(
1021    held: &mut Option<Result<Option<pb::MasterMessage>, tonic::Status>>,
1022    inbound: &mut tonic::Streaming<pb::MasterMessage>,
1023) -> Result<Option<pb::MasterMessage>, tonic::Status> {
1024    if let Some(message) = held.take() {
1025        return message;
1026    }
1027    inbound.message().await
1028}
1029
1030/// The most assignments whose journal records are written as one group (M5.1b), as many as
1031/// [`RESULTS_PER_GROUP`] for the same reason: each a thread writing its file meanwhile.
1032pub const STARTS_PER_GROUP: usize = 32;
1033
1034/// An assignment checked and planned, its journal record not yet written.
1035struct Prepared {
1036    assign: pb::AssignTask,
1037    spec: AttemptSpec,
1038    planned: Result<Plan, NotRun>,
1039    external: Option<Vec<u8>>,
1040    received: std::time::Instant,
1041}
1042
1043/// What a group's assignments before this one take (M5.1b): slots not yet counted as
1044/// running, and their IDs.
1045#[derive(Default)]
1046struct Held {
1047    tasks: u32,
1048    wait_steps: u32,
1049    ids: std::collections::HashSet<String>,
1050}
1051
1052impl Held {
1053    fn add(&mut self, prepared: &Prepared) {
1054        self.ids.insert(prepared.assign.attempt_id.clone());
1055        if matches!(prepared.planned, Err(NotRun::Rejected { .. })) {
1056            return;
1057        }
1058        if assigned_a_wait_step(&prepared.assign) {
1059            self.wait_steps += 1;
1060        } else {
1061            self.tasks += 1;
1062        }
1063    }
1064}
1065
1066enum Done {
1067    Spawned {
1068        attempt_id: String,
1069        identity: ProcessIdentity,
1070        forked: bool,
1071    },
1072    /// A task with a cleanup: its process ended and the cleanup starts.
1073    TaskEnded(pb::Finished),
1074    /// A handle was journaled: on to the master.
1075    Handle {
1076        attempt_id: String,
1077        position: u32,
1078        handle: CleanupHandle,
1079    },
1080    Attempt(pb::Finished),
1081    Trigger(TriggerDone),
1082    /// A task's API call: on to the master, its answer to `answer` (M4.11h).
1083    ApiCall {
1084        call: pb::ApiCall,
1085        answer: oneshot::Sender<pb::ApiAnswer>,
1086    },
1087    Parse {
1088        job_id: String,
1089        root: pb::RootHash,
1090        /// The content hashes of the copies it used (kept meanwhile).
1091        copies: Vec<String>,
1092        files: Result<Vec<ParsedFile>, String>,
1093    },
1094    Connections {
1095        job_id: String,
1096        /// The hash whose copy of the code it held.
1097        hash: Option<String>,
1098        /// A test's attempt, recorded in the journal while its process ran.
1099        attempt_id: Option<String>,
1100        reports: Vec<schedr_model::commands::ConnectionReport>,
1101    },
1102}
1103
1104/// An attempt an earlier agent left, its cleanup still to run.
1105#[derive(Debug)]
1106struct WaitingCleanup {
1107    spec: AttemptSpec,
1108    handles: Vec<CleanupHandle>,
1109    /// The task's result; `None`: it was running, and is `lost`.
1110    ended: Option<pb::Finished>,
1111    /// Only the handles the master didn't have (`CLEAN_REST`, B169): its result says so.
1112    rest: bool,
1113}
1114
1115/// How many connections jobs' answers the agent keeps while no master listens.
1116pub const UNSENT_ANSWERS: usize = 16;
1117
1118/// The worker agent.
1119#[derive(Debug)]
1120pub struct Agent<E> {
1121    settings: AgentSettings,
1122    executor: E,
1123    incarnation: String,
1124    journal: Journal,
1125    /// Master time as this session knows it (B225; see [`crate::master_time`]).
1126    master_time: MasterTime,
1127    /// The highest lease epoch a master's message carried, and when one of it was last
1128    /// accepted: a stream from a lower one, a deposed master's, is ended (decision 444),
1129    /// until a lease passes without word from that epoch (a database restored, its epoch
1130    /// set back; that leader has counted this worker lost by then).
1131    leader_epoch: (i64, Option<tokio::time::Instant>),
1132    /// This session's clock-skew warning, once one sample was past the threshold (decision
1133    /// 449); sent beside the executor's.
1134    clock_skew: Option<pb::WorkerWarning>,
1135    /// The master-time cutoff of the session before, kept over a reconnect until the new one
1136    /// has a stamp to count from (Grok's review of D445: `open` forgot it, and the cutoff
1137    /// moved out to the receipt lease).
1138    carried_cutoff: Option<tokio::time::Instant>,
1139    /// When the heartbeat of the last sample master time was read from left, on the boot
1140    /// clock: the sample-age gauge grows from it while no sample is kept (an outage).
1141    sample_sent: Option<Duration>,
1142    /// How long an attempt's first journal write takes (tests: a stalled disk, F14), and how
1143    /// many were delayed so.
1144    #[cfg(test)]
1145    journal_stall: (Duration, Arc<std::sync::atomic::AtomicUsize>),
1146    watchers: BTreeMap<String, RootWatcher>,
1147    /// The triggers running here, on watcher slots: never attempts, so never journaled, and gone
1148    /// with the agent.
1149    triggers: BTreeMap<String, RunningTrigger>,
1150    /// How triggers ended while the master was away: told on the next stream, on which they are
1151    /// still reported as running, or the master would take them as simply gone.
1152    triggers_ended: BTreeMap<String, pb::TriggerStopped>,
1153    /// The attempts running, with the way to stop each (taken once it is asked to stop).
1154    running: BTreeMap<String, StopSender>,
1155    /// The attempts a fork server forked, until their result is acknowledged: each new session
1156    /// is told so again, before a result sent again, as that `Started` may not have reached
1157    /// the master (sent while disconnected, B24).
1158    forked: BTreeSet<String>,
1159    /// Those of them that are wait steps, on watcher slots: whether each is a poke.
1160    wait_steps: BTreeMap<String, bool>,
1161    /// The attempts in their cleanup, with the task's result (sent again on a reconnect).
1162    cleaning: BTreeMap<String, pb::Finished>,
1163    /// Attempts an earlier agent left, whose cleanups wait for the master's `Continue`
1164    /// (decision 248); in `running` too, for their slots.
1165    waiting: BTreeMap<String, WaitingCleanup>,
1166    /// What each running task's cleanup needs of a drain (one try's timeout).
1167    cleanup_room: BTreeMap<String, Duration>,
1168    /// The attempts a drain has stopped.
1169    stopped: std::collections::BTreeSet<String>,
1170    /// The gate of each running attempt with `cleanup_anywhere`.
1171    gates: BTreeMap<String, watch::Sender<Gate>>,
1172    /// The attempts whose cleanup runs on the handles the master didn't have (B169).
1173    rest_cleaning: BTreeSet<String>,
1174    /// When the master was last heard from.
1175    heard: tokio::time::Instant,
1176    /// `heard` plus the lease, for the cleanup gates (see [`Self::publish_deadline`]).
1177    deadline: watch::Sender<Option<tokio::time::Instant>>,
1178    /// The master's worker lease, once it has told it.
1179    lease: Option<Duration>,
1180    /// The tasks with `cleanup_anywhere` were stopped; till the next registration.
1181    cut_off: bool,
1182    /// The tasks warned of a `cleanup_timeout` that doesn't fit the grace period (decision 250).
1183    warned_room: std::collections::BTreeSet<(String, String)>,
1184    unacked: BTreeMap<String, pb::Finished>,
1185    /// Connections jobs' answers made while no master listened, sent once one does (the
1186    /// newest [`UNSENT_ANSWERS`]; the master calls an unanswered job lost in time anyway).
1187    unsent_answers: std::collections::VecDeque<pb::ConnectionJobDone>,
1188    /// Tasks' API calls not answered yet, by request ID: sent again on a new stream (M4.11h).
1189    api_calls: BTreeMap<u64, (pb::ApiCall, oneshot::Sender<pb::ApiAnswer>)>,
1190    /// The last API call's request ID.
1191    api_call_id: u64,
1192    /// The content hash of each started attempt's root when it started (sent in `Finished`).
1193    code_hashes: BTreeMap<String, String>,
1194    /// The content hashes of the other roots' copies a task runs from (its script root, the
1195    /// other DAG roots on its `sys.path`), while it runs (kept meanwhile).
1196    other_copies: BTreeMap<String, Vec<String>>,
1197    /// The script roots each DAG root uses, as the master last said (decision 304).
1198    uses: BTreeMap<String, std::collections::BTreeSet<String>>,
1199    /// Each root's hash as last reported to the master (decisions 301, 303; B167); a root
1200    /// withdrawn, or never reported, isn't in it.
1201    reported: BTreeMap<String, String>,
1202    /// The parse jobs running, by the hash they parse (their copy is kept meanwhile).
1203    parsing: BTreeMap<String, usize>,
1204    /// The roots and hashes being parsed: a job for one of them sent again (the master gives a
1205    /// worker connecting again the jobs it held, B235) isn't started twice; the running parse
1206    /// answers it, the master matching a result by root and hash.
1207    parses_running: BTreeSet<(String, String)>,
1208    /// Held by the connections job running (decision 199: one at a time).
1209    connection_jobs: Arc<tokio::sync::Mutex<()>>,
1210    done_tx: mpsc::UnboundedSender<Done>,
1211    done_rx: mpsc::UnboundedReceiver<Done>,
1212    /// What is wrong with the worker now (the executor's), sent after `Register` and on change.
1213    warnings: watch::Receiver<Vec<pb::WorkerWarning>>,
1214    heartbeat: Duration,
1215    /// Whether the master registered this agent in the current session.
1216    registered: bool,
1217    /// The largest message the master accepts (from `Registered`; gRPC's default before).
1218    master_limit: usize,
1219    /// Shutdown requests so far (none in a session run without [`Agent::run`]).
1220    shutdown: Option<watch::Receiver<u32>>,
1221    /// The drain, once shutdown was asked for.
1222    drain: Option<Drain>,
1223    /// When the agent's event loop last turned (the worker's liveness).
1224    beat: Beat,
1225    metrics: AgentMetrics,
1226}
1227
1228/// A command's connections given as variables (`connections={"DB": warehouse}`, decision
1229/// 184): their files written, their variables merged; two giving one variable are refused.
1230async fn command_connections(
1231    secrets: &AttemptSecrets,
1232    given: &BTreeMap<String, String>,
1233) -> Result<BTreeMap<String, String>, (&'static str, String)> {
1234    let mut variables: BTreeMap<String, String> = BTreeMap::new();
1235    let mut from: BTreeMap<String, &str> = BTreeMap::new();
1236    for (prefix, name) in given {
1237        let more = secrets
1238            .connection_env(name, prefix)
1239            .await
1240            .map_err(|e| (e.kind(), e.to_string()))?;
1241        for (variable, value) in more {
1242            if let Some(other) = from.insert(variable.clone(), prefix) {
1243                return Err((
1244                    crate::attempt::RENDER_FAILED,
1245                    format!(
1246                        "`{variable}` is a variable of the connections given as {other} and as \
1247                         {prefix}: use prefixes that don't start one another"
1248                    ),
1249                ));
1250            }
1251            variables.insert(variable, value);
1252        }
1253    }
1254    Ok(variables)
1255}
1256
1257/// Removes an attempt's connection files; a failure is logged (the next start sweeps them).
1258async fn remove_connection_files(dir: &Path) {
1259    match tokio::fs::remove_dir_all(dir).await {
1260        Ok(()) => {}
1261        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1262        Err(error) => {
1263            tracing::warn!(dir = %dir.display(), %error, "can't remove an attempt's connection files");
1264        }
1265    }
1266}
1267
1268/// Removes the connection files the previous agent's attempts left (decision 190): all
1269/// but those of the processes it couldn't stop.
1270async fn sweep_connection_files(dir: &Path, alive: &std::collections::BTreeSet<String>) {
1271    let mut entries = match tokio::fs::read_dir(dir).await {
1272        Ok(entries) => entries,
1273        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return,
1274        Err(error) => {
1275            tracing::warn!(dir = %dir.display(), %error, "can't read the connection files' folder");
1276            return;
1277        }
1278    };
1279    while let Ok(Some(entry)) = entries.next_entry().await {
1280        let name = entry.file_name().to_string_lossy().into_owned();
1281        if !alive.contains(&name) {
1282            remove_connection_files(&entry.path()).await;
1283        }
1284    }
1285}
1286
1287impl<E: Executor> Agent<E> {
1288    /// An agent with a new incarnation ID.
1289    #[must_use]
1290    pub fn new(settings: AgentSettings, executor: E, incarnation: String) -> Self {
1291        let unacked_kept = settings.setup.timeouts.unacked_messages_kept;
1292        let sample_window = settings.setup.timeouts.master_sample_window;
1293        let watchers = settings
1294            .setup
1295            .roots
1296            .iter()
1297            .chain(&settings.setup.script_roots)
1298            .map(|(name, dir)| {
1299                let store = settings.code_dir.join(code_folder(name));
1300                (
1301                    name.clone(),
1302                    RootWatcher::new(dir, store, settings.settle_time),
1303                )
1304            })
1305            .collect();
1306        let (done_tx, done_rx) = mpsc::unbounded_channel();
1307        let journal = Journal::new(settings.journal_dir.clone());
1308        let warnings = executor.warnings();
1309        Self {
1310            settings,
1311            executor,
1312            master_time: MasterTime::with_window(sample_window).keeping(unacked_kept),
1313            leader_epoch: (0, None),
1314            clock_skew: None,
1315            carried_cutoff: None,
1316            sample_sent: None,
1317            #[cfg(test)]
1318            journal_stall: (Duration::ZERO, Arc::default()),
1319            warnings,
1320            incarnation,
1321            journal,
1322            watchers,
1323            running: BTreeMap::new(),
1324            forked: BTreeSet::new(),
1325            triggers: BTreeMap::new(),
1326            triggers_ended: BTreeMap::new(),
1327            wait_steps: BTreeMap::new(),
1328            cleaning: BTreeMap::new(),
1329            waiting: BTreeMap::new(),
1330            cleanup_room: BTreeMap::new(),
1331            stopped: std::collections::BTreeSet::new(),
1332            gates: BTreeMap::new(),
1333            rest_cleaning: BTreeSet::new(),
1334            heard: tokio::time::Instant::now(),
1335            deadline: watch::channel(None).0,
1336            lease: None,
1337            cut_off: false,
1338            warned_room: std::collections::BTreeSet::new(),
1339            unacked: BTreeMap::new(),
1340            unsent_answers: std::collections::VecDeque::new(),
1341            api_calls: BTreeMap::new(),
1342            api_call_id: first_api_call_id(),
1343            code_hashes: BTreeMap::new(),
1344            other_copies: BTreeMap::new(),
1345            uses: BTreeMap::new(),
1346            reported: BTreeMap::new(),
1347            parsing: BTreeMap::new(),
1348            parses_running: BTreeSet::new(),
1349            connection_jobs: Arc::new(tokio::sync::Mutex::new(())),
1350            done_tx,
1351            done_rx,
1352            heartbeat: Duration::from_secs(10),
1353            registered: false,
1354            master_limit: GRPC_DEFAULT_LIMIT,
1355            shutdown: None,
1356            drain: None,
1357            beat: Beat::default(),
1358            metrics: AgentMetrics::default(),
1359        }
1360        .with_metrics(AgentMetrics::default())
1361    }
1362
1363    /// The agent recording its metrics in `metrics` (registered by the caller).
1364    #[must_use]
1365    pub fn with_metrics(mut self, metrics: AgentMetrics) -> Self {
1366        metrics.slots.set(i64::from(self.settings.slots));
1367        metrics
1368            .watchers
1369            .slots
1370            .set(i64::from(self.settings.watcher_slots));
1371        self.metrics = metrics;
1372        self
1373    }
1374
1375    /// When the agent's event loop last turned: at least every [`ALIVE_INTERVAL`] whether or
1376    /// not the master is reachable (it is the agent's own health).
1377    #[must_use]
1378    pub fn beat(&self) -> Beat {
1379        self.beat.clone()
1380    }
1381
1382    /// The loop is alive: beat, and update the gauges of slots and the journal.
1383    fn alive(&self) {
1384        self.beat.beat();
1385        self.set_slot_gauges();
1386    }
1387
1388    /// The gauges of slots and the journal, as things are now.
1389    fn set_slot_gauges(&self) {
1390        let running = i64::try_from(self.running.len()).unwrap_or(i64::MAX);
1391        let unacked = i64::try_from(self.unacked.len()).unwrap_or(i64::MAX);
1392        self.metrics
1393            .slots_used
1394            .set(i64::try_from(self.tasks_running()).unwrap_or(i64::MAX));
1395        self.metrics
1396            .watchers
1397            .slots_used
1398            .set(i64::try_from(self.wait_steps.len()).unwrap_or(i64::MAX));
1399        self.metrics.journal_records.set(running + unacked);
1400    }
1401
1402    /// The attempts running now.
1403    #[must_use]
1404    pub fn running(&self) -> Vec<String> {
1405        self.running.keys().cloned().collect()
1406    }
1407
1408    /// Runs until drained after a shutdown request (`shutdown` counts them; see
1409    /// [`crate::drain`]): recovers the journal, connects with `connect`, and again whenever
1410    /// the connection drops, after a backoff with jitter that doubles up to [`MAX_BACKOFF`] and
1411    /// starts from [`FIRST_BACKOFF`] again after a session in which the master registered it.
1412    pub async fn run<C, F>(&mut self, connect: C, mut shutdown: watch::Receiver<u32>)
1413    where
1414        C: Fn() -> F,
1415        F: Future<Output = Result<MasterClient<Channel>, String>>,
1416    {
1417        let requested = *shutdown.borrow_and_update();
1418        self.shutdown = Some(shutdown);
1419        self.recover().await;
1420        self.on_shutdown(requested);
1421        let timeouts = self.settings.setup.timeouts;
1422        let mut backoff = timeouts.reconnect_first;
1423        loop {
1424            self.registered = false;
1425            let Some(connected) = self.offline(connect()).await else {
1426                return;
1427            };
1428            let end = match connected {
1429                Ok(client) => self.session(client).await,
1430                Err(error) => SessionEnd::Lost(error),
1431            };
1432            match end {
1433                SessionEnd::Stopped => return,
1434                SessionEnd::Lost(reason) => {
1435                    tracing::warn!(reason, "master connection lost; connecting again");
1436                    self.hold_cleanups();
1437                }
1438            }
1439            if self.registered {
1440                backoff = timeouts.reconnect_first;
1441            }
1442            // The clock's nanoseconds (below 10^9), spread over all of u32 by a
1443            // multiplicative hash, so the jitter covers its whole range.
1444            let seed = std::time::SystemTime::now()
1445                .duration_since(std::time::UNIX_EPOCH)
1446                .map_or(0, |d| d.subsec_nanos())
1447                .wrapping_mul(2_654_435_761);
1448            if self
1449                .offline(tokio::time::sleep(jittered(
1450                    backoff.min(reconnect_cap(timeouts.reconnect_max, self.lease)),
1451                    seed,
1452                )))
1453                .await
1454                .is_none()
1455            {
1456                return;
1457            }
1458            backoff = (backoff * 2).min(reconnect_cap(timeouts.reconnect_max, self.lease));
1459        }
1460    }
1461
1462    /// Waits for `work` without a master: what ends meanwhile is still journalled (results
1463    /// are reported in the next `Register`), and a drain goes on. `None` once drained.
1464    async fn offline<T>(&mut self, work: impl Future<Output = T>) -> Option<T> {
1465        self.waiting_for(work, false).await
1466    }
1467
1468    /// [`Self::offline`] while a session is being opened (`connecting`): a drain then waits for
1469    /// unacknowledged results as in a session, a while, since they are about to be sent again
1470    /// (Grok's review of B151).
1471    async fn waiting_for<T>(
1472        &mut self,
1473        work: impl Future<Output = T>,
1474        connecting: bool,
1475    ) -> Option<T> {
1476        tokio::pin!(work);
1477        let timeouts = self.settings.setup.timeouts;
1478        let mut tick = tokio::time::interval(timeouts.drain_tick);
1479        let mut alive = tokio::time::interval(timeouts.alive);
1480        loop {
1481            let cut_off_at = self.cut_off_at();
1482            tokio::select! {
1483                _ = alive.tick() => self.on_alive(),
1484                () = at(cut_off_at) => self.stop_cut_off(),
1485                out = &mut work => return Some(out),
1486                Some(done) = self.done_rx.recv() => self.on_done_group(done, None, None).await,
1487                count = next_request(&mut self.shutdown) => {
1488                    self.on_shutdown(count);
1489                }
1490                _ = tick.tick(), if self.drain.is_some() => {
1491                    if self.drain_step(connecting) == DrainStep::Finish {
1492                        return None;
1493                    }
1494                }
1495            }
1496        }
1497    }
1498
1499    /// Fetches an attempt's inputs, which can take long, with the session's timers going on:
1500    /// its loop waits for this. A chunk is word from the master, unless it comes past the
1501    /// lease (decision 281). `None` when the master went silent for the lease (on a stream
1502    /// opened at `opened`): the session ends, and nothing is started.
1503    async fn fetch_with_timers(
1504        &mut self,
1505        client: &mut MasterClient<Channel>,
1506        attempt_id: &str,
1507        to_master: &ToMaster,
1508        (heartbeat, opened): (&mut tokio::time::Interval, tokio::time::Instant),
1509    ) -> Option<Result<Vec<u8>, String>> {
1510        let (heard, seen) = watch::channel(self.heard.max(opened));
1511        let fetching = fetch_inputs(client, attempt_id, &heard, self.lease);
1512        tokio::pin!(fetching);
1513        loop {
1514            self.heard = self.heard.max(*seen.borrow());
1515            self.publish_deadline();
1516            let give_up_at = earliest(self.cut_off_at(), self.silent_at(opened));
1517            tokio::select! {
1518                fetched = &mut fetching => {
1519                    return match fetched {
1520                        Fetched::Bytes(bytes) => Some(Ok(bytes)),
1521                        Fetched::Failed(error) => Some(Err(error)),
1522                        Fetched::Silent => {
1523                            self.cut_off_if_late();
1524                            None
1525                        }
1526                    };
1527                }
1528                _ = heartbeat.tick() => {
1529                    self.send_beat(to_master);
1530                    self.send_poke_reports(to_master);
1531                }
1532                () = at(give_up_at) => {
1533                    self.heard = self.heard.max(*seen.borrow());
1534                    if self.silent_too_long(opened) {
1535                        return None;
1536                    }
1537                }
1538            }
1539        }
1540    }
1541
1542    /// Whether this is a `Registered` older than the lease it states: the master may have
1543    /// counted this worker lost since, moved its cleanups and taken back what it assigned
1544    /// with it (decision 281), so its decisions no longer stand; a worker without a lease yet
1545    /// (its first session) included. Asked again, it answers as things are now.
1546    fn answer_too_late(message: &master_message::Message, age: Duration) -> bool {
1547        let master_message::Message::Registered(registered) = message else {
1548            return false;
1549        };
1550        registered.timing.as_ref().is_some_and(|t| {
1551            t.lease_timeout_ms > 0 && age.as_millis() >= u128::from(t.lease_timeout_ms)
1552        })
1553    }
1554
1555    /// The attempts a drain waits for: not a cleanup waiting for the master, with none to
1556    /// ask. The journal keeps it.
1557    fn drain_running(&self) -> usize {
1558        let held = self
1559            .gates
1560            .iter()
1561            .filter(|(id, gate)| *gate.borrow() == Gate::Held && self.cleaning.contains_key(*id))
1562            .count();
1563        self.running
1564            .len()
1565            .saturating_add(self.triggers.len())
1566            .saturating_sub(self.waiting.len().saturating_add(held))
1567    }
1568
1569    /// What the master hears at once on a new stream.
1570    fn send_state(&mut self, to_master: &ToMaster) {
1571        if self.drain.is_some() {
1572            let _ = to_master.send(wrap(worker_message::Message::Draining(pb::Draining {})));
1573        }
1574        // All of them, after every registration: each report replaces the master's record.
1575        self.report_warnings(to_master);
1576    }
1577
1578    /// The executor's warnings and this session's clock-skew one, to the master.
1579    fn report_warnings(&mut self, to_master: &ToMaster) {
1580        let mut warnings = self.warnings.borrow_and_update().clone();
1581        warnings.extend(self.clock_skew.clone());
1582        let _ = to_master.send(wrap(worker_message::Message::Warnings(pb::Warnings {
1583            warnings,
1584        })));
1585    }
1586
1587    /// The `Register` opening a session.
1588    fn register_message(&self, roots: Vec<pb::RootHash>) -> pb::Register {
1589        pb::Register {
1590            worker_id: self.settings.worker_id.clone(),
1591            incarnation_id: self.incarnation.clone(),
1592            protocol: Some(PROTOCOL_VERSION),
1593            schedr_version: AGENT_VERSION.to_owned(),
1594            queues: self.settings.queues.clone(),
1595            slots: self.settings.slots,
1596            watcher_slots: self.settings.watcher_slots,
1597            running_triggers: self
1598                .triggers
1599                .keys()
1600                .chain(self.triggers_ended.keys())
1601                .cloned()
1602                .collect(),
1603            log_endpoint: self.settings.log_endpoint.clone(),
1604            roots,
1605            secret_storages: self.settings.secrets.names(),
1606            journal: self.journal_entries(),
1607            process_id: self.settings.node.process_id.clone(),
1608            config_json: self.settings.node.config_json.clone(),
1609        }
1610    }
1611
1612    /// A task with `cleanup_anywhere` gets a gate before its cleanup.
1613    fn set_gate(&mut self, spec: &mut AttemptSpec) {
1614        if spec.task.cleanup.as_ref().is_some_and(|c| c.anywhere) {
1615            let (gate, passes) = watch::channel(Gate::Open);
1616            self.gates.insert(spec.attempt_id.clone(), gate);
1617            spec.cleanup_gate = Some(CleanupGate {
1618                gate: passes,
1619                deadline: self.deadline.subscribe(),
1620            });
1621        }
1622    }
1623
1624    /// Tells the cleanup gates when the master's word runs out (`heard` plus the lease).
1625    fn publish_deadline(&self) {
1626        let deadline = self.lease_deadline();
1627        self.deadline.send_if_modified(|now| {
1628            let changed = *now != deadline;
1629            *now = deadline;
1630            changed
1631        });
1632    }
1633
1634    /// When the tasks with `cleanup_anywhere` are stopped, with no word from the master: the
1635    /// worker lease after the last, as the master counts it lost (decision 252).
1636    fn cut_off_at(&self) -> Option<tokio::time::Instant> {
1637        if self.cut_off || self.gates.is_empty() {
1638            return None;
1639        }
1640        self.lease_deadline()
1641    }
1642
1643    /// The earlier of the worker lease after the last message received and the moment master
1644    /// time may have passed the last stamp plus the lease (decision 445): a message held on
1645    /// its way moved the receipt later than the master's own count. What the cleanup gates
1646    /// read too (Grok's review: they had only the receipt).
1647    fn lease_deadline(&self) -> Option<tokio::time::Instant> {
1648        let lease = self.lease?;
1649        let received = self.heard + lease;
1650        Some(
1651            self.master_cutoff(lease)
1652                .map_or(received, |at| at.min(received)),
1653        )
1654    }
1655
1656    /// The master-time cutoff: this session's bound, or the one carried over a reconnect.
1657    fn master_cutoff(&self, lease: Duration) -> Option<tokio::time::Instant> {
1658        let now = tokio::time::Instant::now();
1659        let by_master = self
1660            .master_time
1661            .cutoff_in(lease, Local::now())
1662            .map(|wait| now + wait);
1663        match (by_master, self.carried_cutoff) {
1664            (Some(at), Some(carried)) => Some(at.min(carried)),
1665            (at, carried) => at.or(carried),
1666        }
1667    }
1668
1669    /// A session opens: master time starts afresh, the cutoff the last session's stamps set
1670    /// standing until this one's (Grok's review); its opening on the timer clock.
1671    fn open_session(&mut self) -> tokio::time::Instant {
1672        self.carried_cutoff = self.lease.and_then(|lease| self.master_cutoff(lease));
1673        self.clock_skew = None;
1674        self.master_time.open()
1675    }
1676
1677    /// The alive tick's checks: the lease deadline again (a suspend the timer clock didn't
1678    /// count leaves a timer late, Grok's review), the cutoff if due, the sample's age.
1679    fn on_alive(&mut self) {
1680        self.alive();
1681        self.publish_master_reading();
1682        self.publish_deadline();
1683        self.cut_off_if_late();
1684    }
1685
1686    /// When a stream opened at `opened` is given up with no word from the master, whatever
1687    /// runs: the lease after the master's last word, or after the stream opened. An assignment
1688    /// held on its way (a one-way cut) is then never started after the master took it back
1689    /// at the lease (decision 281, B163).
1690    fn silent_at(&self, opened: tokio::time::Instant) -> Option<tokio::time::Instant> {
1691        self.lease.map(|lease| self.heard.max(opened) + lease)
1692    }
1693
1694    /// Whether a stream opened at `opened` has been silent for the lease
1695    /// ([`Self::silent_at`]); past the lease the tasks are cut off ([`Self::cut_off_if_late`]).
1696    fn silent_too_long(&mut self, opened: tokio::time::Instant) -> bool {
1697        let silent = self.gone_silent(opened);
1698        self.cut_off_if_late() || silent
1699    }
1700
1701    /// Whether the lease has run out with no word from the master ([`Self::silent_at`]).
1702    fn gone_silent(&self, opened: tokio::time::Instant) -> bool {
1703        self.silent_at(opened)
1704            .is_some_and(|at| at <= tokio::time::Instant::now())
1705    }
1706
1707    /// Cuts the tasks off ([`Self::stop_cut_off`]) if the lease has run out since the master's
1708    /// last word; whether it had.
1709    fn cut_off_if_late(&mut self) -> bool {
1710        let late = self
1711            .cut_off_at()
1712            .is_some_and(|at| at <= tokio::time::Instant::now());
1713        if late {
1714            self.stop_cut_off();
1715        }
1716        late
1717    }
1718
1719    /// Stops the tasks whose cleanup may move: it mustn't run during them. Their cleanups wait
1720    /// for the master's answer.
1721    fn stop_cut_off(&mut self) {
1722        self.cut_off = true;
1723        self.hold_cleanups();
1724        // Its bookmark is the master's: one elsewhere takes over from there.
1725        for trigger in self.triggers.values() {
1726            let _ = trigger.stop.send(StopReason::CutOff);
1727        }
1728        for id in self.gates.keys() {
1729            if !self.cleaning.contains_key(id)
1730                && let Some(stop) = self.running.get(id)
1731            {
1732                tracing::warn!(
1733                    attempt_id = id,
1734                    "no word from the master: stopping the task"
1735                );
1736                let _ = stop.send(StopReason::CutOff);
1737            }
1738        }
1739    }
1740
1741    /// With no master to ask, a cleanup with `cleanup_anywhere` doesn't start here: it may be
1742    /// moved (decision 254). One under way goes on (decision 255).
1743    fn hold_cleanups(&self) {
1744        for gate in self.gates.values() {
1745            gate.send_if_modified(|gate| {
1746                let open = *gate == Gate::Open;
1747                if open {
1748                    *gate = Gate::Held;
1749                }
1750                open
1751            });
1752        }
1753    }
1754
1755    /// A shutdown request arrived (`count` so far): the first starts the drain, a later one
1756    /// interrupts at once. Returns whether the drain just started.
1757    fn on_shutdown(&mut self, count: u32) -> bool {
1758        let now = Instant::now();
1759        if let Some(drain) = &mut self.drain {
1760            drain.force(now);
1761            tracing::warn!("asked to stop again: interrupting the running tasks");
1762            return false;
1763        }
1764        if count == 0 {
1765            return false;
1766        }
1767        let mut drain = Drain::new(now, self.settings.drain);
1768        if count > 1 {
1769            drain.force(now);
1770        }
1771        self.drain = Some(drain);
1772        tracing::info!(
1773            running = self.running.len(),
1774            grace = ?self.settings.drain.grace,
1775            "draining: no new tasks; the running ones get until the grace period ends"
1776        );
1777        true
1778    }
1779
1780    /// The drain's next step; stops the attempts still running when their time is up.
1781    fn drain_step(&mut self, connected: bool) -> DrainStep {
1782        let running = self.drain_running();
1783        let Some(drain) = &mut self.drain else {
1784            return DrainStep::Wait;
1785        };
1786        let now = Instant::now();
1787        let step = drain.step(now, running, self.unacked.len(), connected);
1788        // As a poke, they run on elsewhere, losing nothing.
1789        for trigger in self.triggers.values() {
1790            let _ = trigger.stop.send(StopReason::Interrupted);
1791        }
1792        // Each early enough for one try of its cleanup; one in its cleanup isn't stopped. Also
1793        // those already being stopped (cancelled, timed out): their SIGKILL comes no later than
1794        // the drain's (B9).
1795        for (id, stop) in &self.running {
1796            let room = self.cleanup_room.get(id).copied().unwrap_or_default();
1797            // A poke goes at once: it runs on elsewhere, losing nothing (decision 335).
1798            let poke = self.wait_steps.get(id).copied().unwrap_or(false);
1799            if !self.cleaning.contains_key(id)
1800                && (poke || drain.stop_due(now, room))
1801                && self.stopped.insert(id.clone())
1802            {
1803                let _ = stop.send(StopReason::Interrupted);
1804            }
1805        }
1806        if step == DrainStep::Interrupt {
1807            tracing::warn!(
1808                running = self.running.len(),
1809                "the grace period is ending: interrupting the running tasks"
1810            );
1811        }
1812        step
1813    }
1814
1815    /// Takes over from a previous incarnation: its unacknowledged results are reported again,
1816    /// and the processes it left running are stopped and their attempts forgotten (the master
1817    /// ends them `lost`). A journal that can't be read is logged; assignments are then
1818    /// rejected until it can be written.
1819    pub async fn recover(&mut self) {
1820        let journal = self.journal.clone();
1821        let records = match tokio::task::spawn_blocking(move || journal.recover()).await {
1822            Ok(Ok(records)) => records,
1823            Ok(Err(error)) => {
1824                tracing::error!(dir = %self.journal.dir().display(), %error, "can't read the journal");
1825                return;
1826            }
1827            Err(error) => {
1828                tracing::error!(%error, "reading the journal failed");
1829                return;
1830            }
1831        };
1832        let mut orphans = tokio::task::JoinSet::new();
1833        let mut ended = BTreeMap::new();
1834        for (attempt_id, record) in records {
1835            let process = match record {
1836                JournalRecord::Finished(finished) => {
1837                    self.unacked.insert(attempt_id, finished);
1838                    continue;
1839                }
1840                JournalRecord::Running(process) => process,
1841                JournalRecord::Cleaning(finished, process) => {
1842                    ended.insert(attempt_id.clone(), finished);
1843                    process
1844                }
1845            };
1846            let timeouts = self.settings.setup.timeouts;
1847            orphans.spawn(async move {
1848                let Some(identity) = process else {
1849                    return Ok(attempt_id);
1850                };
1851                match stop_orphan(identity, timeouts.orphan_grace, timeouts.orphan).await {
1852                    Ok(Orphan::Gone) => {}
1853                    Ok(how) => tracing::warn!(
1854                        attempt_id,
1855                        pgid = identity.pgid,
1856                        ?how,
1857                        "stopped a task process left by the previous agent"
1858                    ),
1859                    Err(error) => {
1860                        // Kept in the journal: the next start tries again.
1861                        tracing::error!(
1862                            attempt_id,
1863                            pgid = identity.pgid,
1864                            %error,
1865                            "can't stop a task process left by the previous agent"
1866                        );
1867                        return Err(attempt_id);
1868                    }
1869                }
1870                Ok(attempt_id)
1871            });
1872        }
1873        let mut alive = std::collections::BTreeSet::new();
1874        while let Some(stopped) = orphans.join_next().await {
1875            match stopped {
1876                Ok(Ok(attempt_id)) => {
1877                    let ended = ended.remove(&attempt_id);
1878                    if !self.wait_for_cleanup(&attempt_id, ended).await {
1879                        self.forget(&attempt_id).await;
1880                    }
1881                }
1882                Ok(Err(attempt_id)) => {
1883                    alive.insert(attempt_id);
1884                }
1885                Err(_) => {}
1886            }
1887        }
1888        sweep_connection_files(&self.settings.setup.connection_dir, &alive).await;
1889    }
1890
1891    /// Sets aside the cleanup of an attempt the previous agent left, if the journal kept what
1892    /// it needs: it runs on the master's `Continue` (decision 248). Returns whether it did.
1893    async fn wait_for_cleanup(&mut self, attempt_id: &str, ended: Option<pb::Finished>) -> bool {
1894        let journal = self.journal.clone();
1895        let id = attempt_id.to_owned();
1896        let read = tokio::task::spawn_blocking(move || {
1897            Ok::<_, std::io::Error>((journal.kept(&id)?, journal.handles(&id)?))
1898        })
1899        .await;
1900        let (kept, journaled) = match read {
1901            Ok(Ok((Some(kept), handles))) => (kept, handles),
1902            Ok(Ok((None, _))) => return false,
1903            // Run without what it needs, it could report success and leave them behind: the
1904            // master ends its cleanup as not run, which fails the run.
1905            Ok(Err(error)) => {
1906                tracing::error!(attempt_id, %error, "can't read a kept attempt; no cleanup here");
1907                return false;
1908            }
1909            Err(error) => {
1910                tracing::error!(attempt_id, %error, "reading a kept attempt failed");
1911                return false;
1912            }
1913        };
1914        // A moved cleanup's handles came in its assignment, kept whole before it started.
1915        let handles = match kept.assign.cleanup_only.as_ref().map(moved_handles) {
1916            None => journaled,
1917            Some(Ok(handles)) => handles,
1918            Some(Err(error)) => {
1919                tracing::error!(attempt_id, %error, "a moved cleanup's handles don't read");
1920                return false;
1921            }
1922        };
1923        let mut spec = match AttemptSpec::from_assign(&kept.assign, None) {
1924            Ok(spec) if spec.task.cleanup.is_some() => spec,
1925            Ok(_) => return false,
1926            Err(error) => {
1927                tracing::warn!(attempt_id, %error, "can't read a kept attempt; its cleanup is lost");
1928                return false;
1929            }
1930        };
1931        spec.code_dir = kept.code_dir;
1932        spec.root_copies = kept.root_copies;
1933        spec.script_dir = kept.script_dir;
1934        if let Some(hash) = kept.code_hash {
1935            self.code_hashes.insert(attempt_id.to_owned(), hash);
1936        }
1937        self.remember_other_copies(&spec);
1938        let (stop, _) = Stops::new();
1939        self.running.insert(attempt_id.to_owned(), stop);
1940        let waiting = WaitingCleanup {
1941            spec,
1942            handles,
1943            ended,
1944            rest: false,
1945        };
1946        self.waiting.insert(attempt_id.to_owned(), waiting);
1947        true
1948    }
1949
1950    /// The master said `Continue`: a cleanup the previous agent left starts; the task's end is
1951    /// reported first (`lost`, if it hadn't ended).
1952    async fn start_waiting(
1953        &mut self,
1954        attempt_id: &str,
1955        waiting: WaitingCleanup,
1956        to_master: &ToMaster,
1957    ) {
1958        let ended = waiting.ended.unwrap_or_else(|| restarted(attempt_id));
1959        let done = self.done_tx.clone();
1960        let on_spawn = self.done_tx.clone();
1961        let id = attempt_id.to_owned();
1962        let spawned: Spawned = Arc::new(move |identity, forked| {
1963            let _ = on_spawn.send(Done::Spawned {
1964                attempt_id: id.clone(),
1965                identity,
1966                forked,
1967            });
1968        });
1969        self.task_ended(ended.clone(), Some(to_master)).await;
1970        let executor = self.executor.clone();
1971        let (spec, handles, rest) = (waiting.spec, waiting.handles, waiting.rest);
1972        tokio::spawn(async move {
1973            let mut finished = executor.cleanup(spec, ended, handles, spawned).await;
1974            if let Some(cleanup) = finished.cleanup.as_mut() {
1975                cleanup.rest = rest;
1976            }
1977            let _ = done.send(Done::Attempt(finished));
1978        });
1979    }
1980
1981    /// A task with a cleanup ended: on disk, then reported.
1982    async fn task_ended(&mut self, mut finished: pb::Finished, to_master: Option<&ToMaster>) {
1983        fit_result(&mut finished, self.master_limit);
1984        // A moved poke says itself which code it ended on (decision 335).
1985        if let (true, Some(hash)) = (
1986            finished.code_hash.is_empty(),
1987            self.code_hashes.get(&finished.attempt_id),
1988        ) {
1989            finished.code_hash.clone_from(hash);
1990        }
1991        let id = finished.attempt_id.clone();
1992        self.cleanup_room.remove(&id);
1993        let record = JournalRecord::Cleaning(finished.clone(), None);
1994        if let Err(error) = self.record(&id, record).await {
1995            tracing::warn!(attempt_id = id, %error, "can't record the task's end");
1996        }
1997        self.cleaning.insert(id, finished.clone());
1998        if let Some(to_master) = to_master {
1999            let _ = to_master.send(task_ended_message(finished));
2000        }
2001    }
2002
2003    /// Records `record` for an attempt in the journal.
2004    async fn record(&self, attempt_id: &str, record: JournalRecord) -> std::io::Result<()> {
2005        let journal = self.journal.clone();
2006        let attempt_id = attempt_id.to_owned();
2007        tokio::task::spawn_blocking(move || journal.write(&attempt_id, &record))
2008            .await
2009            .map_err(std::io::Error::other)?
2010    }
2011
2012    /// A result the master has: no longer kept, the journal's gauge down by it.
2013    async fn acknowledged(&mut self, attempt_id: &str) {
2014        if self.unacked.remove(attempt_id).is_some() {
2015            self.forget(attempt_id).await;
2016            self.set_slot_gauges();
2017        }
2018    }
2019
2020    /// Removes an attempt from the journal; a failure is logged (the file is then reported
2021    /// again after a restart, and the master decides on it).
2022    async fn forget(&self, attempt_id: &str) {
2023        let journal = self.journal.clone();
2024        let id = attempt_id.to_owned();
2025        let removed = tokio::task::spawn_blocking(move || journal.remove(&id))
2026            .await
2027            .map_err(std::io::Error::other)
2028            .and_then(|removed| removed);
2029        if let Err(error) = removed {
2030            tracing::warn!(attempt_id, %error, "can't remove the attempt from the journal");
2031        }
2032    }
2033
2034    /// The roots' reported hashes, waiting for each to settle the first time; a DAG root
2035    /// using a script root this worker lacks is left out (decision 303).
2036    /// The session's stream to the master opened, `outbound` its messages; the session's end
2037    /// if it doesn't open: given up at the cutoff or a lease of silence, or stopped. Through
2038    /// [`Self::offline`]: a stop asked for meanwhile is heard, and a drain that finishes ends
2039    /// the wait (B151).
2040    async fn open_stream(
2041        &mut self,
2042        client: &mut MasterClient<Channel>,
2043        outbound: mpsc::UnboundedReceiver<pb::WorkerMessage>,
2044        opened: tokio::time::Instant,
2045    ) -> Result<tonic::Streaming<pb::MasterMessage>, SessionEnd> {
2046        let give_up_at = earliest(self.cut_off_at(), self.silent_at(opened));
2047        let opening = async {
2048            tokio::select! {
2049                control = client.control(UnboundedReceiverStream::new(outbound)) => Some(control),
2050                () = at(give_up_at) => None,
2051            }
2052        };
2053        match self.waiting_for(opening, true).await {
2054            None => Err(SessionEnd::Stopped),
2055            Some(Some(Ok(response))) => Ok(response.into_inner()),
2056            Some(Some(Err(status))) => Err(SessionEnd::Lost(status.to_string())),
2057            Some(None) => {
2058                self.cut_off_if_late();
2059                Err(SessionEnd::Lost(NO_WORD.to_owned()))
2060            }
2061        }
2062    }
2063
2064    /// The roots' hashes once each has settled; `None` once a drain finished meanwhile: the
2065    /// waits go through [`Self::offline`], so a root that never settles doesn't hold a stop
2066    /// (B151).
2067    async fn hashes(&mut self) -> Option<Vec<pb::RootHash>> {
2068        let names: Vec<String> = self.watchers.keys().cloned().collect();
2069        for name in names {
2070            while let Some(watcher) = self.watchers.get_mut(&name) {
2071                if watcher.hash().is_some() {
2072                    break;
2073                }
2074                let wait = match watcher.poll(Instant::now()) {
2075                    Ok(Poll::Settling(wait)) => Some(wait),
2076                    Ok(_) => None,
2077                    Err(error) => {
2078                        tracing::warn!(root = name.as_str(), %error, "can't scan the root");
2079                        Some(self.settings.poll_interval)
2080                    }
2081                };
2082                if let Some(wait) = wait
2083                    && self
2084                        .waiting_for(tokio::time::sleep(wait), true)
2085                        .await
2086                        .is_none()
2087                {
2088                    return None;
2089                }
2090            }
2091        }
2092        self.reported = self
2093            .watchers
2094            .keys()
2095            .filter_map(|name| Some((name.clone(), self.reported_hash(name)?)))
2096            .collect();
2097        Some(
2098            self.reported
2099                .iter()
2100                .map(|(name, hash)| root_hash(&self.settings.setup, name, hash))
2101                .collect(),
2102        )
2103    }
2104
2105    /// The hash this worker reports for root `name`, `None` before its first scan or for a
2106    /// DAG root it can't offer (decision 303). A script root's is its content hash marked as
2107    /// a script root's, so a parse of the same files as a DAG root never counts for it
2108    /// (B167); a DAG root's folds in the reported hashes of the script roots it uses (decision
2109    /// 301) and the content hashes of the other DAG roots, all on its `sys.path` (decision 327,
2110    /// B173), so a change to any of them is new code for it.
2111    fn reported_hash(&self, name: &str) -> Option<String> {
2112        let content = self.watchers.get(name)?.hash()?;
2113        let scripts = &self.settings.setup.script_roots;
2114        if scripts.contains_key(name) {
2115            return Some(fold_hash("script", content, &[]));
2116        }
2117        let mut folded = Vec::new();
2118        // Their content hashes, not their reported ones: DAG roots can import each other.
2119        for other in self
2120            .settings
2121            .setup
2122            .roots
2123            .keys()
2124            .filter(|other| *other != name)
2125        {
2126            let hash = self.watchers.get(other)?.hash()?;
2127            folded.push((format!("dag:{other}"), hash.to_owned()));
2128        }
2129        for script in self.uses.get(name).into_iter().flatten() {
2130            if !scripts.contains_key(script) {
2131                return None;
2132            }
2133            folded.push((script.clone(), self.reported_hash(script)?));
2134        }
2135        if folded.is_empty() {
2136            return Some(content.to_owned());
2137        }
2138        Some(fold_hash("dag", content, &folded))
2139    }
2140
2141    /// Reports each root whose hash changed since it was last reported: a new hash, or an
2142    /// empty one for a root withdrawn (decision 303).
2143    fn report_changes(&mut self, to_master: &ToMaster) {
2144        self.executor.code_changed(
2145            self.watchers
2146                .iter()
2147                .filter(|(name, _)| !self.settings.setup.script_roots.contains_key(*name))
2148                .filter_map(|(name, watcher)| {
2149                    Some((name.clone(), watcher.code_dir()?.to_path_buf()))
2150                })
2151                .collect(),
2152        );
2153        let names: Vec<String> = self.watchers.keys().cloned().collect();
2154        for name in names {
2155            let now = self.reported_hash(&name);
2156            if now.as_ref() == self.reported.get(&name) {
2157                continue;
2158            }
2159            if now.is_none() {
2160                let missing: Vec<&str> = self
2161                    .uses
2162                    .get(&name)
2163                    .into_iter()
2164                    .flatten()
2165                    .filter(|script| !self.settings.setup.script_roots.contains_key(*script))
2166                    .map(String::as_str)
2167                    .collect();
2168                tracing::warn!(
2169                    root = name.as_str(),
2170                    missing = missing.join(", "),
2171                    "DAG root withdrawn: its DAGs use script roots this worker doesn't have"
2172                );
2173            }
2174            let hash = now.clone().unwrap_or_default();
2175            match now {
2176                Some(hash) => self.reported.insert(name.clone(), hash),
2177                None => self.reported.remove(&name),
2178            };
2179            let changed = worker_message::Message::CodeVersionChanged(pb::CodeVersionChanged {
2180                root: Some(root_hash(&self.settings.setup, &name, &hash)),
2181            });
2182            let _ = to_master.send(wrap(changed));
2183        }
2184    }
2185
2186    /// The master said which script roots each DAG root uses (decision 304).
2187    fn set_uses(&mut self, roots: Vec<pb::RootUses>, to_master: &ToMaster) {
2188        self.uses = roots
2189            .into_iter()
2190            .map(|uses| (uses.root, uses.script_roots.into_iter().collect()))
2191            .collect();
2192        self.report_changes(to_master);
2193    }
2194
2195    /// One session with the master: register, then handle messages until the connection ends.
2196    pub async fn session(&mut self, mut client: MasterClient<Channel>) -> SessionEnd {
2197        let Some(roots) = self.hashes().await else {
2198            return SessionEnd::Stopped;
2199        };
2200        // Unbounded: the loop never waits on the master (its liveness is the agent's own); the
2201        // messages are few and small (heartbeats, results, reports).
2202        let (sender, outbound) = mpsc::unbounded_channel::<pb::WorkerMessage>();
2203        // The session's numbering starts with its `Register`, 0 (B240).
2204        let opened = self.open_session();
2205        let to_master = ToMaster::new(sender, self.master_time.outbox());
2206        let register = self.register_message(roots);
2207        if to_master
2208            .send(wrap(worker_message::Message::Register(register)))
2209            .is_err()
2210        {
2211            return SessionEnd::Lost("the outbound stream closed".to_owned());
2212        }
2213        let mut inbound = match self.open_stream(&mut client, outbound, opened).await {
2214            Ok(inbound) => inbound,
2215            Err(end) => return end,
2216        };
2217        self.send_state(&to_master);
2218        let mut warnings_open = true;
2219        let mut heartbeat = heartbeat_timer(self.heartbeat);
2220        let mut watch = tokio::time::interval(self.settings.poll_interval);
2221        let timeouts = self.settings.setup.timeouts;
2222        let mut tick = tokio::time::interval(timeouts.drain_tick);
2223        let mut alive = tokio::time::interval(timeouts.alive);
2224        // The unacknowledged results' resends (B41: the master failed to store one and kept
2225        // the stream).
2226        let mut resends = Resends::limited(timeouts.result_resends, timeouts.result_resend_gap_max);
2227        // A message read while gathering a burst of assignments, not one of them: handled
2228        // next, in its turn (M5.1b).
2229        let mut held_message = None;
2230        loop {
2231            let give_up_at = earliest(self.cut_off_at(), self.silent_at(opened));
2232            tokio::select! {
2233                () = at(give_up_at) => {
2234                    self.cut_off_if_late();
2235                    return SessionEnd::Lost(NO_WORD.to_owned());
2236                }
2237                count = next_request(&mut self.shutdown) => {
2238                    if self.on_shutdown(count) {
2239                        let draining = worker_message::Message::Draining(pb::Draining {});
2240                        let _ = to_master.send(wrap(draining));
2241                    }
2242                }
2243                _ = tick.tick(), if self.drain.is_some() => {
2244                    if self.drain_step(true) == DrainStep::Finish {
2245                        let bye = worker_message::Message::Deregister(pb::Deregister {});
2246                        let _ = to_master.send(wrap(bye));
2247                        // Our side ends; the master's ends once it has handled everything
2248                        // (not waited for past the end of the grace period).
2249                        drop(to_master);
2250                        let left = self.drain.map_or(timeouts.deregister, |drain| {
2251                            drain.deregister_by().saturating_duration_since(Instant::now())
2252                        });
2253                        let _ = tokio::time::timeout(timeouts.deregister.min(left), async {
2254                            while let Ok(Some(_)) = inbound.message().await {}
2255                        })
2256                        .await;
2257                        return SessionEnd::Stopped;
2258                    }
2259                }
2260                message = next_inbound(&mut held_message, &mut inbound) => match message {
2261                    Ok(Some(pb::MasterMessage { message: Some(message), clock })) => {
2262                        if let Err(end) = self.take_in(&message, clock.as_ref(), opened, &to_master) {
2263                            return end;
2264                        }
2265                        let link = (&to_master, &mut client, (&mut heartbeat, opened));
2266                        let handled =
2267                            Box::pin(self.handle_inbound(message, clock.as_ref(), &mut inbound, &mut held_message, link));
2268                        if let Err(end) = handled.await {
2269                            return end;
2270                        }
2271                        // Past the lease while handling it (a slow fetch of inputs).
2272                        if self.cut_off || self.gone_silent(opened) {
2273                            return SessionEnd::Lost(NO_WORD.to_owned());
2274                        }
2275                    }
2276                    Ok(Some(_)) => {}
2277                    Ok(None) => return SessionEnd::Lost("the master ended the stream".to_owned()),
2278                    Err(status) => return SessionEnd::Lost(status.to_string()),
2279                },
2280                Some(done) = self.done_rx.recv() => {
2281                    self.on_done_group(done, Some(&to_master), Some(&mut client)).await;
2282                }
2283                _ = heartbeat.tick() => {
2284                    if let Some(end) = self.send_heartbeat(&mut resends, &to_master) {
2285                        return end;
2286                    }
2287                }
2288                _ = watch.tick() => self.watch(&to_master),
2289                _ = alive.tick() => self.on_alive(),
2290                changed = self.warnings.changed(), if warnings_open => {
2291                    if changed.is_ok() {
2292                        self.report_warnings(&to_master);
2293                    } else {
2294                        // No one reports any more: nothing will change.
2295                        warnings_open = false;
2296                    }
2297                }
2298            }
2299        }
2300    }
2301
2302    /// Why a message ends the session before anything of it counts: a `Registered` past its
2303    /// lease ([`Self::answer_too_late`]), or a deposed master's ([`Self::older_leader`]).
2304    fn refused(
2305        &mut self,
2306        message: &master_message::Message,
2307        clock: Option<&pb::MasterClock>,
2308        opened: tokio::time::Instant,
2309    ) -> Option<String> {
2310        if Self::answer_too_late(message, opened.elapsed()) {
2311            return Some(TOO_LATE.to_owned());
2312        }
2313        self.older_leader(clock)
2314    }
2315
2316    /// Why a message stamped `clock` is a deposed master's: its lease epoch is lower than one
2317    /// seen before (decision 444), and nothing of it counts; `None` otherwise, the highest
2318    /// epoch noted.
2319    fn older_leader(&mut self, clock: Option<&pb::MasterClock>) -> Option<String> {
2320        let epoch = clock?.lease_epoch;
2321        let (highest, heard) = self.leader_epoch;
2322        let now = tokio::time::Instant::now();
2323        if epoch < highest {
2324            let fenced = match (heard, self.lease) {
2325                (Some(heard), Some(lease)) => now.duration_since(heard) < lease,
2326                _ => true,
2327            };
2328            if fenced {
2329                self.metrics.older_epoch.inc();
2330                return Some(format!(
2331                    "a master leading with lease epoch {epoch}, after epoch {highest}: deposed, \
2332                     connecting again"
2333                ));
2334            }
2335            tracing::warn!(
2336                epoch,
2337                highest,
2338                "a master with a lower lease epoch, and none of epoch {highest} for a lease: \
2339                 its database was restored or replaced; following it"
2340            );
2341        }
2342        self.leader_epoch = (epoch, Some(now));
2343        None
2344    }
2345
2346    /// A master message arrived on the live stream: the master's word, and its clock read
2347    /// (B225).
2348    fn heard_master(&mut self, clock: Option<&pb::MasterClock>, to_master: &ToMaster) {
2349        self.heard = tokio::time::Instant::now();
2350        let skew = clock.and_then(|clock| self.master_time.heard(clock, Local::now()));
2351        if self
2352            .lease
2353            .is_some_and(|lease| self.master_time.cutoff_in(lease, Local::now()).is_some())
2354        {
2355            self.carried_cutoff = None;
2356        }
2357        self.publish_deadline();
2358        self.publish_master_reading();
2359        let threshold = self.settings.setup.timeouts.clock_skew_warning;
2360        if let Some(skew) = skew
2361            && skew > threshold
2362            && self.clock_skew.is_none()
2363        {
2364            // Once a session: wall clocks are for people (cron times, logs), never a deadline.
2365            tracing::warn!(
2366                skew_ms = skew.as_millis(),
2367                "this worker's wall clock differs from the master's beyond the round trip"
2368            );
2369            self.clock_skew = Some(pb::WorkerWarning {
2370                kind: "clock_skew".to_owned(),
2371                interpreter: String::new(),
2372                message: format!(
2373                    "this worker's wall clock differs from the master's by {:.1} s beyond the \
2374                     round trip: times it shows and logs are off by that much (sync its clock)",
2375                    skew.as_secs_f64()
2376                ),
2377            });
2378            self.report_warnings(to_master);
2379        }
2380    }
2381
2382    /// The age and round trip of the sample master time is read from, as gauges (decision 448).
2383    fn publish_master_reading(&mut self) {
2384        let now = Local::now();
2385        if let Some(reading) = self.master_time.reading(now) {
2386            self.sample_sent = Some(now.boot.saturating_sub(reading.age));
2387            self.metrics
2388                .master_round_trip
2389                .set(reading.round_trip.as_secs_f64());
2390        }
2391        // With no sample kept (between sessions), the age grows from the last one's.
2392        if let Some(sent) = self.sample_sent {
2393            self.metrics
2394                .master_sample_age
2395                .set(now.boot.saturating_sub(sent).as_secs_f64());
2396        }
2397    }
2398
2399    /// Sends a heartbeat (numbered, as every message, by the session's sender, B225, B240).
2400    fn send_beat(&mut self, to_master: &ToMaster) {
2401        self.publish_master_reading();
2402        let _ = to_master.send(self.heartbeat_message());
2403    }
2404
2405    /// A heartbeat, and the unacknowledged results due to be sent again; the session's end
2406    /// if one was sent too often already.
2407    fn heartbeat_message(&self) -> pb::WorkerMessage {
2408        let watcher_hosts = self.executor.watcher_hosts();
2409        let usage = self.usage(&watcher_hosts);
2410        wrap(worker_message::Message::Heartbeat(pb::Heartbeat {
2411            free_slots: self.free_slots(),
2412            free_watcher_slots: self.free_watcher_slots(),
2413            running_attempt_ids: self.running(),
2414            running_triggers: self.triggers.keys().cloned().collect(),
2415            watcher_hosts,
2416            usage,
2417        }))
2418    }
2419
2420    /// What the worker uses, by part (decision 463); none without `/proc`.
2421    fn usage(&self, watcher_hosts: &[pb::WatcherHost]) -> Option<pb::WorkerUsage> {
2422        let node = crate::memory::this_node()?;
2423        let (fork_servers_bytes, tasks) = self.executor.memory_parts();
2424        Some(pb::WorkerUsage {
2425            process: Some(pb::NodeUsage {
2426                resident_bytes: node.resident_bytes,
2427                cpu_seconds: node.cpu_seconds,
2428                container_bytes: node.container_bytes,
2429                container_limit_bytes: node.container_limit_bytes,
2430            }),
2431            fork_servers_bytes,
2432            watcher_hosts_bytes: watcher_hosts.iter().map(|h| h.memory_bytes).sum(),
2433            tasks_bytes: tasks.iter().map(|t| t.bytes).sum(),
2434            largest_tasks: tasks
2435                .into_iter()
2436                .take(LARGEST_TASKS)
2437                .map(|t| pb::TaskMemory {
2438                    attempt_id: t.attempt_id,
2439                    dag_id: t.dag_id,
2440                    run_id: t.run_id,
2441                    task_id: t.task_id,
2442                    map_index: t.map_index,
2443                    bytes: t.bytes,
2444                })
2445                .collect(),
2446        })
2447    }
2448
2449    fn send_heartbeat(
2450        &mut self,
2451        resends: &mut Resends,
2452        to_master: &ToMaster,
2453    ) -> Option<SessionEnd> {
2454        self.send_beat(to_master);
2455        self.send_poke_reports(to_master);
2456        let Some(due) = resends.due(self.unacked.keys()) else {
2457            return Some(SessionEnd::Lost(format!(
2458                "a result is still unacknowledged after {} sends; reconnecting, so the \
2459                 master's reconciliation settles it",
2460                resends.most
2461            )));
2462        };
2463        for id in due {
2464            self.send_again(&id, to_master);
2465        }
2466        None
2467    }
2468
2469    /// A message from the master handled, taken in already: an assignment with the others
2470    /// already waiting behind it as one group (M5.1b), anything else alone; each counted as
2471    /// handled once what it sent is queued (B240). A message read ahead that isn't an
2472    /// assignment is left in `held` for the next turn of the loop.
2473    async fn handle_inbound(
2474        &mut self,
2475        message: master_message::Message,
2476        clock: Option<&pb::MasterClock>,
2477        inbound: &mut tonic::Streaming<pb::MasterMessage>,
2478        held: &mut Option<Result<Option<pb::MasterMessage>, tonic::Status>>,
2479        (to_master, client, timers): (
2480            &ToMaster,
2481            &mut MasterClient<Channel>,
2482            (&mut tokio::time::Interval, tokio::time::Instant),
2483        ),
2484    ) -> Result<(), SessionEnd> {
2485        let (heartbeat, opened) = timers;
2486        let sequence = clock.map_or(0, |c| c.sequence);
2487        let master_message::Message::AssignTask(first) = message else {
2488            Box::pin(self.on_master(message, to_master, client, (heartbeat, opened))).await;
2489            // Handled: what it sent is queued, before anything naming it (B240).
2490            to_master.handled(sequence);
2491            return Ok(());
2492        };
2493        let mut burst = vec![first];
2494        let mut sequences = vec![sequence];
2495        while burst.len() < self.settings.setup.timeouts.starts_per_journal_group {
2496            match futures_util::FutureExt::now_or_never(inbound.message()) {
2497                Some(Ok(Some(pb::MasterMessage {
2498                    message: Some(master_message::Message::AssignTask(next)),
2499                    clock,
2500                }))) => {
2501                    let next = master_message::Message::AssignTask(next);
2502                    if let Err(end) = self.take_in(&next, clock.as_ref(), opened, to_master) {
2503                        // The session ends with it: those taken in before it go on as they
2504                        // would have one by one.
2505                        Box::pin(self.assign_group(burst, to_master, client, (heartbeat, opened)))
2506                            .await;
2507                        for sequence in sequences {
2508                            to_master.handled(sequence);
2509                        }
2510                        return Err(end);
2511                    }
2512                    let master_message::Message::AssignTask(next) = next else {
2513                        unreachable!("built as an assignment above")
2514                    };
2515                    burst.push(next);
2516                    sequences.push(clock.as_ref().map_or(0, |c| c.sequence));
2517                }
2518                Some(other) => {
2519                    *held = Some(other);
2520                    break;
2521                }
2522                None => break,
2523            }
2524        }
2525        Box::pin(self.assign_group(burst, to_master, client, (heartbeat, opened))).await;
2526        // Handled once their `Started`s (or `Rejected`s) are queued (B240).
2527        for sequence in sequences {
2528            to_master.handled(sequence);
2529        }
2530        Ok(())
2531    }
2532
2533    /// A message from the master taken in: refused (the session ends) if it isn't this
2534    /// session's or arrives past the lease, else its clock read.
2535    fn take_in(
2536        &mut self,
2537        message: &master_message::Message,
2538        clock: Option<&pb::MasterClock>,
2539        opened: tokio::time::Instant,
2540        to_master: &ToMaster,
2541    ) -> Result<(), SessionEnd> {
2542        if let Some(why) = self.refused(message, clock, opened) {
2543            return Err(SessionEnd::Lost(why));
2544        }
2545        // Past the lease, a message (one held while this worker was frozen, B162, or on its
2546        // way through a one-way cut, B163) doesn't count as the master's word.
2547        if self.silent_too_long(opened) {
2548            return Err(SessionEnd::Lost(NO_WORD.to_owned()));
2549        }
2550        self.heard_master(clock, to_master);
2551        Ok(())
2552    }
2553
2554    async fn on_master(
2555        &mut self,
2556        message: master_message::Message,
2557        to_master: &ToMaster,
2558        client: &mut MasterClient<Channel>,
2559        (heartbeat, opened): (&mut tokio::time::Interval, tokio::time::Instant),
2560    ) {
2561        match message {
2562            master_message::Message::Registered(registered) => {
2563                self.registered = true;
2564                if registered.max_message_size > 0 {
2565                    self.master_limit =
2566                        usize::try_from(registered.max_message_size).unwrap_or(usize::MAX);
2567                }
2568                if let Some(timing) = registered.timing.filter(|t| t.heartbeat_interval_ms > 0) {
2569                    self.heartbeat = Duration::from_millis(timing.heartbeat_interval_ms);
2570                    *heartbeat = heartbeat_timer(self.heartbeat);
2571                    self.lease = (timing.lease_timeout_ms > 0)
2572                        .then(|| Duration::from_millis(timing.lease_timeout_ms));
2573                    self.publish_deadline();
2574                }
2575                self.cut_off = false;
2576                for decision in registered.decisions {
2577                    self.decide(&decision, to_master).await;
2578                }
2579                for event in self.unstored_events() {
2580                    let _ = to_master.send(event);
2581                }
2582                for stopped in std::mem::take(&mut self.triggers_ended).into_values() {
2583                    let _ = to_master.send(wrap(worker_message::Message::TriggerStopped(stopped)));
2584                }
2585                // What went out on the old stream may not have got there.
2586                for trigger in self.triggers.values_mut() {
2587                    trigger.poke.unsent = trigger.poke.at.is_some();
2588                }
2589                // What went out on the old stream may not have got there, or its answer back.
2590                self.api_calls.retain(|_, (_, answer)| !answer.is_closed());
2591                for (call, _) in self.api_calls.values() {
2592                    let _ = to_master.send(wrap(worker_message::Message::ApiCall(call.clone())));
2593                }
2594                for done in self.unsent_answers.drain(..) {
2595                    let _ = to_master.send(wrap(worker_message::Message::ConnectionJobDone(done)));
2596                }
2597                self.set_uses(registered.script_uses, to_master);
2598            }
2599            master_message::Message::ScriptUses(uses) => self.set_uses(uses.roots, to_master),
2600            master_message::Message::AssignTask(assign) => {
2601                self.assign(assign, to_master, client, (heartbeat, opened))
2602                    .await;
2603            }
2604            master_message::Message::AssignParse(job) => self.parse(job),
2605            // Heard: its clock was read as it arrived (B225).
2606            master_message::Message::HeartbeatAck(_) => {}
2607            master_message::Message::ConnectionJob(job) => self.connection_job(job),
2608            master_message::Message::AssignTrigger(assign) => {
2609                self.start_trigger(&assign, to_master);
2610            }
2611            master_message::Message::CancelTrigger(cancel) => {
2612                if let Some(trigger) = self.triggers.get(&cancel.instance_id) {
2613                    let _ = trigger.stop.send(StopReason::Cancelled);
2614                }
2615            }
2616            master_message::Message::ApiAnswer(answer) => {
2617                if let Some((_, to)) = self.api_calls.remove(&answer.request_id) {
2618                    let _ = to.send(answer);
2619                }
2620            }
2621            master_message::Message::TriggerEventAck(ack) => {
2622                if let Some(trigger) = self.triggers.get_mut(&ack.instance_id)
2623                    && let Some((_, stored)) = trigger.unstored.remove(&ack.seq)
2624                {
2625                    let _ = stored.send(());
2626                }
2627            }
2628            master_message::Message::CancelAttempt(cancel) => {
2629                // It stays running (its slot taken) until its process has ended and reported;
2630                // a repeated cancel changes nothing.
2631                if let Some(stop) = self.running.get(&cancel.attempt_id) {
2632                    let _ = stop.send(if cancel.interrupted {
2633                        StopReason::Interrupted
2634                    } else {
2635                        StopReason::Cancelled
2636                    });
2637                }
2638            }
2639            master_message::Message::FinishedAck(ack) => {
2640                self.forked.remove(&ack.attempt_id);
2641                self.acknowledged(&ack.attempt_id).await;
2642            }
2643        }
2644    }
2645
2646    async fn decide(&mut self, decision: &pb::JournalDecision, to_master: &ToMaster) {
2647        let id = &decision.attempt_id;
2648        match pb::AttemptDecision::try_from(decision.decision) {
2649            Ok(pb::AttemptDecision::Ack) => {
2650                self.forked.remove(id);
2651                self.acknowledged(id).await;
2652            }
2653            Ok(pb::AttemptDecision::CleanRest) => {
2654                // Ended, its cleanup moved without the handles from `cleanup_from` on: they
2655                // are cleaned here, the master adding the result to the attempt's (B169).
2656                let from = decision.cleanup_from;
2657                self.rest_cleaning.insert(id.clone());
2658                if let Some(gate) = self.gates.get(id) {
2659                    gate.send_replace(Gate::Rest(from));
2660                }
2661                if let Some(mut waiting) = self.waiting.remove(id) {
2662                    let from = (from as usize).min(waiting.handles.len());
2663                    waiting.handles.drain(..from);
2664                    waiting.rest = true;
2665                    self.start_waiting(id, waiting, to_master).await;
2666                }
2667                // The master ended the task: stopped here, the rest cleaned once it stops.
2668                if let Some(stop) = self.running.get(id) {
2669                    let _ = stop.send(StopReason::Cancelled);
2670                }
2671            }
2672            Ok(pb::AttemptDecision::Kill) => {
2673                self.forked.remove(id);
2674                self.acknowledged(id).await;
2675                if let Some(gate) = self.gates.get(id) {
2676                    gate.send_replace(Gate::Dropped);
2677                }
2678                if self.waiting.remove(id).is_some() {
2679                    // The master ended it, or it moved: its cleanup isn't run here.
2680                    self.running.remove(id);
2681                    self.set_slot_gauges();
2682                    self.release_code(id);
2683                    self.forget(id).await;
2684                    self.collect_code();
2685                }
2686                if let Some(stop) = self.running.get(id) {
2687                    let _ = stop.send(StopReason::Cancelled);
2688                }
2689            }
2690            _ => {
2691                if let Some(gate) = self.gates.get(id) {
2692                    gate.send_replace(Gate::Open);
2693                }
2694                if self.running.contains_key(id) {
2695                    if self.forked.contains(id) {
2696                        let _ = to_master.send(forked_started(id));
2697                    }
2698                    self.send_handles(id, to_master).await;
2699                }
2700                if let Some(waiting) = self.waiting.remove(id) {
2701                    self.start_waiting(id, waiting, to_master).await;
2702                } else if let Some(ended) = self.cleaning.get(id) {
2703                    // Its report may have gone with the old stream; fitted to the limit now,
2704                    // as a result sent again is (B47).
2705                    let mut ended = ended.clone();
2706                    fit_result(&mut ended, self.master_limit);
2707                    let _ = to_master.send(task_ended_message(ended));
2708                } else {
2709                    if self.unacked.contains_key(id) && self.forked.contains(id) {
2710                        let _ = to_master.send(forked_started(id));
2711                    }
2712                    self.send_again(id, to_master);
2713                }
2714            }
2715        }
2716    }
2717
2718    /// Sends an attempt's handles again: some may have gone with the old stream, or never
2719    /// left (decision 242). The master keeps what it has.
2720    async fn send_handles(&self, attempt_id: &str, to_master: &ToMaster) {
2721        let journal = self.journal.clone();
2722        let id = attempt_id.to_owned();
2723        let read = tokio::task::spawn_blocking(move || journal.handles(&id)).await;
2724        match read {
2725            Ok(Ok(handles)) if !handles.is_empty() => {
2726                let _ = to_master.send(handles_message(attempt_id.to_owned(), 0, &handles));
2727            }
2728            Ok(Ok(_)) => {}
2729            Ok(Err(error)) => {
2730                tracing::warn!(attempt_id, %error, "can't read the handles to send them again");
2731            }
2732            Err(error) => tracing::warn!(attempt_id, %error, "reading the handles failed"),
2733        }
2734    }
2735
2736    /// Sends unacknowledged result `id` again, fitted to the master's limit now: it was
2737    /// journalled under the limit of its time, which a master since may have lowered (B47).
2738    /// The journal keeps it whole, for a master accepting it.
2739    fn send_again(&self, id: &str, to_master: &ToMaster) {
2740        if let Some(finished) = self.unacked.get(id) {
2741            let mut finished = finished.clone();
2742            fit_result(&mut finished, self.master_limit);
2743            let _ = to_master.send(wrap(worker_message::Message::Finished(finished)));
2744        }
2745    }
2746
2747    /// An assignment's inputs fetched from the master when they came apart from it: `None`
2748    /// when it isn't started, rejected (a failed fetch) or the master gone silent (the session
2749    /// ends, and the master takes it back at the lease).
2750    async fn external_inputs(
2751        &mut self,
2752        assign: &pb::AssignTask,
2753        to_master: &ToMaster,
2754        client: &mut MasterClient<Channel>,
2755        timers: (&mut tokio::time::Interval, tokio::time::Instant),
2756    ) -> Option<Option<Vec<u8>>> {
2757        if !assign.inputs_external {
2758            return Some(None);
2759        }
2760        match self
2761            .fetch_with_timers(client, &assign.attempt_id, to_master, timers)
2762            .await?
2763        {
2764            Ok(bytes) => Some(Some(bytes)),
2765            Err(detail) => {
2766                let rejected = pb::Rejected {
2767                    attempt_id: assign.attempt_id.clone(),
2768                    reason: pb::RejectReason::InvalidSpecification.into(),
2769                    detail,
2770                };
2771                let _ = to_master.send(wrap(worker_message::Message::Rejected(rejected)));
2772                None
2773            }
2774        }
2775    }
2776
2777    async fn assign(
2778        &mut self,
2779        assign: pb::AssignTask,
2780        to_master: &ToMaster,
2781        client: &mut MasterClient<Channel>,
2782        timers: (&mut tokio::time::Interval, tokio::time::Instant),
2783    ) {
2784        Box::pin(self.assign_group(vec![assign], to_master, client, timers)).await;
2785    }
2786
2787    /// A burst of assignments (M5.1b): each prepared up to its journal record, their records
2788    /// written as one group ([`Journal::write_many`]), then each started (or failed, or
2789    /// rejected) in order. No `Started` goes before its record is on disk.
2790    async fn assign_group(
2791        &mut self,
2792        assigns: Vec<pb::AssignTask>,
2793        to_master: &ToMaster,
2794        client: &mut MasterClient<Channel>,
2795        timers: (&mut tokio::time::Interval, tokio::time::Instant),
2796    ) {
2797        let (heartbeat, opened) = timers;
2798        let mut ready = Vec::new();
2799        let mut held = Held::default();
2800        for assign in assigns {
2801            // Its inputs fetched from the master first: those before it don't wait on the
2802            // network, they start now.
2803            if assign.inputs_external && !ready.is_empty() {
2804                Box::pin(self.start_group(std::mem::take(&mut ready), to_master, opened)).await;
2805                held = Held::default();
2806            }
2807            // Cut off (a fetch reaching the cutoff, or the alive tick) or past the lease: the
2808            // session ends, nothing more of the burst is prepared or started.
2809            if self.cut_off || self.gone_silent(opened) {
2810                break;
2811            }
2812            let prepared = self
2813                .prepare(assign, to_master, client, (&mut *heartbeat, opened), &held)
2814                .await;
2815            if let Some(prepared) = prepared {
2816                held.add(&prepared);
2817                ready.push(prepared);
2818            }
2819        }
2820        Box::pin(self.start_group(ready, to_master, opened)).await;
2821    }
2822
2823    /// Prepared assignments' records written as one group, then each started in order.
2824    async fn start_group(
2825        &mut self,
2826        ready: Vec<Prepared>,
2827        to_master: &ToMaster,
2828        opened: tokio::time::Instant,
2829    ) {
2830        let journaled = self.journal_starts(&ready, opened).await;
2831        for (prepared, journaled) in ready.into_iter().zip(journaled) {
2832            self.after_journal(prepared, journaled, to_master).await;
2833        }
2834    }
2835
2836    /// An assignment checked and planned, up to its journal record; `None` when it was
2837    /// refused (its `Rejected` sent) or ignored. `held`: the group's assignments before it,
2838    /// whose slots are taken though not yet started.
2839    async fn prepare(
2840        &mut self,
2841        assign: pb::AssignTask,
2842        to_master: &ToMaster,
2843        client: &mut MasterClient<Channel>,
2844        timers: (&mut tokio::time::Interval, tokio::time::Instant),
2845        held: &Held,
2846    ) -> Option<Prepared> {
2847        let received = std::time::Instant::now();
2848        let reject = |reason: pb::RejectReason, detail: String| {
2849            wrap(worker_message::Message::Rejected(pb::Rejected {
2850                attempt_id: assign.attempt_id.clone(),
2851                reason: reason.into(),
2852                detail,
2853            }))
2854        };
2855        if assign.cleanup_only.is_some() && self.cleaning_rest(&assign.attempt_id) {
2856            // Its whole cleanup, given here while this worker cleans the handles the master
2857            // didn't have (B169): refused, it goes elsewhere or comes back after.
2858            let detail = "cleaning the rest of this attempt's handles".to_owned();
2859            let _ = to_master.send(reject(pb::RejectReason::NoFreeSlot, detail));
2860            return None;
2861        }
2862        if self.running.contains_key(&assign.attempt_id)
2863            || self.unacked.contains_key(&assign.attempt_id)
2864            || held.ids.contains(&assign.attempt_id)
2865        {
2866            // Already started here: its journal entry must not be replaced.
2867            tracing::warn!(
2868                attempt_id = assign.attempt_id.as_str(),
2869                "assignment of an attempt this worker already has; ignored"
2870            );
2871            return None;
2872        }
2873        if let Some((reason, detail)) = self.cannot_take_held(assigned_a_wait_step(&assign), held) {
2874            let _ = to_master.send(reject(reason, detail.to_owned()));
2875            return None;
2876        }
2877        let external = self
2878            .external_inputs(&assign, to_master, client, timers)
2879            .await?;
2880        let mut spec = match AttemptSpec::from_assign(&assign, external.as_deref()) {
2881            Ok(spec) => spec,
2882            Err(error) => {
2883                let _ = to_master.send(reject(
2884                    pb::RejectReason::InvalidSpecification,
2885                    error.to_string(),
2886                ));
2887                return None;
2888            }
2889        };
2890        if let Some(detail) = self.code_mismatch(&assign) {
2891            let _ = to_master.send(reject(pb::RejectReason::CodeMismatch, detail));
2892            return None;
2893        }
2894        // Planned with stand-ins for its secrets (fetched once it is started, so a slow
2895        // storage never holds up the agent): whether it runs here doesn't depend on them.
2896        spec.stand_in_secrets();
2897        let planned = self.plan(&mut spec, &assign);
2898        Some(Prepared {
2899            assign,
2900            spec,
2901            planned,
2902            external,
2903            received,
2904        })
2905    }
2906
2907    /// An assignment whose journal record is on disk (or failed, `journaled`): started,
2908    /// failed before it could start, or rejected, in the group's order.
2909    async fn after_journal(
2910        &mut self,
2911        prepared: Prepared,
2912        journaled: Result<(), Option<(pb::RejectReason, String)>>,
2913        to_master: &ToMaster,
2914    ) {
2915        let Prepared {
2916            assign,
2917            mut spec,
2918            planned,
2919            received,
2920            ..
2921        } = prepared;
2922        let reject = |reason: pb::RejectReason, detail: String| {
2923            wrap(worker_message::Message::Rejected(pb::Rejected {
2924                attempt_id: assign.attempt_id.clone(),
2925                reason: reason.into(),
2926                detail,
2927            }))
2928        };
2929        if let Err(why) = journaled {
2930            if let Some((reason, detail)) = why {
2931                let _ = to_master.send(reject(reason, detail));
2932            }
2933            return;
2934        }
2935        self.remember_code(&assign, &spec);
2936        self.note_cleanup(&mut spec, &assign);
2937        spec.api = Some(ApiCaller::of_attempt(&spec.attempt_id, self.api_send()));
2938        if let Some(only) = &assign.cleanup_only
2939            && !matches!(planned, Err(NotRun::Rejected { .. }))
2940        {
2941            match moved_handles(only) {
2942                Ok(handles) => {
2943                    self.moved_cleanup(spec, handles, to_master, received).await;
2944                }
2945                // Run without them, it could report success and leave them behind.
2946                Err(error) => {
2947                    self.release_code(&spec.attempt_id);
2948                    self.forget(&spec.attempt_id).await;
2949                    let detail = format!("a handle that doesn't read: {error}");
2950                    let _ = to_master.send(reject(pb::RejectReason::InvalidSpecification, detail));
2951                }
2952            }
2953            return;
2954        }
2955        self.start_planned(spec, planned, to_master, received);
2956    }
2957
2958    /// A `Started` for `attempt_id` started now by `method`, with the start in master time as
2959    /// this session estimates it (M5.1m).
2960    fn started(&self, attempt_id: &str, method: pb::StartMethod) -> pb::Started {
2961        let estimate = self.master_time.estimate(Local::now());
2962        pb::Started {
2963            attempt_id: attempt_id.to_owned(),
2964            start_method: method.into(),
2965            started_master_ms: estimate.map(|(_, ms)| ms),
2966            started_timeline: estimate.map_or(0, |(timeline, _)| timeline),
2967        }
2968    }
2969
2970    /// An assignment journaled: started (`Started`, then launched), failed before it could
2971    /// start, or rejected, as `planned` says.
2972    fn start_planned(
2973        &mut self,
2974        mut spec: AttemptSpec,
2975        planned: Result<Plan, NotRun>,
2976        to_master: &ToMaster,
2977        received: std::time::Instant,
2978    ) {
2979        let started = wrap(worker_message::Message::Started(
2980            self.started(&spec.attempt_id, pb::StartMethod::Spawn),
2981        ));
2982        match planned {
2983            Err(NotRun::Rejected { reason, detail }) => {
2984                self.release_code(&spec.attempt_id);
2985                let _ = to_master.send(wrap(worker_message::Message::Rejected(pb::Rejected {
2986                    attempt_id: spec.attempt_id.clone(),
2987                    reason: reason.into(),
2988                    detail,
2989                })));
2990            }
2991            Err(NotRun::Failed { kind, message }) => {
2992                let _ = to_master.send(started);
2993                self.metrics
2994                    .assign_to_started
2995                    .observe(received.elapsed().as_secs_f64());
2996                let failed = failed_before_start(&spec.attempt_id, &kind, &message);
2997                let _ = self.done_tx.send(Done::Attempt(failed));
2998            }
2999            Ok(plan) => {
3000                let (stop, stopped) = Stops::new();
3001                self.running.insert(spec.attempt_id.clone(), stop);
3002                self.note_wait_step(&spec);
3003                self.set_gate(&mut spec);
3004                let _ = to_master.send(started);
3005                self.metrics
3006                    .assign_to_started
3007                    .observe(received.elapsed().as_secs_f64());
3008                // At once, not at the next alive tick: a burst of starts shows as it happens.
3009                self.set_slot_gauges();
3010                self.launch(spec, plan, stopped);
3011            }
3012        }
3013    }
3014
3015    /// Starts a DAG's trigger here: as a wait step's attempt would run, but no attempt, so nothing
3016    /// of it is journaled and the master keeps no result of it.
3017    fn start_trigger(&mut self, assign: &pb::AssignTrigger, to_master: &ToMaster) {
3018        let stopped = |kind: &str, message: String| {
3019            wrap(worker_message::Message::TriggerStopped(
3020                pb::TriggerStopped {
3021                    dag_id: assign.dag_id.clone(),
3022                    instance_id: assign.instance_id.clone(),
3023                    error_kind: kind.to_owned(),
3024                    message,
3025                    ..pb::TriggerStopped::default()
3026                },
3027            ))
3028        };
3029        if let Some((_, detail)) = self.cannot_take(true) {
3030            let _ = to_master.send(stopped("not_placed", detail.to_owned()));
3031            return;
3032        }
3033        if self.triggers.contains_key(&assign.instance_id) {
3034            return;
3035        }
3036        let now = proto_time(Timestamp::now());
3037        let task_assign = pb::AssignTask {
3038            attempt_id: assign.instance_id.clone(),
3039            map_index: -1,
3040            try_number: 1,
3041            run: Some(pb::RunInfo {
3042                run_id: assign.instance_id.clone(),
3043                kind: "event".to_owned(),
3044                planned_for: Some(now),
3045                since: Some(now),
3046                dag_id: assign.dag_id.clone(),
3047                ..pb::RunInfo::default()
3048            }),
3049            task_json: assign.task_json.clone(),
3050            dag_file: assign.dag_file.clone(),
3051            expected_code_hash: assign.expected_code_hash.clone(),
3052            cancel_grace_ms: assign.cancel_grace_ms,
3053            connections_json: assign.connections_json.clone(),
3054            ..pb::AssignTask::default()
3055        };
3056        let mut spec = match AttemptSpec::from_assign(&task_assign, None) {
3057            Ok(spec) => spec,
3058            Err(error) => {
3059                let _ = to_master.send(stopped("not_placed", error.to_string()));
3060                return;
3061            }
3062        };
3063        if let Some(detail) = self.code_mismatch(&task_assign) {
3064            let _ = to_master.send(stopped("not_placed", detail));
3065            return;
3066        }
3067        let instance_id = assign.instance_id.clone();
3068        let sink = self.trigger_sink(&instance_id, batches(&spec.task));
3069        let start = schedr_model::runner::TriggerStart {
3070            after: assign.after.clone(),
3071        };
3072        spec.trigger = Some((start, sink));
3073        let send = self.api_send();
3074        spec.api = Some(ApiCaller::of_trigger(
3075            &assign.instance_id,
3076            &assign.dag_id,
3077            send,
3078        ));
3079        spec.stand_in_secrets();
3080        let plan = match self.plan(&mut spec, &task_assign) {
3081            Ok(plan) => plan,
3082            Err(NotRun::Rejected { detail, .. }) => {
3083                let _ = to_master.send(stopped("not_placed", detail));
3084                return;
3085            }
3086            Err(NotRun::Failed { kind, message }) => {
3087                let _ = to_master.send(stopped(&kind, message));
3088                return;
3089            }
3090        };
3091        self.remember_code(&task_assign, &spec);
3092        let (stop, stops) = Stops::new();
3093        self.triggers.insert(
3094            instance_id.clone(),
3095            RunningTrigger {
3096                dag_id: assign.dag_id.clone(),
3097                stop,
3098                next_seq: 0,
3099                unstored: BTreeMap::new(),
3100                poke: PokeReport {
3101                    failures: assign.failures,
3102                    ..PokeReport::default()
3103                },
3104            },
3105        );
3106        let executor = self.executor.clone();
3107        let ended = self.done_tx.clone();
3108        tokio::spawn(async move {
3109            let spawned: Spawned = Arc::new(|_, _| {});
3110            let finished = executor
3111                .run(spec, plan, stops, spawned, Box::new(|_| {}))
3112                .await;
3113            let _ = ended.send(Done::Trigger(TriggerDone::Ended {
3114                instance_id,
3115                finished: Box::new(finished),
3116            }));
3117        });
3118    }
3119
3120    /// A task's result made ready to keep and send: fitted to the master's limit, counted, its
3121    /// code hash named and its copy of the code let go.
3122    fn result_ready(&mut self, mut finished: pb::Finished) -> pb::Finished {
3123        fit_result(&mut finished, self.master_limit);
3124        let status = attempt_status_from_proto(finished.status)
3125            .map_or_else(|_| "unknown".to_owned(), |s| s.to_string());
3126        self.metrics.attempt_ended(&status);
3127        if let Some(hash) = self.release_code(&finished.attempt_id) {
3128            with_code_hash(&mut finished, hash);
3129            self.collect_code();
3130        }
3131        finished
3132    }
3133
3134    /// A result in the journal: the attempt is done here, and the result goes to the master.
3135    fn result_recorded(&mut self, finished: pb::Finished, to_master: Option<&ToMaster>) {
3136        self.ended_running(&finished.attempt_id);
3137        self.cleaning.remove(&finished.attempt_id);
3138        self.cleanup_room.remove(&finished.attempt_id);
3139        self.stopped.remove(&finished.attempt_id);
3140        self.gates.remove(&finished.attempt_id);
3141        self.unacked
3142            .insert(finished.attempt_id.clone(), finished.clone());
3143        // Now in `unacked`: the journal's gauge counts it again.
3144        self.set_slot_gauges();
3145        if let Some(to_master) = to_master {
3146            let _ = to_master.send(wrap(worker_message::Message::Finished(finished)));
3147        }
3148    }
3149
3150    /// What ended, with the results waiting behind it (M4B.5, B184): those results, up to
3151    /// [`RESULTS_PER_GROUP`] in a row, are kept in the journal as one group
3152    /// ([`Journal::write_many`]), then each goes on as alone; the first other news after them
3153    /// is handled next.
3154    async fn on_done_group(
3155        &mut self,
3156        done: Done,
3157        to_master: Option<&ToMaster>,
3158        client: Option<&mut MasterClient<Channel>>,
3159    ) {
3160        let link = to_master.zip(client);
3161        let first = match done {
3162            Done::Attempt(first) => first,
3163            Done::Spawned {
3164                attempt_id,
3165                identity,
3166                forked,
3167            } => {
3168                let (record, repeat) = self.spawned_record(&attempt_id, identity, forked);
3169                return Box::pin(self.spawned_group((attempt_id, record, repeat), link)).await;
3170            }
3171            other => return self.on_done(other, link).await,
3172        };
3173        let mut results = vec![self.result_ready(first)];
3174        let mut next = None;
3175        while results.len() < self.settings.setup.timeouts.results_per_journal_group {
3176            match self.done_rx.try_recv() {
3177                Ok(Done::Attempt(finished)) => results.push(self.result_ready(finished)),
3178                Ok(other) => {
3179                    next = Some(other);
3180                    break;
3181                }
3182                Err(_) => break,
3183            }
3184        }
3185        self.record_results(&results).await;
3186        let to_master = link.as_ref().map(|(to_master, _)| *to_master);
3187        for finished in results {
3188            self.result_recorded(finished, to_master);
3189        }
3190        if let Some(next) = next {
3191            Box::pin(self.on_done(next, link)).await;
3192        }
3193    }
3194
3195    /// A started process's identity for its journal record (so a restart can stop it); a
3196    /// forked one's `Started` sent again with its method (the master keeps the first start
3197    /// time).
3198    fn spawned_record(
3199        &mut self,
3200        attempt_id: &str,
3201        identity: ProcessIdentity,
3202        forked: bool,
3203    ) -> (JournalRecord, bool) {
3204        // `Started` went before the process existed, as `spawn`; a repeat sets the method, sent
3205        // once the identity is on disk (`resend_forked`).
3206        let ended = self.cleaning.get(attempt_id).cloned();
3207        let repeat = forked && ended.is_none();
3208        if repeat {
3209            self.forked.insert(attempt_id.to_owned());
3210        }
3211        let record = match ended {
3212            Some(ended) => JournalRecord::Cleaning(ended, Some(identity)),
3213            None => JournalRecord::Running(Some(identity)),
3214        };
3215        (record, repeat)
3216    }
3217
3218    /// Started processes' identities, the first and those waiting behind it, kept in the
3219    /// journal as one group (M5.1b); the first other news after them is handled next.
3220    async fn spawned_group(
3221        &mut self,
3222        first: (String, JournalRecord, bool),
3223        link: Option<(&ToMaster, &mut MasterClient<Channel>)>,
3224    ) {
3225        let to_master = link.as_ref().map(|(to_master, _)| *to_master);
3226        let mut records = vec![first];
3227        let mut next = None;
3228        while records.len() < self.settings.setup.timeouts.starts_per_journal_group {
3229            match self.done_rx.try_recv() {
3230                Ok(Done::Spawned {
3231                    attempt_id,
3232                    identity,
3233                    forked,
3234                }) => {
3235                    let (record, repeat) = self.spawned_record(&attempt_id, identity, forked);
3236                    records.push((attempt_id, record, repeat));
3237                }
3238                Ok(other) => {
3239                    next = Some(other);
3240                    break;
3241                }
3242                Err(_) => break,
3243            }
3244        }
3245        self.keep_processes(records, to_master).await;
3246        if let Some(next) = next {
3247            Box::pin(self.on_done(next, link)).await;
3248        }
3249    }
3250
3251    /// Started processes' identities kept in the journal (one write for several, M5.1b), then
3252    /// each forked one's `Started` repeated with its method: after its identity is on disk.
3253    async fn keep_processes(
3254        &mut self,
3255        records: Vec<(String, JournalRecord, bool)>,
3256        to_master: Option<&ToMaster>,
3257    ) {
3258        let began = std::time::Instant::now();
3259        let written = if let [(id, record, _)] = records.as_slice() {
3260            self.record(id, record.clone()).await
3261        } else {
3262            let journal = self.journal.clone();
3263            let group: Vec<(String, JournalRecord)> = records
3264                .iter()
3265                .map(|(id, record, _)| (id.clone(), record.clone()))
3266                .collect();
3267            tokio::task::spawn_blocking(move || {
3268                let refs: Vec<(&str, &JournalRecord)> = group
3269                    .iter()
3270                    .map(|(id, record)| (id.as_str(), record))
3271                    .collect();
3272                journal.write_many(&refs)
3273            })
3274            .await
3275            .map_err(std::io::Error::other)
3276            .and_then(|written| written)
3277        };
3278        match written {
3279            Ok(()) => self.metrics.journal_written("process", began.elapsed()),
3280            Err(_) if records.len() > 1 => {
3281                // The group failed: each kept on its own, as before groups.
3282                for (attempt_id, record, _) in &records {
3283                    if let Err(error) = self.record(attempt_id, record.clone()).await {
3284                        tracing::warn!(attempt_id, %error, "can't record the task's process");
3285                    }
3286                }
3287            }
3288            Err(error) => {
3289                let attempt_id = records[0].0.as_str();
3290                tracing::warn!(attempt_id, %error, "can't record the task's process");
3291            }
3292        }
3293        if let Some(to_master) = to_master {
3294            for (attempt_id, _, repeat) in &records {
3295                if *repeat {
3296                    let _ = to_master.send(forked_started(attempt_id));
3297                }
3298            }
3299        }
3300    }
3301
3302    /// Keeps results in the journal until the master has them, as one group.
3303    async fn record_results(&self, results: &[pb::Finished]) {
3304        if let [one] = results {
3305            return self.record_finished(one).await;
3306        }
3307        let journal = self.journal.clone();
3308        let records: Vec<(String, JournalRecord)> = results
3309            .iter()
3310            .map(|f| (f.attempt_id.clone(), JournalRecord::Finished(f.clone())))
3311            .collect();
3312        let began = std::time::Instant::now();
3313        let written = tokio::task::spawn_blocking(move || {
3314            let refs: Vec<(&str, &JournalRecord)> =
3315                records.iter().map(|(id, r)| (id.as_str(), r)).collect();
3316            journal.write_many(&refs)
3317        })
3318        .await
3319        .map_err(std::io::Error::other)
3320        .and_then(|written| written);
3321        if written.is_ok() {
3322            self.metrics.journal_written("results", began.elapsed());
3323        }
3324        if let Err(error) = written {
3325            tracing::warn!(
3326                results = results.len(),
3327                %error,
3328                "can't record the results; they are lost if the agent restarts before the \
3329                 master acknowledges them"
3330            );
3331        }
3332    }
3333
3334    /// Keeps a result in the journal until the master has it.
3335    async fn record_finished(&self, finished: &pb::Finished) {
3336        let began = std::time::Instant::now();
3337        let recorded = self
3338            .record(
3339                &finished.attempt_id,
3340                JournalRecord::Finished(finished.clone()),
3341            )
3342            .await;
3343        if recorded.is_ok() {
3344            self.metrics.journal_written("results", began.elapsed());
3345        }
3346        if let Err(error) = recorded {
3347            tracing::warn!(
3348                attempt_id = finished.attempt_id.as_str(),
3349                %error,
3350                "can't record the result; it is lost if the agent restarts before the \
3351                 master acknowledges it"
3352            );
3353        }
3354    }
3355
3356    /// Where a trigger's words go: to [`Self::trigger_done`].
3357    fn trigger_sink(&self, instance_id: &str, batched: bool) -> crate::watchers::EventSink {
3358        let done = self.done_tx.clone();
3359        let found = instance_id.to_owned();
3360        let poke_done = self.done_tx.clone();
3361        let poked = instance_id.to_owned();
3362        crate::watchers::EventSink {
3363            batched,
3364            found: Arc::new(move |event| {
3365                let (stored, answer) = tokio::sync::oneshot::channel();
3366                let _ = done.send(Done::Trigger(TriggerDone::Found {
3367                    instance_id: found.clone(),
3368                    event,
3369                    stored,
3370                }));
3371                answer
3372            }),
3373            poked: Arc::new(move |error| {
3374                let _ = poke_done.send(Done::Trigger(TriggerDone::Poked {
3375                    instance_id: poked.clone(),
3376                    error,
3377                }));
3378            }),
3379        }
3380    }
3381
3382    /// What a trigger did reaches the master.
3383    fn trigger_done(&mut self, done: TriggerDone, to_master: Option<&ToMaster>) {
3384        match done {
3385            TriggerDone::Found {
3386                instance_id,
3387                event,
3388                stored,
3389            } => self.trigger_found(instance_id, event, stored, to_master),
3390            TriggerDone::Poked { instance_id, error } => {
3391                self.trigger_poked(&instance_id, error, to_master);
3392            }
3393            TriggerDone::Ended {
3394                instance_id,
3395                finished,
3396            } => self.trigger_ended(&instance_id, &finished, to_master),
3397        }
3398    }
3399
3400    /// A trigger found something: on to the master; what it hasn't said it has is sent again
3401    /// on a new stream.
3402    fn trigger_found(
3403        &mut self,
3404        instance_id: String,
3405        event: crate::watchers::FoundEvent,
3406        stored: tokio::sync::oneshot::Sender<()>,
3407        to_master: Option<&ToMaster>,
3408    ) {
3409        let Some(trigger) = self.triggers.get_mut(&instance_id) else {
3410            return;
3411        };
3412        trigger.next_seq += 1;
3413        let message = pb::TriggerEvent {
3414            dag_id: trigger.dag_id.clone(),
3415            instance_id,
3416            seq: trigger.next_seq,
3417            key: event.key,
3418            data_json: serde_json::to_vec(&event.data).unwrap_or_default(),
3419            at: event.at.map(proto_time),
3420        };
3421        trigger
3422            .unstored
3423            .insert(trigger.next_seq, (message.clone(), stored));
3424        if let Some(to_master) = to_master {
3425            let _ = to_master.send(wrap(worker_message::Message::TriggerEvent(message)));
3426        }
3427    }
3428
3429    /// A poke's call ended: told at once when that changes things, with a heartbeat otherwise.
3430    fn trigger_poked(
3431        &mut self,
3432        instance_id: &str,
3433        error: Option<String>,
3434        to_master: Option<&ToMaster>,
3435    ) {
3436        let Some(trigger) = self.triggers.get_mut(instance_id) else {
3437            return;
3438        };
3439        let changed = trigger.poke.error != error;
3440        trigger.poke.failures = if error.is_some() {
3441            trigger.poke.failures.saturating_add(1)
3442        } else {
3443            0
3444        };
3445        trigger.poke.error = error;
3446        trigger.poke.at = Some(Timestamp::now());
3447        trigger.poke.unsent = true;
3448        if changed && let Some(to_master) = to_master {
3449            let _ = to_master.send(poke_report(instance_id, trigger));
3450            trigger.poke.unsent = false;
3451        }
3452    }
3453
3454    /// The pokes' reports not sent yet.
3455    fn send_poke_reports(&mut self, to_master: &ToMaster) {
3456        for (instance_id, trigger) in &mut self.triggers {
3457            if trigger.poke.unsent {
3458                let _ = to_master.send(poke_report(instance_id, trigger));
3459                trigger.poke.unsent = false;
3460            }
3461        }
3462    }
3463
3464    /// A trigger ended: its slot and its code are free. A master that doesn't hear it learns
3465    /// from the next registration, which no longer lists it.
3466    fn trigger_ended(
3467        &mut self,
3468        instance_id: &str,
3469        finished: &pb::Finished,
3470        to_master: Option<&ToMaster>,
3471    ) {
3472        let code = self.release_code(instance_id);
3473        self.collect_code();
3474        let Some(trigger) = self.triggers.remove(instance_id) else {
3475            return;
3476        };
3477        let mut stopped = trigger_stopped(trigger.dag_id, instance_id.to_owned(), finished);
3478        stopped.returned_event = trigger.next_seq > 0;
3479        if let Some(code) = code {
3480            stopped.code_hash = code;
3481        }
3482        match to_master {
3483            Some(to_master) => {
3484                let _ = to_master.send(wrap(worker_message::Message::TriggerStopped(stopped)));
3485            }
3486            None => {
3487                self.triggers_ended.insert(instance_id.to_owned(), stopped);
3488            }
3489        }
3490    }
3491
3492    /// What it found that the master hasn't said it has: a new session sends it again.
3493    fn unstored_events(&self) -> impl Iterator<Item = pb::WorkerMessage> {
3494        self.triggers
3495            .values()
3496            .flat_map(|trigger| trigger.unstored.values())
3497            .map(|(event, _)| wrap(worker_message::Message::TriggerEvent(event.clone())))
3498    }
3499
3500    /// Runs the cleanup of an attempt whose worker was lost (decision 243). Its task's result
3501    /// is the master's: what is reported here only stands for it.
3502    async fn moved_cleanup(
3503        &mut self,
3504        spec: AttemptSpec,
3505        handles: Vec<CleanupHandle>,
3506        to_master: &ToMaster,
3507        received: std::time::Instant,
3508    ) {
3509        let id = spec.attempt_id.clone();
3510        let _ = to_master.send(wrap(worker_message::Message::Started(
3511            self.started(&id, pb::StartMethod::Spawn),
3512        )));
3513        self.metrics
3514            .assign_to_started
3515            .observe(received.elapsed().as_secs_f64());
3516        let (stop, _) = Stops::new();
3517        self.running.insert(id.clone(), stop);
3518        self.set_slot_gauges();
3519        let waiting = WaitingCleanup {
3520            spec,
3521            handles,
3522            ended: None,
3523            rest: false,
3524        };
3525        self.start_waiting(&id, waiting, to_master).await;
3526    }
3527
3528    /// The journal records of a group's assignments (M5.1b): those planned to run (or to fail
3529    /// before they could start) kept on disk together, a cleanup's assignment kept beside its
3530    /// record first. Each one's outcome in order: on disk, refused for the disk
3531    /// (`DiskNotWritable`), or dropped (`None`) because the lease ran out meanwhile.
3532    async fn journal_starts(
3533        &self,
3534        ready: &[Prepared],
3535        opened: tokio::time::Instant,
3536    ) -> Vec<Result<(), Option<(pb::RejectReason, String)>>> {
3537        let disk = |error: &std::io::Error| {
3538            let detail = format!(
3539                "can't write the journal in `{}`: {error}; check the worker's data directory",
3540                self.journal.dir().display()
3541            );
3542            Some((pb::RejectReason::DiskNotWritable, detail))
3543        };
3544        let mut outcomes: Vec<Result<(), Option<(pb::RejectReason, String)>>> =
3545            ready.iter().map(|_| Ok(())).collect();
3546        let began = std::time::Instant::now();
3547        let mut writing = Vec::new();
3548        for (at, prepared) in ready.iter().enumerate() {
3549            if matches!(prepared.planned, Err(NotRun::Rejected { .. })) {
3550                continue;
3551            }
3552            #[cfg(test)]
3553            if !self.journal_stall.0.is_zero() {
3554                tokio::time::sleep(self.journal_stall.0).await;
3555                self.journal_stall
3556                    .1
3557                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
3558            }
3559            match self.keep_for_cleanup(prepared).await {
3560                Ok(()) => writing.push(at),
3561                Err(error) => outcomes[at] = Err(disk(&error)),
3562            }
3563        }
3564        if writing.is_empty() {
3565            return outcomes;
3566        }
3567        let ids: Vec<String> = writing
3568            .iter()
3569            .map(|&at| ready[at].spec.attempt_id.clone())
3570            .collect();
3571        let written = if let [id] = ids.as_slice() {
3572            self.record(id, JournalRecord::Running(None)).await
3573        } else {
3574            let journal = self.journal.clone();
3575            let records = ids.clone();
3576            tokio::task::spawn_blocking(move || {
3577                let running = JournalRecord::Running(None);
3578                let refs: Vec<(&str, &JournalRecord)> =
3579                    records.iter().map(|id| (id.as_str(), &running)).collect();
3580                journal.write_many(&refs)
3581            })
3582            .await
3583            .map_err(std::io::Error::other)
3584            .and_then(|written| written)
3585        };
3586        match written {
3587            Ok(()) => self.metrics.journal_written("start", began.elapsed()),
3588            Err(_) if ids.len() > 1 => {
3589                // The group failed: each written on its own, so each gets its own outcome.
3590                for (&at, id) in writing.iter().zip(&ids) {
3591                    if let Err(error) = self.record(id, JournalRecord::Running(None)).await {
3592                        outcomes[at] = Err(disk(&error));
3593                    }
3594                }
3595            }
3596            Err(error) => outcomes[writing[0]] = Err(disk(&error)),
3597        }
3598        // Cut off or past the lease while journaling: not started (decision 281; Grok's review
3599        // of M5.1b: the cutoff too, not only the lease).
3600        if self.cut_off || self.gone_silent(opened) {
3601            for &at in &writing {
3602                if outcomes[at].is_ok() {
3603                    let id = &ready[at].spec.attempt_id;
3604                    tracing::warn!(
3605                        attempt_id = id.as_str(),
3606                        "the lease ran out while the attempt was journaled; not started"
3607                    );
3608                    self.forget(id).await;
3609                    outcomes[at] = Err(None);
3610                }
3611            }
3612        }
3613        // No start deadline: the master takes an assignment back only once this worker's
3614        // messages show it never started it (B240), so however late it came, it is still this
3615        // worker's to start.
3616        outcomes
3617    }
3618
3619    /// A cleanup's assignment kept beside its journal record (to run it again after a
3620    /// restart, decision 248); nothing for a task without a cleanup.
3621    async fn keep_for_cleanup(&self, prepared: &Prepared) -> std::io::Result<()> {
3622        let Prepared {
3623            assign,
3624            spec,
3625            external,
3626            ..
3627        } = prepared;
3628        if spec.task.cleanup.is_none() {
3629            return Ok(());
3630        }
3631        let mut assign = assign.clone();
3632        if let Some(inputs) = external {
3633            assign.inputs_json.clone_from(inputs);
3634            assign.inputs_external = false;
3635        }
3636        let kept = KeptAttempt {
3637            assign,
3638            code_dir: spec.code_dir.clone(),
3639            code_hash: self.code_hash_of(spec),
3640            root_copies: spec.root_copies.clone(),
3641            script_dir: spec.script_dir.clone(),
3642        };
3643        let journal = self.journal.clone();
3644        let id = spec.attempt_id.clone();
3645        tokio::task::spawn_blocking(move || journal.keep(&id, &kept))
3646            .await
3647            .map_err(std::io::Error::other)
3648            .and_then(|kept| kept)
3649    }
3650
3651    /// The hash of the code `spec` was planned against.
3652    fn code_hash_of(&self, spec: &AttemptSpec) -> Option<String> {
3653        self.watchers
3654            .get(&spec.dag_root)
3655            .and_then(RootWatcher::hash)
3656            .map(str::to_owned)
3657    }
3658
3659    /// A task's API call: given its ID (and a key, if it has none), sent on to the master and
3660    /// kept until answered; refused here when over the master's limit (M4.11h).
3661    fn api_call(
3662        &mut self,
3663        mut call: pb::ApiCall,
3664        answer: oneshot::Sender<pb::ApiAnswer>,
3665        to_master: Option<&ToMaster>,
3666    ) {
3667        // Its task gone or out of time: not sent (Grok's review), the call left to its key.
3668        if answer.is_closed() {
3669            return;
3670        }
3671        self.api_call_id = self.api_call_id.wrapping_add(1);
3672        call.request_id = self.api_call_id;
3673        // Over the master's limit, it would end the stream, the other calls with it.
3674        let size = prost::Message::encoded_len(&call);
3675        if size > self.master_limit.saturating_sub(1024) {
3676            let error = format!(
3677                "the request is {size} bytes, over the {} the master takes ([grpc] \
3678                 max_message_size)",
3679                self.master_limit
3680            );
3681            let _ = answer.send(pb::ApiAnswer {
3682                request_id: call.request_id,
3683                status: 413,
3684                body_json: serde_json::to_vec(&serde_json::json!({ "error": error }))
3685                    .unwrap_or_default(),
3686            });
3687            return;
3688        }
3689        if let Some(to_master) = to_master {
3690            let _ = to_master.send(wrap(worker_message::Message::ApiCall(call.clone())));
3691        }
3692        // Calls given up (their task gone, or out of time) aren't kept.
3693        self.api_calls.retain(|_, (_, answer)| !answer.is_closed());
3694        self.api_calls.insert(call.request_id, (call, answer));
3695    }
3696
3697    /// Where a task's API calls go: through the agent's loop, on to the master (M4.11h).
3698    /// (See [`first_api_call_id`] for their IDs.)
3699    fn api_send(&self) -> crate::api::ApiSend {
3700        let done = self.done_tx.clone();
3701        Arc::new(move |call| {
3702            let (answer, answered) = oneshot::channel();
3703            let _ = done.send(Done::ApiCall { call, answer });
3704            answered
3705        })
3706    }
3707
3708    /// A task with a cleanup: its handles go to the journal, a drain leaves room for one try,
3709    /// and a timeout too long for the grace period is warned of, once per task (decision 250).
3710    fn note_cleanup(&mut self, spec: &mut AttemptSpec, assign: &pb::AssignTask) {
3711        let Some(cleanup) = &spec.task.cleanup else {
3712            return;
3713        };
3714        spec.journal = Some(self.journal.clone());
3715        let done = self.done_tx.clone();
3716        let attempt_id = spec.attempt_id.clone();
3717        spec.handle_sink = Some(HandleSink(Arc::new(move |position, handle| {
3718            let _ = done.send(Done::Handle {
3719                attempt_id: attempt_id.clone(),
3720                position,
3721                handle: handle.clone(),
3722            });
3723        })));
3724        let room = cleanup
3725            .timeout_ms
3726            .map_or(self.settings.setup.timeouts.cleanup, Duration::from_millis);
3727        self.cleanup_room.insert(spec.attempt_id.clone(), room);
3728        let drain = self.settings.drain;
3729        let dag = assign.run.as_ref().map_or("", |run| run.dag_id.as_str());
3730        // The default is said once, at the worker's start: here, what the task itself asks for.
3731        if cleanup.timeout_ms.is_some()
3732            && !drain.cleanup_fits(room)
3733            && self
3734                .warned_room
3735                .insert((dag.to_owned(), assign.task_id.clone()))
3736        {
3737            tracing::warn!(
3738                dag,
3739                task = assign.task_id.as_str(),
3740                cleanup_timeout = ?room,
3741                grace = ?drain.grace,
3742                "the task's `cleanup_timeout` doesn't fit in `termination_grace_period`: whatever \
3743                 ends the worker at the end of a drain (a pod's kill, a service manager) would \
3744                 lose its cleanup"
3745            );
3746        }
3747    }
3748
3749    /// Runs a started attempt in the background; what happens is reported on `done_tx`.
3750    fn launch(&self, spec: AttemptSpec, plan: Plan, stopped: Stops) {
3751        let executor = self.executor.clone();
3752        let done = self.done_tx.clone();
3753        let on_spawn = self.done_tx.clone();
3754        let attempt_id = spec.attempt_id.clone();
3755        let spawned: Spawned = Arc::new(move |identity, forked| {
3756            let _ = on_spawn.send(Done::Spawned {
3757                attempt_id: attempt_id.clone(),
3758                identity,
3759                forked,
3760            });
3761        });
3762        let on_end = self.done_tx.clone();
3763        let ended: TaskEnded = Box::new(move |finished| {
3764            let _ = on_end.send(Done::TaskEnded(finished));
3765        });
3766        tokio::spawn(async move {
3767            let finished = executor.run(spec, plan, stopped, spawned, ended).await;
3768            let _ = done.send(Done::Attempt(finished));
3769        });
3770    }
3771
3772    /// Keeps the other roots' copies a task was planned against while it runs: its script
3773    /// root's, the other DAG roots' on its `sys.path` (held by their folder, named after the
3774    /// hash).
3775    fn remember_other_copies(&mut self, spec: &AttemptSpec) {
3776        let held: Vec<String> = spec
3777            .root_copies
3778            .values()
3779            .chain(&spec.script_dir)
3780            .filter_map(|dir| Some(dir.file_name()?.to_string_lossy().into_owned()))
3781            .collect();
3782        if !held.is_empty() {
3783            self.other_copies.insert(spec.attempt_id.clone(), held);
3784        }
3785    }
3786
3787    fn release_code(&mut self, attempt_id: &str) -> Option<String> {
3788        self.other_copies.remove(attempt_id);
3789        self.rest_cleaning.remove(attempt_id);
3790        self.code_hashes.remove(attempt_id)
3791    }
3792
3793    /// Notes the hash of the task's root now, for its `Finished`.
3794    fn remember_code(&mut self, assign: &pb::AssignTask, spec: &AttemptSpec) {
3795        let attempt_id = spec.attempt_id.as_str();
3796        self.remember_other_copies(spec);
3797        if let Some(hash) = assign
3798            .dag_file
3799            .as_ref()
3800            .and_then(|f| self.watchers.get(&f.root))
3801            .and_then(RootWatcher::hash)
3802        {
3803            self.code_hashes
3804                .insert(attempt_id.to_owned(), hash.to_owned());
3805        }
3806    }
3807
3808    /// Why this worker takes no new attempt now, if it doesn't: draining, or no free slot.
3809    fn cannot_take(&self, wait_step: bool) -> Option<(pb::RejectReason, &'static str)> {
3810        self.cannot_take_held(wait_step, &Held::default())
3811    }
3812
3813    /// As [`Self::cannot_take`], with `held`'s slots taken too (a group's assignments not yet
3814    /// started, M5.1b).
3815    fn cannot_take_held(
3816        &self,
3817        wait_step: bool,
3818        held: &Held,
3819    ) -> Option<(pb::RejectReason, &'static str)> {
3820        if self.drain.is_some() {
3821            Some((pb::RejectReason::Draining, "the worker is draining"))
3822        } else if wait_step && self.free_watcher_slots() <= held.wait_steps {
3823            Some((pb::RejectReason::NoFreeSlot, "no free watcher slot"))
3824        } else if !wait_step && self.free_slots() <= held.tasks {
3825            Some((pb::RejectReason::NoFreeSlot, "no free slot"))
3826        } else {
3827            None
3828        }
3829    }
3830
3831    /// Plans an attempt here; a DAG file missing from the code the master expects fails it
3832    /// (the file is gone) instead of rejecting it as "code not there yet".
3833    fn plan(&self, spec: &mut AttemptSpec, assign: &pb::AssignTask) -> Result<Plan, NotRun> {
3834        spec.default_timeout(assign, &self.settings.setup.timeouts);
3835        // The copy of the code the root's reported hash is of (decision 102); the configured
3836        // path until the root's first scan.
3837        let code = self
3838            .watchers
3839            .get(&spec.dag_root)
3840            .and_then(RootWatcher::code_dir);
3841        spec.code_dir = code.map(Path::to_path_buf);
3842        spec.root_copies = self
3843            .watchers
3844            .iter()
3845            .filter(|(name, _)| {
3846                **name != spec.dag_root && !self.settings.setup.script_roots.contains_key(*name)
3847            })
3848            .filter_map(|(name, watcher)| Some((name.clone(), watcher.code_dir()?.to_path_buf())))
3849            .collect();
3850        // A script task's script root: its copy at the hash folded into the task's (301).
3851        if let TaskKind::Script { job, .. } = &spec.task.kind {
3852            let root = job.split_once(':').map_or(job.as_str(), |(root, _)| root);
3853            spec.script_dir = self
3854                .watchers
3855                .get(root)
3856                .filter(|_| self.settings.setup.script_roots.contains_key(root))
3857                .and_then(RootWatcher::code_dir)
3858                .map(Path::to_path_buf);
3859        }
3860        // A moved cleanup runs only the cleanup: what the task itself needed doesn't matter here.
3861        let mut moved = None;
3862        if assign.cleanup_only.is_some() {
3863            let mut cleanup = spec.clone();
3864            use_cleanup_script(&mut cleanup.task);
3865            moved = Some(cleanup);
3866        }
3867        let planning = moved.as_ref().unwrap_or(spec);
3868        let planned = match code {
3869            Some(dir) => plan_at(planning, &self.settings.setup, dir),
3870            None => plan(planning, &self.settings.setup),
3871        };
3872        match planned {
3873            Err(NotRun::Rejected {
3874                reason: pb::RejectReason::DagFileMissing | pb::RejectReason::ScriptReferenceNotFound,
3875                detail,
3876            }) if self.has_expected_code(assign) => Err(NotRun::Failed {
3877                kind: DAG_FILE_MISSING.to_owned(),
3878                message: format!("{detail}, in the newest code of its root: the file is gone"),
3879            }),
3880            planned => planned,
3881        }
3882    }
3883
3884    /// Whether the task's root is here at the hash the master expects.
3885    fn has_expected_code(&self, assign: &pb::AssignTask) -> bool {
3886        let expected = assign.expected_code_hash.as_str();
3887        !expected.is_empty()
3888            && assign
3889                .dag_file
3890                .as_ref()
3891                .and_then(|f| self.reported_hash(&f.root))
3892                .as_deref()
3893                == Some(expected)
3894    }
3895
3896    /// Why the task's root here isn't the code the master expects (`None` when it is, or
3897    /// when the root isn't here at all: planning rejects that).
3898    fn code_mismatch(&self, assign: &pb::AssignTask) -> Option<String> {
3899        let root = assign.dag_file.as_ref()?.root.as_str();
3900        let scanned = self
3901            .watchers
3902            .get(root)
3903            .and_then(RootWatcher::hash)
3904            .is_some();
3905        let Some(here) = self.reported_hash(root) else {
3906            // Withdrawn (303): it lacks a script root the root uses, so runs none of its tasks.
3907            return scanned.then(|| {
3908                format!(
3909                    "root `{root}` is withdrawn here: a script root it uses isn't on this worker"
3910                )
3911            });
3912        };
3913        let expected = assign.expected_code_hash.as_str();
3914        (!expected.is_empty() && here != expected)
3915            .then(|| format!("root `{root}` here is at {here}, the task expects {expected}"))
3916    }
3917
3918    /// Removes the copies of code (decision 102) nothing needs any more: each root's but its
3919    /// current hash's and those a running attempt or parse job imports from.
3920    fn collect_code(&self) {
3921        let mut in_use: std::collections::BTreeSet<String> = self
3922            .code_hashes
3923            .values()
3924            .chain(self.other_copies.values().flatten())
3925            .chain(self.parsing.keys())
3926            .map(|hash| hash.replace(':', "-"))
3927            .collect();
3928        in_use.extend(self.executor.code_in_use());
3929        for watcher in self.watchers.values() {
3930            let Ok(entries) = std::fs::read_dir(watcher.store()) else {
3931                continue;
3932            };
3933            let current = watcher.code_dir();
3934            for entry in entries.flatten() {
3935                let path = entry.path();
3936                let name = entry.file_name().to_string_lossy().into_owned();
3937                if Some(path.as_path()) == current || in_use.contains(&name) {
3938                    continue;
3939                }
3940                if let Err(error) = crate::scan::remove_capture(&path) {
3941                    tracing::warn!(path = %path.display(), %error, "can't remove old DAG code");
3942                }
3943            }
3944        }
3945    }
3946
3947    fn parse(&mut self, job: pb::AssignParse) {
3948        let Some(root) = job.root else {
3949            return;
3950        };
3951        if self.drain.is_some() {
3952            // Sent before the master knew: it gives the job to another worker.
3953            tracing::info!(
3954                root = root.root.as_str(),
3955                "parse job while draining; left to others"
3956            );
3957            return;
3958        }
3959        let Some(watcher) = self.watchers.get(&root.root) else {
3960            tracing::warn!(
3961                root = root.root.as_str(),
3962                "parse job for a root this worker doesn't have"
3963            );
3964            return;
3965        };
3966        if self.reported_hash(&root.root).as_deref() != Some(root.content_hash.as_str()) {
3967            // The root changed since: its new hash was (or will be) reported.
3968            return;
3969        }
3970        let Some(copy) = watcher.hash().map(str::to_owned) else {
3971            return;
3972        };
3973        let (Some(snapshot), Some(code)) = (watcher.snapshot(), watcher.code_dir()) else {
3974            return;
3975        };
3976        if !self
3977            .parses_running
3978            .insert((root.root.clone(), root.content_hash.clone()))
3979        {
3980            tracing::debug!(root = root.root.as_str(), "parse job already running");
3981            return;
3982        }
3983        // The copy of the code that hash is of (decision 102), not the configured path, which
3984        // git-sync may have moved on (B58).
3985        let mut files = snapshot.python_files();
3986        // Only the files chosen, for `schedr dags test` of one file (decision 117).
3987        if let Some(only) = self.settings.setup.parse_only.get(&root.root) {
3988            files.retain(|file| only.contains(file));
3989        }
3990        let dir = code.to_path_buf();
3991        let done = self.done_tx.clone();
3992        if self.settings.setup.script_roots.contains_key(&root.root) {
3993            // Read here, in Rust, never imported (decision 293).
3994            let files: Vec<String> = snapshot.files().keys().cloned().collect();
3995            let wanted: Vec<String> = files
3996                .iter()
3997                .filter(|file| crate::jobs::is_config(file))
3998                .cloned()
3999                .collect();
4000            *self.parsing.entry(copy.clone()).or_default() += 1;
4001            tokio::task::spawn_blocking(move || {
4002                let parsed = crate::jobs::read_root(&root.root, &dir, (&files, &wanted), None);
4003                let _ = done.send(Done::Parse {
4004                    job_id: job.parse_job_id,
4005                    root,
4006                    copies: vec![copy],
4007                    files: Ok(parsed),
4008                });
4009            });
4010            return;
4011        }
4012        let (code, mut copies) = self.parse_code(&root.root);
4013        copies.push(copy);
4014        for copy in &copies {
4015            *self.parsing.entry(copy.clone()).or_default() += 1;
4016        }
4017        let executor = self.executor.clone();
4018        tokio::spawn(async move {
4019            let parsed = executor.parse(root.root.clone(), dir, files, code).await;
4020            let _ = done.send(Done::Parse {
4021                job_id: job.parse_job_id,
4022                root,
4023                copies,
4024                files: parsed,
4025            });
4026        });
4027    }
4028
4029    /// The copies of the other roots a parse of `root` sees (script roots for a
4030    /// `ScriptOperator`, DAG roots on `sys.path`), with their content hashes to hold meanwhile.
4031    fn parse_code(&self, root: &str) -> (ParseCode, Vec<String>) {
4032        let mut code = ParseCode::default();
4033        let mut held = Vec::new();
4034        for (name, watcher) in &self.watchers {
4035            let (Some(hash), Some(dir)) = (watcher.hash(), watcher.code_dir()) else {
4036                continue;
4037            };
4038            if name == root {
4039                continue;
4040            }
4041            if let Some(configured) = self.settings.setup.script_roots.get(name) {
4042                code.scripts.insert(
4043                    name.clone(),
4044                    crate::jobs::ScriptRoot {
4045                        configured: configured.clone(),
4046                        copy: dir.to_path_buf(),
4047                    },
4048                );
4049            } else {
4050                code.roots.insert(name.clone(), dir.to_path_buf());
4051            }
4052            held.push(hash.to_owned());
4053        }
4054        (code, held)
4055    }
4056
4057    /// A connections job (decisions 174, 193): run beside the tasks, no slot, one at a time;
4058    /// a job this worker can't run is answered with why.
4059    fn connection_job(&mut self, job: pb::ConnectionJob) {
4060        let job_id = job.job_id.clone();
4061        let root = job.root.unwrap_or_default();
4062        let registry: Registry = match serde_json::from_slice(&job.connections_json) {
4063            Ok(registry) => registry,
4064            Err(e) => {
4065                tracing::warn!(job_id, error = %e, "a connections job that doesn't read");
4066                return;
4067            }
4068        };
4069        // The copy of the code it was sent for (a test imports from it), held meanwhile.
4070        let watcher = self.watchers.get(&root.root);
4071        let current = self.reported_hash(&root.root).as_deref() == Some(root.content_hash.as_str());
4072        let code_dir = watcher
4073            .filter(|_| current)
4074            .and_then(|w| w.code_dir().map(Path::to_path_buf));
4075        // The copy's content hash, by which it is kept meanwhile.
4076        let hash = code_dir
4077            .as_ref()
4078            .and_then(|_| watcher.and_then(RootWatcher::hash).map(str::to_owned));
4079        if let Some(hash) = &hash {
4080            *self.parsing.entry(hash.clone()).or_default() += 1;
4081        }
4082        let test = job
4083            .test
4084            .map(|t| (t.name, Duration::from_millis(t.timeout_ms)));
4085        if test.is_some() && code_dir.is_none() {
4086            let name = test.map(|(name, _)| name).unwrap_or_default();
4087            let why = format!(
4088                "this worker no longer has root `{}` at the code it was sent for: try again",
4089                root.root
4090            );
4091            let _ = self.done_tx.send(Done::Connections {
4092                job_id,
4093                hash,
4094                attempt_id: None,
4095                reports: vec![crate::connection_jobs::failed(&name, why)],
4096            });
4097            return;
4098        }
4099        // Its time counts from now, its wait for its turn included: the caller waits no
4100        // longer than that and a margin.
4101        let allowed = test.as_ref().map_or(
4102            Duration::from_millis(schedr_model::commands::CONNECTION_CHECK_TIMEOUT_MS),
4103            |(_, timeout)| *timeout,
4104        );
4105        let deadline = tokio::time::Instant::now() + allowed;
4106        // A name of its own for its folders and its journal record.
4107        let attempt_id = format!("connection-test-{}", jiff::Timestamp::now().as_nanosecond());
4108        let tested = test.is_some().then(|| attempt_id.clone());
4109        let job = ConnectionJob {
4110            root: root.root,
4111            code_dir,
4112            registry: Arc::new(registry),
4113            test,
4114            cancel_grace: self.settings.setup.timeouts.connection_cancel_grace,
4115            attempt_id: attempt_id.clone(),
4116            deadline,
4117        };
4118        let executor = self.executor.clone();
4119        let done = self.done_tx.clone();
4120        let on_spawn = self.done_tx.clone();
4121        // Recorded as an attempt's process: a worker killed meanwhile stops it on its start.
4122        let spawned: Spawned = Arc::new(move |identity, _| {
4123            let _ = on_spawn.send(Done::Spawned {
4124                attempt_id: attempt_id.clone(),
4125                identity,
4126                forked: false,
4127            });
4128        });
4129        let one_at_a_time = Arc::clone(&self.connection_jobs);
4130        tokio::spawn(async move {
4131            let reports = match tokio::time::timeout_at(deadline, one_at_a_time.lock()).await {
4132                Ok(_turn) => executor.connection_job(job, spawned).await,
4133                Err(_) => job
4134                    .registry
4135                    .names()
4136                    .map(|name| {
4137                        crate::connection_jobs::failed(
4138                            name,
4139                            crate::connection_jobs::out_of_time(
4140                                "wait for its turn (one connections job at a time per worker)",
4141                            ),
4142                        )
4143                    })
4144                    .collect(),
4145            };
4146            let _ = done.send(Done::Connections {
4147                job_id,
4148                hash,
4149                attempt_id: tested,
4150                reports,
4151            });
4152        });
4153    }
4154
4155    /// Records what ended, and reports it over `link` (the outbound stream and the client)
4156    /// when connected.
4157    async fn on_done(&mut self, done: Done, link: Option<(&ToMaster, &mut MasterClient<Channel>)>) {
4158        match done {
4159            Done::Spawned {
4160                attempt_id,
4161                identity,
4162                forked,
4163            } => {
4164                let to_master = link.as_ref().map(|(to_master, _)| *to_master);
4165                let (record, repeat) = self.spawned_record(&attempt_id, identity, forked);
4166                self.keep_processes(vec![(attempt_id, record, repeat)], to_master)
4167                    .await;
4168            }
4169            Done::TaskEnded(finished) => {
4170                self.task_ended(finished, link.map(|(to_master, _)| to_master))
4171                    .await;
4172            }
4173            Done::Handle {
4174                attempt_id,
4175                position,
4176                handle,
4177            } => {
4178                if let Some((to_master, _)) = link {
4179                    let _ = to_master.send(handles_message(attempt_id, position, &[handle]));
4180                }
4181            }
4182            Done::Attempt(finished) => {
4183                let finished = self.result_ready(finished);
4184                self.record_finished(&finished).await;
4185                self.result_recorded(finished, link.map(|(to_master, _)| to_master));
4186            }
4187            Done::Trigger(done) => self.trigger_done(done, link.map(|(to, _)| to)),
4188            Done::ApiCall { call, answer } => {
4189                self.api_call(call, answer, link.map(|(to, _)| to));
4190            }
4191            Done::Parse {
4192                job_id,
4193                root,
4194                copies,
4195                files,
4196            } => {
4197                self.parses_running
4198                    .remove(&(root.root.clone(), root.content_hash.clone()));
4199                for copy in copies {
4200                    if let Some(count) = self.parsing.get_mut(&copy) {
4201                        *count -= 1;
4202                        if *count == 0 {
4203                            self.parsing.remove(&copy);
4204                        }
4205                    }
4206                }
4207                self.collect_code();
4208                self.report_parse(job_id, root, files, link);
4209            }
4210            Done::Connections {
4211                job_id,
4212                hash,
4213                attempt_id,
4214                reports,
4215            } => {
4216                self.connections_done(job_id, hash, attempt_id, &reports, link.map(|(to, _)| to))
4217                    .await;
4218            }
4219        }
4220    }
4221
4222    /// A connections job ended: its code and journal record let go, its answer sent (kept
4223    /// while no master listens).
4224    async fn connections_done(
4225        &mut self,
4226        job_id: String,
4227        hash: Option<String>,
4228        attempt_id: Option<String>,
4229        reports: &[schedr_model::commands::ConnectionReport],
4230        to_master: Option<&ToMaster>,
4231    ) {
4232        if let Some(attempt_id) = attempt_id {
4233            self.forget(&attempt_id).await;
4234        }
4235        if let Some(hash) = hash
4236            && let Some(count) = self.parsing.get_mut(&hash)
4237        {
4238            *count -= 1;
4239            if *count == 0 {
4240                self.parsing.remove(&hash);
4241            }
4242            self.collect_code();
4243        }
4244        let report_json = reports
4245            .iter()
4246            .filter_map(|report| serde_json::to_vec(report).ok())
4247            .collect();
4248        let done = pb::ConnectionJobDone {
4249            job_id,
4250            report_json,
4251        };
4252        if let Some(to_master) = to_master {
4253            let _ = to_master.send(wrap(worker_message::Message::ConnectionJobDone(done)));
4254        } else {
4255            // Sent once registered again (the master drops an answer it gave up on).
4256            if self.unsent_answers.len() >= self.settings.setup.timeouts.unsent_connection_answers {
4257                self.unsent_answers.pop_front();
4258            }
4259            self.unsent_answers.push_back(done);
4260        }
4261    }
4262
4263    /// Uploads a parse job's result over `link`, or says why it can't.
4264    fn report_parse(
4265        &self,
4266        job_id: String,
4267        root: pb::RootHash,
4268        files: Result<Vec<ParsedFile>, String>,
4269        link: Option<(&ToMaster, &mut MasterClient<Channel>)>,
4270    ) {
4271        match (files, link) {
4272            (Ok(_), None) => tracing::warn!(
4273                root = root.root.as_str(),
4274                "parse result dropped: no master connection (the job is given out again)"
4275            ),
4276            (Ok(files), Some((_, client))) => {
4277                let limit = self.master_limit;
4278                let result = pb::ParseResult {
4279                    parse_job_id: job_id,
4280                    worker_id: self.settings.worker_id.clone(),
4281                    root: Some(root),
4282                    schedr_version: AGENT_VERSION.to_owned(),
4283                    files: files
4284                        .iter()
4285                        .map(|file| fitted_file(parsed_file_to_proto(file), limit))
4286                        .collect(),
4287                };
4288                // In a task of its own: a large root's upload takes a while, and the
4289                // session's loop must keep sending heartbeats meanwhile (B34). A file a
4290                // message, so only one file's size counts against the limit (B35).
4291                let parts = tokio_stream::iter(parse_upload_parts(result));
4292                let mut client = client.clone();
4293                tokio::spawn(async move {
4294                    if let Err(status) = client.upload_parse_result(parts).await {
4295                        tracing::error!(%status, "parse result not uploaded");
4296                    }
4297                });
4298            }
4299            (Err(error), _) => {
4300                tracing::error!(root = root.root.as_str(), error, "parse job failed");
4301            }
4302        }
4303    }
4304
4305    fn watch(&mut self, to_master: &ToMaster) {
4306        let mut changed_any = false;
4307        for (name, watcher) in &mut self.watchers {
4308            match watcher.poll(Instant::now()) {
4309                Ok(Poll::Changed { .. }) => changed_any = true,
4310                Ok(_) => {}
4311                Err(error) => tracing::warn!(root = name.as_str(), %error, "can't scan the root"),
4312            }
4313        }
4314        if changed_any {
4315            // A script root's change is new code for the DAG roots using it too (decision 301).
4316            self.report_changes(to_master);
4317            // The previous code's copy, unless something still runs from it.
4318            self.collect_code();
4319        }
4320    }
4321
4322    /// Whether this worker cleans the rest of attempt `id`'s handles (`CLEAN_REST`, B169).
4323    fn cleaning_rest(&self, id: &str) -> bool {
4324        self.rest_cleaning.contains(id)
4325    }
4326
4327    /// How many cleanup handles attempt `id` has journaled: the master compares it with what
4328    /// it has (B169). Read from the journal, which has a handle before the loop hears of it
4329    /// (Codex's review of B169: a `Register` built in between said one fewer).
4330    fn handle_count(&self, id: &str) -> u32 {
4331        let waiting = self.waiting.get(id).map_or(0, |w| w.handles.len());
4332        let journaled = self.journal.handles(id).map_or_else(
4333            |error| {
4334                tracing::warn!(attempt_id = id, %error, "can't read the journaled handles");
4335                0
4336            },
4337            |handles| handles.len(),
4338        );
4339        u32::try_from(journaled.max(waiting)).unwrap_or(u32::MAX)
4340    }
4341
4342    fn journal_entries(&self) -> Vec<pb::JournalEntry> {
4343        let running = self.running.keys().map(|id| pb::JournalEntry {
4344            attempt_id: id.clone(),
4345            state: pb::JournalState::Running.into(),
4346            handles: self.handle_count(id),
4347        });
4348        let finished = self.unacked.keys().map(|id| pb::JournalEntry {
4349            attempt_id: id.clone(),
4350            state: pb::JournalState::Finished.into(),
4351            handles: self.handle_count(id),
4352        });
4353        running.chain(finished).collect()
4354    }
4355
4356    fn free_slots(&self) -> u32 {
4357        if self.drain.is_some() {
4358            return 0;
4359        }
4360        self.settings
4361            .slots
4362            .saturating_sub(u32::try_from(self.tasks_running()).unwrap_or(u32::MAX))
4363    }
4364
4365    fn free_watcher_slots(&self) -> u32 {
4366        if self.drain.is_some() {
4367            return 0;
4368        }
4369        self.settings
4370            .watcher_slots
4371            .saturating_sub(u32::try_from(self.wait_steps.len()).unwrap_or(u32::MAX))
4372            .saturating_sub(u32::try_from(self.triggers.len()).unwrap_or(u32::MAX))
4373    }
4374
4375    fn note_wait_step(&mut self, spec: &AttemptSpec) {
4376        if let schedr_model::TaskKind::Sensor { mode, .. } = spec.task.kind {
4377            self.wait_steps.insert(
4378                spec.attempt_id.clone(),
4379                mode == schedr_model::SensorMode::Poke,
4380            );
4381        }
4382    }
4383
4384    fn ended_running(&mut self, attempt_id: &str) {
4385        self.running.remove(attempt_id);
4386        self.wait_steps.remove(attempt_id);
4387        self.set_slot_gauges();
4388    }
4389
4390    /// The attempts running on task slots.
4391    fn tasks_running(&self) -> usize {
4392        self.running.len().saturating_sub(self.wait_steps.len())
4393    }
4394}
4395
4396/// The `Started` saying a fork server forked `attempt_id` (the master keeps the first start
4397/// time and takes the method).
4398fn forked_started(attempt_id: &str) -> pb::WorkerMessage {
4399    wrap(worker_message::Message::Started(pb::Started {
4400        attempt_id: attempt_id.to_owned(),
4401        start_method: pb::StartMethod::Fork.into(),
4402        // The first `Started`'s time is kept: this one says only the method.
4403        ..pb::Started::default()
4404    }))
4405}
4406
4407/// What a trigger did.
4408enum TriggerDone {
4409    /// It found something: on to the master, `stored` told once it has it.
4410    Found {
4411        instance_id: String,
4412        event: crate::watchers::FoundEvent,
4413        stored: tokio::sync::oneshot::Sender<()>,
4414    },
4415    /// A poke's call ended; why it failed, if it did.
4416    Poked {
4417        instance_id: String,
4418        error: Option<String>,
4419    },
4420    /// It ended.
4421    Ended {
4422        instance_id: String,
4423        finished: Box<pb::Finished>,
4424    },
4425}
4426
4427/// How a poke's calls have gone, for the master: at most once a heartbeat unless that changes.
4428#[derive(Debug, Default)]
4429struct PokeReport {
4430    at: Option<Timestamp>,
4431    error: Option<String>,
4432    failures: u32,
4433    unsent: bool,
4434}
4435
4436/// A trigger running on this worker.
4437#[derive(Debug)]
4438struct RunningTrigger {
4439    dag_id: String,
4440    stop: StopSender,
4441    next_seq: u64,
4442    /// What it found that the master hasn't said it has, by its place.
4443    unstored: BTreeMap<u64, (pb::TriggerEvent, tokio::sync::oneshot::Sender<()>)>,
4444    poke: PokeReport,
4445}
4446
4447fn poke_report(instance_id: &str, trigger: &RunningTrigger) -> pb::WorkerMessage {
4448    wrap(worker_message::Message::TriggerPoked(pb::TriggerPoked {
4449        dag_id: trigger.dag_id.clone(),
4450        instance_id: instance_id.to_owned(),
4451        at: trigger.poke.at.map(proto_time),
4452        error: trigger.poke.error.clone().unwrap_or_default(),
4453        failures: trigger.poke.failures,
4454    }))
4455}
4456
4457fn proto_time(time: Timestamp) -> prost_types::Timestamp {
4458    prost_types::Timestamp {
4459        seconds: time.as_second(),
4460        nanos: time.subsec_nanosecond(),
4461    }
4462}
4463
4464/// How a trigger ended, as the master hears it: asked to stop, or done with the run it was
4465/// called for (`@trigger(wait_for=...)`, decision 353), it is no error.
4466fn trigger_stopped(
4467    dag_id: String,
4468    instance_id: String,
4469    finished: &pb::Finished,
4470) -> pb::TriggerStopped {
4471    let asked = finished.status == pb::AttemptStatus::Cancelled as i32
4472        || finished.status == pb::AttemptStatus::Interrupted as i32
4473        || finished.status == pb::AttemptStatus::Success as i32;
4474    let (error_kind, message) = if asked {
4475        (String::new(), String::new())
4476    } else {
4477        let summary: Option<schedr_model::runner::ErrorSummary> =
4478            serde_json::from_slice(&finished.error_summary_json).ok();
4479        let kind = if finished.error_kind.is_empty() {
4480            "trigger_failed".to_owned()
4481        } else {
4482            finished.error_kind.clone()
4483        };
4484        (
4485            kind,
4486            summary.map_or_else(String::new, |s| format!("{}: {}", s.exception, s.message)),
4487        )
4488    };
4489    pb::TriggerStopped {
4490        dag_id,
4491        instance_id,
4492        error_kind,
4493        message,
4494        struck: finished.struck,
4495        code_hash: finished.code_hash.clone(),
4496        done: finished.status == pb::AttemptStatus::Success as i32,
4497        returned_event: false,
4498    }
4499}
4500
4501/// Whether an assignment is of a wait step; one that doesn't read is found out later.
4502fn assigned_a_wait_step(assign: &pb::AssignTask) -> bool {
4503    serde_json::from_slice::<schedr_model::Task>(&assign.task_json)
4504        .is_ok_and(|task| matches!(task.kind, schedr_model::TaskKind::Sensor { .. }))
4505}
4506
4507/// A heartbeat timer of `period`: a tick missed (the loop busy, the process paused) is
4508/// delayed, not caught up in a burst.
4509fn heartbeat_timer(period: Duration) -> tokio::time::Interval {
4510    let mut interval = tokio::time::interval(period);
4511    interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
4512    interval
4513}
4514
4515/// When each unacknowledged result is sent again over a session, counted in heartbeats:
4516/// first at the second heartbeat that finds it unacknowledged (at least one interval after it
4517/// was sent), then after twice the last gap, up to its `gap_max` ([`MAX_RESEND_GAP`] by
4518/// default); at most `most` times ([`MAX_RESENDS`]).
4519#[derive(Debug)]
4520struct Resends {
4521    /// Heartbeats so far.
4522    beat: u64,
4523    /// Per result: the heartbeat it is due at, the gap after that, and the sends so far.
4524    due: BTreeMap<String, Resend>,
4525    /// The most sends of one result.
4526    most: u32,
4527    /// The longest gap, in heartbeats.
4528    gap_max: u32,
4529}
4530
4531impl Default for Resends {
4532    fn default() -> Self {
4533        Self::limited(MAX_RESENDS, MAX_RESEND_GAP)
4534    }
4535}
4536
4537#[derive(Debug, Clone, Copy)]
4538struct Resend {
4539    at: u64,
4540    gap: u32,
4541    sent: u32,
4542}
4543
4544impl Resends {
4545    /// None due yet; at most `most` sends of one, gaps of at most `gap_max` heartbeats.
4546    fn limited(most: u32, gap_max: u32) -> Self {
4547        Self {
4548            beat: 0,
4549            due: BTreeMap::new(),
4550            most: most.max(1),
4551            gap_max: gap_max.max(1),
4552        }
4553    }
4554
4555    /// A heartbeat, `unacked` the results unacknowledged now: those due to be sent again; none
4556    /// when one has been sent `most` times already and is due again (the session is
4557    /// given up).
4558    fn due<'a>(&mut self, unacked: impl Iterator<Item = &'a String>) -> Option<Vec<String>> {
4559        self.beat += 1;
4560        let beat = self.beat;
4561        let mut due = BTreeMap::new();
4562        let mut send = Vec::new();
4563        for id in unacked {
4564            let mut resend = self.due.get(id).copied().unwrap_or(Resend {
4565                at: beat + 1,
4566                gap: 1,
4567                sent: 0,
4568            });
4569            if resend.at <= beat {
4570                if resend.sent >= self.most {
4571                    return None;
4572                }
4573                send.push(id.clone());
4574                resend.gap = resend.gap.saturating_mul(2).min(self.gap_max);
4575                resend.at = beat + u64::from(resend.gap);
4576                resend.sent += 1;
4577            }
4578            due.insert(id.clone(), resend);
4579        }
4580        self.due = due;
4581        Some(send)
4582    }
4583}
4584
4585/// The folder of root `name`'s code copies under the code directory: its name with anything
4586/// but letters, digits, `-` and `_` replaced, and a hash of the real name, so two roots never
4587/// share one (each root's cleanup removes what its folder holds).
4588fn code_folder(name: &str) -> String {
4589    use sha2::Digest as _;
4590    let readable: String = name
4591        .chars()
4592        .map(|c| {
4593            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
4594                c
4595            } else {
4596                '_'
4597            }
4598        })
4599        .collect();
4600    let digest = sha2::Sha256::digest(name.as_bytes());
4601    format!(
4602        "{readable}-{:02x}{:02x}{:02x}{:02x}",
4603        digest[0], digest[1], digest[2], digest[3]
4604    )
4605}
4606
4607/// What a fetch of inputs ended with.
4608enum Fetched {
4609    Bytes(Vec<u8>),
4610    Failed(String),
4611    /// A chunk came past the `lease` after the master's last word: not word any more.
4612    Silent,
4613}
4614
4615/// Fetches an attempt's inputs, noting each chunk in `heard` (from its value now) unless it
4616/// came past `lease` after the last.
4617async fn fetch_inputs(
4618    client: &mut MasterClient<Channel>,
4619    attempt_id: &str,
4620    heard: &watch::Sender<tokio::time::Instant>,
4621    lease: Option<Duration>,
4622) -> Fetched {
4623    let stream = client
4624        .fetch_inputs(pb::FetchInputsRequest {
4625            attempt_id: attempt_id.to_owned(),
4626        })
4627        .await;
4628    let mut stream = match stream {
4629        Ok(response) => response.into_inner(),
4630        Err(status) => return Fetched::Failed(status.to_string()),
4631    };
4632    let mut bytes = Vec::new();
4633    loop {
4634        match stream.message().await {
4635            Ok(Some(chunk)) => {
4636                let now = tokio::time::Instant::now();
4637                if lease.is_some_and(|lease| now >= *heard.borrow() + lease) {
4638                    return Fetched::Silent;
4639                }
4640                heard.send_replace(now);
4641                bytes.extend(chunk.data);
4642            }
4643            Ok(None) => return Fetched::Bytes(bytes),
4644            Err(status) => return Fetched::Failed(status.to_string()),
4645        }
4646    }
4647}
4648
4649/// A root's hash as reported, of its kind: a script root or a DAG root.
4650/// A reported hash made from a root's content hash: `kind` (`script` or `dag`) and the
4651/// reported hashes of the script roots it uses, by name, folded in (decision 301; B167).
4652#[must_use]
4653pub fn fold_hash(kind: &str, content: &str, used: &[(String, String)]) -> String {
4654    use sha2::{Digest, Sha256};
4655    let mut hasher = Sha256::new();
4656    hasher.update(kind.as_bytes());
4657    hasher.update(b"\n");
4658    hasher.update(content.as_bytes());
4659    for (name, hash) in used {
4660        hasher.update(b"\n");
4661        hasher.update(name.as_bytes());
4662        hasher.update(b"=");
4663        hasher.update(hash.as_bytes());
4664    }
4665    let digest = hasher.finalize();
4666    let mut text = String::with_capacity(crate::scan::HASH_PREFIX.len() + 64);
4667    text.push_str(crate::scan::HASH_PREFIX);
4668    for byte in digest {
4669        use std::fmt::Write as _;
4670        let _ = write!(text, "{byte:02x}");
4671    }
4672    text
4673}
4674
4675fn root_hash(setup: &WorkerSetup, name: &str, hash: &str) -> pb::RootHash {
4676    let kind = if setup.script_roots.contains_key(name) {
4677        pb::RootKind::Script
4678    } else {
4679        pb::RootKind::Dag
4680    };
4681    pb::RootHash {
4682        kind: kind.into(),
4683        root: name.to_owned(),
4684        content_hash: hash.to_owned(),
4685    }
4686}
4687
4688/// gRPC's own message limit, assumed until the master says its own in `Registered`.
4689const GRPC_DEFAULT_LIMIT: usize = 4 << 20;
4690
4691/// Room a message needs around its largest field (ids, versions, framing).
4692const MESSAGE_OVERHEAD: usize = 64 << 10;
4693
4694/// A result that can't reach the master (bigger than its message `limit`) becomes a failed
4695/// attempt, `output_too_large` (not retried), before it is journalled: sent as it was, it
4696/// would end the worker's stream, and again on every `Register` (B33). The cleanup's error
4697/// gives way first: it must not cost the task its result.
4698fn fit_result(finished: &mut pb::Finished, limit: usize) {
4699    let fits = |finished: &pb::Finished| {
4700        prost::Message::encoded_len(finished).saturating_add(MESSAGE_OVERHEAD) <= limit
4701    };
4702    if fits(finished) {
4703        return;
4704    }
4705    if let Some(cleanup) = finished.cleanup.as_mut()
4706        && !cleanup.error_summary_json.is_empty()
4707    {
4708        let message = format!(
4709            "the cleanup's error took {} bytes, too many to report",
4710            cleanup.error_summary_json.len()
4711        );
4712        cleanup.error_summary_json = ErrorSummary::json("ResultTooLarge", &message).into_bytes();
4713        if fits(finished) {
4714            return;
4715        }
4716    }
4717    let size = prost::Message::encoded_len(finished);
4718    let message = format!(
4719        "the result is {size} bytes, more than the master accepts ({limit} bytes, [grpc] \
4720         max_message_size): lower the task's max_output_size, or raise the setting"
4721    );
4722    tracing::error!(attempt_id = finished.attempt_id.as_str(), %message, "result too large");
4723    finished.status = pb::AttemptStatus::Failed.into();
4724    finished.output_json = Vec::new();
4725    finished.outcome = String::new();
4726    "output_too_large".clone_into(&mut finished.error_kind);
4727    finished.error_summary_json = ErrorSummary::json("ResultTooLarge", &message).into_bytes();
4728}
4729
4730/// A parsed file as uploaded: itself, or, when it is too big for the master's message
4731/// `limit`, an import error saying so and naming the setting (B35).
4732fn fitted_file(file: pb::ParsedFile, limit: usize) -> pb::ParsedFile {
4733    let size = prost::Message::encoded_len(&file);
4734    if size.saturating_add(MESSAGE_OVERHEAD) <= limit {
4735        return file;
4736    }
4737    let message = format!(
4738        "the file's parse result is {size} bytes, more than the master accepts ({limit} \
4739         bytes, [grpc] max_message_size): raise the setting, or split the file"
4740    );
4741    tracing::error!(path = file.path.as_str(), %message, "parsed file not uploaded");
4742    pb::ParsedFile {
4743        path: file.path,
4744        dag_json: Vec::new(),
4745        import_error: Some(pb::ImportError {
4746            exception: schedr_model::runner::PARSE_RESULT_TOO_LARGE_EXCEPTION.to_owned(),
4747            message,
4748            traceback: String::new(),
4749        }),
4750        connection_json: Vec::new(),
4751        // Kept: its DAG root still uses them (decision 304).
4752        script_roots: file.script_roots,
4753    }
4754}
4755
4756/// How long a deregistered agent waits for the master to end the stream, at most: until the
4757/// drain's `deregister_by` (B237) by default, longer than any grace period. A stalled master
4758/// still takes the `Deregister` once it reads again, the worker then shown offline (B242: a
4759/// worker gone after 5 s dropped the unsent frame with its connection, and was shown
4760/// disconnected).
4761pub const DEREGISTER_WAIT: Duration = Duration::from_hours(1);
4762
4763/// How often a drain checks its deadline and whether it is done.
4764pub const DRAIN_TICK: Duration = Duration::from_millis(100);
4765
4766/// The next change of the shutdown request count; never, without one (or once it is gone).
4767async fn next_request(shutdown: &mut Option<watch::Receiver<u32>>) -> u32 {
4768    if let Some(requests) = shutdown
4769        && requests.changed().await.is_ok()
4770    {
4771        return *requests.borrow();
4772    }
4773    std::future::pending().await
4774}
4775
4776/// Handles for the master, from place `first` on.
4777fn handles_message(attempt_id: String, first: u32, handles: &[CleanupHandle]) -> pb::WorkerMessage {
4778    wrap(worker_message::Message::HandlesAdded(pb::HandlesAdded {
4779        attempt_id,
4780        first,
4781        handle_json: handles
4782            .iter()
4783            .filter_map(|handle| serde_json::to_vec(handle).ok())
4784            .collect(),
4785    }))
4786}
4787
4788/// A task's end, as the master hears of it.
4789fn task_ended_message(result: pb::Finished) -> pb::WorkerMessage {
4790    wrap(worker_message::Message::TaskEnded(pb::TaskEnded {
4791        result: Some(result),
4792    }))
4793}
4794
4795/// Why a session ends when the master has gone silent.
4796const NO_WORD: &str = "no word from the master for the worker lease";
4797
4798/// The earlier of two moments, either of them maybe none.
4799fn earliest(
4800    a: Option<tokio::time::Instant>,
4801    b: Option<tokio::time::Instant>,
4802) -> Option<tokio::time::Instant> {
4803    a.into_iter().chain(b).min()
4804}
4805
4806/// Why a session ends when the answer to its `Register` no longer stands.
4807const TOO_LATE: &str = "the master's answer came after the worker lease; asking again";
4808
4809/// Waits until `when`; forever without one.
4810async fn at(when: Option<tokio::time::Instant>) {
4811    match when {
4812        Some(when) => tokio::time::sleep_until(when).await,
4813        None => std::future::pending().await,
4814    }
4815}
4816
4817/// The handles a moved cleanup came with.
4818fn moved_handles(only: &pb::CleanupOnly) -> Result<Vec<CleanupHandle>, serde_json::Error> {
4819    only.handle_json
4820        .iter()
4821        .map(|json| serde_json::from_slice(json))
4822        .collect()
4823}
4824
4825/// The result of a task the agent's restart stopped: `lost`, as the master would end it, and
4826/// using a retry (the crash may have been its own).
4827fn restarted(attempt_id: &str) -> pb::Finished {
4828    let message = "the worker's agent restarted while the attempt ran (possibly out of memory)";
4829    pb::Finished {
4830        attempt_id: attempt_id.to_owned(),
4831        status: pb::AttemptStatus::Lost.into(),
4832        error_summary_json: ErrorSummary::json("WorkerRestarted", message).into_bytes(),
4833        ..pb::Finished::default()
4834    }
4835}
4836
4837const fn wrap(message: worker_message::Message) -> pb::WorkerMessage {
4838    pb::WorkerMessage {
4839        message: Some(message),
4840        clock: None,
4841    }
4842}
4843
4844/// A session's sender to the master: each message numbered, and stamped with the latest of
4845/// the master's messages handled, as it is queued (B240). Queued in that order, so a message
4846/// naming the master's message `n` comes after everything sent while handling `n`; its send
4847/// counted from the queueing, no later than the stream's write (sooner deadlines, never
4848/// later).
4849struct ToMaster {
4850    sender: mpsc::UnboundedSender<pb::WorkerMessage>,
4851    outbox: SharedOutbox,
4852}
4853
4854impl ToMaster {
4855    const fn new(sender: mpsc::UnboundedSender<pb::WorkerMessage>, outbox: SharedOutbox) -> Self {
4856        Self { sender, outbox }
4857    }
4858
4859    /// Numbers, stamps and queues `message`; the stream closed, it is dropped.
4860    fn send(&self, mut message: pb::WorkerMessage) -> Result<(), mpsc::error::SendError<()>> {
4861        // Held over the queueing: numbers in queue order.
4862        let mut outbox = crate::master_time::lock(&self.outbox);
4863        message.clock = Some(outbox.stamp(Local::now()));
4864        self.sender
4865            .send(message)
4866            .map_err(|_| mpsc::error::SendError(()))
4867    }
4868
4869    /// The master's message numbered `sequence` was handled.
4870    fn handled(&self, sequence: u64) {
4871        crate::master_time::lock(&self.outbox).handled(sequence);
4872    }
4873}
4874
4875/// The result of an attempt that had secrets: its Python output and error summary masked
4876/// (a command's are its masked streams already), and a failure after a failed on-demand read
4877/// given that read's error kind (decision 168).
4878fn ended_with_secrets(finished: &mut pb::Finished, secrets: &AttemptSecrets, python: bool) {
4879    if python && !secrets.mask.is_empty() {
4880        for field in [&mut finished.output_json, &mut finished.error_summary_json] {
4881            if field.is_empty() {
4882                continue;
4883            }
4884            if let Ok(value) = serde_json::from_slice::<serde_json::Value>(field) {
4885                *field = serde_json::to_vec(&secrets.mask.mask_json(&value)).unwrap_or_default();
4886            } else {
4887                *field = secrets.mask.mask(field);
4888            }
4889        }
4890    }
4891    let failed = finished.status == i32::from(pb::AttemptStatus::Failed);
4892    if failed
4893        && finished.error_kind.is_empty()
4894        && let Some(kind) = secrets.failed_kind()
4895    {
4896        kind.clone_into(&mut finished.error_kind);
4897    }
4898}
4899
4900/// The log's warning for each secret too short to be masked (never its value), once: those
4901/// noted since the last call.
4902fn too_short_lines(secrets: &AttemptSecrets, min: usize) -> String {
4903    use std::fmt::Write as _;
4904    let short = std::mem::take(
4905        &mut *secrets
4906            .too_short
4907            .lock()
4908            .unwrap_or_else(PoisonError::into_inner),
4909    );
4910    let mut lines = String::new();
4911    for name in &short {
4912        let _ = writeln!(
4913            lines,
4914            "schedr: `{name}` is too short to be masked (under {min} characters, \
4915             [secret_storage] min_mask_length): it shows in this log as it is"
4916        );
4917    }
4918    lines
4919}
4920
4921/// The log's note of each secret masked (decision 167: an output may have changed).
4922fn masked_lines(secrets: &AttemptSecrets) -> String {
4923    use std::fmt::Write as _;
4924    let mut lines = String::new();
4925    for (label, count) in secrets.mask.counts() {
4926        let times = if count == 1 {
4927            "once".to_owned()
4928        } else {
4929            format!("{count} times")
4930        };
4931        let _ = writeln!(
4932            lines,
4933            "schedr: `{label}` was masked {times} in this task's log and output (`****`): \
4934             every text equal to its value is masked, also where it isn't the secret"
4935        );
4936    }
4937    // A value can be a word of the note, or its own path or key: masked here too.
4938    secrets.mask.mask_text(&lines)
4939}
4940
4941/// Appends the agent's own lines to a task's log (never through a link, as the log is
4942/// opened for the task).
4943async fn append_log(path: &Path, text: &str) {
4944    if text.is_empty() {
4945        return;
4946    }
4947    match crate::process::open_log_file(path).await {
4948        Ok(mut file) => {
4949            use tokio::io::AsyncWriteExt as _;
4950            let _ = file.write_all(text.as_bytes()).await;
4951            let _ = file.flush().await;
4952        }
4953        Err(error) => tracing::warn!(%error, path = %path.display(), "can't write to a task log"),
4954    }
4955}
4956
4957/// Sleeps for `timeout`; forever without one.
4958async fn sleep_for(timeout: Option<Duration>) {
4959    match timeout {
4960        Some(timeout) => tokio::time::sleep(timeout).await,
4961        None => std::future::pending().await,
4962    }
4963}
4964
4965/// An attempt stopped while its secrets were fetched: ended as a stop before its process
4966/// started is (cancelled, interrupted or timed out).
4967fn stopped_before_start(
4968    spec: &AttemptSpec,
4969    reason: StopReason,
4970    duration: Duration,
4971) -> pb::Finished {
4972    let ran = Ran {
4973        supervised: crate::supervise::Supervised {
4974            termination: crate::status::Termination::Unknown,
4975            stopped: Some(reason),
4976            killed: false,
4977        },
4978        runner_result: None,
4979        output: None,
4980        duration,
4981        start: None,
4982        forked: false,
4983        ended: crate::usage::Ended::default(),
4984        moved_to: None,
4985        host_lost: None,
4986        struck: false,
4987    };
4988    finished(&spec.attempt_id, &spec.task, &ran)
4989}
4990
4991/// Whether a trigger's task batches what it finds (`@trigger.poke(batch=...)`, decision 352).
4992fn batches(task: &schedr_model::Task) -> bool {
4993    matches!(
4994        task.kind,
4995        schedr_model::TaskKind::Sensor {
4996            batch_ms: Some(_),
4997            ..
4998        }
4999    )
5000}
5001
5002/// The first API call's ID less one: the clock's nanoseconds, so a restarted agent's calls never
5003/// take the IDs of its last incarnation's, whose answers may still come (Codex's review).
5004fn first_api_call_id() -> u64 {
5005    std::time::SystemTime::now()
5006        .duration_since(std::time::UNIX_EPOCH)
5007        .map_or(0, |since| {
5008            u64::try_from(since.as_nanos()).unwrap_or(u64::MAX)
5009        })
5010}