1use std::collections::HashMap;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::time::Duration;
7
8use crate::config::{
9 ComputeMode, Config, ConfigSnapshot, FailurePolicy, PersistenceSpecification,
10 ProjectSpecification, ReplicatePolicy, ReplicateScheduling, StudyManifest,
11};
12use crate::persistence::PersistencePlan;
13use crate::task::{
14 ExecutionUnitCatalog, ExecutionUnitTaskProvenance, Task, TaskDefinition, TaskKind,
15};
16
17use super::compilation;
18use super::error::StudyError;
19
20#[derive(Clone)]
22pub struct StudyPlan {
23 inner: Arc<StudyInner>,
24}
25
26impl StudyPlan {
27 pub fn load(project_root: &Path) -> Result<Self, StudyError> {
32 let project = ProjectSpecification::load(project_root)?;
33 let catalog = ExecutionUnitCatalog::discovered()?;
34 compilation::compile(project, &catalog)
35 }
36
37 pub(crate) fn from_parts(project: ProjectSpecification, phases: Box<[StudyPhase]>) -> Self {
38 let project_root = project.project_root().to_path_buf();
39 let config = project.config().clone();
40 let output_root = project.config().runtime().workspace.root.join("executions");
41 let manifest: StudyManifest = project.manifest().clone();
42 let workflow_schema = manifest.workflow_schema();
43 let threads = manifest.threads();
44 let compute_mode = manifest.compute_mode();
45 let replicate_policy = manifest.replicate_policy();
46 let master_seed = manifest.master_seed();
47 let persistence: PersistenceSpecification = manifest.persistence();
48 let persistence_plan = PersistencePlan::local(
49 persistence.chunk_target_bytes(),
50 persistence.queue_capacity_bytes(),
51 );
52 Self {
53 inner: Arc::new(StudyInner {
54 reproduction: manifest.reproduction().clone(),
55 verification: manifest.verification().cloned(),
56 disk_pause_at: manifest.disk_pause_at(),
57 active_phases: manifest.active_phases().into(),
58 reuse_from: manifest.reuse_from().map(Path::to_path_buf),
59 phase_order: topological_positions(&phases).into_boxed_slice(),
60 project_root,
61 config,
62 phases,
63 output_root,
64 workflow_schema,
65 threads,
66 compute_mode,
67 master_seed,
68 replicate_policy,
69 persistence_plan,
70 }),
71 }
72 }
73
74 pub fn project_root(&self) -> &Path {
76 &self.inner.project_root
77 }
78
79 pub fn output_root(&self) -> &Path {
81 &self.inner.output_root
82 }
83
84 pub fn threads(&self) -> usize {
86 self.inner.threads
87 }
88
89 pub(crate) fn with_recovery(mut self, path: PathBuf) -> Self {
90 Arc::make_mut(&mut self.inner).reuse_from = Some(path);
91 self
92 }
93
94 pub(crate) fn verify_capture(&self, path: &Path) -> Result<(), crate::config::ConfigError> {
95 self.inner.config.verify_capture(path)
96 }
97
98 pub(crate) fn verification(&self) -> Option<&crate::config::VerificationSpecification> {
99 self.inner.verification.as_ref()
100 }
101
102 pub(crate) fn reproduction(&self) -> &crate::config::ReproductionSpecification {
103 &self.inner.reproduction
104 }
105
106 pub(crate) fn runtime_settings(&self) -> &crate::config::RuntimeSettings {
107 self.inner.config.runtime()
108 }
109
110 pub(crate) fn disk_pause_at(&self) -> Option<f64> {
111 self.inner.disk_pause_at
112 }
113
114 pub(crate) fn compute_mode(&self) -> ComputeMode {
115 self.inner.compute_mode
116 }
117
118 pub fn plan_summary(&self) -> PlanSummary<'_> {
123 PlanSummary { study: self }
124 }
125
126 pub(crate) fn phase_order(&self) -> &[usize] {
128 &self.inner.phase_order
129 }
130
131 pub(crate) fn phase_is_active(&self, index: usize) -> bool {
133 self.inner.active_phases.contains(&index)
134 }
135
136 pub(crate) fn reuse_from(&self) -> Option<&Path> {
138 self.inner.reuse_from.as_deref()
139 }
140
141 pub(crate) fn phases(&self) -> &[StudyPhase] {
143 &self.inner.phases
144 }
145
146 pub(crate) fn replicate_policy(&self) -> ReplicatePolicy {
148 self.inner.replicate_policy
149 }
150
151 pub(crate) fn master_seed(&self) -> Option<u64> {
153 self.inner.master_seed
154 }
155
156 pub(crate) fn persistence_plan(&self) -> PersistencePlan {
159 self.inner.persistence_plan
160 }
161}
162
163impl std::fmt::Debug for StudyPlan {
164 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165 formatter
166 .debug_struct("StudyPlan")
167 .field("project_root", &self.project_root())
168 .field("output_root", &self.output_root())
169 .field("threads", &self.threads())
170 .field("compute_mode", &self.plan_summary().compute_mode())
171 .field("config", &self.inner.config)
172 .field("persistence", &self.persistence_plan())
173 .field("phases", &self.phases().len())
174 .finish_non_exhaustive()
175 }
176}
177
178#[derive(Clone)]
179struct StudyInner {
180 verification: Option<crate::config::VerificationSpecification>,
181 reproduction: crate::config::ReproductionSpecification,
182 disk_pause_at: Option<f64>,
183 active_phases: Box<[usize]>,
184 reuse_from: Option<PathBuf>,
185 phase_order: Box<[usize]>,
186 project_root: PathBuf,
187 config: Config,
188 phases: Box<[StudyPhase]>,
189 output_root: PathBuf,
190 workflow_schema: u64,
191 threads: usize,
192 compute_mode: ComputeMode,
193 master_seed: Option<u64>,
194 replicate_policy: ReplicatePolicy,
195 persistence_plan: PersistencePlan,
196}
197
198#[derive(Clone, Copy)]
200pub struct PlanSummary<'a> {
201 study: &'a StudyPlan,
202}
203
204impl std::fmt::Debug for PlanSummary<'_> {
205 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
206 formatter
207 .debug_struct("PlanSummary")
208 .field("workflow_schema", &self.workflow_schema())
209 .field("threads", &self.threads())
210 .field("compute_mode", &self.compute_mode())
211 .field("replicate_count", &self.replicate_count())
212 .field("phases", &self.study.phases().len())
213 .finish_non_exhaustive()
214 }
215}
216
217impl<'a> PlanSummary<'a> {
218 pub fn workflow_schema(self) -> u64 {
220 self.study.inner.workflow_schema
221 }
222
223 pub fn threads(self) -> usize {
225 self.study.threads()
226 }
227
228 pub fn compute_mode(self) -> PlanComputeMode {
230 match self.study.compute_mode() {
231 ComputeMode::Auto => PlanComputeMode::Auto,
232 ComputeMode::Isolated => PlanComputeMode::Isolated,
233 }
234 }
235
236 pub fn replicate_count(self) -> u64 {
238 self.study.replicate_policy().count()
239 }
240
241 pub fn replicate_scheduling(self) -> PlanReplicateScheduling {
243 match self.study.replicate_policy().scheduling() {
244 ReplicateScheduling::Sequential => PlanReplicateScheduling::Sequential,
245 ReplicateScheduling::Parallel => PlanReplicateScheduling::Parallel,
246 }
247 }
248
249 pub fn replicate_failure_policy(self) -> PlanFailurePolicy {
251 public_failure_policy(self.study.replicate_policy().failure_policy())
252 }
253
254 pub fn has_master_seed(self) -> bool {
259 self.study.master_seed().is_some()
260 }
261
262 pub fn persistence_chunk_target_bytes(self) -> u64 {
264 self.study.persistence_plan().chunk_target().get()
265 }
266
267 pub fn persistence_queue_capacity_bytes(self) -> u64 {
269 self.study.persistence_plan().queue_capacity().get()
270 }
271
272 pub fn phases(self) -> impl ExactSizeIterator<Item = PhasePlanSummary<'a>> {
274 self.study
275 .phase_order()
276 .iter()
277 .enumerate()
278 .map(|(index, &position)| PhasePlanSummary {
279 phase: &self.study.phases()[position],
280 index,
281 active: self.study.phase_is_active(index),
282 })
283 }
284}
285
286#[derive(Clone, Copy, Debug, Eq, PartialEq)]
288pub enum PlanReplicateScheduling {
289 Sequential,
291 Parallel,
293}
294
295#[derive(Clone, Copy, Debug, Eq, PartialEq)]
297pub enum PlanComputeMode {
298 Auto,
300 Isolated,
302}
303
304#[derive(Clone, Copy, Debug, Eq, PartialEq)]
306pub enum PlanFailurePolicy {
307 FailFast,
309 FinishAll,
311}
312
313#[derive(Clone, Copy)]
315pub struct PhasePlanSummary<'a> {
316 index: usize,
317 active: bool,
318 phase: &'a StudyPhase,
319}
320
321impl std::fmt::Debug for PhasePlanSummary<'_> {
322 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
323 formatter
324 .debug_struct("PhasePlanSummary")
325 .field("name", &self.name())
326 .field("dependencies", &self.phase.dependencies.len())
327 .field("tasks", &self.phase.tasks.len())
328 .finish_non_exhaustive()
329 }
330}
331
332impl<'a> PhasePlanSummary<'a> {
333 pub fn index(self) -> usize {
335 self.index
336 }
337
338 pub fn is_active(self) -> bool {
340 self.active
341 }
342
343 pub fn name(self) -> &'a str {
345 self.phase.name()
346 }
347
348 pub fn dependencies(self) -> impl ExactSizeIterator<Item = &'a str> {
350 self.phase.dependencies()
351 }
352
353 pub fn max_concurrency(self) -> usize {
355 self.phase.max_concurrency()
356 }
357
358 pub fn start_interval(self) -> Duration {
360 self.phase.start_interval()
361 }
362
363 pub fn timeout(self) -> Option<Duration> {
365 self.phase.timeout()
366 }
367
368 pub fn failure_policy(self) -> PlanFailurePolicy {
370 public_failure_policy(self.phase.failure_policy())
371 }
372
373 pub fn tasks(self) -> impl ExactSizeIterator<Item = TaskPlanSummary<'a>> {
375 self.phase.tasks().iter().map(move |task| TaskPlanSummary {
376 task,
377 active: self.active && task.is_active(),
378 })
379 }
380}
381
382#[derive(Clone, Copy)]
384pub struct TaskPlanSummary<'a> {
385 task: &'a StudyTask,
386 active: bool,
387}
388
389impl std::fmt::Debug for TaskPlanSummary<'_> {
390 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
391 formatter
392 .debug_struct("TaskPlanSummary")
393 .field("identity", &self.identity())
394 .field("label", &self.label())
395 .field("active", &self.is_active())
396 .field("kind", &self.kind())
397 .finish_non_exhaustive()
398 }
399}
400
401impl<'a> TaskPlanSummary<'a> {
402 pub fn identity(self) -> &'a str {
404 self.task.identity()
405 }
406
407 pub fn label(self) -> &'a str {
409 self.task.label()
410 }
411
412 pub fn output_ordinal(self) -> u64 {
414 self.task.output_ordinal()
415 }
416
417 pub fn is_active(self) -> bool {
419 self.active
420 }
421
422 pub fn timeout(self) -> Option<Duration> {
424 self.task.timeout()
425 }
426
427 pub fn seed_purpose(self) -> Option<&'a str> {
429 self.task.program_seed_purpose()
430 }
431
432 pub fn kind(self) -> PlannedTaskKind<'a> {
434 if let Some(provenance) = self.task.execution_unit_provenance() {
435 PlannedTaskKind::ExecutionUnit {
436 execution_unit: provenance.execution_unit(),
437 state: provenance.state(),
438 parameter_ordinal: provenance.parameter_ordinal(),
439 parameter_source: provenance.parameter_source(),
440 threads: self.task.threads,
441 }
442 } else if let Some(script) = self.task.python_script() {
443 PlannedTaskKind::Python {
444 launcher: self
445 .task
446 .program_path()
447 .expect("a compiled Python task has a resolved launcher"),
448 script,
449 threads: self.task.program_threads(),
450 }
451 } else {
452 PlannedTaskKind::Program {
453 executable: self
454 .task
455 .program_path()
456 .expect("a compiled program task has a resolved executable"),
457 threads: self.task.program_threads(),
458 }
459 }
460 }
461}
462
463#[derive(Clone, Copy, Debug, Eq, PartialEq)]
465pub enum PlannedTaskKind<'a> {
466 ExecutionUnit {
468 execution_unit: &'a str,
470 state: &'a str,
472 parameter_ordinal: u64,
474 parameter_source: &'a Path,
476 threads: Option<usize>,
478 },
479 Program {
481 executable: &'a Path,
483 threads: usize,
485 },
486 Python {
488 launcher: &'a Path,
490 script: &'a Path,
492 threads: usize,
494 },
495}
496
497fn public_failure_policy(policy: FailurePolicy) -> PlanFailurePolicy {
498 match policy {
499 FailurePolicy::FailFast => PlanFailurePolicy::FailFast,
500 FailurePolicy::FinishAll => PlanFailurePolicy::FinishAll,
501 }
502}
503
504#[derive(Clone, Debug)]
506pub(crate) struct StudyPhase {
507 pub(crate) name: Box<str>,
508 pub(crate) dependencies: Box<[Box<str>]>,
509 pub(crate) tasks: Box<[StudyTask]>,
510 pub(crate) max_concurrency: usize,
511 pub(crate) start_interval: Duration,
512 pub(crate) timeout: Option<Duration>,
513 pub(crate) failure_policy: FailurePolicy,
514}
515
516impl StudyPhase {
517 pub(crate) fn name(&self) -> &str {
519 &self.name
520 }
521
522 pub(crate) fn dependencies(&self) -> impl ExactSizeIterator<Item = &str> {
524 self.dependencies.iter().map(Box::as_ref)
525 }
526
527 pub(crate) fn tasks(&self) -> &[StudyTask] {
529 &self.tasks
530 }
531
532 pub(crate) const fn max_concurrency(&self) -> usize {
534 self.max_concurrency
535 }
536
537 pub(crate) const fn start_interval(&self) -> Duration {
539 self.start_interval
540 }
541
542 pub(crate) const fn timeout(&self) -> Option<Duration> {
544 self.timeout
545 }
546
547 pub(crate) const fn failure_policy(&self) -> FailurePolicy {
549 self.failure_policy
550 }
551}
552
553#[derive(Clone)]
555pub(crate) struct StudyTask {
556 pub(crate) artifacts: crate::artifact::ArtifactDeclarations,
557 pub(crate) active: bool,
558 pub(crate) identity: Box<str>,
559 pub(crate) label: Box<str>,
560 pub(crate) output_ordinal: u64,
561 pub(crate) configuration: usize,
562 pub(crate) config_snapshot: ConfigSnapshot,
563 pub(crate) task: Task,
564 pub(crate) threads: Option<usize>,
565}
566
567impl StudyTask {
568 pub(crate) const fn is_active(&self) -> bool {
570 self.active
571 }
572
573 pub(crate) fn identity(&self) -> &str {
575 &self.identity
576 }
577
578 pub(crate) fn label(&self) -> &str {
580 &self.label
581 }
582
583 pub(crate) fn kind(&self) -> TaskKind {
584 self.task.kind()
585 }
586
587 pub(crate) fn kind_name(&self) -> &'static str {
588 self.task.kind_name()
589 }
590
591 pub(crate) fn execution_unit(&self) -> Option<&str> {
593 self.task.execution_unit()
594 }
595
596 pub(crate) fn subject(&self) -> &str {
598 self.task.subject()
599 }
600
601 pub(crate) fn timeout(&self) -> Option<Duration> {
603 self.task.timeout()
604 }
605
606 pub(crate) fn output_ordinal(&self) -> u64 {
607 self.output_ordinal
608 }
609
610 pub(crate) const fn configuration(&self) -> usize {
611 self.configuration
612 }
613
614 pub(crate) fn config_snapshot(&self) -> ConfigSnapshot {
615 self.config_snapshot.clone()
616 }
617
618 pub(crate) fn definition(&self) -> &dyn TaskDefinition {
619 &self.task
620 }
621
622 pub(crate) fn execution_unit_provenance(&self) -> Option<ExecutionUnitTaskProvenance<'_>> {
623 self.task.execution_unit_provenance()
624 }
625
626 pub(crate) fn program_declaration(&self) -> Option<&crate::config::ResolvedProgramTask> {
627 self.task.program()
628 }
629
630 pub(crate) fn program_path(&self) -> Option<&Path> {
631 self.task.program_path()
632 }
633
634 pub(crate) fn python_script(&self) -> Option<&Path> {
635 self.task.python_script()
636 }
637
638 pub(crate) fn program_seed_purpose(&self) -> Option<&str> {
639 self.task.program_seed_purpose()
640 }
641
642 pub(crate) fn program_threads(&self) -> usize {
643 self.task
644 .program_threads()
645 .expect("a compiled program task retains its positive thread request")
646 }
647
648 pub(crate) const fn execution_unit_threads(&self) -> Option<usize> {
649 self.threads
650 }
651
652 pub(crate) fn is_npy(&self) -> bool {
653 self.task.is_npy()
654 }
655}
656
657impl std::fmt::Debug for StudyTask {
658 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
659 formatter
660 .debug_struct("StudyTask")
661 .field("identity", &self.identity())
662 .field("label", &self.label())
663 .field("kind", &self.kind())
664 .field("subject", &self.subject())
665 .finish_non_exhaustive()
666 }
667}
668
669fn topological_positions(phases: &[StudyPhase]) -> Vec<usize> {
670 fn visit(
671 index: usize,
672 phases: &[StudyPhase],
673 by_name: &std::collections::HashMap<&str, usize>,
674 visited: &mut [bool],
675 positions: &mut Vec<usize>,
676 ) {
677 if visited[index] {
678 return;
679 }
680 for dependency in phases[index].dependencies() {
681 visit(by_name[dependency], phases, by_name, visited, positions);
682 }
683 visited[index] = true;
684 positions.push(index);
685 }
686
687 let by_name = phases
688 .iter()
689 .enumerate()
690 .map(|(index, phase)| (phase.name(), index))
691 .collect::<HashMap<_, _>>();
692 let mut visited = vec![false; phases.len()];
693 let mut positions = Vec::with_capacity(phases.len());
694 for index in 0..phases.len() {
695 visit(index, phases, &by_name, &mut visited, &mut positions);
696 }
697 positions
698}