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