Skip to main content

schedr_master/
execution.rs

1//! Moving runs forward: task instances for new runs, results of attempts, retries whose delay
2//! passed, cancelling, and the run result (the rules are in [`crate::progress`]).
3//!
4//! Every change is stored as it is decided, a new run's preparation in one transaction (B79).
5//! Assigning tasks to workers and the messages of the
6//! protocol use these operations (see archive/PROJECT.md, Task assignment).
7
8use std::collections::{BTreeMap, BTreeSet};
9use std::sync::Arc;
10
11use jiff::Timestamp;
12use schedr_db::instances::{InstanceUpdate, NewlyRunning, RunTasks, StoredInstance};
13use schedr_db::{Database, DbError};
14use schedr_model::{
15    AttemptStatus, CleanupResult, Dag, Reference, RunState, TaskId, TaskInstanceState, TaskKind,
16};
17
18use schedr_model::notify::NotifyEvent;
19use serde_json::json;
20
21use crate::notifications::{Event, MAX_FAILED_TASKS, Notifications};
22
23/// What an `@sensor(wait_for=...)`'s attempt ends with when its function returned `NOT_YET` for
24/// the run it was given (decision 353): it waits for a later one.
25pub const NOT_YET_OUTCOME: &str = "NotYet";
26
27/// `wait_for`'s outcome for a run, or task, it waited for that didn't succeed.
28pub const FAILED: &str = "Failed";
29
30/// A wait step's outcome when its time ran out.
31pub const TIMED_OUT: &str = "TimedOut";
32
33/// How a `wait_for` step ends.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum WaitEnd {
36    /// The run, or its task, succeeded.
37    Ran {
38        /// That run's ID.
39        run_id: String,
40    },
41    /// It ended otherwise.
42    Failed {
43        /// How: `failed`, `upstream_failed`, `skipped`, `cancelled`.
44        state: String,
45        /// That run's ID.
46        run_id: String,
47    },
48    /// Its `max_wait` ran out first.
49    TimedOut,
50    /// The event a `wait_for(EventNamed(...))` waited for came (decision 354): its value.
51    Event {
52        /// The event, as the node's output (`Event[Json]`).
53        value: serde_json::Value,
54    },
55    /// It can't wait: its key isn't one (decision 354); it fails with this reason.
56    Refused {
57        /// Why.
58        reason: String,
59    },
60}
61
62/// Why a `first_of` failed whose output didn't fit, as an attempt's error kind says it.
63const OUTPUT_TOO_LARGE: &str = "output_too_large";
64
65use crate::mapping::{self, Dim};
66use crate::metrics::MasterMetrics;
67use crate::progress::{AfterAttempt, Expansion, Instances, RunProgress, Snapshot, after_attempt};
68use crate::quiet::{WakeReason, Wakes};
69
70/// The most task instances a round creates for runs that just started (whole runs only, at
71/// least one): many runs starting at once go over a few rounds (B18).
72pub const INSTANCES_PER_ROUND: usize = 2000;
73
74/// The most failed tasks a round queues again once their retry delay passed (B18).
75pub const RETRIES_PER_ROUND: usize = 100;
76
77/// `[mapping] max_instances` by default.
78pub const DEFAULT_MAX_INSTANCES: usize = 1024;
79#[cfg(test)]
80mod tests;
81
82/// The outcome of every successful task until outcome types arrive (milestone M4).
83pub const SUCCESS: &str = "SUCCESS";
84
85/// Why an execution operation failed.
86#[derive(Debug, thiserror::Error)]
87pub enum ExecutionError {
88    /// The database failed.
89    #[error(transparent)]
90    Db(#[from] DbError),
91    /// No such run.
92    #[error("no run `{0}`")]
93    UnknownRun(String),
94    /// No such task in the run.
95    #[error("run `{run_id}` has no task `{task_id}`")]
96    UnknownTask {
97        /// The run.
98        run_id: String,
99        /// The task.
100        task_id: TaskId,
101    },
102    /// No such instance of the task in the run (not mapped, not expanded, out of range).
103    #[error("task `{task_id}` of run `{run_id}` has no instance {map_index}")]
104    UnknownInstance {
105        /// The run.
106        run_id: String,
107        /// The task.
108        task_id: TaskId,
109        /// The instance asked for.
110        map_index: i32,
111    },
112}
113
114/// How an attempt ended, as the master needs it.
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct AttemptResult {
117    /// The attempt's status.
118    pub status: AttemptStatus,
119    /// The error kind schedr recognised, for failures.
120    pub error_kind: Option<String>,
121    /// The output (stored JSON) on success.
122    pub output: Option<serde_json::Value>,
123    /// The outcome on success, as the worker reported it (`SUCCESS` when it named none).
124    pub outcome: Option<String>,
125    /// How its cleanup ended, if the task has one.
126    pub cleanup: Option<CleanupResult>,
127}
128
129/// What recording an attempt's result did.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct Recorded {
132    /// The task's new state; `None` when the task wasn't running (a repeated result).
133    pub state: Option<TaskInstanceState>,
134    /// The run's result, if it finished now.
135    pub run_result: Option<RunState>,
136    /// Running instances to stop, by `map_index`: their mapped task's step failed (75a).
137    pub stops: Vec<(TaskId, i32)>,
138}
139
140/// One result's change to its instance ([`Execution::result_update`]).
141struct Planned {
142    update: InstanceUpdate,
143    /// `(instance ID, outcome, value)`, for a success.
144    output: Option<(String, String, serde_json::Value)>,
145}
146
147/// What cancelling a run did.
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct Cancelled {
150    /// Tasks and instances still running, by `map_index`: their attempts are to be cancelled.
151    pub running: Vec<(TaskId, i32)>,
152    /// The run's result, if it finished now.
153    pub run_result: Option<RunState>,
154}
155
156/// What cancelling one task did.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub enum TaskCancel {
159    /// It hadn't started: it is `cancelled` now, with the tasks downstream of it; the run's
160    /// result, if it finished now.
161    Cancelled(Option<RunState>),
162    /// It runs: its attempt is to be stopped, and it ends `cancelled` when it reports.
163    Stopping,
164    /// It had already finished, in this state: nothing to do.
165    AlreadyFinished(TaskInstanceState),
166    /// The run had already finished, in this state.
167    RunFinished(RunState),
168    /// The run is queued: its tasks don't exist yet (cancel the run instead).
169    RunQueued,
170}
171
172/// What retrying an `unschedulable` task did.
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub enum TaskRetry {
175    /// It is queued again (this task instance).
176    Queued(String),
177    /// It isn't `unschedulable` (it is in this state).
178    NotUnschedulable(TaskInstanceState),
179    /// The run had already finished, in this state.
180    RunFinished(RunState),
181    /// The run's tasks don't exist yet.
182    RunQueued,
183}
184
185/// Runs moved forward in a database.
186#[derive(Debug, Clone)]
187pub struct Execution {
188    db: Database,
189    metrics: MasterMetrics,
190    wakes: Wakes,
191    /// `[mapping] max_instances`.
192    max_instances: usize,
193    /// `[notifications]`.
194    notifications: Arc<Notifications>,
195    /// How much a round does at most (decision 493).
196    rounds: crate::core::RoundLimits,
197}
198
199impl Execution {
200    /// Execution over `db`.
201    #[must_use]
202    pub fn new(db: Database) -> Self {
203        Self {
204            db,
205            metrics: MasterMetrics::default(),
206            wakes: Wakes::default(),
207            max_instances: DEFAULT_MAX_INSTANCES,
208            notifications: Arc::default(),
209            rounds: crate::core::RoundLimits::default(),
210        }
211    }
212
213    /// Wakes a finished run's DAG through `wakes` (a queued run may take its place).
214    pub fn set_wakes(&mut self, wakes: Wakes) {
215        self.wakes = wakes;
216    }
217
218    /// Counts finished runs in `metrics`.
219    pub fn set_metrics(&mut self, metrics: MasterMetrics) {
220        self.metrics = metrics;
221    }
222
223    /// What finished runs and tasks notify (`[notifications]`).
224    pub fn set_notifications(&mut self, notifications: Arc<Notifications>) {
225        self.notifications = notifications;
226    }
227
228    /// The most instances a mapped task may have (`[mapping] max_instances`).
229    pub const fn set_max_instances(&mut self, max_instances: usize) {
230        self.max_instances = max_instances;
231    }
232
233    /// How much a round does at most (decision 493).
234    pub const fn set_rounds(&mut self, rounds: crate::core::RoundLimits) {
235        self.rounds = rounds;
236    }
237
238    /// Finishes run `run_id` of `dag` with `result`, queues its notifications with it (decision
239    /// 410), and counts it.
240    async fn finish(
241        &self,
242        run_id: &str,
243        dag: &Dag,
244        result: RunState,
245        now: Timestamp,
246    ) -> Result<(), ExecutionError> {
247        Box::pin(self.db.atomically(async {
248            self.db.finish_run(run_id, result, now).await?;
249            self.notify_run(run_id, dag, result, now).await
250        }))
251        .await?;
252        self.metrics.run_finished(dag.id.as_str(), &result);
253        self.wakes.wake(&dag.id, WakeReason::RunEnded);
254        Ok(())
255    }
256
257    /// Queues what run `run_id` ending `result` tells its DAG's channels.
258    async fn notify_run(
259        &self,
260        run_id: &str,
261        dag: &Dag,
262        result: RunState,
263        now: Timestamp,
264    ) -> Result<(), ExecutionError> {
265        if dag.notify.is_empty() {
266            return Ok(());
267        }
268        let kinds = match result {
269            RunState::Failed => vec![NotifyEvent::RunFailed],
270            RunState::Cancelled => vec![NotifyEvent::RunCancelled],
271            RunState::Success if self.db.previous_run_failed(dag.id.as_str(), run_id).await? => {
272                vec![NotifyEvent::RunSucceeded, NotifyEvent::RunRecovered]
273            }
274            RunState::Success => vec![NotifyEvent::RunSucceeded],
275            RunState::Queued | RunState::Running => return Ok(()),
276        };
277        let state = result.to_string();
278        let mut event = Event::new(dag, now);
279        event.run_id = Some(run_id);
280        event.state = Some(&state);
281        event.planned_for = self.db.run_record(run_id).await?.map(|r| r.planned_for);
282        if result == RunState::Failed {
283            event.failed_tasks = self.db.failed_tasks(run_id, MAX_FAILED_TASKS).await?;
284        }
285        let queued: Vec<_> = kinds
286            .into_iter()
287            .flat_map(|kind| self.notifications.queued(&event, kind, &self.metrics))
288            .collect();
289        self.db.queue_notifications(&queued, now).await?;
290        Ok(())
291    }
292
293    /// Queues `LATE_CLEANUP_FAILED` for run `run_id`: a cleanup of `task` failed after the run
294    /// had succeeded (decision 309).
295    ///
296    /// # Errors
297    ///
298    /// [`ExecutionError`] for an unknown run or a database failure.
299    pub async fn late_cleanup_failed(
300        &self,
301        run_id: &str,
302        task: &str,
303        error: Option<String>,
304        now: Timestamp,
305    ) -> Result<(), ExecutionError> {
306        let run = self.run(run_id).await?;
307        if run.dag.notify.is_empty() {
308            return Ok(());
309        }
310        let mut event = Event::new(&run.dag, now);
311        event.run_id = Some(run_id);
312        event.state = Some("success");
313        event.task = Some(task);
314        event.error = error;
315        event.planned_for = self.db.run_record(run_id).await?.map(|r| r.planned_for);
316        let queued =
317            self.notifications
318                .queued(&event, NotifyEvent::LateCleanupFailed, &self.metrics);
319        self.db.queue_notifications(&queued, now).await?;
320        Ok(())
321    }
322
323    /// Queues what a task's attempt ending `state` tells its DAG's channels: `TASK_FAILED`
324    /// after its last retry, `TASK_RETRY` before another.
325    async fn notify_task(
326        &self,
327        (run_id, dag): (&str, &Dag),
328        instance: &StoredInstance,
329        state: TaskInstanceState,
330        now: Timestamp,
331    ) -> Result<(), ExecutionError> {
332        let kind = match state {
333            TaskInstanceState::Failed => NotifyEvent::TaskFailed,
334            TaskInstanceState::UpForRetry => NotifyEvent::TaskRetry,
335            _ => return Ok(()),
336        };
337        if dag.notify.is_empty() {
338            return Ok(());
339        }
340        let task = if instance.map_index >= 0 {
341            format!("{}[{}]", instance.task_id, instance.map_index)
342        } else {
343            instance.task_id.to_string()
344        };
345        let state = state.to_string();
346        let mut event = Event::new(dag, now);
347        event.run_id = Some(run_id);
348        event.state = Some(&state);
349        event.task = Some(&task);
350        event.attempt = Some(instance.try_number);
351        event.error = self.db.instance_error(&instance.id).await?;
352        event.planned_for = self.db.run_record(run_id).await?.map(|r| r.planned_for);
353        let queued = self.notifications.queued(&event, kind, &self.metrics);
354        self.db.queue_notifications(&queued, now).await?;
355        Ok(())
356    }
357
358    /// Creates the task instances of runs that started: empty tasks are completed, tasks with
359    /// no upstream tasks are queued, mapped tasks with nothing to wait for expanded. Returns
360    /// the runs prepared.
361    ///
362    /// # Errors
363    ///
364    /// [`ExecutionError::Db`] if the database fails.
365    pub async fn prepare_runs(&self, now: Timestamp) -> Result<Vec<String>, ExecutionError> {
366        let mut prepared = Vec::new();
367        let mut created = 0;
368        for run in self.db.newly_running().await? {
369            // At most so many instances a round (a run is never split, and one is always
370            // made): many runs starting at once go over a few rounds (B18).
371            let tasks = run.dag.tasks.len();
372            if !prepared.is_empty() && created + tasks > self.rounds.started_instances {
373                break;
374            }
375            created += tasks;
376            // Whole or not at all (B79): a run is found again only while it has no task rows.
377            Box::pin(self.db.atomically(self.prepare(&run, now))).await?;
378            prepared.push(run.run_id);
379        }
380        Ok(prepared)
381    }
382
383    /// A newly running run's task rows, settled (and the run finished if that ends it).
384    async fn prepare(&self, run: &NewlyRunning, now: Timestamp) -> Result<(), ExecutionError> {
385        let first: Vec<(TaskId, i32, TaskInstanceState)> = run
386            .dag
387            .tasks
388            .iter()
389            .map(|t| (t.id.clone(), -1, TaskInstanceState::Scheduled))
390            .collect();
391        self.db.create_instances(&run.run_id, &first, now).await?;
392        let mut progress = RunProgress::new(&run.dag, BTreeMap::new());
393        let before = progress.snapshot();
394        self.settle_all(&run.run_id, &run.dag, &mut progress, &[])
395            .await?;
396        self.store(&run.run_id, &mut progress, &before, Vec::new(), now)
397            .await?;
398        if let Some(result) = progress.result() {
399            self.finish(&run.run_id, &run.dag, result, now).await?;
400        }
401        Ok(())
402    }
403
404    /// Records how an attempt of a running task instance ended, moves the run forward and
405    /// finishes it when every task has. A result for an instance that isn't running is
406    /// ignored (delivery is at least once).
407    ///
408    /// # Errors
409    ///
410    /// [`ExecutionError`] for an unknown run or task, or a database failure.
411    pub async fn attempt_finished(
412        &self,
413        run_id: &str,
414        task_id: &TaskId,
415        map_index: i32,
416        result: &AttemptResult,
417        now: Timestamp,
418    ) -> Result<Recorded, ExecutionError> {
419        self.attempts_finished(run_id, &[(task_id, map_index, result)], now)
420            .await
421    }
422
423    /// Records how several attempts of one run's running instances ended, as
424    /// [`Self::attempt_finished`] does one, reading the run once and moving it forward once
425    /// (M4B.4, B184): their outputs stored in one statement, their instances and what follows
426    /// from them in one advance. `state` is the last result's. A result for an instance that
427    /// isn't running, or for one already given here, is ignored.
428    ///
429    /// Results that arrived together are taken as if in the order that keeps each: a mapped
430    /// instance's success beside another's failure of the same step stays a success (in turn,
431    /// had the failure come first, it was cancelled, decision 75a); either order is what
432    /// arrived.
433    ///
434    /// # Errors
435    ///
436    /// [`ExecutionError`] for an unknown run or task, or a database failure.
437    pub async fn attempts_finished(
438        &self,
439        run_id: &str,
440        results: &[(&TaskId, i32, &AttemptResult)],
441        now: Timestamp,
442    ) -> Result<Recorded, ExecutionError> {
443        let mut run = self.run(run_id).await?;
444        let mut updates = Vec::with_capacity(results.len());
445        let mut outputs: Vec<(String, String, serde_json::Value)> = Vec::new();
446        let mut state_now = None;
447        for &(task_id, map_index, result) in results {
448            if updates
449                .iter()
450                .any(|u: &InstanceUpdate| &u.task_id == task_id && u.map_index == map_index)
451            {
452                continue;
453            }
454            let Some(planned) = self
455                .result_update(run_id, &mut run, (task_id, map_index), result, now)
456                .await?
457            else {
458                continue;
459            };
460            state_now = Some(planned.update.state);
461            outputs.extend(planned.output);
462            updates.push(planned.update);
463        }
464        if updates.is_empty() {
465            return Ok(Recorded {
466                state: None,
467                run_result: None,
468                stops: Vec::new(),
469            });
470        }
471        if !outputs.is_empty() {
472            let rows: Vec<(&str, &str, &serde_json::Value)> = outputs
473                .iter()
474                .map(|(id, outcome, value)| (id.as_str(), outcome.as_str(), value))
475                .collect();
476            self.db.store_outputs(&rows).await?;
477        }
478        let (run_result, stops) = self.advance(run_id, &run, updates, now).await?;
479        Ok(Recorded {
480            state: state_now,
481            run_result,
482            stops,
483        })
484    }
485
486    /// What one result changes of its instance: its update, and its output to store; `None`
487    /// for an instance that isn't running. Its cleanup's result, an `@sensor(wait_for=...)`'s
488    /// `NOT_YET` and a notification are written here.
489    async fn result_update(
490        &self,
491        run_id: &str,
492        run: &mut RunTasks,
493        (task_id, map_index): (&TaskId, i32),
494        result: &AttemptResult,
495        now: Timestamp,
496    ) -> Result<Option<Planned>, ExecutionError> {
497        let unknown = || ExecutionError::UnknownTask {
498            run_id: run_id.to_owned(),
499            task_id: task_id.clone(),
500        };
501        let instance = run
502            .instances
503            .iter_mut()
504            .find(|i| &i.task_id == task_id && i.map_index == map_index)
505            .ok_or_else(unknown)?;
506        if !matches!(
507            instance.state,
508            TaskInstanceState::Running | TaskInstanceState::CleaningUp
509        ) {
510            return Ok(None);
511        }
512        if let Some(cleanup) = result.cleanup {
513            self.db
514                .set_cleanup_result(&instance.id, cleanup, now)
515                .await?;
516            if !instance
517                .cleanup_result
518                .is_some_and(CleanupResult::fails_the_run)
519            {
520                instance.cleanup_result = Some(cleanup);
521            }
522        }
523        let instance = instance.clone();
524        let task = run.dag.task(task_id).ok_or_else(unknown)?;
525        let next = after_attempt(
526            result.status,
527            result.error_kind.as_deref(),
528            instance.retries_used,
529            &task.settings,
530            run.cancels(&instance),
531            now,
532        );
533        // An instance whose mapped task already failed was being stopped: its result is
534        // ignored, whatever it is (decision 75a).
535        let step_ended = map_index >= 0
536            && run
537                .instances
538                .iter()
539                .any(|i| &i.task_id == task_id && i.map_index == -1 && i.state.is_final());
540        let next = if step_ended {
541            AfterAttempt::Cancelled
542        } else {
543            next
544        };
545        let (state, ready_at) = match next {
546            AfterAttempt::Succeeded => (TaskInstanceState::Success, None),
547            AfterAttempt::RetryAt(at) => (TaskInstanceState::UpForRetry, Some(at)),
548            AfterAttempt::Failed => (TaskInstanceState::Failed, None),
549            AfterAttempt::Requeue => (TaskInstanceState::Queued, Some(now)),
550            AfterAttempt::Cancelled => (TaskInstanceState::Cancelled, None),
551        };
552        let outcome = result
553            .outcome
554            .as_deref()
555            .filter(|o| !o.is_empty())
556            .unwrap_or(SUCCESS);
557        // An `@sensor(wait_for=...)` saying `NOT_YET` to its run waits for a later one, as it
558        // waited for the first: queued again, no retry used (decision 353).
559        let waits = matches!(
560            task.kind,
561            TaskKind::Sensor {
562                wait_for: Some(_),
563                ..
564            }
565        );
566        if waits && state == TaskInstanceState::Success && outcome == NOT_YET_OUTCOME {
567            self.db.not_yet(&instance.id).await?;
568            return Ok(Some(Planned {
569                update: InstanceUpdate {
570                    ready_at: Some(now),
571                    ..update(task_id, map_index, TaskInstanceState::Queued)
572                },
573                output: None,
574            }));
575        }
576        self.notify_task((run_id, &run.dag), &instance, state, now)
577            .await?;
578        let output = (state == TaskInstanceState::Success).then(|| {
579            (
580                instance.id.clone(),
581                outcome.to_owned(),
582                result.output.clone().unwrap_or(serde_json::Value::Null),
583            )
584        });
585        Ok(Some(Planned {
586            update: InstanceUpdate {
587                ready_at,
588                outcome: (state == TaskInstanceState::Success).then(|| outcome.to_owned()),
589                used_retry: next.uses_retry(),
590                ..update(task_id, map_index, state)
591            },
592            output,
593        }))
594    }
595
596    /// A running instance's task ended and its cleanup runs: its attempt stays open, and
597    /// nothing downstream moves, until the attempt's result.
598    ///
599    /// # Errors
600    ///
601    /// [`ExecutionError::Db`] if the database fails.
602    pub async fn cleaning_up(
603        &self,
604        run_id: &str,
605        task_id: &TaskId,
606        map_index: i32,
607        now: Timestamp,
608    ) -> Result<(), ExecutionError> {
609        let cleaning = update(task_id, map_index, TaskInstanceState::CleaningUp);
610        self.db.update_instances(run_id, &[cleaning], now).await?;
611        Ok(())
612    }
613
614    /// Queues the task instances whose retry delay has passed. Returns how many.
615    ///
616    /// # Errors
617    ///
618    /// [`ExecutionError::Db`] if the database fails.
619    pub async fn queue_due_retries(&self, now: Timestamp) -> Result<usize, ExecutionError> {
620        let mut due = self.db.due_retries(now).await?;
621        // At most so many a round, the earliest due first; the rest in the next ones (B18).
622        due.truncate(self.rounds.retries);
623        for (run_id, task_id, map_index) in &due {
624            let queued = InstanceUpdate {
625                ready_at: Some(now),
626                ..update(task_id, *map_index, TaskInstanceState::Queued)
627            };
628            self.db.update_instances(run_id, &[queued], now).await?;
629        }
630        Ok(due.len())
631    }
632
633    /// Cancels a run: a queued run ends `cancelled` at once; in a running one every task and
634    /// instance that hasn't started is cancelled, and the running ones are returned to be
635    /// stopped (their results still count, and a failure among them isn't retried).
636    ///
637    /// # Errors
638    ///
639    /// [`ExecutionError`] for an unknown run or a database failure.
640    pub async fn cancel_run(
641        &self,
642        run_id: &str,
643        now: Timestamp,
644    ) -> Result<Cancelled, ExecutionError> {
645        let run = self.run(run_id).await?;
646        if run.state.is_final() {
647            return Ok(Cancelled {
648                running: Vec::new(),
649                run_result: None,
650            });
651        }
652        self.db.request_cancel(run_id, now).await?;
653        if run.state == RunState::Queued {
654            self.finish(run_id, &run.dag, RunState::Cancelled, now)
655                .await?;
656            return Ok(Cancelled {
657                running: Vec::new(),
658                run_result: Some(RunState::Cancelled),
659            });
660        }
661        let mut progress = progress_of(&run);
662        let before = progress.snapshot();
663        let (_, running) = progress.cancel();
664        // A mapped task whose instances are all cancelled now ends as a whole.
665        self.settle_all(run_id, &run.dag, &mut progress, &[])
666            .await?;
667        self.store(run_id, &mut progress, &before, Vec::new(), now)
668            .await?;
669        let run_result = progress.result();
670        if let Some(result) = run_result {
671            self.finish(run_id, &run.dag, result, now).await?;
672        }
673        Ok(Cancelled {
674            running,
675            run_result,
676        })
677    }
678
679    /// Winds down a run of a removed DAG (B192; archive/PROJECT.md, DAG code delivery: "attempts
680    /// already running finish; tasks not started yet are cancelled"): a queued run ends
681    /// `cancelled`; in a running one every task and instance not started is cancelled, as
682    /// [`Self::cancel_run`] does, but nothing running is stopped or marked. A resource's
683    /// cleanup still runs. Returns the run's result, if it finished now.
684    ///
685    /// # Errors
686    ///
687    /// [`ExecutionError`] for an unknown run or a database failure.
688    pub async fn wind_down(
689        &self,
690        run_id: &str,
691        now: Timestamp,
692    ) -> Result<Option<RunState>, ExecutionError> {
693        let run = self.run(run_id).await?;
694        if run.state.is_final() {
695            return Ok(None);
696        }
697        if run.state == RunState::Queued {
698            self.finish(run_id, &run.dag, RunState::Cancelled, now)
699                .await?;
700            return Ok(Some(RunState::Cancelled));
701        }
702        let mut progress = progress_of(&run);
703        let before = progress.snapshot();
704        let _ = progress.cancel();
705        self.settle_all(run_id, &run.dag, &mut progress, &[])
706            .await?;
707        self.store(run_id, &mut progress, &before, Vec::new(), now)
708            .await?;
709        let result = progress.result();
710        if let Some(result) = result {
711            self.finish(run_id, &run.dag, result, now).await?;
712        }
713        Ok(result)
714    }
715
716    /// Cancels one task of a run: one that hasn't started becomes `cancelled` at once, one
717    /// that runs is marked so that whatever its attempt reports (or a rejection, an expired
718    /// assignment, a lost worker) ends it `cancelled` without a retry, a failure staying a
719    /// failure. The tasks downstream of it are cancelled when it is. For a mapped task, every
720    /// instance of it.
721    ///
722    /// # Errors
723    ///
724    /// [`ExecutionError`] for an unknown run or task, or a database failure.
725    pub async fn cancel_task(
726        &self,
727        run_id: &str,
728        (task_id, map_index): (&TaskId, Option<i32>),
729        now: Timestamp,
730    ) -> Result<TaskCancel, ExecutionError> {
731        use TaskInstanceState as S;
732        let run = self.run(run_id).await?;
733        if run.state.is_final() {
734            return Ok(TaskCancel::RunFinished(run.state));
735        }
736        if run.dag.task(task_id).is_none() {
737            return Err(ExecutionError::UnknownTask {
738                run_id: run_id.to_owned(),
739                task_id: task_id.clone(),
740            });
741        }
742        if let Some(index) = map_index.filter(|i| *i >= 0) {
743            return self
744                .cancel_instance(run_id, &run, (task_id, index), now)
745                .await;
746        }
747        // A run that just started may not have its instances yet either.
748        let Some(state) = run
749            .instances
750            .iter()
751            .find(|i| &i.task_id == task_id && i.map_index == -1)
752            .map(|i| i.state)
753        else {
754            return Ok(TaskCancel::RunQueued);
755        };
756        let instances: Vec<(usize, S)> = run
757            .instances
758            .iter()
759            .filter(|i| &i.task_id == task_id && i.map_index >= 0)
760            .filter_map(|i| Some((usize::try_from(i.map_index).ok()?, i.state)))
761            .collect();
762        if state == S::Running && !instances.is_empty() {
763            // An expanded mapped task: its instances that haven't started are cancelled, the
764            // running ones stopped; it ends as a whole once they have.
765            let mut progress = progress_of(&run);
766            let before = progress.snapshot();
767            let mut running = false;
768            for (index, instance) in instances {
769                match instance {
770                    S::Scheduled | S::Queued | S::UpForRetry | S::Unschedulable => {
771                        progress.set_instance(task_id, index, S::Cancelled);
772                    }
773                    S::Running | S::CleaningUp => running = true,
774                    _ => {}
775                }
776            }
777            if running {
778                self.db.request_task_cancel(run_id, task_id, now).await?;
779            }
780            self.settle_all(run_id, &run.dag, &mut progress, &[])
781                .await?;
782            self.store(run_id, &mut progress, &before, Vec::new(), now)
783                .await?;
784            let result = progress.result();
785            if let Some(result) = result {
786                self.finish(run_id, &run.dag, result, now).await?;
787            }
788            return Ok(if running {
789                TaskCancel::Stopping
790            } else {
791                TaskCancel::Cancelled(result)
792            });
793        }
794        match state {
795            S::Running | S::CleaningUp => {
796                self.db.request_task_cancel(run_id, task_id, now).await?;
797                Ok(TaskCancel::Stopping)
798            }
799            S::Scheduled | S::Queued | S::UpForRetry | S::Unschedulable => {
800                let first = vec![update(task_id, -1, S::Cancelled)];
801                Ok(TaskCancel::Cancelled(
802                    self.advance(run_id, &run, first, now).await?.0,
803                ))
804            }
805            S::Success | S::Failed | S::Cancelled | S::Skipped | S::UpstreamFailed => {
806                Ok(TaskCancel::AlreadyFinished(state))
807            }
808        }
809    }
810
811    /// Cancels one instance of a mapped task (decision 82): one that hasn't started is
812    /// cancelled at once (the task as a whole ends cancelled once its others have), a running
813    /// one is stopped.
814    async fn cancel_instance(
815        &self,
816        run_id: &str,
817        run: &RunTasks,
818        (task_id, map_index): (&TaskId, i32),
819        now: Timestamp,
820    ) -> Result<TaskCancel, ExecutionError> {
821        use TaskInstanceState as S;
822        let instance = run
823            .instances
824            .iter()
825            .find(|i| &i.task_id == task_id && i.map_index == map_index)
826            .ok_or_else(|| ExecutionError::UnknownInstance {
827                run_id: run_id.to_owned(),
828                task_id: task_id.clone(),
829                map_index,
830            })?;
831        match instance.state {
832            S::Running | S::CleaningUp => {
833                self.db
834                    .request_instance_cancel(run_id, task_id, map_index, now)
835                    .await?;
836                Ok(TaskCancel::Stopping)
837            }
838            S::Scheduled | S::Queued | S::UpForRetry | S::Unschedulable => {
839                let first = vec![update(task_id, map_index, S::Cancelled)];
840                Ok(TaskCancel::Cancelled(
841                    self.advance(run_id, run, first, now).await?.0,
842                ))
843            }
844            state => Ok(TaskCancel::AlreadyFinished(state)),
845        }
846    }
847
848    /// Queues an `unschedulable` task again (`schedr tasks retry`); for a mapped task, its
849    /// `unschedulable` instances.
850    ///
851    /// # Errors
852    ///
853    /// [`ExecutionError`] for an unknown run or task, or a database failure.
854    pub async fn retry_task(
855        &self,
856        run_id: &str,
857        (task_id, map_index): (&TaskId, Option<i32>),
858        now: Timestamp,
859    ) -> Result<TaskRetry, ExecutionError> {
860        let run = self.run(run_id).await?;
861        if run.state.is_final() {
862            return Ok(TaskRetry::RunFinished(run.state));
863        }
864        if run.dag.task(task_id).is_none() {
865            return Err(ExecutionError::UnknownTask {
866                run_id: run_id.to_owned(),
867                task_id: task_id.clone(),
868            });
869        }
870        let mut of_task = run
871            .instances
872            .iter()
873            .filter(|i| &i.task_id == task_id)
874            .filter(|i| map_index.is_none_or(|m| i.map_index == m));
875        let Some(instance) = of_task
876            .clone()
877            .find(|i| i.state == TaskInstanceState::Unschedulable)
878            .or_else(|| of_task.next())
879        else {
880            if let Some(map_index) = map_index.filter(|_| !run.instances.is_empty()) {
881                return Err(ExecutionError::UnknownInstance {
882                    run_id: run_id.to_owned(),
883                    task_id: task_id.clone(),
884                    map_index,
885                });
886            }
887            return Ok(TaskRetry::RunQueued);
888        };
889        if instance.state == TaskInstanceState::Unschedulable
890            && self
891                .db
892                .retry_unschedulable(run_id, (task_id, map_index), now)
893                .await?
894        {
895            return Ok(TaskRetry::Queued(instance.id.clone()));
896        }
897        Ok(TaskRetry::NotUnschedulable(instance.state))
898    }
899
900    /// Fails a resource's user that waited too long for a worker, so the cleanup can run
901    /// (decision 273); nothing if it isn't `unschedulable` any more. Returns the run's result,
902    /// if it finished now, and the instances to stop (a mapped task's others, its step failed).
903    ///
904    /// # Errors
905    ///
906    /// [`ExecutionError`] for an unknown run or a database failure.
907    pub async fn fail_unschedulable(
908        &self,
909        run_id: &str,
910        (task_id, map_index): (&TaskId, i32),
911        reason: String,
912        now: Timestamp,
913    ) -> Result<(Option<RunState>, Vec<(TaskId, i32)>), ExecutionError> {
914        let run = self.run(run_id).await?;
915        let waiting = run.instances.iter().any(|i| {
916            &i.task_id == task_id
917                && i.map_index == map_index
918                && i.state == TaskInstanceState::Unschedulable
919        });
920        if run.state.is_final() || !waiting {
921            return Ok((None, Vec::new()));
922        }
923        let mut failed = update(task_id, map_index, TaskInstanceState::Failed);
924        failed.reason = Some(reason);
925        self.advance(run_id, &run, vec![failed], now).await
926    }
927
928    /// Ends a `wait_for` step (decision 353): with the other run's ID; `Failed` where the DAG
929    /// routes it, or else the step fails (the user's B); `TimedOut`. Nothing if it isn't
930    /// `queued` any more. Returns the run's result, if it finished now, and the instances to stop.
931    ///
932    /// # Errors
933    ///
934    /// [`ExecutionError`] for an unknown run or a database failure.
935    pub async fn wait_ended(
936        &self,
937        run_id: &str,
938        task_id: &TaskId,
939        ended: WaitEnd,
940        now: Timestamp,
941    ) -> Result<(Option<RunState>, Vec<(TaskId, i32)>), ExecutionError> {
942        let run = self.run(run_id).await?;
943        let instance = run
944            .instances
945            .iter()
946            .find(|i| &i.task_id == task_id && i.map_index == -1);
947        let Some(instance) = instance.filter(|i| i.state == TaskInstanceState::Queued) else {
948            return Ok((None, Vec::new()));
949        };
950        if run.state.is_final() {
951            return Ok((None, Vec::new()));
952        }
953        let routed = |outcome: &str| {
954            run.dag
955                .edges
956                .iter()
957                .any(|e| &e.from == task_id && e.on.iter().any(|on| on == outcome))
958        };
959        let (outcome, value) = match ended {
960            WaitEnd::Ran { run_id } => (SUCCESS.to_owned(), json!(run_id)),
961            WaitEnd::Failed {
962                state,
963                run_id: other,
964            } => {
965                if !routed(FAILED) {
966                    let mut failed = update(task_id, -1, TaskInstanceState::Failed);
967                    failed.reason = Some(format!(
968                        "the run `{other}` it waits for ended `{state}`, and nothing here takes \
969                         `.on(Failed)`"
970                    ));
971                    return self.advance(run_id, &run, vec![failed], now).await;
972                }
973                (FAILED.to_owned(), json!({"state": state, "run_id": other}))
974            }
975            WaitEnd::TimedOut => (TIMED_OUT.to_owned(), json!({})),
976            WaitEnd::Event { value } => (SUCCESS.to_owned(), value),
977            WaitEnd::Refused { reason } => {
978                let mut failed = update(task_id, -1, TaskInstanceState::Failed);
979                failed.reason = Some(reason);
980                return self.advance(run_id, &run, vec![failed], now).await;
981            }
982        };
983        self.db.store_output(&instance.id, &outcome, &value).await?;
984        let ended = InstanceUpdate {
985            outcome: Some(outcome),
986            ..update(task_id, -1, TaskInstanceState::Success)
987        };
988        self.advance(run_id, &run, vec![ended], now).await
989    }
990
991    /// Moves a run forward after a task's state was changed directly (an assignment of a
992    /// task being cancelled taken back as `cancelled`). Returns the run's result, if it
993    /// finished now.
994    ///
995    /// # Errors
996    ///
997    /// [`ExecutionError`] for an unknown run or a database failure.
998    pub async fn settle(
999        &self,
1000        run_id: &str,
1001        now: Timestamp,
1002    ) -> Result<Option<RunState>, ExecutionError> {
1003        let run = self.run(run_id).await?;
1004        if run.state.is_final() {
1005            return Ok(None);
1006        }
1007        Ok(self.advance(run_id, &run, Vec::new(), now).await?.0)
1008    }
1009
1010    async fn run(&self, run_id: &str) -> Result<RunTasks, ExecutionError> {
1011        self.db
1012            .run_tasks(run_id)
1013            .await?
1014            .ok_or_else(|| ExecutionError::UnknownRun(run_id.to_owned()))
1015    }
1016
1017    /// Applies `first`, settles the run's other tasks, stores everything and finishes the run
1018    /// if it is done. Returns the run's result, if it finished, and the instances to stop.
1019    async fn advance(
1020        &self,
1021        run_id: &str,
1022        run: &RunTasks,
1023        first: Vec<InstanceUpdate>,
1024        now: Timestamp,
1025    ) -> Result<(Option<RunState>, Vec<(TaskId, i32)>), ExecutionError> {
1026        let mut progress = progress_of(run).with_chosen(self.chosen_of(run_id, run, &first).await?);
1027        let before = progress.snapshot();
1028        for change in &first {
1029            if let Ok(index) = usize::try_from(change.map_index) {
1030                progress.set_instance(&change.task_id, index, change.state);
1031                if let Some(outcome) = &change.outcome {
1032                    progress.set_instance_outcome(&change.task_id, index, outcome);
1033                }
1034                continue;
1035            }
1036            progress.set(&change.task_id, change.state);
1037            if let Some(outcome) = &change.outcome {
1038                progress.set_outcome(&change.task_id, outcome);
1039            }
1040        }
1041        // The successes now, in the order they arrived: after every stored one (M4B.4).
1042        let ending: Vec<TaskId> = first
1043            .iter()
1044            .filter(|u| u.map_index == -1 && u.state == TaskInstanceState::Success)
1045            .map(|u| u.task_id.clone())
1046            .collect();
1047        self.settle_all(run_id, &run.dag, &mut progress, &ending)
1048            .await?;
1049        let stops = self
1050            .store(run_id, &mut progress, &before, first, now)
1051            .await?;
1052        let result = progress.result();
1053        if let Some(result) = result {
1054            self.finish(run_id, &run.dag, result, now).await?;
1055        }
1056        Ok((result, stops))
1057    }
1058
1059    /// Settles a run, expanding each mapped task as it becomes ready, until nothing changes.
1060    async fn settle_all(
1061        &self,
1062        run_id: &str,
1063        dag: &Dag,
1064        progress: &mut RunProgress<'_>,
1065        ending: &[TaskId],
1066    ) -> Result<(), ExecutionError> {
1067        loop {
1068            progress.settle();
1069            let chose = self
1070                .store_first_of_outputs(run_id, progress, ending)
1071                .await?;
1072            let ready = progress.take_expansions();
1073            if ready.is_empty() {
1074                if chose {
1075                    continue;
1076                }
1077                return Ok(());
1078            }
1079            for task_id in ready {
1080                let expansion = self.expansion(run_id, dag, &task_id, progress).await?;
1081                progress.expand(&task_id, expansion);
1082            }
1083        }
1084    }
1085
1086    /// How a mapped task expands: its dimensions' sizes from what it is mapped over (a lane:
1087    /// its upstream's instances), or why it can't (not a list, too many instances).
1088    async fn expansion(
1089        &self,
1090        run_id: &str,
1091        dag: &Dag,
1092        task_id: &TaskId,
1093        progress: &RunProgress<'_>,
1094    ) -> Result<Expansion, ExecutionError> {
1095        let Some(task) = dag.task(task_id) else {
1096            return Ok(Expansion::Fail(format!("no task `{task_id}`")));
1097        };
1098        let dims = mapping::dims(dag, task);
1099        let used: BTreeSet<&TaskId> = dims
1100            .iter()
1101            .filter_map(|(_, dim)| match dim {
1102                Dim::Values(value) => Some(value.references()),
1103                Dim::Lane(_) => None,
1104            })
1105            .flatten()
1106            .filter_map(Reference::upstream_task)
1107            .collect();
1108        // The states as this step has them: a result it applies isn't stored yet (B78).
1109        let known = |task: &TaskId, index: i32| {
1110            let index = usize::try_from(index).ok()?;
1111            progress.instances(task)?.states.get(index).copied()
1112        };
1113        let mut sources = mapping::sources(&self.db, dag, run_id, &used, known).await?;
1114        // Each whole task's outcome as this step has it too: `None` for skipped, absent while
1115        // it hasn't ended.
1116        for task in &used {
1117            match progress.states().get(*task) {
1118                Some(TaskInstanceState::Success) => {
1119                    let outcome = progress
1120                        .outcome(task)
1121                        .unwrap_or(schedr_model::DEFAULT_OUTCOME);
1122                    sources
1123                        .outcomes
1124                        .insert((*task).clone(), Some(outcome.to_owned()));
1125                }
1126                Some(TaskInstanceState::Skipped) => {
1127                    sources.outcomes.insert((*task).clone(), None);
1128                }
1129                _ => {
1130                    sources.outcomes.remove(*task);
1131                }
1132            }
1133        }
1134        let mut sizes = Vec::with_capacity(dims.len());
1135        for (name, dim) in &dims {
1136            let what = name.map_or_else(
1137                || "`.expand_kwargs()`".to_owned(),
1138                |name| format!("mapped argument `{name}`"),
1139            );
1140            let size = match dim {
1141                Dim::Lane(upstream) => progress.instances(upstream).map_or(0, |i| i.states.len()),
1142                Dim::Values(value) => match mapping::resolve_mapped(value, &sources) {
1143                    Ok(serde_json::Value::Array(items)) => {
1144                        if name.is_none() && items.iter().any(|item| !item.is_object()) {
1145                            return Ok(Expansion::Fail(format!(
1146                                "{what}: every element must be a dict of arguments"
1147                            )));
1148                        }
1149                        items.len()
1150                    }
1151                    Ok(other) => {
1152                        return Ok(Expansion::Fail(format!(
1153                            "{what}: expected a list, got {}",
1154                            mapping::kind_of(&other)
1155                        )));
1156                    }
1157                    Err(error) => return Ok(Expansion::Fail(format!("{what}: {error}"))),
1158                },
1159            };
1160            sizes.push(size);
1161        }
1162        Ok(match mapping::count(&sizes) {
1163            Some(n) if n <= self.max_instances => Expansion::Sizes(sizes),
1164            n => Expansion::Fail(format!(
1165                "`{task_id}` would have {} instances, more than [mapping] max_instances ({})",
1166                n.map_or_else(|| "too many".to_owned(), |n| n.to_string()),
1167                self.max_instances
1168            )),
1169        })
1170    }
1171
1172    /// Stores what changed since `before` (`first` as given: the attempt's own change) and
1173    /// marks the instances to stop, in one transaction (an expansion's instances and its
1174    /// whole task's row together). Returns those.
1175    async fn store(
1176        &self,
1177        run_id: &str,
1178        progress: &mut RunProgress<'_>,
1179        before: &Snapshot,
1180        first: Vec<InstanceUpdate>,
1181        now: Timestamp,
1182    ) -> Result<Vec<(TaskId, i32)>, ExecutionError> {
1183        let writes = self.write_changes(run_id, progress, before, first, now);
1184        Box::pin(self.db.atomically(writes)).await
1185    }
1186
1187    /// Stores what each `first_of` that ended now keeps, `{"$value": ..., "winner": ...}`, with
1188    /// the first of what can have ended it in the order they ended. At once, as a mapped task
1189    /// after it expands over it (a crash here stores it again: nothing has read it).
1190    /// Returns whether one ended. One whose values are over what its options may give together
1191    /// (the sum of their `max_output_size`) fails instead. `ending` are the successes not
1192    /// stored yet, in the order they arrived: they ended after the stored ones.
1193    async fn store_first_of_outputs(
1194        &self,
1195        run_id: &str,
1196        progress: &mut RunProgress<'_>,
1197        ending: &[TaskId],
1198    ) -> Result<bool, ExecutionError> {
1199        let ended = progress.take_winners();
1200        let chose = !ended.is_empty();
1201        for (task_id, mut winners) in ended {
1202            let Some(task) = progress.dag().task(&task_id) else {
1203                continue;
1204            };
1205            // What each option may give, together (the user's, 2026-11-07): never smaller than
1206            // what they were each allowed, still bounded.
1207            let limit = progress
1208                .dag()
1209                .edges_into(&task_id)
1210                .filter(|edge| edge.kind != schedr_model::EdgeKind::Requirement)
1211                .filter_map(|edge| progress.dag().task(&edge.from))
1212                .map(|option| option.settings.max_output_size)
1213                .fold(0_u64, u64::saturating_add);
1214            let at_least = match &task.kind {
1215                TaskKind::FirstOf { at_least } => *at_least,
1216                _ => None,
1217            };
1218            let names: Vec<&TaskId> = winners.iter().collect();
1219            let order = self.db.ended_in_order(run_id, &names).await?;
1220            let rank = |winner: &TaskId| {
1221                order
1222                    .iter()
1223                    .position(|e| e == winner)
1224                    .or_else(|| {
1225                        let at = ending.iter().position(|e| e == winner)?;
1226                        Some(order.len() + at)
1227                    })
1228                    .unwrap_or(usize::MAX)
1229            };
1230            winners.sort_by_key(rank);
1231            winners.truncate(crate::progress::need_of(at_least));
1232            let names: Vec<&TaskId> = winners.iter().collect();
1233            let outputs = self.db.outputs_of(run_id, &names).await?;
1234            let value = |winner: &TaskId| {
1235                outputs
1236                    .get(winner)
1237                    .cloned()
1238                    .unwrap_or(serde_json::Value::Null)
1239            };
1240            let (output, outcome) = if at_least.is_some() {
1241                let values: Vec<_> = winners.iter().map(value).collect();
1242                (
1243                    json!({"$value": values, "winner": winners}),
1244                    SUCCESS.to_owned(),
1245                )
1246            } else {
1247                let winner = winners.first();
1248                let outcome = winner.and_then(|w| progress.outcome(w)).unwrap_or(SUCCESS);
1249                (
1250                    json!({
1251                        "$value": winner.map_or(serde_json::Value::Null, value),
1252                        "winner": winner.map(TaskId::as_str),
1253                    }),
1254                    outcome.to_owned(),
1255                )
1256            };
1257            let size = serde_json::to_vec(&output["$value"]).map_or(0, |bytes| bytes.len());
1258            if u64::try_from(size).unwrap_or(u64::MAX) > limit {
1259                let reason = format!(
1260                    "{OUTPUT_TOO_LARGE}: what it chose is {size} bytes, over the {limit} its \
1261                     options may give together"
1262                );
1263                progress.fail_first_of(&task_id, reason);
1264                continue;
1265            }
1266            self.db
1267                .store_task_output(run_id, &task_id, &outcome, &output)
1268                .await?;
1269            progress.set_outcome(&task_id, &outcome);
1270        }
1271        Ok(chose)
1272    }
1273
1274    async fn write_changes(
1275        &self,
1276        run_id: &str,
1277        progress: &mut RunProgress<'_>,
1278        before: &Snapshot,
1279        first: Vec<InstanceUpdate>,
1280        now: Timestamp,
1281    ) -> Result<Vec<(TaskId, i32)>, ExecutionError> {
1282        let changes = progress.changes_since(before);
1283        if !changes.created.is_empty() {
1284            self.db
1285                .create_instances(run_id, &changes.created, now)
1286                .await?;
1287        }
1288        let mut updates = first;
1289        for (task_id, map_index, state) in changes.updated {
1290            let given = updates
1291                .iter()
1292                .any(|u| u.task_id == task_id && u.map_index == map_index && u.state == state);
1293            if given {
1294                continue;
1295            }
1296            let mut next = update(&task_id, map_index, state);
1297            if state == TaskInstanceState::Queued {
1298                next.ready_at = Some(now);
1299            }
1300            if map_index == -1 {
1301                if is_first_of(progress.dag(), &task_id) && state == TaskInstanceState::Success {
1302                    next.outcome = progress.outcome(&task_id).map(str::to_owned);
1303                }
1304                next.reason = progress.reason(&task_id).map(str::to_owned);
1305                next.map_sizes = progress.instances(&task_id).map(|i| i.sizes.clone());
1306            }
1307            updates.push(next);
1308        }
1309        self.db.update_instances(run_id, &updates, now).await?;
1310        let mut stops = Vec::new();
1311        for (task_id, index) in progress.take_stops() {
1312            let map_index = i32::try_from(index).unwrap_or(i32::MAX);
1313            self.db
1314                .request_instance_cancel(run_id, &task_id, map_index, now)
1315                .await?;
1316            stops.push((task_id, map_index));
1317        }
1318        Ok(stops)
1319    }
1320}
1321
1322impl Execution {
1323    /// What the run's `@branch` tasks chose (their outputs), for those that have succeeded or
1324    /// succeed with `first`.
1325    async fn chosen_of(
1326        &self,
1327        run_id: &str,
1328        run: &RunTasks,
1329        first: &[InstanceUpdate],
1330    ) -> Result<BTreeMap<TaskId, Vec<TaskId>>, ExecutionError> {
1331        let succeeded = |task: &TaskId| {
1332            first
1333                .iter()
1334                .any(|c| &c.task_id == task && c.state == TaskInstanceState::Success)
1335                || run
1336                    .instances
1337                    .iter()
1338                    .any(|i| &i.task_id == task && i.state == TaskInstanceState::Success)
1339        };
1340        let branches: Vec<&TaskId> = run
1341            .dag
1342            .tasks
1343            .iter()
1344            .filter(|t| matches!(t.kind, TaskKind::Python { branch: true, .. }))
1345            .map(|t| &t.id)
1346            .filter(|id| succeeded(id))
1347            .collect();
1348        if branches.is_empty() {
1349            return Ok(BTreeMap::new());
1350        }
1351        let outputs = self.db.outputs_of(run_id, &branches).await?;
1352        Ok(outputs
1353            .into_iter()
1354            .map(|(task, output)| {
1355                let chosen = output
1356                    .as_array()
1357                    .into_iter()
1358                    .flatten()
1359                    .filter_map(|id| id.as_str().and_then(|id| TaskId::new(id).ok()))
1360                    .collect();
1361                (task, chosen)
1362            })
1363            .collect())
1364    }
1365}
1366
1367/// A run's progress as stored: its tasks (the `-1` rows) and the instances of the mapped
1368/// tasks that expanded.
1369fn is_first_of(dag: &Dag, task: &TaskId) -> bool {
1370    dag.task(task)
1371        .is_some_and(|task| matches!(task.kind, TaskKind::FirstOf { .. }))
1372}
1373
1374fn progress_of(run: &RunTasks) -> RunProgress<'_> {
1375    let mut instances: BTreeMap<TaskId, Instances> = BTreeMap::new();
1376    for row in run.instances.iter().filter(|i| i.map_index >= 0) {
1377        let entry = instances
1378            .entry(row.task_id.clone())
1379            .or_insert_with(|| Instances {
1380                sizes: Vec::new(),
1381                states: Vec::new(),
1382                outcomes: Vec::new(),
1383            });
1384        entry.states.push(row.state);
1385        entry.outcomes.push(row.outcome.clone());
1386    }
1387    for row in run.instances.iter().filter(|i| i.map_index == -1) {
1388        if let Some(entry) = instances.get_mut(&row.task_id) {
1389            entry.sizes = row
1390                .map_sizes
1391                .clone()
1392                .unwrap_or_else(|| vec![entry.states.len()]);
1393        }
1394    }
1395    RunProgress::new(&run.dag, states_of(run))
1396        .with_cancelling(run.cancel_requested)
1397        .with_failed_cleanup(
1398            run.instances
1399                .iter()
1400                .any(|i| i.cleanup_result.is_some_and(CleanupResult::fails_the_run)),
1401        )
1402        .with_outcomes(outcomes_of(run))
1403        .with_instances(instances)
1404}
1405
1406fn outcomes_of(run: &RunTasks) -> BTreeMap<TaskId, String> {
1407    run.instances
1408        .iter()
1409        .filter(|i| i.map_index == -1)
1410        .filter_map(|i| Some((i.task_id.clone(), i.outcome.clone()?)))
1411        .collect()
1412}
1413
1414fn states_of(run: &RunTasks) -> BTreeMap<TaskId, TaskInstanceState> {
1415    run.instances
1416        .iter()
1417        .filter(|i| i.map_index == -1)
1418        .map(|i| (i.task_id.clone(), i.state))
1419        .collect()
1420}
1421
1422/// A plain state change; empty tasks (and mapped tasks as a whole) that succeed get the
1423/// success outcome.
1424fn update(task_id: &TaskId, map_index: i32, state: TaskInstanceState) -> InstanceUpdate {
1425    InstanceUpdate {
1426        task_id: task_id.clone(),
1427        map_index,
1428        state,
1429        ready_at: None,
1430        outcome: (state == TaskInstanceState::Success).then(|| SUCCESS.to_owned()),
1431        used_retry: false,
1432        reason: None,
1433        map_sizes: None,
1434    }
1435}