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