Skip to main content

schedr_master/
mapping.rs

1//! Mapped tasks (decisions 69, 70, 74-79): which edges are lanes, the dimensions a mapped
2//! task's instances span, an instance's place in each, and the master's resolution of what a
3//! task is mapped over.
4//!
5//! - A mapped task's instances are the cartesian product of its mapped lists, the first
6//!   argument written varying slowest (`.expand_kwargs`: one dimension, a list of dicts).
7//! - A **lane** is an element-wise data edge: the task is mapped over the whole output of a
8//!   mapped upstream task, which it references nowhere else; instance `i` then waits only for
9//!   that upstream's instance `i` (70 B). Every other edge into a mapped task counts its
10//!   upstream as a whole (70.1).
11
12use std::collections::{BTreeMap, BTreeSet};
13
14use schedr_db::{Database, DbError};
15use schedr_model::{
16    Dag, Edge, EdgeKind, Expand, PathElem, Reference, ResourceRole, Task, TaskId,
17    TaskInstanceState, TaskKind, Value,
18};
19use serde_json::Value as Json;
20
21#[cfg(test)]
22mod tests;
23
24/// Whether `task` is mapped (`.expand(...)`).
25#[must_use]
26pub const fn is_mapped(task: &Task) -> bool {
27    task.expand.is_some()
28}
29
30/// One dimension of a mapped task's instances.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum Dim<'a> {
33    /// A list the master resolves: a literal, or a reference to a list.
34    Values(&'a Value),
35    /// The whole output of a mapped upstream task, element by element (a lane).
36    Lane(&'a TaskId),
37}
38
39/// A mapped task's dimensions, in order: each with the parameter it fills (`None` for
40/// `.expand_kwargs`, whose elements are dicts of arguments).
41#[must_use]
42pub fn dims<'a>(dag: &Dag, task: &'a Task) -> Vec<(Option<&'a str>, Dim<'a>)> {
43    let lanes = lane_sources(dag, task);
44    let dim = |value: &'a Value| match lane_of(value) {
45        Some(upstream) if lanes.contains(upstream) => Dim::Lane(upstream),
46        _ => Dim::Values(value),
47    };
48    match &task.expand {
49        Some(Expand::Product(over)) => over
50            .iter()
51            .map(|m| (Some(m.name.as_str()), dim(&m.value)))
52            .collect(),
53        Some(Expand::Kwargs(over)) => vec![(None, dim(over))],
54        None => Vec::new(),
55    }
56}
57
58/// The upstream task a mapped value takes whole (no path), if it is one reference.
59fn lane_of(value: &Value) -> Option<&TaskId> {
60    match value {
61        Value::Ref(Reference::Output { task, path, .. }) if path.is_empty() => Some(task),
62        _ => None,
63    }
64}
65
66/// The mapped upstream tasks `task` is mapped over element by element (its lanes): each the
67/// whole output of a mapped task, referenced nowhere else in `task` (a second reference,
68/// `.partial(all=sizes)` or `sizes[0]`, makes it count as a whole: 70.1).
69#[must_use]
70pub fn lane_sources<'a>(dag: &Dag, task: &'a Task) -> BTreeSet<&'a TaskId> {
71    let mapped_values: Vec<&Value> = match &task.expand {
72        Some(Expand::Product(over)) => over.iter().map(|m| &m.value).collect(),
73        Some(Expand::Kwargs(over)) => vec![over],
74        None => return BTreeSet::new(),
75    };
76    let mut uses: BTreeMap<&TaskId, usize> = BTreeMap::new();
77    for reference in task.references() {
78        if let Some(upstream) = reference.upstream_task() {
79            *uses.entry(upstream).or_default() += 1;
80        }
81    }
82    mapped_values
83        .into_iter()
84        .filter_map(lane_of)
85        .filter(|upstream| uses.get(upstream) == Some(&1))
86        .filter(|upstream| dag.task(upstream).is_some_and(is_mapped))
87        .collect()
88}
89
90/// Whether `edge` is a lane: an element-wise data edge into a mapped task (70 B). An order
91/// edge, or a data edge whose upstream is used as a whole, counts its upstream as a whole.
92#[must_use]
93pub fn is_lane(dag: &Dag, edge: &Edge) -> bool {
94    edge.kind == EdgeKind::Data
95        && dag
96            .task(&edge.to)
97            .is_some_and(|task| lane_sources(dag, task).contains(&edge.from))
98}
99
100/// The mapped upstream task a dimension narrows element by element though it counts as a
101/// whole (used elsewhere in the task, so not a lane), with the outcomes taken:
102/// `.partial(all=results).expand(rows=results.on(Rows))`. Its instance whose upstream
103/// instance ended with another outcome, or was skipped, is skipped, as on a lane (decision
104/// 119).
105#[must_use]
106pub fn narrowed_whole<'a>(dag: &Dag, dim: &Dim<'a>) -> Option<(&'a TaskId, &'a [String])> {
107    match dim {
108        Dim::Values(Value::Ref(Reference::Output { task, path, on }))
109            if path.is_empty() && !on.is_empty() && dag.task(task).is_some_and(is_mapped) =>
110        {
111            Some((task, on))
112        }
113        _ => None,
114    }
115}
116
117/// Whether `edge`'s outcomes are taken per element ([`narrowed_whole`]), not on the whole
118/// upstream task, whose own outcome is only that its instances ended.
119#[must_use]
120pub fn narrows_per_element(dag: &Dag, edge: &Edge) -> bool {
121    edge.kind == EdgeKind::Data
122        && !edge.on.is_empty()
123        && dag.task(&edge.to).is_some_and(|task| {
124            dims(dag, task).iter().any(|(_, dim)| {
125                narrowed_whole(dag, dim)
126                    .is_some_and(|(up, on)| *up == edge.from && on == edge.on.as_slice())
127            })
128        })
129}
130
131/// Instance `index`'s place in each dimension of `sizes` (the first varying slowest).
132#[must_use]
133pub fn coordinates(index: usize, sizes: &[usize]) -> Vec<usize> {
134    let mut rest = index;
135    let mut place = vec![0; sizes.len()];
136    for (at, size) in sizes.iter().enumerate().rev() {
137        if *size > 0 {
138            place[at] = rest % size;
139            rest /= size;
140        }
141    }
142    place
143}
144
145/// The number of instances of `sizes`; `None` past `usize`.
146#[must_use]
147pub fn count(sizes: &[usize]) -> Option<usize> {
148    sizes
149        .iter()
150        .try_fold(1_usize, |n, size| n.checked_mul(*size))
151}
152
153/// What a mapped value is resolved against: the whole outputs of the tasks it references (a
154/// mapped task's as the list of its instances' outputs) and their outcomes (`None`: skipped).
155#[derive(Debug, Default)]
156pub struct Sources {
157    /// Whole outputs by task.
158    pub outputs: BTreeMap<TaskId, Json>,
159    /// Outcomes by task, of those that succeeded or were skipped.
160    pub outcomes: BTreeMap<TaskId, Option<String>>,
161    /// The mapped tasks among them: a whole mapped task's outcome only says its instances
162    /// ended, so `.on(...)` over its output narrows its elements one by one (decision 119),
163    /// never the list.
164    pub mapped: BTreeSet<TaskId>,
165}
166
167/// The stored JSON `value` stands for, as the runner would resolve it (`None` for a
168/// reference whose edge wasn't taken). Errors say why a value can't be resolved here.
169///
170/// # Errors
171///
172/// A message for a reference the master can't resolve (the run's context, a missing output
173/// or path).
174pub fn resolve(value: &Value, sources: &Sources) -> Result<Json, String> {
175    match value {
176        Value::Literal(json) => Ok(json.clone()),
177        Value::Ref(reference) => resolve_ref(reference, sources),
178        Value::List(items) => items
179            .iter()
180            .map(|item| resolve(item, sources))
181            .collect::<Result<Vec<_>, _>>()
182            .map(Json::Array),
183        Value::Map(entries) => entries
184            .iter()
185            .map(|(key, item)| Ok((key.clone(), resolve(item, sources)?)))
186            .collect::<Result<serde_json::Map<_, _>, String>>()
187            .map(Json::Object),
188        Value::Template(_) => Err("a text template isn't a list".to_owned()),
189    }
190}
191
192/// Whether a value is left to its instance's runner to build: it holds a template or a
193/// `dag_ctx` reference, which the master doesn't render (decision 118), the run's parameters
194/// included, or a secret, which the master never sees.
195#[must_use]
196pub fn built_by_runner(value: &Value) -> bool {
197    match value {
198        Value::Template(_)
199        | Value::Ref(Reference::DagCtx { .. } | Reference::Param { .. } | Reference::Secret(_)) => {
200            true
201        }
202        Value::List(items) => items.iter().any(built_by_runner),
203        Value::Map(entries) => entries.values().any(built_by_runner),
204        Value::Literal(_) | Value::Ref(_) => false,
205    }
206}
207
208/// What a mapped value stands for, as [`resolve`], except that the elements of a list
209/// written in the file that its runners build ([`built_by_runner`]) are `null` here (in a
210/// dict, its entries the runners build): each reaches its instance in its stored form
211/// (decision 118), and the list's length is known.
212///
213/// # Errors
214///
215/// As [`resolve`].
216pub fn resolve_mapped(value: &Value, sources: &Sources) -> Result<Json, String> {
217    match value {
218        Value::List(items) => items
219            .iter()
220            .map(|item| match item {
221                // A dict keeps its keys, for `.expand_kwargs()`: only its entries the runner
222                // builds are `null`.
223                Value::Map(entries) => entries
224                    .iter()
225                    .map(|(key, entry)| {
226                        let entry = if built_by_runner(entry) {
227                            Json::Null
228                        } else {
229                            resolve(entry, sources)?
230                        };
231                        Ok((key.clone(), entry))
232                    })
233                    .collect::<Result<serde_json::Map<_, _>, String>>()
234                    .map(Json::Object),
235                item if built_by_runner(item) => Ok(Json::Null),
236                item => resolve(item, sources),
237            })
238            .collect::<Result<Vec<_>, _>>()
239            .map(Json::Array),
240        _ => resolve(value, sources),
241    }
242}
243
244fn resolve_ref(reference: &Reference, sources: &Sources) -> Result<Json, String> {
245    match reference {
246        Reference::DagCtx { .. } => Err("the run's context isn't a list".to_owned()),
247        // Refused when the DAG is validated: the number of instances would depend on them.
248        Reference::Param { .. } => Err("a run's parameters can't be mapped over".to_owned()),
249        Reference::Secret(_) => Err("a secret can't be mapped over".to_owned()),
250        Reference::Outcome { task } => Ok(sources
251            .outcomes
252            .get(task)
253            .cloned()
254            .flatten()
255            .map_or(Json::Null, Json::String)),
256        Reference::Output { task, path, on } => {
257            if let Some(outcome) = sources.outcomes.get(task) {
258                // Skipped, or another outcome than it was narrowed to: `None` (a mapped task:
259                // only skipped, its `.on(...)` being per element).
260                let on: &[String] = if sources.mapped.contains(task) {
261                    &[]
262                } else {
263                    on
264                };
265                let taken = outcome
266                    .as_ref()
267                    .is_some_and(|o| on.is_empty() || on.contains(o));
268                if !taken {
269                    return Ok(Json::Null);
270                }
271            }
272            let value = sources
273                .outputs
274                .get(task)
275                .ok_or_else(|| format!("the output of `{task}` isn't stored"))?;
276            follow(value, path, &format!("`{task}`"), "the output")
277        }
278    }
279}
280
281/// `path` into a stored `value` (`what` of `whose`, for messages), as the runner reads it: a
282/// dict shaped like a tag is stored escaped (`$dict`, B66), a tuple as `$tuple`.
283///
284/// # Errors
285///
286/// A message for a path that doesn't exist in it.
287pub fn follow(value: &Json, path: &[PathElem], whose: &str, what: &str) -> Result<Json, String> {
288    let mut value = value;
289    for step in path {
290        value = match (step, value) {
291            (PathElem::Field(name), Json::Object(fields)) => match fields.get("$dict") {
292                Some(Json::Object(inner)) if fields.len() == 1 => inner,
293                _ => fields,
294            }
295            .get(name)
296            .ok_or_else(|| format!("{whose}: `{name}` doesn't exist in {what}"))?,
297            (PathElem::Index(i), Json::Array(items)) => usize::try_from(*i)
298                .ok()
299                .and_then(|i| items.get(i))
300                .ok_or_else(|| format!("{whose}: index {i} doesn't exist"))?,
301            (PathElem::Index(i), Json::Object(fields)) => fields
302                .get("$tuple")
303                .and_then(Json::as_array)
304                .and_then(|items| usize::try_from(*i).ok().and_then(|i| items.get(i)))
305                .ok_or_else(|| format!("{whose}: index {i} doesn't exist"))?,
306            _ => return Err(format!("{whose}: the path doesn't exist in {what}")),
307        };
308    }
309    Ok(value.clone())
310}
311
312/// A short description of `json`'s kind, for messages ("null", "a string").
313#[must_use]
314pub fn kind_of(json: &Json) -> &'static str {
315    match json {
316        Json::Null => "null",
317        Json::Bool(_) => "a boolean",
318        Json::Number(_) => "a number",
319        Json::String(_) => "a string",
320        Json::Array(_) => "a list",
321        Json::Object(_) => "an object",
322    }
323}
324
325/// The whole outputs and outcomes of `tasks` in a run, to resolve mapped values against: a
326/// mapped task's output is the list of its instances' outputs, in `map_index` order, `null`
327/// for one that didn't succeed (decision 77). `known` gives an instance's state when the
328/// caller knows it ahead of the database (a result being applied, its state not stored yet,
329/// B78): it is used instead of the stored one.
330///
331/// # Errors
332///
333/// [`DbError`] if the database fails.
334pub async fn sources(
335    db: &Database,
336    dag: &Dag,
337    run_id: &str,
338    tasks: &BTreeSet<&TaskId>,
339    known: impl Fn(&TaskId, i32) -> Option<TaskInstanceState>,
340) -> Result<Sources, DbError> {
341    let all: Vec<&TaskId> = tasks.iter().copied().collect();
342    let (mapped, plain): (Vec<&TaskId>, Vec<&TaskId>) = all
343        .iter()
344        .partition(|task| dag.task(task).is_some_and(is_mapped));
345    let mut sources = Sources {
346        outputs: db.outputs_of(run_id, &plain).await?,
347        outcomes: db.upstream_outcomes(run_id, &all).await?,
348        mapped: BTreeSet::new(),
349    };
350    for task in mapped {
351        let list = db
352            .instance_results(run_id, task)
353            .await?
354            .into_iter()
355            .map(|r| {
356                let state = known(task, r.map_index).unwrap_or(r.state);
357                if state == TaskInstanceState::Success {
358                    r.output.unwrap_or(Json::Null)
359                } else {
360                    Json::Null
361                }
362            })
363            .collect();
364        sources.outputs.insert(task.clone(), Json::Array(list));
365        sources.mapped.insert(task.clone());
366    }
367    Ok(sources)
368}
369
370/// Mapped lists already resolved, by (run, task, dimension): the instances of one task share
371/// them, so assigning N of them resolves each list once, not N times. Kept for one step.
372pub type Resolved = BTreeMap<(String, TaskId, usize), Json>;
373
374/// Why a task instance's inputs can't be made.
375#[derive(Debug, thiserror::Error)]
376pub enum InputsError {
377    /// The database failed.
378    #[error(transparent)]
379    Db(#[from] DbError),
380    /// An element `.expand_kwargs()` maps over isn't a dict of arguments: the instance can't
381    /// run (it would every time).
382    #[error("{0}")]
383    NotArguments(String),
384}
385
386/// The setup whose value a resource's command or script cleanup reads (`schedr task-ctx resource get`),
387/// whatever its templates name.
388fn resource_setup(task: &Task) -> Option<&TaskId> {
389    match &task.kind {
390        TaskKind::Command {
391            resource: Some(ResourceRole::Cleanup { setup }),
392            ..
393        }
394        | TaskKind::Script {
395            resource: Some(ResourceRole::Cleanup { setup }),
396            ..
397        } => Some(setup),
398        _ => None,
399    }
400}
401
402/// A task instance's inputs, as JSON: the whole outputs of the upstream tasks it uses (not
403/// its lanes), and for an instance of a mapped task its own arguments under `$expand`, with
404/// the outcome of each taken from a lane under `$expand_outcomes` (decision 76), and those its
405/// runner builds in their stored form under `$expand_values` (decision 118). A lane reads
406/// its one upstream instance; a mapped list is resolved once per `resolved`.
407///
408/// # Errors
409///
410/// [`InputsError::Db`] if the database fails; [`InputsError::NotArguments`] for an element
411/// of `.expand_kwargs()` over a mapped task that isn't a dict (a mapped list's elements are
412/// checked when the task expands).
413pub async fn inputs(
414    db: &Database,
415    dag: &Dag,
416    run_id: &str,
417    (task, map_index): (&Task, i32),
418    resolved: &mut Resolved,
419) -> Result<Json, InputsError> {
420    let lanes = lane_sources(dag, task);
421    let upstream = |references: Vec<&Reference>| -> BTreeSet<TaskId> {
422        references
423            .into_iter()
424            .filter_map(Reference::upstream_task)
425            .filter(|upstream| !lanes.contains(upstream))
426            .cloned()
427            .collect()
428    };
429    // Whole outputs only for the arguments' output references: what the task is mapped over
430    // reaches each instance as its element, under `$expand`, and an outcome reference is
431    // answered from the outcomes, so neither is sent again whole (B83).
432    let dims = dims(dag, task);
433    // An element its runner builds (decision 118) needs the outputs its template references,
434    // as an argument does.
435    let runner_built = dims.iter().filter_map(|(_, dim)| match dim {
436        Dim::Values(Value::List(items)) => Some(items.iter().filter(|i| built_by_runner(i))),
437        _ => None,
438    });
439    let mut whole = upstream(
440        task.argument_references()
441            .into_iter()
442            .chain(runner_built.flatten().flat_map(Value::references))
443            .filter(|r| matches!(r, Reference::Output { .. }))
444            .collect(),
445    );
446    whole.extend(resource_setup(task).cloned());
447    // The mapped values' sources only while their resolved lists aren't known yet.
448    let unresolved = dims.iter().enumerate().any(|(d, (_, dim))| {
449        matches!(dim, Dim::Values(_))
450            && !resolved.contains_key(&(run_id.to_owned(), task.id.clone(), d))
451    });
452    let used = if unresolved && map_index >= 0 {
453        upstream(task.references())
454    } else {
455        whole.clone()
456    };
457    let used: BTreeSet<&TaskId> = used.iter().collect();
458    let sources = sources(db, dag, run_id, &used, |_, _| None).await?;
459    let mut inputs: serde_json::Map<String, Json> = sources
460        .outputs
461        .iter()
462        .filter(|(task, _)| whole.contains(task))
463        .map(|(task, output)| (task.to_string(), output.clone()))
464        .collect();
465    let Ok(index) = usize::try_from(map_index) else {
466        return Ok(Json::Object(inputs));
467    };
468    let sizes = db.map_sizes(run_id, &task.id).await?.unwrap_or_default();
469    let place = coordinates(index, &sizes);
470    let mut arguments = InstanceArguments::default();
471    for (d, ((name, dim), at)) in dims.into_iter().zip(place).enumerate() {
472        let lane = match dim {
473            Dim::Lane(upstream) => Some(upstream),
474            Dim::Values(_) => None,
475        };
476        let (element, outcome) = match dim {
477            Dim::Values(value) => {
478                let list = resolved
479                    .entry((run_id.to_owned(), task.id.clone(), d))
480                    .or_insert_with(|| {
481                        resolve_mapped(value, &sources).unwrap_or_else(|error| {
482                            tracing::warn!(
483                                task_id = %task.id, %error, "a mapped value no longer resolves"
484                            );
485                            Json::Null
486                        })
487                    });
488                let element = list.get(at).cloned().unwrap_or(Json::Null);
489                // The whole output of a mapped task used whole: the element is its instance's
490                // output, decoded as that instance's outcome, as on a lane.
491                let outcome = match lane_of(value) {
492                    Some(upstream) if dag.task(upstream).is_some_and(is_mapped) => {
493                        let place = i32::try_from(at).unwrap_or(i32::MAX);
494                        db.instance_result(run_id, upstream, place)
495                            .await?
496                            .and_then(|r| r.outcome)
497                    }
498                    _ => None,
499                };
500                (element, outcome)
501            }
502            Dim::Lane(upstream) => {
503                let place = i32::try_from(at).unwrap_or(i32::MAX);
504                let result = db.instance_result(run_id, upstream, place).await?;
505                let output = result.as_ref().and_then(|r| r.output.clone());
506                (output.unwrap_or(Json::Null), result.and_then(|r| r.outcome))
507            }
508        };
509        // An element its runner builds, in its stored form (decision 118).
510        let runner_element = match dim {
511            Dim::Values(Value::List(items)) => items.get(at).filter(|i| built_by_runner(i)),
512            _ => None,
513        };
514        let element = Element {
515            name,
516            value: element,
517            outcome,
518            stored: runner_element,
519        };
520        arguments.place(element, at, lane)?;
521    }
522    arguments.into_inputs(&mut inputs);
523    Ok(Json::Object(inputs))
524}
525
526/// One dimension's element for an instance.
527struct Element<'a> {
528    /// The parameter it fills; `None` for `.expand_kwargs()`.
529    name: Option<&'a str>,
530    /// What it resolved to.
531    value: Json,
532    /// The outcome of its lane's upstream instance.
533    outcome: Option<String>,
534    /// Written with a template or the run's context: built by the runner (decision 118).
535    stored: Option<&'a Value>,
536}
537
538/// An instance's own arguments: `$expand`, `$expand_outcomes` and `$expand_values`.
539#[derive(Default)]
540struct InstanceArguments {
541    expand: serde_json::Map<String, Json>,
542    stored: serde_json::Map<String, Json>,
543    outcomes: serde_json::Map<String, Json>,
544}
545
546impl InstanceArguments {
547    /// Places element `at` of a dimension (`lane`: its mapped upstream task, if a lane).
548    fn place(
549        &mut self,
550        element: Element<'_>,
551        at: usize,
552        lane: Option<&TaskId>,
553    ) -> Result<(), InputsError> {
554        let Element {
555            name,
556            value,
557            outcome,
558            stored,
559        } = element;
560        match name {
561            Some(name) => {
562                if let Some(outcome) = outcome {
563                    self.outcomes.insert(name.to_owned(), Json::String(outcome));
564                }
565                match stored {
566                    Some(item) => {
567                        let item = serde_json::to_value(item).unwrap_or(Json::Null);
568                        self.stored.insert(name.to_owned(), item);
569                    }
570                    None => {
571                        self.expand.insert(name.to_owned(), value);
572                    }
573                }
574            }
575            // `.expand_kwargs()`: the element is a dict of arguments.
576            None => match (value, lane) {
577                (Json::Object(mut arguments), _) => {
578                    // Arguments written with a template or the run's context are built by the
579                    // runner (decision 118).
580                    if let Some(Value::Map(entries)) = stored {
581                        for (key, entry) in entries.iter().filter(|(_, e)| built_by_runner(e)) {
582                            arguments.remove(key);
583                            let entry = serde_json::to_value(entry).unwrap_or(Json::Null);
584                            self.stored.insert(key.clone(), entry);
585                        }
586                    }
587                    self.expand.extend(arguments);
588                }
589                (element, Some(upstream)) => {
590                    return Err(InputsError::NotArguments(format!(
591                        "element {at} of `{upstream}` isn't a dict of arguments for \
592                         `.expand_kwargs()`: {element}"
593                    )));
594                }
595                // A mapped list was checked when the task expanded.
596                (_, None) => {}
597            },
598        }
599        Ok(())
600    }
601
602    fn into_inputs(self, inputs: &mut serde_json::Map<String, Json>) {
603        inputs.insert("$expand".to_owned(), Json::Object(self.expand));
604        inputs.insert("$expand_outcomes".to_owned(), Json::Object(self.outcomes));
605        if !self.stored.is_empty() {
606            inputs.insert("$expand_values".to_owned(), Json::Object(self.stored));
607        }
608    }
609}