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