Skip to main content

schedr_agent/
attempt.rs

1//! One attempt on the worker, from `AssignTask` to `Finished`: what to run and how it ended.
2//!
3//! Pure: [`AttemptSpec::from_assign`] reads the assignment, [`plan`] decides how to run it (a
4//! Python task through the runner, a command rendered here) or why not (a rejection, or a failure
5//! such as a reference that can't be rendered), and [`finished`] turns how the process ended into
6//! the `Finished` message (see archive/PROJECT.md, Task assignment). Starting processes is
7//! [`crate::launch`]'s job.
8
9use std::collections::BTreeMap;
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12use std::time::Duration;
13
14use jiff::Timestamp;
15use schedr_model::connection::Registry;
16use schedr_model::runner::CleanupHandle;
17use schedr_model::runner::{
18    DagFile, ErrorSummary, RunInfo, RunnerMessage, SecretValue, TaskRequest,
19};
20use schedr_model::task::CleanupRun;
21use schedr_model::{AttemptStatus, SecretDecl, SecretName, Task, TaskKind};
22use schedr_proto::convert::{attempt_status_to_proto, run_kind_from_proto};
23use schedr_proto::pb;
24use serde_json::Value;
25
26use crate::env::{RunVars, task_environment};
27use crate::mask::Mask;
28use crate::output::{TailBuffer, process_result};
29use crate::process::ProcessSpec;
30use crate::render::{RenderContext, command_line, render};
31use crate::status::attempt_status;
32use crate::supervise::Supervised;
33
34#[cfg(test)]
35mod tests;
36
37/// Whether a task's cleanup may start here, with `cleanup_anywhere`: while the worker is cut
38/// off, the cleanup may be on another worker already.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum Gate {
41    /// It may.
42    Open,
43    /// Not until the master's answer.
44    Held,
45    /// Never: the master answered `Kill`.
46    Dropped,
47    /// On the handles from this one on: its cleanup moved without them (B169).
48    Rest(u32),
49}
50
51/// What a cleanup passing its [`CleanupGate`] runs on.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum Pass {
54    /// All its handles.
55    All,
56    /// The handles from this one on (B169: its cleanup moved without them).
57    From(usize),
58}
59
60/// The agent's [`Gate`] for one attempt, and when the master's word runs out: the last word
61/// plus the worker lease (`None` before the master told its lease).
62#[derive(Debug, Clone)]
63pub struct CleanupGate {
64    /// What the agent says.
65    pub gate: tokio::sync::watch::Receiver<Gate>,
66    /// When the master's word runs out.
67    pub deadline: tokio::sync::watch::Receiver<Option<tokio::time::Instant>>,
68}
69
70/// Compared by what it says now, for a spec's equality.
71impl PartialEq for CleanupGate {
72    fn eq(&self, other: &Self) -> bool {
73        *self.gate.borrow() == *other.gate.borrow()
74    }
75}
76
77impl CleanupGate {
78    /// Waits while held, and while open past the deadline: the agent's loop hasn't held it yet
79    /// (B162: a worker frozen past its lease saw its task end before its overdue timer, and ran
80    /// a cleanup the master had moved); it does next, and the master's answer decides, unless
81    /// the master's word moves the deadline on first (a heartbeat answered just in time).
82    /// Returns whether the cleanup may start, and on which handles.
83    pub async fn passes(mut self) -> Option<Pass> {
84        loop {
85            let gate = *self.gate.borrow_and_update();
86            let late = self
87                .deadline
88                .borrow_and_update()
89                .is_some_and(|at| tokio::time::Instant::now() >= at);
90            let changed = match gate {
91                Gate::Dropped => return None,
92                Gate::Rest(from) => return Some(Pass::From(from as usize)),
93                Gate::Open if !late => return Some(Pass::All),
94                Gate::Open => tokio::select! {
95                    changed = self.gate.changed() => changed.is_ok(),
96                    changed = self.deadline.changed() => changed.is_ok(),
97                },
98                Gate::Held => self.gate.changed().await.is_ok(),
99            };
100            if !changed {
101                return None;
102            }
103        }
104    }
105}
106
107/// The error kind of a command whose templates can't be rendered (a missing or truncated
108/// input, a value with no text form).
109pub const RENDER_FAILED: &str = "render_failed";
110
111/// The error kind of a Python task whose runner ended without reporting a result.
112pub const RUNNER_FAILED: &str = "runner_failed";
113
114/// The error kind of a `CommandResource` setup that exited 0 without reporting its value.
115pub const RESOURCE_NOT_REPORTED: &str = "resource_not_reported";
116
117/// The error kind of a forked task whose end isn't known: its shim ended before reporting it.
118pub const PROCESS_STATUS_UNKNOWN: &str = "process_status_unknown";
119
120/// An assignment, read.
121#[derive(Debug, Clone, PartialEq)]
122pub struct AttemptSpec {
123    /// The attempt's ID.
124    pub attempt_id: String,
125    /// The task.
126    pub task: Task,
127    /// The DAG root and file the task is defined in.
128    pub dag_root: String,
129    /// The file, relative to the root.
130    pub dag_path: String,
131    /// The run information.
132    pub run: RunInfo,
133    /// The upstream outputs the task uses, by task ID.
134    pub inputs: BTreeMap<String, Value>,
135    /// The upstream tasks' outcomes, by task ID: a name, or `null` for a skipped one.
136    pub outcomes: BTreeMap<String, Value>,
137    /// The time between SIGTERM and SIGKILL when it is stopped.
138    pub cancel_grace: Duration,
139    /// The secrets fetched for it, by name ([`AttemptSpec::needed_secrets`]): filled into its
140    /// templates and sent to its runner. Empty until fetched.
141    pub secrets: BTreeMap<SecretName, Value>,
142    /// The values masked in its output.
143    pub mask: Mask,
144    /// The copy of its root's code it was planned against (decision 102); `None`: the
145    /// configured root.
146    pub code_dir: Option<PathBuf>,
147    /// For a script task, the copy of its script root's code it was planned against; `None`:
148    /// the configured script root.
149    pub script_dir: Option<PathBuf>,
150    /// The copies of the other DAG roots it was planned against, on a Python task's
151    /// `sys.path` in place of their configured paths (a library in another root comes from
152    /// one copy for the whole task).
153    pub root_copies: BTreeMap<String, PathBuf>,
154    /// Its root's connections (decision 174): rendered when the task opens one.
155    pub connections: Arc<Registry>,
156    /// A command's connections given as variables (`connections={"DB": warehouse}`, decision
157    /// 184), by variable (`DB_URL`). Empty until its secrets are fetched.
158    pub connection_env: BTreeMap<String, String>,
159    /// Set for a connection test (decision 174): the runner opens and checks it, no task.
160    pub connection_test: Option<String>,
161    /// Set for a Python task's cleanup: the attempt's handles, for its function.
162    pub cleanup_handles: Option<Vec<CleanupHandle>>,
163    /// Only its cleanup, moved here from a lost worker (`cleanup_only`).
164    pub moved_cleanup: bool,
165    /// The journal its handles go to; `None` keeps them in memory only.
166    pub journal: Option<crate::journal::Journal>,
167    /// Told each handle, to send it on to the master; `None` keeps them here.
168    pub handle_sink: Option<crate::handles::HandleSink>,
169    /// What it calls schedr's REST API with (`schedr.api`, M4.11h); `None`: it can't.
170    pub api: Option<crate::api::ApiCaller>,
171    /// Passed between the task's end and its cleanup, with `cleanup_anywhere` (decision 253).
172    pub cleanup_gate: Option<CleanupGate>,
173    /// Set for a trigger: what it starts from, and where its events go.
174    pub trigger: Option<(
175        schedr_model::runner::TriggerStart,
176        crate::watchers::EventSink,
177    )>,
178}
179
180/// Why an assignment can't be read.
181#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
182#[error("invalid assignment: {0}")]
183pub struct InvalidAssignment(pub String);
184
185impl AttemptSpec {
186    /// Reads an assignment; `inputs` are the ones fetched separately when the assignment
187    /// says they are external.
188    ///
189    /// # Errors
190    ///
191    /// [`InvalidAssignment`] for a task, run or inputs that don't read (the worker rejects it
192    /// as an invalid specification).
193    pub fn from_assign(
194        assign: &pb::AssignTask,
195        external_inputs: Option<&[u8]>,
196    ) -> Result<Self, InvalidAssignment> {
197        let invalid =
198            |what: &str, e: &dyn std::fmt::Display| InvalidAssignment(format!("{what}: {e}"));
199        let task: Task =
200            serde_json::from_slice(&assign.task_json).map_err(|e| invalid("task", &e))?;
201        let waits = matches!(task.kind, schedr_model::TaskKind::Sensor { .. });
202        let run = assign
203            .run
204            .as_ref()
205            .ok_or_else(|| InvalidAssignment("no run information".to_owned()))?;
206        let dag_file = assign
207            .dag_file
208            .as_ref()
209            .ok_or_else(|| InvalidAssignment("no DAG file".to_owned()))?;
210        let inputs_json = match external_inputs {
211            Some(bytes) => bytes,
212            None => assign.inputs_json.as_slice(),
213        };
214        let inputs = if inputs_json.is_empty() {
215            BTreeMap::new()
216        } else {
217            serde_json::from_slice(inputs_json).map_err(|e| invalid("inputs", &e))?
218        };
219        Ok(Self {
220            attempt_id: assign.attempt_id.clone(),
221            task,
222            dag_root: dag_file.root.clone(),
223            dag_path: dag_file.path.clone(),
224            run: RunInfo {
225                dag_id: run.dag_id.clone(),
226                run_id: run.run_id.clone(),
227                kind: run_kind_from_proto(&run.kind).map_err(|e| invalid("run kind", &e))?,
228                planned_for: time(run.planned_for.as_ref())
229                    .ok_or_else(|| invalid("planned_for", &"missing"))?,
230                since: time(run.since.as_ref()).ok_or_else(|| invalid("since", &"missing"))?,
231                try_number: assign.try_number,
232                map_index: u32::try_from(assign.map_index).ok(),
233                params: if run.params_json.is_empty() {
234                    serde_json::json!({})
235                } else {
236                    serde_json::from_slice(&run.params_json)
237                        .map_err(|e| invalid("run params", &e))?
238                },
239                event: if run.event_json.is_empty() {
240                    None
241                } else {
242                    Some(
243                        serde_json::from_slice(&run.event_json)
244                            .map_err(|e| invalid("run event", &e))?,
245                    )
246                },
247                // On its first try, a wait step's start is now: kept with the request, so a host
248                // restarted in the same attempt counts from it too (Codex's review, M4.11g).
249                first_started: time(assign.first_started.as_ref())
250                    .or_else(|| waits.then(Timestamp::now)),
251            },
252            inputs,
253            outcomes: assign
254                .upstream_outcomes
255                .iter()
256                .map(|(task, outcome)| {
257                    let outcome = if outcome.is_empty() {
258                        Value::Null
259                    } else {
260                        Value::String(outcome.clone())
261                    };
262                    (task.clone(), outcome)
263                })
264                .collect(),
265            cancel_grace: Duration::from_millis(assign.cancel_grace_ms),
266            secrets: BTreeMap::new(),
267            mask: Mask::default(),
268            code_dir: None,
269            script_dir: None,
270            root_copies: BTreeMap::new(),
271            connections: Arc::new(if assign.connections_json.is_empty() {
272                Registry::default()
273            } else {
274                serde_json::from_slice(&assign.connections_json)
275                    .map_err(|e| invalid("connections", &e))?
276            }),
277            connection_env: BTreeMap::new(),
278            connection_test: None,
279            cleanup_handles: None,
280            moved_cleanup: assign.cleanup_only.is_some(),
281            journal: None,
282            handle_sink: None,
283            api: None,
284            cleanup_gate: None,
285            trigger: None,
286        })
287    }
288
289    /// The secrets fetched before it starts: those its references name, and those it
290    /// declares (prefixes aside, read when the task asks), each once.
291    #[must_use]
292    pub fn needed_secrets(&self) -> Vec<SecretName> {
293        let mut needed: Vec<SecretName> =
294            self.task.secret_references().into_iter().cloned().collect();
295        for declared in &self.task.secrets {
296            if let SecretDecl::Secret(name) = declared
297                && !needed.contains(name)
298            {
299                needed.push(name.clone());
300            }
301        }
302        needed
303    }
304
305    /// Stand-ins for the secrets it needs (a key's `""`, a whole secret's `{}`): planning it
306    /// before they are fetched shows whether it can run here at all.
307    pub fn stand_in_secrets(&mut self) {
308        self.secrets = self
309            .needed_secrets()
310            .into_iter()
311            .map(|name| {
312                let value = if name.key.is_some() {
313                    Value::String(String::new())
314                } else {
315                    Value::Object(serde_json::Map::new())
316                };
317                (name, value)
318            })
319            .collect();
320    }
321
322    /// Gives a resource's cleanup without a timeout of its own the worker's
323    /// `resource_cleanup_timeout`: a hung one would hold its run, which doesn't cancel it.
324    pub fn default_timeout(&mut self, assign: &pb::AssignTask, timeouts: &WorkerTimeouts) {
325        if assign.resource_cleanup && self.task.settings.timeout_ms.is_none() {
326            self.task.settings.timeout_ms =
327                Some(u64::try_from(timeouts.resource_cleanup.as_millis()).unwrap_or(u64::MAX));
328        }
329        if let TaskKind::Sensor {
330            max_wait_ms: wait @ None,
331            ..
332        } = &mut self.task.kind
333        {
334            *wait = Some(u64::try_from(timeouts.sensor_max_wait.as_millis()).unwrap_or(u64::MAX));
335        }
336        if let TaskKind::Sensor {
337            max_wait_ms: Some(wait),
338            ..
339        } = self.task.kind
340        {
341            // It ends itself at its `max_wait`, with `TimedOut`. This is for one that ignores the
342            // cancel: past its grace, it is stopped like any task over its time.
343            let margin = self.cancel_grace.saturating_add(timeouts.runner_start);
344            let margin = u64::try_from(margin.as_millis()).unwrap_or(u64::MAX);
345            self.task.settings.timeout_ms = Some(wait.saturating_add(margin));
346        }
347    }
348
349    /// The task's timeout, if any.
350    #[must_use]
351    pub fn timeout(&self) -> Option<Duration> {
352        self.task.settings.timeout_ms.map(Duration::from_millis)
353    }
354}
355
356/// How long what a worker starts may take (`[worker]`).
357#[derive(Debug, Clone, Copy, PartialEq, Eq)]
358pub struct WorkerTimeouts {
359    /// A runner's hello (`runner_start_timeout`).
360    pub runner_start: Duration,
361    /// A fork server's preloading (`fork_server_preload_timeout`).
362    pub fork_preload: Duration,
363    /// One try of a cleanup that sets no timeout of its own (`cleanup_timeout`).
364    pub cleanup: Duration,
365    /// How long a wait step without a `max_wait` waits (`[sensors] default_max_wait`).
366    pub sensor_max_wait: Duration,
367    /// How long a wait step may hold its host's loop (`[watchers] block_limit`).
368    pub watcher_block_limit: Duration,
369    /// How long importing a DAG file may hold it (`[dags] parse_file_timeout`).
370    pub watcher_import_limit: Duration,
371    /// The memory of all watcher hosts together (`[watchers] memory_budget`).
372    pub watcher_memory_budget: u64,
373    /// How many calls in a row may run past a sensor poke's `every` (`[watchers]
374    /// poke_overruns`).
375    pub watcher_poke_overruns: u32,
376    /// One try of a resource's cleanup that sets no `timeout` (`resource_cleanup_timeout`).
377    pub resource_cleanup: Duration,
378    /// How long a stopped process's output may take to reach its log (`output_drain_timeout`).
379    pub output_drain: Duration,
380    /// How long a fork server may take to answer a request (`fork_answer_timeout`).
381    pub fork_answer: Duration,
382    /// How a fork server's restarts are spaced.
383    pub fork_backoff: crate::fork::ForkBackoff,
384    /// How often old logs are swept (`log_sweep_interval`).
385    pub log_sweep: Duration,
386    /// How an orphan is stopped.
387    pub orphan: crate::journal::OrphanWaits,
388    /// How long an orphan gets to end on SIGTERM (`orphan_grace`).
389    pub orphan_grace: Duration,
390    /// The first wait after the master connection drops (`reconnect_backoff_first`).
391    pub reconnect_first: Duration,
392    /// The longest one (`reconnect_backoff_max`).
393    pub reconnect_max: Duration,
394    /// How often the event loop turns at least, however quiet (`alive_interval`).
395    pub alive: Duration,
396    /// How long deregistering may take (`deregister_wait`).
397    pub deregister: Duration,
398    /// How often a drain looks at its state (`drain_tick`).
399    pub drain_tick: Duration,
400    /// How often a stopped process's group is looked at (`stop_poll`).
401    pub stop_poll: Duration,
402    /// How long a connection test's process gets from SIGTERM to SIGKILL
403    /// (`connection_job_cancel_grace`).
404    pub connection_cancel_grace: Duration,
405    /// How long the log endpoint waits after a failed accept (`accept_retry`).
406    pub accept_retry: Duration,
407    /// How far back the tightest master-time sample is looked for (`master_sample_window`,
408    /// decision 447).
409    pub master_sample_window: Duration,
410    /// The wall-clock difference from the master, beyond the round trip, that is warned about
411    /// (`clock_skew_warning`, decision 449).
412    pub clock_skew_warning: Duration,
413    /// The most results kept in the journal as one group (`RESULTS_PER_JOURNAL_GROUP`).
414    pub results_per_journal_group: usize,
415    /// The most assignments whose journal records are written as one group
416    /// (`STARTS_PER_JOURNAL_GROUP`).
417    pub starts_per_journal_group: usize,
418    /// How many times a result is sent again over one session before it reconnects
419    /// (`RESULT_RESENDS`).
420    pub result_resends: u32,
421    /// The most heartbeats between two sends of an unacknowledged result
422    /// (`RESULT_RESEND_GAP_MAX`).
423    pub result_resend_gap_max: u32,
424    /// The messages kept waiting to be heard of (`UNACKED_MESSAGES_KEPT`).
425    pub unacked_messages_kept: usize,
426    /// The connections jobs' answers kept while no master listens
427    /// (`UNSENT_CONNECTION_ANSWERS`).
428    pub unsent_connection_answers: usize,
429    /// The most context connections a task may have open at once (`TASK_CONNECTIONS_OPEN`).
430    pub task_connections_open: usize,
431    /// A wait step's messages waiting for its attempt before its host waits too
432    /// (`WATCHER_LOG_BACKLOG`).
433    pub watcher_log_backlog: usize,
434}
435
436impl Default for WorkerTimeouts {
437    /// What every worker runs with.
438    fn default() -> Self {
439        Self {
440            runner_start: crate::launch::RUNNER_START_TIMEOUT,
441            fork_preload: crate::fork::PRELOAD_TIMEOUT,
442            // What the default grace period leaves a cleanup (decision 497): 30 s less the
443            // drain's 3 s to terminate and 2 s to report.
444            cleanup: Duration::from_secs(25),
445            sensor_max_wait: Duration::from_hours(24),
446            watcher_block_limit: Duration::from_secs(30),
447            watcher_import_limit: Duration::from_mins(1),
448            watcher_memory_budget: 1024 * 1024 * 1024,
449            watcher_poke_overruns: 3,
450            resource_cleanup: Duration::from_mins(30),
451            output_drain: crate::launch::OUTPUT_DRAIN_TIMEOUT,
452            fork_answer: crate::fork::FORK_ANSWER_TIMEOUT,
453            fork_backoff: crate::fork::ForkBackoff::default(),
454            log_sweep: crate::retention::SWEEP_INTERVAL,
455            orphan: crate::journal::OrphanWaits::default(),
456            orphan_grace: crate::agent::ORPHAN_GRACE,
457            reconnect_first: crate::agent::FIRST_BACKOFF,
458            reconnect_max: crate::agent::MAX_BACKOFF,
459            alive: crate::agent::ALIVE_INTERVAL,
460            deregister: crate::agent::DEREGISTER_WAIT,
461            drain_tick: crate::agent::DRAIN_TICK,
462            stop_poll: crate::supervise::STOP_POLL,
463            connection_cancel_grace: crate::connection_jobs::CANCEL_GRACE,
464            accept_retry: Duration::from_millis(100),
465            master_sample_window: crate::master_time::DEFAULT_SAMPLE_WINDOW,
466            clock_skew_warning: crate::master_time::DEFAULT_SKEW_WARNING,
467            results_per_journal_group: crate::agent::RESULTS_PER_GROUP,
468            starts_per_journal_group: crate::agent::STARTS_PER_GROUP,
469            result_resends: crate::agent::MAX_RESENDS,
470            result_resend_gap_max: crate::agent::MAX_RESEND_GAP,
471            unacked_messages_kept: crate::master_time::SENT_KEPT,
472            unsent_connection_answers: crate::agent::UNSENT_ANSWERS,
473            task_connections_open: crate::ctx::MAX_CONNECTIONS,
474            watcher_log_backlog: crate::watchers::ROUTE_MESSAGES,
475        }
476    }
477}
478
479/// What the worker knows to run tasks.
480#[derive(Debug, Clone, PartialEq, Eq)]
481pub struct WorkerSetup {
482    /// The DAG roots, by name.
483    pub roots: BTreeMap<String, PathBuf>,
484    /// The roots of which only some `.py` files are parsed, those files by root (decision
485    /// 117: `schedr dags test` of one file); a root not here is parsed whole.
486    pub parse_only: BTreeMap<String, Vec<String>>,
487    /// The script roots, by name (`SCHEDR_SCRIPT_PATH`): read for their `schedr.toml` files,
488    /// never imported.
489    pub script_roots: BTreeMap<String, PathBuf>,
490    /// The interpreters it has (`[interpreters]`): each name's executable, for scripts.
491    pub interpreters: BTreeMap<String, PathBuf>,
492    /// The interpreter for Python tasks (`[dags] interpreter`).
493    pub python: PathBuf,
494    /// The agent's own environment (the allow-listed variables pass to tasks).
495    pub agent_env: BTreeMap<String, String>,
496    /// Agent variables passed to tasks on top of the allow-list (`[worker] pass_env`).
497    pub pass_env: Vec<String>,
498    /// Where task log files go.
499    pub log_dir: PathBuf,
500    /// Where a command's connection files go (decision 184): a folder per attempt, mode
501    /// 0700, removed when it ends.
502    pub connection_dir: PathBuf,
503    /// How the memory watchdog watches tasks and parse runners.
504    pub memory: crate::memory::MemoryWatch,
505    /// How long what it starts may take.
506    pub timeouts: WorkerTimeouts,
507    /// The DAG interpreter's fork servers, when it has `fork_server = true`.
508    pub fork_server: Option<crate::fork::ForkConfig>,
509}
510
511impl WorkerSetup {
512    /// The log file of an attempt.
513    #[must_use]
514    pub fn log_file(&self, attempt_id: &str) -> PathBuf {
515        self.log_dir.join(format!("{attempt_id}.log"))
516    }
517
518    /// Every root directory, as `sys.path` entries for the runner.
519    #[must_use]
520    pub fn sys_path(&self) -> Vec<String> {
521        self.roots
522            .values()
523            .map(|p| p.to_string_lossy().into_owned())
524            .collect()
525    }
526
527    /// As [`Self::sys_path`], with each root of `copies` at its copy instead (decision 102).
528    #[must_use]
529    pub fn sys_path_at(&self, copies: &BTreeMap<String, PathBuf>) -> Vec<String> {
530        self.roots
531            .iter()
532            .map(|(name, p)| copies.get(name).unwrap_or(p))
533            .map(|p| p.to_string_lossy().into_owned())
534            .collect()
535    }
536
537    /// As [`Self::sys_path`], with root `root` at `dir` instead (the copy of its code,
538    /// decision 102), so its modules come from the same code as its DAG file.
539    #[must_use]
540    pub fn sys_path_with(&self, root: &str, dir: &Path) -> Vec<String> {
541        self.roots
542            .iter()
543            .map(|(name, p)| if name == root { dir } else { p.as_path() })
544            .map(|p| p.to_string_lossy().into_owned())
545            .collect()
546    }
547}
548
549/// How to run an attempt.
550#[derive(Debug, Clone, PartialEq)]
551pub enum Plan {
552    /// A Python task: start the runner in task mode and send it this request.
553    Python {
554        /// The runner process (interpreter, `-m schedr.runner task`, environment, log).
555        process: ProcessSpec,
556        /// The request.
557        request: Box<TaskRequest>,
558    },
559    /// A command: start this process.
560    Command(ProcessSpec),
561}
562
563/// Why an attempt isn't run as planned.
564#[derive(Debug, Clone, PartialEq, Eq)]
565pub enum NotRun {
566    /// Rejected (not a try): with the protocol's reason and a detail.
567    Rejected {
568        /// The reason.
569        reason: pb::RejectReason,
570        /// What exactly, for the master's message.
571        detail: String,
572    },
573    /// Failed before starting (e.g. a reference that can't be rendered).
574    Failed {
575        /// The error kind.
576        kind: String,
577        /// What went wrong.
578        message: String,
579    },
580}
581
582/// Plans an attempt on this worker.
583///
584/// # Errors
585///
586/// [`NotRun::Rejected`] when the DAG file isn't here (code not there yet) or the task can't
587/// run on a worker (an empty task); [`NotRun::Failed`] when a command's templates can't be
588/// rendered or its environment sets a reserved variable.
589pub fn plan(spec: &AttemptSpec, setup: &WorkerSetup) -> Result<Plan, NotRun> {
590    let root_dir = setup
591        .roots
592        .get(&spec.dag_root)
593        .ok_or_else(|| NotRun::Rejected {
594            reason: pb::RejectReason::DagFileMissing,
595            detail: format!("DAG root `{}` isn't on this worker", spec.dag_root),
596        })?;
597    plan_at(spec, setup, root_dir)
598}
599
600/// As [`plan`], with the task's root at `root_dir`: the agent's copy of the code whose hash
601/// it reported (decision 102), so the code that runs is the code hashed whatever happens to
602/// the configured root meanwhile (git-sync moving its link and deleting the old checkout, an
603/// edit in place).
604///
605/// # Errors
606///
607/// As [`plan`].
608pub fn plan_at(spec: &AttemptSpec, setup: &WorkerSetup, root_dir: &Path) -> Result<Plan, NotRun> {
609    let file = root_dir.join(&spec.dag_path);
610    if !file.is_file() {
611        return Err(NotRun::Rejected {
612            reason: pb::RejectReason::DagFileMissing,
613            detail: format!("{} not found on this worker", file.display()),
614        });
615    }
616    let settings = &spec.task.settings;
617    // A cleanup must run somewhere: never turned away, it is watched at what this worker gives
618    // (Codex's review of M4.15).
619    if let (Some(own), Some(ceiling)) = (settings.memory_bytes, setup.memory.ceiling)
620        && own > ceiling
621        && !spec.moved_cleanup
622    {
623        return Err(NotRun::Rejected {
624            reason: pb::RejectReason::MemoryBudgetTooLarge,
625            detail: format!(
626                "the task asks for a memory budget of {}; this worker gives one task at most {} \
627                 (its memory limit less its reserve)",
628                crate::memory::show_size(own),
629                crate::memory::show_size(ceiling)
630            ),
631        });
632    }
633    let plan = plan_kind(spec, setup, root_dir, &file)?;
634    capped(plan, spec, setup)
635}
636
637/// `plan`'s process started through `schedr task-exec` when its task caps its memory hard
638/// (`hard_memory_limit=True`, decisions 50, 438): the limit is set before its program runs.
639fn capped(plan: Plan, spec: &AttemptSpec, setup: &WorkerSetup) -> Result<Plan, NotRun> {
640    let settings = &spec.task.settings;
641    let (true, Some(limit)) = (settings.hard_memory_limit, settings.memory_bytes) else {
642        return Ok(plan);
643    };
644    let Some(exec) = &setup.memory.task_exec else {
645        return Err(failed(
646            crate::agent::START_FAILED,
647            &"this worker can't cap a task's memory (`schedr task-exec` isn't found)",
648        ));
649    };
650    let wrap = |mut process: ProcessSpec| {
651        let program = std::mem::replace(&mut process.program, exec.clone());
652        // Its arguments are text: a path that isn't is refused, not changed (Codex's review).
653        let program = program.into_os_string().into_string().map_err(|path| {
654            failed(
655                crate::agent::START_FAILED,
656                &format!(
657                    "can't cap {}: its path isn't UTF-8",
658                    Path::new(&path).display()
659                ),
660            )
661        })?;
662        let mut args = vec![
663            "task-exec".to_owned(),
664            "--data-limit".to_owned(),
665            limit.to_string(),
666            "--".to_owned(),
667            program,
668        ];
669        args.append(&mut process.args);
670        process.args = args;
671        Ok(process)
672    };
673    Ok(match plan {
674        Plan::Python { process, request } => Plan::Python {
675            process: wrap(process)?,
676            request,
677        },
678        Plan::Command(process) => Plan::Command(wrap(process)?),
679    })
680}
681
682/// The plan of `spec`'s kind of task, `file` its DAG file.
683fn plan_kind(
684    spec: &AttemptSpec,
685    setup: &WorkerSetup,
686    root_dir: &Path,
687    file: &Path,
688) -> Result<Plan, NotRun> {
689    let vars = run_vars(spec);
690    let log_file = setup.log_file(&spec.attempt_id);
691    let max_output_size = usize::try_from(spec.task.settings.max_output_size).unwrap_or(usize::MAX);
692    match &spec.task.kind {
693        TaskKind::Python { .. } | TaskKind::Sensor { .. } => {
694            let env = task_environment(&setup.agent_env, &setup.pass_env, &BTreeMap::new(), &vars)
695                .map_err(|e| failed(RENDER_FAILED, &e))?;
696            Ok(Plan::Python {
697                process: ProcessSpec {
698                    program: setup.python.clone(),
699                    args: vec![
700                        // Not the working directory first: a root's file can't shadow what the runner imports (B178).
701                        "-P".to_owned(),
702                        "-m".to_owned(),
703                        "schedr.runner".to_owned(),
704                        "task".to_owned(),
705                    ],
706                    env,
707                    working_dir: root_dir.to_path_buf(),
708                    log_file,
709                    max_output_size,
710                    mask: spec.mask.clone(),
711                    start_timeout: setup.timeouts.runner_start,
712                    output_drain: setup.timeouts.output_drain,
713                },
714                request: Box::new(TaskRequest {
715                    dag_file: DagFile {
716                        root: spec.dag_root.clone(),
717                        root_dir: root_dir.to_string_lossy().into_owned(),
718                        path: spec.dag_path.clone(),
719                    },
720                    dag_id: spec.run.dag_id.clone(),
721                    task: spec.task.clone(),
722                    inputs: spec.inputs.clone(),
723                    outcomes: spec.outcomes.clone(),
724                    run: spec.run.clone(),
725                    sys_path: setup.sys_path_at(
726                        &spec
727                            .root_copies
728                            .clone()
729                            .into_iter()
730                            .chain([(spec.dag_root.clone(), root_dir.to_path_buf())])
731                            .collect(),
732                    ),
733                    secrets: spec
734                        .secrets
735                        .iter()
736                        .map(|(name, value)| SecretValue {
737                            name: name.clone(),
738                            value: value.clone(),
739                        })
740                        .collect(),
741                    connection_test: spec.connection_test.clone(),
742                    trigger: spec.trigger.as_ref().map(|(start, _)| start.clone()),
743                    cleanup: spec.cleanup_handles.clone(),
744                }),
745            })
746        }
747        TaskKind::Command { command, env, .. } => {
748            let ctx = render_context(spec);
749            let (program, args) =
750                command_line(command, &ctx).map_err(|e| failed(RENDER_FAILED, &e))?;
751            let mut task_env = render_env(env, &ctx)?;
752            add_connection_env(&mut task_env, &spec.connection_env)?;
753            let env = task_environment(&setup.agent_env, &setup.pass_env, &task_env, &vars)
754                .map_err(|e| failed(RENDER_FAILED, &e))?;
755            Ok(Plan::Command(ProcessSpec {
756                program: PathBuf::from(program),
757                args,
758                env,
759                working_dir: file
760                    .parent()
761                    .map_or_else(|| root_dir.to_path_buf(), Path::to_path_buf),
762                log_file,
763                max_output_size,
764                mask: spec.mask.clone(),
765                start_timeout: setup.timeouts.runner_start,
766                output_drain: setup.timeouts.output_drain,
767            }))
768        }
769        TaskKind::Empty => Err(NotRun::Rejected {
770            reason: pb::RejectReason::InvalidSpecification,
771            detail: "empty tasks are completed by the master".to_owned(),
772        }),
773        TaskKind::FirstOf { .. }
774        | TaskKind::WaitFor { .. }
775        | TaskKind::WaitForEvent { .. }
776        | TaskKind::TriggerDag { .. } => Err(NotRun::Rejected {
777            reason: pb::RejectReason::InvalidSpecification,
778            detail: "first_of, wait_for and TriggerDagOperator are completed by the master"
779                .to_owned(),
780        }),
781        TaskKind::Script { .. } => plan_script(spec, setup, root_dir, &vars),
782    }
783}
784
785/// A script task's process (decision 293): its interpreter running the script from its
786/// script root's copy.
787fn plan_script(
788    spec: &AttemptSpec,
789    setup: &WorkerSetup,
790    root_dir: &Path,
791    vars: &RunVars,
792) -> Result<Plan, NotRun> {
793    let TaskKind::Script {
794        job,
795        script,
796        interpreter,
797        args,
798        env,
799        working_dir,
800        ..
801    } = &spec.task.kind
802    else {
803        unreachable!("planned as a script")
804    };
805    let log_file = setup.log_file(&spec.attempt_id);
806    let max_output_size = usize::try_from(spec.task.settings.max_output_size).unwrap_or(usize::MAX);
807    // Checked when it was read; checked again, as the path is about to run (decision 293).
808    if !crate::jobs::stays_inside(script)
809        || !(working_dir.is_empty() || crate::jobs::stays_inside(working_dir))
810    {
811        return Err(NotRun::Failed {
812            kind: RENDER_FAILED.to_owned(),
813            message: format!("`{job}`: its script or working directory leaves its script root"),
814        });
815    }
816    let script_dir = script_dir(spec, setup, job, root_dir)?;
817    let program = setup
818        .interpreters
819        .get(interpreter)
820        .ok_or_else(|| NotRun::Rejected {
821            reason: pb::RejectReason::InterpreterUndefined,
822            detail: format!(
823                "interpreter `{interpreter}` of `{job}` isn't defined on this worker \
824                     ([interpreters])"
825            ),
826        })?;
827    let file = script_dir.join(script);
828    if !file.is_file() {
829        return Err(NotRun::Rejected {
830            reason: pb::RejectReason::ScriptReferenceNotFound,
831            detail: format!("`{job}`: its script `{script}` isn't on this worker"),
832        });
833    }
834    can_run_cleanup_script(spec, setup, &script_dir, job)?;
835    let ctx = render_context(spec);
836    let mut argv = vec![file.to_string_lossy().into_owned()];
837    for template in args {
838        argv.push(render(template, &ctx).map_err(|e| failed(RENDER_FAILED, &e))?);
839    }
840    let mut task_env = render_env(env, &ctx)?;
841    // Its root's libraries importable from anywhere in it (a Python script).
842    task_env
843        .entry(PYTHONPATH.to_owned())
844        .or_insert_with(|| python_path(&script_dir, setup));
845    let env = task_environment(&setup.agent_env, &setup.pass_env, &task_env, vars)
846        .map_err(|e| failed(RENDER_FAILED, &e))?;
847    Ok(Plan::Command(ProcessSpec {
848        program: program.clone(),
849        args: argv,
850        env,
851        working_dir: script_dir.join(working_dir),
852        log_file,
853        max_output_size,
854        mask: spec.mask.clone(),
855        start_timeout: setup.timeouts.runner_start,
856        output_drain: setup.timeouts.output_drain,
857    }))
858}
859
860/// Makes a script task run its cleanup script instead (with the task's environment and working
861/// directory); any other task is left as it is. A setup's own cleanup reports no value.
862pub fn use_cleanup_script(task: &mut Task) {
863    let Some(CleanupRun::Script {
864        script: own_script,
865        interpreter: own_interpreter,
866        args: own_args,
867    }) = task.cleanup.as_ref().map(|cleanup| &cleanup.run)
868    else {
869        return;
870    };
871    if let TaskKind::Script {
872        script,
873        interpreter,
874        args,
875        resource,
876        ..
877    } = &mut task.kind
878    {
879        script.clone_from(own_script);
880        interpreter.clone_from(own_interpreter);
881        args.clone_from(own_args);
882        *resource = None;
883    }
884}
885
886/// A worker that couldn't run the task's cleanup script doesn't take the task: its cleanup
887/// would fail after the task, and a moved one should go to a worker that can run it.
888fn can_run_cleanup_script(
889    spec: &AttemptSpec,
890    setup: &WorkerSetup,
891    script_dir: &Path,
892    job: &str,
893) -> Result<(), NotRun> {
894    let Some(CleanupRun::Script {
895        script,
896        interpreter,
897        ..
898    }) = spec.task.cleanup.as_ref().map(|cleanup| &cleanup.run)
899    else {
900        return Ok(());
901    };
902    if !crate::jobs::stays_inside(script) {
903        return Err(NotRun::Failed {
904            kind: RENDER_FAILED.to_owned(),
905            message: format!("`{job}`: its cleanup script leaves its script root"),
906        });
907    }
908    if !setup.interpreters.contains_key(interpreter) {
909        return Err(NotRun::Rejected {
910            reason: pb::RejectReason::InterpreterUndefined,
911            detail: format!(
912                "interpreter `{interpreter}` of `{job}`'s cleanup isn't defined on this worker \
913                 ([interpreters])"
914            ),
915        });
916    }
917    if !script_dir.join(script).is_file() {
918        return Err(NotRun::Rejected {
919            reason: pb::RejectReason::ScriptReferenceNotFound,
920            detail: format!("`{job}`: its cleanup script `{script}` isn't on this worker"),
921        });
922    }
923    Ok(())
924}
925
926/// The variable a Python script finds its root's libraries through.
927const PYTHONPATH: &str = "PYTHONPATH";
928
929/// A script's `PYTHONPATH`: its script root's copy, then the agent's own when the worker
930/// passes it on (`[worker] pass_env`).
931fn python_path(script_dir: &Path, setup: &WorkerSetup) -> String {
932    let own = script_dir.to_string_lossy().into_owned();
933    match setup.agent_env.get(PYTHONPATH) {
934        Some(passed) if setup.pass_env.iter().any(|name| name == PYTHONPATH) => {
935            format!("{own}:{passed}")
936        }
937        _ => own,
938    }
939}
940
941/// The script root a script task's `job` (`<root>:<path>#<name>`) is in, as this worker has
942/// it: the copy it was planned against, else the configured directory; the task's own root
943/// when it is a standalone job's.
944fn script_dir(
945    spec: &AttemptSpec,
946    setup: &WorkerSetup,
947    job: &str,
948    root_dir: &Path,
949) -> Result<PathBuf, NotRun> {
950    let root = job.split_once(':').map_or(job, |(root, _)| root);
951    if let Some(dir) = &spec.script_dir {
952        return Ok(dir.clone());
953    }
954    if root == spec.dag_root {
955        return Ok(root_dir.to_path_buf());
956    }
957    setup
958        .script_roots
959        .get(root)
960        .cloned()
961        .ok_or_else(|| NotRun::Rejected {
962            reason: pb::RejectReason::ScriptRootUnknown,
963            detail: format!("script root `{root}` of `{job}` isn't on this worker"),
964        })
965}
966
967/// What a command's or a script's templates are rendered with.
968fn render_context(spec: &AttemptSpec) -> RenderContext {
969    let mut ctx = RenderContext::new(
970        &spec.run.dag_id,
971        &spec.run.run_id,
972        &spec.run.kind.to_string(),
973        &spec.run.planned_for.to_string(),
974        &spec.run.since.to_string(),
975    );
976    ctx.inputs.clone_from(&spec.inputs);
977    ctx.outcomes.clone_from(&spec.outcomes);
978    ctx.params.clone_from(&spec.run.params);
979    ctx.secrets.clone_from(&spec.secrets);
980    match &spec.run.event {
981        Some(event) => ctx.with_event(event, &spec.run.planned_for.to_string()),
982        None => ctx,
983    }
984}
985
986/// A task's `env`, rendered.
987fn render_env(
988    env: &BTreeMap<String, schedr_model::value::Template>,
989    ctx: &RenderContext,
990) -> Result<BTreeMap<String, String>, NotRun> {
991    env.iter()
992        .map(|(name, template)| Ok((name.clone(), render(template, ctx)?)))
993        .collect::<Result<BTreeMap<_, _>, crate::render::RenderError>>()
994        .map_err(|e| failed(RENDER_FAILED, &e))
995}
996
997/// How a started attempt ended.
998#[derive(Debug, Clone)]
999pub struct Ran {
1000    /// The process's end, and why the agent stopped it, if it did.
1001    pub supervised: Supervised,
1002    /// For a Python task: the runner's result message, if it sent one.
1003    pub runner_result: Option<RunnerMessage>,
1004    /// For a command: the tails of its stdout and stderr.
1005    pub output: Option<(TailBuffer, TailBuffer)>,
1006    /// How long it ran.
1007    pub duration: Duration,
1008    /// For a Python task that said hello: how long it took to start.
1009    pub start: Option<StartTimes>,
1010    /// Whether it was forked from a fork server (else spawned).
1011    pub forked: bool,
1012    /// What it used and whether it dumped core.
1013    pub ended: crate::usage::Ended,
1014    /// The code it ended on, when that isn't the code it started on: a poke moved to new code
1015    /// (decision 335).
1016    pub moved_to: Option<String>,
1017    /// A wait step's host ended with none of them to blame: why. Its attempt ends `lost`.
1018    pub host_lost: Option<String>,
1019    /// A wait step's: whether it got its host killed (decision 338).
1020    pub struck: bool,
1021}
1022
1023impl Ran {
1024    /// A run with no process of its own to tell more: none started, or a wait step on its host.
1025    #[must_use]
1026    pub fn with_no_process(
1027        supervised: Supervised,
1028        runner_result: Option<RunnerMessage>,
1029        duration: Duration,
1030    ) -> Self {
1031        Self {
1032            supervised,
1033            runner_result,
1034            output: None,
1035            duration,
1036            start: None,
1037            forked: false,
1038            ended: crate::usage::Ended::default(),
1039            moved_to: None,
1040            host_lost: None,
1041            struck: false,
1042        }
1043    }
1044}
1045
1046/// How long a Python task's process took to start, by phase.
1047#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1048pub struct StartTimes {
1049    /// From starting the process to its runner's hello: the interpreter and `schedr`.
1050    pub runner: Duration,
1051    /// From sending the task to `task_imported`: the DAG file imported and the arguments
1052    /// built; `None` when that failed or the runner sent nothing.
1053    pub import: Option<Duration>,
1054}
1055
1056/// The `Finished` message for an attempt of `task` that ran. A command succeeds with an exit
1057/// code of one of its outcomes (`SUCCESS` for 0 unless it declares others), which becomes its
1058/// outcome; any other code is a failure.
1059#[must_use]
1060pub fn finished(attempt_id: &str, task: &Task, ran: &Ran) -> pb::Finished {
1061    let termination = ran.supervised.termination;
1062    let success_codes: Vec<i32> = if ran.output.is_some() {
1063        task.outcomes.iter().filter_map(|o| o.exit_code).collect()
1064    } else {
1065        vec![0]
1066    };
1067    let status = attempt_status(termination, ran.supervised.stopped, &success_codes);
1068    let mut message = pb::Finished {
1069        code_hash: ran.moved_to.clone().unwrap_or_default(),
1070        attempt_id: attempt_id.to_owned(),
1071        status: attempt_status_to_proto(status).into(),
1072        duration_ms: Some(u64::try_from(ran.duration.as_millis()).unwrap_or(u64::MAX)),
1073        usage: ran.ended.usage.map(|u| pb::ProcessUsage {
1074            user_cpu_micros: u.user_cpu_micros,
1075            system_cpu_micros: u.system_cpu_micros,
1076            peak_rss_bytes: u.peak_rss_bytes,
1077            major_faults: u.major_faults,
1078            voluntary_context_switches: u.voluntary_context_switches,
1079            involuntary_context_switches: u.involuntary_context_switches,
1080        }),
1081        core_dumped: ran.ended.core_dumped,
1082        wait_step: matches!(task.kind, schedr_model::TaskKind::Sensor { .. }),
1083        struck: ran.struck,
1084        ..pb::Finished::default()
1085    };
1086    match termination {
1087        crate::status::Termination::Exited(code) => message.exit_code = Some(code),
1088        crate::status::Termination::Signaled(signal) => message.signal = Some(signal),
1089        crate::status::Termination::Unknown => {}
1090    }
1091    if let Some((stdout, stderr)) = &ran.output {
1092        let result = process_result(stdout, stderr, termination.exit_code());
1093        let bytes = serde_json::to_vec(&result).unwrap_or_default();
1094        if status == AttemptStatus::Success {
1095            message.output_json = bytes;
1096            task.outcome_of_exit(termination.exit_code())
1097                .unwrap_or(schedr_model::DEFAULT_OUTCOME)
1098                .clone_into(&mut message.outcome);
1099        } else {
1100            message.error_summary_json = bytes;
1101        }
1102        return message;
1103    }
1104    if let Some(why) = &ran.host_lost {
1105        // Not its own doing: as a lost worker's tasks, each uses a retry (M4.11a3).
1106        message.status = attempt_status_to_proto(AttemptStatus::Lost).into();
1107        schedr_model::runner::WATCHER_HOST_LOST.clone_into(&mut message.error_kind);
1108        message.error_summary_json = summary("WatcherHostLost", why);
1109        return message;
1110    }
1111    match (&ran.runner_result, status) {
1112        (Some(RunnerMessage::TaskSucceeded { output, outcome }), AttemptStatus::Success) => {
1113            message.output_json = serde_json::to_vec(output).unwrap_or_default();
1114            message.outcome.clone_from(outcome);
1115        }
1116        (Some(RunnerMessage::TaskFailed { error, kind }), _) => {
1117            message.error_summary_json = serde_json::to_vec(error).unwrap_or_default();
1118            message.error_kind = kind.clone().unwrap_or_default();
1119            message.status = attempt_status_to_proto(status_or_failed(status)).into();
1120        }
1121        (_, AttemptStatus::Success) => {
1122            // Exited 0 without a result: the runner didn't do its job.
1123            message.status = attempt_status_to_proto(AttemptStatus::Failed).into();
1124            RUNNER_FAILED.clone_into(&mut message.error_kind);
1125            message.error_summary_json =
1126                summary("RunnerFailed", "the runner exited without a result");
1127        }
1128        (None, _) if termination == crate::status::Termination::Unknown => {
1129            PROCESS_STATUS_UNKNOWN.clone_into(&mut message.error_kind);
1130            message.error_summary_json = summary(
1131                "ProcessStatusUnknown",
1132                "the task's process ended, but how isn't known: the fork server's shim that \
1133                 reports it ended first (what was left of its process group was killed)",
1134            );
1135        }
1136        _ => {}
1137    }
1138    message
1139}
1140
1141/// A `CommandResource` setup's result: on success its output is the value it reported, not
1142/// its `ProcessResult`; with nothing reported (and a value declared) it fails.
1143pub fn with_resource_value(message: &mut pb::Finished, outcome: Result<serde_json::Value, ()>) {
1144    if message.status != i32::from(pb::AttemptStatus::Success) {
1145        return;
1146    }
1147    let Ok(value) = outcome else {
1148        message.status = attempt_status_to_proto(AttemptStatus::Failed).into();
1149        message.output_json = Vec::new();
1150        message.outcome = String::new();
1151        RESOURCE_NOT_REPORTED.clone_into(&mut message.error_kind);
1152        message.error_summary_json = summary(
1153            "ResourceNotReported",
1154            "resource value not reported: the setup exited 0 without `schedr task-ctx resource \
1155             set`",
1156        );
1157        return;
1158    };
1159    message.output_json = serde_json::to_vec(&value).unwrap_or_default();
1160}
1161
1162/// The `Finished` message for an attempt that failed before starting.
1163#[must_use]
1164pub fn failed_before_start(attempt_id: &str, kind: &str, message: &str) -> pb::Finished {
1165    pb::Finished {
1166        attempt_id: attempt_id.to_owned(),
1167        status: pb::AttemptStatus::Failed.into(),
1168        error_kind: kind.to_owned(),
1169        error_summary_json: summary("TaskNotStarted", message),
1170        ..pb::Finished::default()
1171    }
1172}
1173
1174/// A failure stays a failure; anything the agent stopped keeps its own status.
1175const fn status_or_failed(status: AttemptStatus) -> AttemptStatus {
1176    match status {
1177        AttemptStatus::Success => AttemptStatus::Failed,
1178        other => other,
1179    }
1180}
1181
1182fn summary(exception: &str, message: &str) -> Vec<u8> {
1183    ErrorSummary::json(exception, message).into_bytes()
1184}
1185
1186/// A command's connections' variables added to its `env=`; one in both is refused.
1187fn add_connection_env(
1188    env: &mut BTreeMap<String, String>,
1189    connection_env: &BTreeMap<String, String>,
1190) -> Result<(), NotRun> {
1191    for (name, value) in connection_env {
1192        if env.contains_key(name) {
1193            return Err(failed(
1194                RENDER_FAILED,
1195                &format!(
1196                    "`{name}` is in the task's `env=` and is a variable of a connection it is \
1197                     given: rename one"
1198                ),
1199            ));
1200        }
1201        env.insert(name.clone(), value.clone());
1202    }
1203    Ok(())
1204}
1205
1206fn failed(kind: &str, error: &dyn std::fmt::Display) -> NotRun {
1207    NotRun::Failed {
1208        kind: kind.to_owned(),
1209        message: error.to_string(),
1210    }
1211}
1212
1213fn run_vars(spec: &AttemptSpec) -> RunVars {
1214    RunVars {
1215        dag_id: spec.run.dag_id.clone(),
1216        run_id: spec.run.run_id.clone(),
1217        run_kind: spec.run.kind.to_string(),
1218        task_id: spec.task.id.to_string(),
1219        map_index: spec.run.map_index,
1220        try_number: spec.run.try_number,
1221        planned_for: spec.run.planned_for.to_string(),
1222        since: spec.run.since.to_string(),
1223    }
1224}
1225
1226fn time(t: Option<&prost_types::Timestamp>) -> Option<Timestamp> {
1227    let t = t?;
1228    Timestamp::new(t.seconds, t.nanos).ok()
1229}