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