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 Study {
23 inner: Arc<StudyInner>,
24}
25
26impl Study {
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_root.join("output");
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 disk_pause_at: manifest.disk_pause_at(),
55 active_phases: manifest.active_phases().into(),
56 reuse_from: manifest.reuse_from().map(Path::to_path_buf),
57 phase_order: topological_positions(&phases).into_boxed_slice(),
58 project_root,
59 config,
60 phases,
61 output_root,
62 workflow_schema,
63 threads,
64 compute_mode,
65 master_seed,
66 replicate_policy,
67 persistence_plan,
68 }),
69 }
70 }
71
72 pub fn project_root(&self) -> &Path {
74 &self.inner.project_root
75 }
76
77 pub fn output_root(&self) -> &Path {
79 &self.inner.output_root
80 }
81
82 pub fn threads(&self) -> usize {
84 self.inner.threads
85 }
86
87 pub(crate) fn disk_pause_at(&self) -> Option<f64> {
88 self.inner.disk_pause_at
89 }
90
91 pub(crate) fn compute_mode(&self) -> ComputeMode {
92 self.inner.compute_mode
93 }
94
95 pub fn plan_summary(&self) -> PlanSummary<'_> {
100 PlanSummary { study: self }
101 }
102
103 pub(crate) fn phase_order(&self) -> &[usize] {
105 &self.inner.phase_order
106 }
107
108 pub(crate) fn phase_is_active(&self, index: usize) -> bool {
110 self.inner.active_phases.contains(&index)
111 }
112
113 pub(crate) fn reuse_from(&self) -> Option<&Path> {
115 self.inner.reuse_from.as_deref()
116 }
117
118 pub(crate) fn phases(&self) -> &[StudyPhase] {
120 &self.inner.phases
121 }
122
123 pub(crate) fn replicate_policy(&self) -> ReplicatePolicy {
125 self.inner.replicate_policy
126 }
127
128 pub(crate) fn master_seed(&self) -> Option<u64> {
130 self.inner.master_seed
131 }
132
133 pub(crate) fn persistence_plan(&self) -> PersistencePlan {
136 self.inner.persistence_plan
137 }
138}
139
140impl std::fmt::Debug for Study {
141 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142 formatter
143 .debug_struct("Study")
144 .field("project_root", &self.project_root())
145 .field("output_root", &self.output_root())
146 .field("threads", &self.threads())
147 .field("compute_mode", &self.plan_summary().compute_mode())
148 .field("config", &self.inner.config)
149 .field("persistence", &self.persistence_plan())
150 .field("phases", &self.phases().len())
151 .finish_non_exhaustive()
152 }
153}
154
155struct StudyInner {
156 disk_pause_at: Option<f64>,
157 active_phases: Box<[usize]>,
158 reuse_from: Option<PathBuf>,
159 phase_order: Box<[usize]>,
160 project_root: PathBuf,
161 config: Config,
162 phases: Box<[StudyPhase]>,
163 output_root: PathBuf,
164 workflow_schema: u64,
165 threads: usize,
166 compute_mode: ComputeMode,
167 master_seed: Option<u64>,
168 replicate_policy: ReplicatePolicy,
169 persistence_plan: PersistencePlan,
170}
171
172#[derive(Clone, Copy)]
174pub struct PlanSummary<'a> {
175 study: &'a Study,
176}
177
178impl std::fmt::Debug for PlanSummary<'_> {
179 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180 formatter
181 .debug_struct("PlanSummary")
182 .field("workflow_schema", &self.workflow_schema())
183 .field("threads", &self.threads())
184 .field("compute_mode", &self.compute_mode())
185 .field("replicate_count", &self.replicate_count())
186 .field("phases", &self.study.phases().len())
187 .finish_non_exhaustive()
188 }
189}
190
191impl<'a> PlanSummary<'a> {
192 pub fn workflow_schema(self) -> u64 {
194 self.study.inner.workflow_schema
195 }
196
197 pub fn threads(self) -> usize {
199 self.study.threads()
200 }
201
202 pub fn compute_mode(self) -> PlanComputeMode {
204 match self.study.compute_mode() {
205 ComputeMode::Auto => PlanComputeMode::Auto,
206 ComputeMode::Isolated => PlanComputeMode::Isolated,
207 }
208 }
209
210 pub fn replicate_count(self) -> u64 {
212 self.study.replicate_policy().count()
213 }
214
215 pub fn replicate_scheduling(self) -> PlanReplicateScheduling {
217 match self.study.replicate_policy().scheduling() {
218 ReplicateScheduling::Sequential => PlanReplicateScheduling::Sequential,
219 ReplicateScheduling::Parallel => PlanReplicateScheduling::Parallel,
220 }
221 }
222
223 pub fn replicate_failure_policy(self) -> PlanFailurePolicy {
225 public_failure_policy(self.study.replicate_policy().failure_policy())
226 }
227
228 pub fn has_master_seed(self) -> bool {
233 self.study.master_seed().is_some()
234 }
235
236 pub fn persistence_chunk_target_bytes(self) -> u64 {
238 self.study.persistence_plan().chunk_target().get()
239 }
240
241 pub fn persistence_queue_capacity_bytes(self) -> u64 {
243 self.study.persistence_plan().queue_capacity().get()
244 }
245
246 pub fn phases(self) -> impl ExactSizeIterator<Item = PhasePlanSummary<'a>> {
248 self.study
249 .phase_order()
250 .iter()
251 .enumerate()
252 .map(|(index, &position)| PhasePlanSummary {
253 phase: &self.study.phases()[position],
254 index,
255 active: self.study.phase_is_active(index),
256 })
257 }
258}
259
260#[derive(Clone, Copy, Debug, Eq, PartialEq)]
262pub enum PlanReplicateScheduling {
263 Sequential,
265 Parallel,
267}
268
269#[derive(Clone, Copy, Debug, Eq, PartialEq)]
271pub enum PlanComputeMode {
272 Auto,
274 Isolated,
276}
277
278#[derive(Clone, Copy, Debug, Eq, PartialEq)]
280pub enum PlanFailurePolicy {
281 FailFast,
283 FinishAll,
285}
286
287#[derive(Clone, Copy)]
289pub struct PhasePlanSummary<'a> {
290 index: usize,
291 active: bool,
292 phase: &'a StudyPhase,
293}
294
295impl std::fmt::Debug for PhasePlanSummary<'_> {
296 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
297 formatter
298 .debug_struct("PhasePlanSummary")
299 .field("name", &self.name())
300 .field("dependencies", &self.phase.dependencies.len())
301 .field("tasks", &self.phase.tasks.len())
302 .finish_non_exhaustive()
303 }
304}
305
306impl<'a> PhasePlanSummary<'a> {
307 pub fn index(self) -> usize {
309 self.index
310 }
311
312 pub fn is_active(self) -> bool {
314 self.active
315 }
316
317 pub fn name(self) -> &'a str {
319 self.phase.name()
320 }
321
322 pub fn dependencies(self) -> impl ExactSizeIterator<Item = &'a str> {
324 self.phase.dependencies()
325 }
326
327 pub fn max_concurrency(self) -> usize {
329 self.phase.max_concurrency()
330 }
331
332 pub fn start_interval(self) -> Duration {
334 self.phase.start_interval()
335 }
336
337 pub fn timeout(self) -> Option<Duration> {
339 self.phase.timeout()
340 }
341
342 pub fn failure_policy(self) -> PlanFailurePolicy {
344 public_failure_policy(self.phase.failure_policy())
345 }
346
347 pub fn tasks(self) -> impl ExactSizeIterator<Item = TaskPlanSummary<'a>> {
349 self.phase.tasks().iter().map(move |task| TaskPlanSummary {
350 task,
351 active: self.active && task.is_active(),
352 })
353 }
354}
355
356#[derive(Clone, Copy)]
358pub struct TaskPlanSummary<'a> {
359 task: &'a StudyTask,
360 active: bool,
361}
362
363impl std::fmt::Debug for TaskPlanSummary<'_> {
364 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
365 formatter
366 .debug_struct("TaskPlanSummary")
367 .field("identity", &self.identity())
368 .field("label", &self.label())
369 .field("active", &self.is_active())
370 .field("kind", &self.kind())
371 .finish_non_exhaustive()
372 }
373}
374
375impl<'a> TaskPlanSummary<'a> {
376 pub fn identity(self) -> &'a str {
378 self.task.identity()
379 }
380
381 pub fn label(self) -> &'a str {
383 self.task.label()
384 }
385
386 pub fn output_ordinal(self) -> u64 {
388 self.task.output_ordinal()
389 }
390
391 pub fn is_active(self) -> bool {
393 self.active
394 }
395
396 pub fn timeout(self) -> Option<Duration> {
398 self.task.timeout()
399 }
400
401 pub fn seed_purpose(self) -> Option<&'a str> {
403 self.task.program_seed_purpose()
404 }
405
406 pub fn kind(self) -> PlannedTaskKind<'a> {
408 if let Some(provenance) = self.task.execution_unit_provenance() {
409 PlannedTaskKind::ExecutionUnit {
410 execution_unit: provenance.execution_unit(),
411 state: provenance.state(),
412 parameter_ordinal: provenance.parameter_ordinal(),
413 parameter_source: provenance.parameter_source(),
414 threads: self.task.threads,
415 }
416 } else if let Some(script) = self.task.python_script() {
417 PlannedTaskKind::Python {
418 launcher: self
419 .task
420 .program_path()
421 .expect("a compiled Python task has a resolved launcher"),
422 script,
423 threads: self.task.program_threads(),
424 }
425 } else {
426 PlannedTaskKind::Program {
427 executable: self
428 .task
429 .program_path()
430 .expect("a compiled program task has a resolved executable"),
431 threads: self.task.program_threads(),
432 }
433 }
434 }
435}
436
437#[derive(Clone, Copy, Debug, Eq, PartialEq)]
439pub enum PlannedTaskKind<'a> {
440 ExecutionUnit {
442 execution_unit: &'a str,
444 state: &'a str,
446 parameter_ordinal: u64,
448 parameter_source: &'a Path,
450 threads: Option<usize>,
452 },
453 Program {
455 executable: &'a Path,
457 threads: usize,
459 },
460 Python {
462 launcher: &'a Path,
464 script: &'a Path,
466 threads: usize,
468 },
469}
470
471fn public_failure_policy(policy: FailurePolicy) -> PlanFailurePolicy {
472 match policy {
473 FailurePolicy::FailFast => PlanFailurePolicy::FailFast,
474 FailurePolicy::FinishAll => PlanFailurePolicy::FinishAll,
475 }
476}
477
478#[derive(Clone, Debug)]
480pub(crate) struct StudyPhase {
481 pub(crate) name: Box<str>,
482 pub(crate) dependencies: Box<[Box<str>]>,
483 pub(crate) tasks: Box<[StudyTask]>,
484 pub(crate) max_concurrency: usize,
485 pub(crate) start_interval: Duration,
486 pub(crate) timeout: Option<Duration>,
487 pub(crate) failure_policy: FailurePolicy,
488}
489
490impl StudyPhase {
491 pub(crate) fn name(&self) -> &str {
493 &self.name
494 }
495
496 pub(crate) fn dependencies(&self) -> impl ExactSizeIterator<Item = &str> {
498 self.dependencies.iter().map(Box::as_ref)
499 }
500
501 pub(crate) fn tasks(&self) -> &[StudyTask] {
503 &self.tasks
504 }
505
506 pub(crate) const fn max_concurrency(&self) -> usize {
508 self.max_concurrency
509 }
510
511 pub(crate) const fn start_interval(&self) -> Duration {
513 self.start_interval
514 }
515
516 pub(crate) const fn timeout(&self) -> Option<Duration> {
518 self.timeout
519 }
520
521 pub(crate) const fn failure_policy(&self) -> FailurePolicy {
523 self.failure_policy
524 }
525}
526
527#[derive(Clone)]
529pub(crate) struct StudyTask {
530 pub(crate) active: bool,
531 pub(crate) identity: Box<str>,
532 pub(crate) label: Box<str>,
533 pub(crate) output_ordinal: u64,
534 pub(crate) configuration: usize,
535 pub(crate) config_snapshot: ConfigSnapshot,
536 pub(crate) task: Task,
537 pub(crate) threads: Option<usize>,
538}
539
540impl StudyTask {
541 pub(crate) const fn is_active(&self) -> bool {
543 self.active
544 }
545
546 pub(crate) fn identity(&self) -> &str {
548 &self.identity
549 }
550
551 pub(crate) fn label(&self) -> &str {
553 &self.label
554 }
555
556 pub(crate) fn kind(&self) -> TaskKind {
557 self.task.kind()
558 }
559
560 pub(crate) fn kind_name(&self) -> &'static str {
561 self.task.kind_name()
562 }
563
564 pub(crate) fn execution_unit(&self) -> Option<&str> {
566 self.task.execution_unit()
567 }
568
569 pub(crate) fn subject(&self) -> &str {
571 self.task.subject()
572 }
573
574 pub(crate) fn timeout(&self) -> Option<Duration> {
576 self.task.timeout()
577 }
578
579 pub(crate) fn output_ordinal(&self) -> u64 {
580 self.output_ordinal
581 }
582
583 pub(crate) const fn configuration(&self) -> usize {
584 self.configuration
585 }
586
587 pub(crate) fn config_snapshot(&self) -> ConfigSnapshot {
588 self.config_snapshot.clone()
589 }
590
591 pub(crate) fn definition(&self) -> &dyn TaskDefinition {
592 &self.task
593 }
594
595 pub(crate) fn execution_unit_provenance(&self) -> Option<ExecutionUnitTaskProvenance<'_>> {
596 self.task.execution_unit_provenance()
597 }
598
599 pub(crate) fn program_path(&self) -> Option<&Path> {
600 self.task.program_path()
601 }
602
603 pub(crate) fn python_script(&self) -> Option<&Path> {
604 self.task.python_script()
605 }
606
607 pub(crate) fn program_seed_purpose(&self) -> Option<&str> {
608 self.task.program_seed_purpose()
609 }
610
611 pub(crate) fn program_threads(&self) -> usize {
612 self.task
613 .program_threads()
614 .expect("a compiled program task retains its positive thread request")
615 }
616
617 pub(crate) const fn execution_unit_threads(&self) -> Option<usize> {
618 self.threads
619 }
620
621 pub(crate) fn is_npy(&self) -> bool {
622 self.task.is_npy()
623 }
624}
625
626impl std::fmt::Debug for StudyTask {
627 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
628 formatter
629 .debug_struct("StudyTask")
630 .field("identity", &self.identity())
631 .field("label", &self.label())
632 .field("kind", &self.kind())
633 .field("subject", &self.subject())
634 .finish_non_exhaustive()
635 }
636}
637
638fn topological_positions(phases: &[StudyPhase]) -> Vec<usize> {
639 fn visit(
640 index: usize,
641 phases: &[StudyPhase],
642 by_name: &std::collections::HashMap<&str, usize>,
643 visited: &mut [bool],
644 positions: &mut Vec<usize>,
645 ) {
646 if visited[index] {
647 return;
648 }
649 for dependency in phases[index].dependencies() {
650 visit(by_name[dependency], phases, by_name, visited, positions);
651 }
652 visited[index] = true;
653 positions.push(index);
654 }
655
656 let by_name = phases
657 .iter()
658 .enumerate()
659 .map(|(index, phase)| (phase.name(), index))
660 .collect::<HashMap<_, _>>();
661 let mut visited = vec![false; phases.len()];
662 let mut positions = Vec::with_capacity(phases.len());
663 for index in 0..phases.len() {
664 visit(index, phases, &by_name, &mut visited, &mut positions);
665 }
666 positions
667}