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