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