Skip to main content

scientific_workflow/runtime/
execution.rs

1//! Runtime scheduling for a completed immutable Study.
2
3use std::collections::{HashMap, VecDeque};
4use std::panic::{AssertUnwindSafe, catch_unwind};
5use std::path::{Path, PathBuf};
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::{Arc, mpsc};
8use std::thread::{self, JoinHandle};
9use std::time::{Duration, Instant};
10
11use crate::config::advanced::{ConfigSnapshot, FailurePolicy, ReplicateScheduling};
12use crate::persistence::advanced::{ModelRecordingProvenance, PersistencePlan};
13use crate::study::advanced::{Study, StudyPhase, StudyTask};
14use crate::task::advanced::TaskKind;
15use crate::ui::advanced::{UiEvent, UiSession};
16
17use super::error::RuntimeError;
18use super::host::{RuntimeTaskEnvironment, RuntimeTaskHost};
19use super::output::{create_execution, create_replicate};
20use super::summary::{
21    PhaseRunSummary, ReplicateRunSummary, RunSummary, TaskRunKind, TaskRunSummary,
22};
23
24const SCHEDULER_POLL: Duration = Duration::from_millis(5);
25
26/// Executes one already validated immutable study and returns its summary.
27pub fn execute(study: Study) -> Result<RunSummary, RuntimeError> {
28    let output = create_execution(study.output_root())?;
29    let count = study.replicate_policy().count();
30    let task_count_per_replicate = study.phases().iter().map(|phase| phase.tasks().len()).sum();
31    let ui = UiSession::automatic(study.ui_plan());
32    for replicate in 0..count {
33        for phase in study.phases() {
34            for task in phase.tasks() {
35                ui.publish(UiEvent::TaskPlanned {
36                    replicate,
37                    phase: phase.name(),
38                    identity: task.identity(),
39                    label: task.label(),
40                    kind: task.kind_name(),
41                    subject: task.subject(),
42                });
43            }
44        }
45    }
46    ui.publish(UiEvent::ExecutionStarted {
47        output_directory: &output,
48        replicate_count: count,
49        task_count_per_replicate,
50    });
51
52    let result = (|| {
53        let mut scopes = Vec::new();
54        for index in 0..count {
55            scopes.push((index, create_replicate(&output, index)?));
56        }
57        match study.replicate_policy().scheduling() {
58            ReplicateScheduling::Sequential => run_replicates_sequential(&study, scopes, &ui),
59            ReplicateScheduling::Parallel => run_replicates_parallel(&study, scopes, &ui),
60        }
61    })();
62
63    let result = if ui.cancellation_requested() {
64        Err(RuntimeError::ExecutionCancelled)
65    } else {
66        result
67    };
68    let outcome = match result {
69        Ok(replicates) => {
70            ui.publish(UiEvent::ExecutionCompleted {
71                output_directory: &output,
72            });
73            Ok(RunSummary {
74                output_directory: output,
75                replicates: replicates.into_boxed_slice(),
76            })
77        }
78        Err(error) => {
79            if matches!(error, RuntimeError::ExecutionCancelled) {
80                ui.publish(UiEvent::ExecutionCancelled);
81            } else {
82                let reason = error.to_string();
83                ui.publish(UiEvent::ExecutionFailed { reason: &reason });
84            }
85            Err(error)
86        }
87    };
88    ui.finish();
89    outcome
90}
91
92fn run_replicates_sequential(
93    study: &Study,
94    scopes: Vec<(u64, PathBuf)>,
95    ui: &UiSession,
96) -> Result<Vec<ReplicateRunSummary>, RuntimeError> {
97    let mut summaries = Vec::with_capacity(scopes.len());
98    let mut first_error = None;
99    for (index, scope) in scopes {
100        let cancellation = AtomicBool::new(false);
101        match run_replicate(study, index, scope, ui, &cancellation) {
102            Ok(summary) => summaries.push(summary),
103            Err(source) => {
104                first_error.get_or_insert(RuntimeError::Replicate {
105                    index,
106                    source: Box::new(source),
107                });
108                if study.replicate_policy().failure_policy() == FailurePolicy::FailFast {
109                    break;
110                }
111            }
112        }
113    }
114    match first_error {
115        Some(error) => Err(error),
116        None => Ok(summaries),
117    }
118}
119
120fn run_replicates_parallel(
121    study: &Study,
122    scopes: Vec<(u64, PathBuf)>,
123    ui: &UiSession,
124) -> Result<Vec<ReplicateRunSummary>, RuntimeError> {
125    enum WorkerOutcome {
126        Finished(Result<ReplicateRunSummary, RuntimeError>),
127        Panicked,
128    }
129
130    let worker_count = scopes.len();
131    let cancellation = Arc::new(AtomicBool::new(false));
132    let (outcomes, completed) = mpsc::channel();
133    let mut workers: Vec<(u64, JoinHandle<()>)> = Vec::with_capacity(worker_count);
134    for (index, scope) in scopes {
135        let study = study.clone();
136        let ui = ui.clone();
137        let outcomes = outcomes.clone();
138        let worker_cancellation = Arc::clone(&cancellation);
139        let worker = match thread::Builder::new()
140            .name(format!("workflow-replicate-{index}"))
141            .spawn(move || {
142                let outcome = catch_unwind(AssertUnwindSafe(|| {
143                    run_replicate(&study, index, scope, &ui, &worker_cancellation)
144                }))
145                .map_or(WorkerOutcome::Panicked, WorkerOutcome::Finished);
146                let _ = outcomes.send((index, outcome));
147            }) {
148            Ok(worker) => worker,
149            Err(source) => {
150                cancellation.store(true, Ordering::Release);
151                for (_, worker) in workers {
152                    let _ = worker.join();
153                }
154                return Err(RuntimeError::StartWorker {
155                    scope: format!("replicate {index}"),
156                    source,
157                });
158            }
159        };
160        workers.push((index, worker));
161    }
162    drop(outcomes);
163
164    let fail_fast = study.replicate_policy().failure_policy() == FailurePolicy::FailFast;
165    let mut summaries = Vec::with_capacity(worker_count);
166    let mut first_error = None;
167    for _ in 0..worker_count {
168        let (index, outcome) = completed
169            .recv()
170            .expect("replicate worker reports exactly one terminal outcome");
171        let error = match outcome {
172            WorkerOutcome::Finished(Ok(summary)) => {
173                summaries.push(summary);
174                None
175            }
176            WorkerOutcome::Finished(Err(RuntimeError::ExecutionCancelled))
177                if fail_fast && first_error.is_some() =>
178            {
179                None
180            }
181            WorkerOutcome::Finished(Err(source)) => Some(RuntimeError::Replicate {
182                index,
183                source: Box::new(source),
184            }),
185            WorkerOutcome::Panicked => Some(RuntimeError::ReplicatePanicked { index }),
186        };
187        if let Some(error) = error
188            && first_error.is_none()
189        {
190            first_error = Some(error);
191            if fail_fast {
192                cancellation.store(true, Ordering::Release);
193            }
194        }
195    }
196    for (index, worker) in workers {
197        if worker.join().is_err() && first_error.is_none() {
198            // The closure catches the replicate body. A panic here can only
199            // arise while tearing down worker-owned values after reporting.
200            first_error = Some(RuntimeError::ReplicatePanicked { index });
201        }
202    }
203    summaries.sort_by_key(ReplicateRunSummary::index);
204    match first_error {
205        Some(error) => Err(error),
206        None => Ok(summaries),
207    }
208}
209
210fn run_replicate(
211    study: &Study,
212    index: u64,
213    scope: PathBuf,
214    ui: &UiSession,
215    scheduler_cancellation: &AtomicBool,
216) -> Result<ReplicateRunSummary, RuntimeError> {
217    ui.publish(UiEvent::ReplicateStarted { index });
218    let result = run_replicate_inner(study, index, scope, ui, scheduler_cancellation);
219    match &result {
220        Ok(_) => ui.publish(UiEvent::ReplicateCompleted { index }),
221        Err(RuntimeError::ExecutionCancelled) => {
222            ui.publish(UiEvent::ReplicateCancelled { index });
223        }
224        Err(error) => {
225            let reason = error.to_string();
226            ui.publish(UiEvent::ReplicateFailed {
227                index,
228                reason: &reason,
229            });
230        }
231    }
232    result
233}
234
235fn run_replicate_inner(
236    study: &Study,
237    index: u64,
238    scope: PathBuf,
239    ui: &UiSession,
240    scheduler_cancellation: &AtomicBool,
241) -> Result<ReplicateRunSummary, RuntimeError> {
242    let positions = topological_positions(study.phases());
243    let mut phases = Vec::with_capacity(positions.len());
244    for position in positions {
245        if scheduler_cancellation.load(Ordering::Acquire) {
246            return Err(RuntimeError::ExecutionCancelled);
247        }
248        let phase = &study.phases()[position];
249        let dependencies_json = dependency_snapshot(phase, &phases);
250        let context = PhaseRuntime {
251            study,
252            replicate_directory: &scope,
253            dependencies_json,
254            replicate: index,
255            ui,
256            scheduler_cancellation,
257        };
258        phases.push(run_phase(phase, &context)?);
259    }
260    Ok(ReplicateRunSummary {
261        index,
262        output_directory: scope,
263        phases: phases.into_boxed_slice(),
264    })
265}
266
267fn topological_positions(phases: &[StudyPhase]) -> Vec<usize> {
268    fn visit(
269        index: usize,
270        phases: &[StudyPhase],
271        by_name: &HashMap<&str, usize>,
272        visited: &mut [bool],
273        positions: &mut Vec<usize>,
274    ) {
275        if visited[index] {
276            return;
277        }
278        for dependency in phases[index].dependencies() {
279            visit(by_name[dependency], phases, by_name, visited, positions);
280        }
281        visited[index] = true;
282        positions.push(index);
283    }
284
285    let by_name = phases
286        .iter()
287        .enumerate()
288        .map(|(index, phase)| (phase.name(), index))
289        .collect::<HashMap<_, _>>();
290    let mut visited = vec![false; phases.len()];
291    let mut positions = Vec::with_capacity(phases.len());
292    for index in 0..phases.len() {
293        visit(index, phases, &by_name, &mut visited, &mut positions);
294    }
295    positions
296}
297
298struct ActiveTask {
299    task: StudyTask,
300    cancellation: Arc<AtomicBool>,
301    started: Instant,
302    worker: JoinHandle<TaskWorkerOutcome>,
303}
304
305struct TaskWorkerOutcome {
306    finished: Instant,
307    result: Result<TaskRunSummary, RuntimeError>,
308}
309
310struct PhaseRuntime<'a> {
311    study: &'a Study,
312    replicate_directory: &'a Path,
313    dependencies_json: Box<[u8]>,
314    replicate: u64,
315    ui: &'a UiSession,
316    scheduler_cancellation: &'a AtomicBool,
317}
318
319struct TaskRuntime {
320    persistence_plan: PersistencePlan,
321    config_snapshot: ConfigSnapshot,
322    project_root: PathBuf,
323    replicate_directory: PathBuf,
324    dependencies_json: Box<[u8]>,
325    replicate: u64,
326    ui: UiSession,
327}
328
329fn run_phase(
330    phase: &StudyPhase,
331    context: &PhaseRuntime<'_>,
332) -> Result<PhaseRunSummary, RuntimeError> {
333    context.ui.publish(UiEvent::PhaseStarted {
334        replicate: context.replicate,
335        name: phase.name(),
336        task_count: phase.tasks().len(),
337    });
338    let result = run_phase_inner(phase, context);
339    match &result {
340        Ok(_) => context.ui.publish(UiEvent::PhaseCompleted {
341            replicate: context.replicate,
342            name: phase.name(),
343        }),
344        Err(RuntimeError::ExecutionCancelled) => {
345            context.ui.publish(UiEvent::PhaseCancelled {
346                replicate: context.replicate,
347                name: phase.name(),
348            });
349        }
350        Err(error) => {
351            let reason = error.to_string();
352            context.ui.publish(UiEvent::PhaseFailed {
353                replicate: context.replicate,
354                name: phase.name(),
355                reason: &reason,
356            });
357        }
358    }
359    result
360}
361
362fn run_phase_inner(
363    phase: &StudyPhase,
364    context: &PhaseRuntime<'_>,
365) -> Result<PhaseRunSummary, RuntimeError> {
366    let phase_started = Instant::now();
367    let mut pending = phase.tasks().iter().cloned().collect::<VecDeque<_>>();
368    let mut active = Vec::<ActiveTask>::new();
369    let mut completed = Vec::with_capacity(pending.len());
370    let mut next_admission = phase_started;
371    let mut first_error = None;
372    let mut phase_timed_out = false;
373    let mut execution_cancelled = false;
374
375    while !pending.is_empty() || !active.is_empty() {
376        if (context.ui.cancellation_requested()
377            || context.scheduler_cancellation.load(Ordering::Acquire))
378            && !execution_cancelled
379        {
380            execution_cancelled = true;
381            pending.clear();
382            for task in &active {
383                task.cancellation.store(true, Ordering::Release);
384            }
385        }
386        if let Some(timeout) = phase.timeout()
387            && phase_started.elapsed() >= timeout
388            && (!pending.is_empty() || active.iter().any(|task| !task.worker.is_finished()))
389        {
390            phase_timed_out = true;
391            pending.clear();
392            for task in &active {
393                task.cancellation.store(true, Ordering::Release);
394            }
395        }
396
397        let may_admit = !phase_timed_out
398            && !execution_cancelled
399            && (first_error.is_none() || phase.failure_policy() == FailurePolicy::FinishAll);
400        while may_admit
401            && active.len() < phase.max_concurrency()
402            && !pending.is_empty()
403            && Instant::now() >= next_admission
404        {
405            let task = pending.pop_front().expect("checked nonempty task queue");
406            match spawn_task(task, phase.name(), context) {
407                Ok(task) => active.push(task),
408                Err(error) => {
409                    first_error = Some(error);
410                    pending.clear();
411                    for task in &active {
412                        task.cancellation.store(true, Ordering::Release);
413                    }
414                    break;
415                }
416            }
417            next_admission = Instant::now() + phase.start_interval();
418        }
419
420        for task in &mut active {
421            if let Some(timeout) = task.task.timeout()
422                && task.started.elapsed() >= timeout
423                && !task.worker.is_finished()
424            {
425                task.cancellation.store(true, Ordering::Release);
426            }
427        }
428
429        let mut position = 0;
430        while position < active.len() {
431            if !active[position].worker.is_finished() {
432                position += 1;
433                continue;
434            }
435            let active_task = active.swap_remove(position);
436            let identity = active_task.task.identity().to_owned();
437            let outcome = active_task
438                .worker
439                .join()
440                .unwrap_or_else(|_| TaskWorkerOutcome {
441                    finished: Instant::now(),
442                    result: Err(RuntimeError::TaskPanicked {
443                        task: identity.clone(),
444                    }),
445                });
446            let timed_out = active_task.task.timeout().is_some_and(|timeout| {
447                task_exceeded_timeout(active_task.started, outcome.finished, timeout)
448            });
449            let result = if timed_out {
450                Err(RuntimeError::TaskTimedOut {
451                    task: identity,
452                    timeout: active_task.task.timeout().expect("timed task has timeout"),
453                })
454            } else {
455                outcome.result
456            };
457            match result {
458                Ok(summary) => {
459                    context.ui.publish(UiEvent::TaskCompleted {
460                        replicate: context.replicate,
461                        identity: active_task.task.identity(),
462                        final_iteration: summary.final_iteration(),
463                        output_directory: summary.output_directory(),
464                    });
465                    completed.push((active_task.task.output_ordinal(), summary));
466                }
467                Err(error) => {
468                    if matches!(error, RuntimeError::TaskCancelled { .. }) {
469                        context.ui.publish(UiEvent::TaskCancelled {
470                            replicate: context.replicate,
471                            identity: active_task.task.identity(),
472                        });
473                    } else {
474                        let reason = error.to_string();
475                        context.ui.publish(UiEvent::TaskFailed {
476                            replicate: context.replicate,
477                            identity: active_task.task.identity(),
478                            reason: &reason,
479                        });
480                    }
481                    if first_error.is_none() {
482                        first_error = Some(error);
483                    }
484                    if phase.failure_policy() == FailurePolicy::FailFast {
485                        pending.clear();
486                        for sibling in &active {
487                            sibling.cancellation.store(true, Ordering::Release);
488                        }
489                    }
490                }
491            }
492        }
493
494        if (!pending.is_empty() || !active.is_empty())
495            && active.iter().all(|task| !task.worker.is_finished())
496        {
497            thread::sleep(SCHEDULER_POLL);
498        }
499    }
500
501    if execution_cancelled {
502        return Err(RuntimeError::ExecutionCancelled);
503    }
504    if phase_timed_out {
505        return Err(RuntimeError::PhaseTimedOut {
506            phase: phase.name().to_owned(),
507            timeout: phase.timeout().expect("timed phase has timeout"),
508        });
509    }
510    if let Some(error) = first_error {
511        return Err(error);
512    }
513    completed.sort_by_key(|(ordinal, _)| *ordinal);
514    Ok(PhaseRunSummary {
515        name: phase.name().into(),
516        tasks: completed
517            .into_iter()
518            .map(|(_, summary)| summary)
519            .collect::<Vec<_>>()
520            .into_boxed_slice(),
521    })
522}
523
524pub(super) fn task_exceeded_timeout(
525    started: Instant,
526    finished: Instant,
527    timeout: Duration,
528) -> bool {
529    finished.saturating_duration_since(started) >= timeout
530}
531
532fn spawn_task(
533    task: StudyTask,
534    phase: &str,
535    context: &PhaseRuntime<'_>,
536) -> Result<ActiveTask, RuntimeError> {
537    let cancellation = Arc::new(AtomicBool::new(false));
538    let worker_cancellation = Arc::clone(&cancellation);
539    let worker_task = task.clone();
540    let output_directory = context
541        .replicate_directory
542        .join(format!("task-{:06}", worker_task.output_ordinal()));
543    let runtime = TaskRuntime {
544        persistence_plan: context.study.persistence_plan(),
545        config_snapshot: context.study.config_snapshot(),
546        project_root: context.study.project_root().to_path_buf(),
547        replicate_directory: context.replicate_directory.to_path_buf(),
548        dependencies_json: context.dependencies_json.clone(),
549        replicate: context.replicate,
550        ui: context.ui.clone(),
551    };
552    let thread_name = format!("workflow-task-{:06}", worker_task.output_ordinal());
553    let started = Instant::now();
554    let worker = match thread::Builder::new().name(thread_name).spawn(move || {
555        let identity = worker_task.identity().to_owned();
556        let result = catch_unwind(AssertUnwindSafe(|| {
557            run_task(worker_task, runtime, worker_cancellation, output_directory)
558        }))
559        .unwrap_or_else(|_| Err(RuntimeError::TaskPanicked { task: identity }));
560        TaskWorkerOutcome {
561            finished: Instant::now(),
562            result,
563        }
564    }) {
565        Ok(worker) => worker,
566        Err(source) => {
567            let error = RuntimeError::StartWorker {
568                scope: task.identity().to_owned(),
569                source,
570            };
571            let reason = error.to_string();
572            context.ui.publish(UiEvent::TaskFailed {
573                replicate: context.replicate,
574                identity: task.identity(),
575                reason: &reason,
576            });
577            return Err(error);
578        }
579    };
580    context.ui.publish(UiEvent::TaskStarted {
581        replicate: context.replicate,
582        phase,
583        identity: task.identity(),
584        label: task.label(),
585        kind: task.kind_name(),
586        subject: task.subject(),
587    });
588    Ok(ActiveTask {
589        task,
590        cancellation,
591        started,
592        worker,
593    })
594}
595
596fn run_task(
597    task: StudyTask,
598    runtime: TaskRuntime,
599    cancellation: Arc<AtomicBool>,
600    output_directory: PathBuf,
601) -> Result<TaskRunSummary, RuntimeError> {
602    let provenance = task.model_provenance().map(|provenance| {
603        ModelRecordingProvenance::new(
604            task.identity(),
605            provenance.model(),
606            provenance.state(),
607            provenance.parameter_ordinal(),
608            provenance.parameter_source(),
609            provenance.constants().clone(),
610        )
611    });
612    let environment = RuntimeTaskEnvironment::new(
613        runtime.config_snapshot,
614        runtime.project_root,
615        runtime.replicate_directory,
616        runtime.dependencies_json,
617    );
618    let mut host = RuntimeTaskHost::new(
619        runtime.persistence_plan,
620        cancellation,
621        output_directory,
622        provenance,
623        runtime.ui.task(runtime.replicate, task.identity()),
624        environment,
625    );
626    match catch_unwind(AssertUnwindSafe(|| task.definition().execute(&mut host))) {
627        Ok(Ok(())) => {}
628        Ok(Err(source)) => {
629            host.fail(&source.to_string());
630            return Err(RuntimeError::Task {
631                task: task.identity().to_owned(),
632                source,
633            });
634        }
635        Err(payload) => {
636            let reason = panic_reason(payload.as_ref());
637            host.fail(&format!("task panicked: {reason}"));
638            return Err(RuntimeError::TaskPanicked {
639                task: task.identity().to_owned(),
640            });
641        }
642    }
643    if host.cancellation_requested() {
644        host.fail("runtime cancellation requested");
645        return Err(RuntimeError::TaskCancelled {
646            task: task.identity().to_owned(),
647        });
648    }
649    let (kind, model, program, program_kind, python_script, final_iteration) = match task.kind() {
650        TaskKind::Model => (
651            TaskRunKind::Model,
652            task.model().map(Into::into),
653            None,
654            None,
655            None,
656            host.final_iteration(),
657        ),
658        TaskKind::Program => {
659            let program = task
660                .program_path()
661                .expect("program task retains its resolved invocation");
662            (
663                TaskRunKind::Program,
664                None,
665                Some(program.to_path_buf()),
666                task.program_kind_name().map(Into::into),
667                task.python_script().map(Path::to_path_buf),
668                None,
669            )
670        }
671    };
672    Ok(TaskRunSummary {
673        identity: task.identity().into(),
674        kind,
675        model,
676        program,
677        program_kind,
678        python_script,
679        final_iteration,
680        output_directory: host.output_directory().to_path_buf(),
681    })
682}
683
684fn panic_reason(payload: &(dyn std::any::Any + Send)) -> String {
685    const MAX_CHARS: usize = 1_024;
686
687    let message = payload
688        .downcast_ref::<&str>()
689        .map(|message| (*message).to_owned())
690        .or_else(|| payload.downcast_ref::<String>().cloned())
691        .unwrap_or_else(|| "non-string panic payload".to_owned());
692    let mut characters = message.chars();
693    let bounded = characters.by_ref().take(MAX_CHARS).collect::<String>();
694    if characters.next().is_some() {
695        format!("{bounded}…")
696    } else {
697        bounded
698    }
699}
700
701fn dependency_snapshot(phase: &StudyPhase, completed: &[PhaseRunSummary]) -> Box<[u8]> {
702    let dependencies = phase
703        .dependencies()
704        .collect::<std::collections::HashSet<_>>();
705    let values = completed
706        .iter()
707        .filter(|summary| dependencies.contains(summary.name()))
708        .map(|summary| {
709            serde_json::json!({
710                "phase": summary.name(),
711                "tasks": summary.tasks().iter().map(|task| {
712                    serde_json::json!({
713                        "identity": task.identity(),
714                        "kind": match task.kind() {
715                            TaskRunKind::Model => "model",
716                            TaskRunKind::Program => "program",
717                        },
718                        "model": task.model(),
719                        "program": task.program().map(|path| path.to_str()
720                            .expect("Config preflight requires UTF-8 program paths")),
721                        "program_kind": task.program_kind(),
722                        "python_script": task.python_script().map(|path| path.to_str()
723                            .expect("Config preflight requires UTF-8 Python script paths")),
724                        "final_iteration": task.final_iteration(),
725                        "output_directory": task.output_directory().to_str()
726                            .expect("UTF-8 project roots produce UTF-8 output paths")
727                    })
728                }).collect::<Vec<_>>()
729            })
730        })
731        .collect::<Vec<_>>();
732    serde_json::to_vec_pretty(&values)
733        .expect("serializing runtime dependency summaries cannot fail")
734        .into_boxed_slice()
735}