scientific_workflow/study/
plan.rs1use std::collections::HashMap;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::time::Duration;
7
8use crate::config::{
9 Config, ConfigSnapshot, FailurePolicy, PersistenceSpecification, ProjectSpecification,
10 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 replicate_policy = manifest.replicate_policy();
45 let master_seed = manifest.master_seed();
46 let persistence: PersistenceSpecification = manifest.persistence();
47 let persistence_plan = PersistencePlan::local(
48 persistence.chunk_target_bytes(),
49 persistence.queue_capacity_bytes(),
50 );
51 Self {
52 inner: Arc::new(StudyInner {
53 active_phases: manifest.active_phases().into(),
54 reuse_from: manifest.reuse_from().map(Path::to_path_buf),
55 phase_order: topological_positions(&phases).into_boxed_slice(),
56 project_root,
57 config,
58 phases,
59 output_root,
60 workflow_schema,
61 threads,
62 master_seed,
63 replicate_policy,
64 persistence_plan,
65 }),
66 }
67 }
68
69 pub fn project_root(&self) -> &Path {
71 &self.inner.project_root
72 }
73
74 pub fn output_root(&self) -> &Path {
76 &self.inner.output_root
77 }
78
79 pub fn threads(&self) -> usize {
81 self.inner.threads
82 }
83
84 pub fn plan_summary(&self) -> PlanSummary<'_> {
89 PlanSummary { study: self }
90 }
91
92 pub(crate) fn phase_order(&self) -> &[usize] {
94 &self.inner.phase_order
95 }
96
97 pub(crate) fn phase_is_active(&self, index: usize) -> bool {
99 self.inner.active_phases.contains(&index)
100 }
101
102 pub(crate) fn reuse_from(&self) -> Option<&Path> {
104 self.inner.reuse_from.as_deref()
105 }
106
107 pub(crate) fn phases(&self) -> &[StudyPhase] {
109 &self.inner.phases
110 }
111
112 pub(crate) fn replicate_policy(&self) -> ReplicatePolicy {
114 self.inner.replicate_policy
115 }
116
117 pub(crate) fn master_seed(&self) -> Option<u64> {
119 self.inner.master_seed
120 }
121
122 pub(crate) fn persistence_plan(&self) -> PersistencePlan {
125 self.inner.persistence_plan
126 }
127}
128
129impl std::fmt::Debug for Study {
130 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131 formatter
132 .debug_struct("Study")
133 .field("project_root", &self.project_root())
134 .field("output_root", &self.output_root())
135 .field("threads", &self.threads())
136 .field("config", &self.inner.config)
137 .field("persistence", &self.persistence_plan())
138 .field("phases", &self.phases().len())
139 .finish_non_exhaustive()
140 }
141}
142
143struct StudyInner {
144 active_phases: Box<[usize]>,
145 reuse_from: Option<PathBuf>,
146 phase_order: Box<[usize]>,
147 project_root: PathBuf,
148 config: Config,
149 phases: Box<[StudyPhase]>,
150 output_root: PathBuf,
151 workflow_schema: u64,
152 threads: usize,
153 master_seed: Option<u64>,
154 replicate_policy: ReplicatePolicy,
155 persistence_plan: PersistencePlan,
156}
157
158#[derive(Clone, Copy)]
160pub struct PlanSummary<'a> {
161 study: &'a Study,
162}
163
164impl std::fmt::Debug for PlanSummary<'_> {
165 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166 formatter
167 .debug_struct("PlanSummary")
168 .field("workflow_schema", &self.workflow_schema())
169 .field("threads", &self.threads())
170 .field("replicate_count", &self.replicate_count())
171 .field("phases", &self.study.phases().len())
172 .finish_non_exhaustive()
173 }
174}
175
176impl<'a> PlanSummary<'a> {
177 pub fn workflow_schema(self) -> u64 {
179 self.study.inner.workflow_schema
180 }
181
182 pub fn threads(self) -> usize {
184 self.study.threads()
185 }
186
187 pub fn replicate_count(self) -> u64 {
189 self.study.replicate_policy().count()
190 }
191
192 pub fn replicate_scheduling(self) -> PlanReplicateScheduling {
194 match self.study.replicate_policy().scheduling() {
195 ReplicateScheduling::Sequential => PlanReplicateScheduling::Sequential,
196 ReplicateScheduling::Parallel => PlanReplicateScheduling::Parallel,
197 }
198 }
199
200 pub fn replicate_failure_policy(self) -> PlanFailurePolicy {
202 public_failure_policy(self.study.replicate_policy().failure_policy())
203 }
204
205 pub fn has_master_seed(self) -> bool {
210 self.study.master_seed().is_some()
211 }
212
213 pub fn persistence_chunk_target_bytes(self) -> u64 {
215 self.study.persistence_plan().chunk_target().get()
216 }
217
218 pub fn persistence_queue_capacity_bytes(self) -> u64 {
220 self.study.persistence_plan().queue_capacity().get()
221 }
222
223 pub fn phases(self) -> impl ExactSizeIterator<Item = PhasePlanSummary<'a>> {
225 self.study
226 .phase_order()
227 .iter()
228 .enumerate()
229 .map(|(index, &position)| PhasePlanSummary {
230 phase: &self.study.phases()[position],
231 index,
232 active: self.study.phase_is_active(index),
233 })
234 }
235}
236
237#[derive(Clone, Copy, Debug, Eq, PartialEq)]
239pub enum PlanReplicateScheduling {
240 Sequential,
242 Parallel,
244}
245
246#[derive(Clone, Copy, Debug, Eq, PartialEq)]
248pub enum PlanFailurePolicy {
249 FailFast,
251 FinishAll,
253}
254
255#[derive(Clone, Copy)]
257pub struct PhasePlanSummary<'a> {
258 index: usize,
259 active: bool,
260 phase: &'a StudyPhase,
261}
262
263impl std::fmt::Debug for PhasePlanSummary<'_> {
264 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
265 formatter
266 .debug_struct("PhasePlanSummary")
267 .field("name", &self.name())
268 .field("dependencies", &self.phase.dependencies.len())
269 .field("tasks", &self.phase.tasks.len())
270 .finish_non_exhaustive()
271 }
272}
273
274impl<'a> PhasePlanSummary<'a> {
275 pub fn index(self) -> usize {
277 self.index
278 }
279
280 pub fn is_active(self) -> bool {
282 self.active
283 }
284
285 pub fn name(self) -> &'a str {
287 self.phase.name()
288 }
289
290 pub fn dependencies(self) -> impl ExactSizeIterator<Item = &'a str> {
292 self.phase.dependencies()
293 }
294
295 pub fn max_concurrency(self) -> usize {
297 self.phase.max_concurrency()
298 }
299
300 pub fn start_interval(self) -> Duration {
302 self.phase.start_interval()
303 }
304
305 pub fn timeout(self) -> Option<Duration> {
307 self.phase.timeout()
308 }
309
310 pub fn failure_policy(self) -> PlanFailurePolicy {
312 public_failure_policy(self.phase.failure_policy())
313 }
314
315 pub fn tasks(self) -> impl ExactSizeIterator<Item = TaskPlanSummary<'a>> {
317 self.phase
318 .tasks()
319 .iter()
320 .map(|task| TaskPlanSummary { task })
321 }
322}
323
324#[derive(Clone, Copy)]
326pub struct TaskPlanSummary<'a> {
327 task: &'a StudyTask,
328}
329
330impl std::fmt::Debug for TaskPlanSummary<'_> {
331 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
332 formatter
333 .debug_struct("TaskPlanSummary")
334 .field("identity", &self.identity())
335 .field("label", &self.label())
336 .field("kind", &self.kind())
337 .finish_non_exhaustive()
338 }
339}
340
341impl<'a> TaskPlanSummary<'a> {
342 pub fn identity(self) -> &'a str {
344 self.task.identity()
345 }
346
347 pub fn label(self) -> &'a str {
349 self.task.label()
350 }
351
352 pub fn output_ordinal(self) -> u64 {
354 self.task.output_ordinal()
355 }
356
357 pub fn timeout(self) -> Option<Duration> {
359 self.task.timeout()
360 }
361
362 pub fn seed_purpose(self) -> Option<&'a str> {
364 self.task.program_seed_purpose()
365 }
366
367 pub fn kind(self) -> PlannedTaskKind<'a> {
369 if let Some(provenance) = self.task.execution_unit_provenance() {
370 PlannedTaskKind::ExecutionUnit {
371 execution_unit: provenance.execution_unit(),
372 state: provenance.state(),
373 parameter_ordinal: provenance.parameter_ordinal(),
374 parameter_source: provenance.parameter_source(),
375 }
376 } else if let Some(script) = self.task.python_script() {
377 PlannedTaskKind::Python {
378 launcher: self
379 .task
380 .program_path()
381 .expect("a compiled Python task has a resolved launcher"),
382 script,
383 threads: self.task.program_threads(),
384 }
385 } else {
386 PlannedTaskKind::Program {
387 executable: self
388 .task
389 .program_path()
390 .expect("a compiled program task has a resolved executable"),
391 threads: self.task.program_threads(),
392 }
393 }
394 }
395}
396
397#[derive(Clone, Copy, Debug, Eq, PartialEq)]
399pub enum PlannedTaskKind<'a> {
400 ExecutionUnit {
402 execution_unit: &'a str,
404 state: &'a str,
406 parameter_ordinal: u64,
408 parameter_source: &'a Path,
410 },
411 Program {
413 executable: &'a Path,
415 threads: usize,
417 },
418 Python {
420 launcher: &'a Path,
422 script: &'a Path,
424 threads: usize,
426 },
427}
428
429fn public_failure_policy(policy: FailurePolicy) -> PlanFailurePolicy {
430 match policy {
431 FailurePolicy::FailFast => PlanFailurePolicy::FailFast,
432 FailurePolicy::FinishAll => PlanFailurePolicy::FinishAll,
433 }
434}
435
436#[derive(Clone, Debug)]
438pub(crate) struct StudyPhase {
439 pub(crate) name: Box<str>,
440 pub(crate) dependencies: Box<[Box<str>]>,
441 pub(crate) tasks: Box<[StudyTask]>,
442 pub(crate) max_concurrency: usize,
443 pub(crate) start_interval: Duration,
444 pub(crate) timeout: Option<Duration>,
445 pub(crate) failure_policy: FailurePolicy,
446}
447
448impl StudyPhase {
449 pub(crate) fn name(&self) -> &str {
451 &self.name
452 }
453
454 pub(crate) fn dependencies(&self) -> impl ExactSizeIterator<Item = &str> {
456 self.dependencies.iter().map(Box::as_ref)
457 }
458
459 pub(crate) fn tasks(&self) -> &[StudyTask] {
461 &self.tasks
462 }
463
464 pub(crate) const fn max_concurrency(&self) -> usize {
466 self.max_concurrency
467 }
468
469 pub(crate) const fn start_interval(&self) -> Duration {
471 self.start_interval
472 }
473
474 pub(crate) const fn timeout(&self) -> Option<Duration> {
476 self.timeout
477 }
478
479 pub(crate) const fn failure_policy(&self) -> FailurePolicy {
481 self.failure_policy
482 }
483}
484
485#[derive(Clone)]
487pub(crate) struct StudyTask {
488 pub(crate) identity: Box<str>,
489 pub(crate) label: Box<str>,
490 pub(crate) output_ordinal: u64,
491 pub(crate) configuration: usize,
492 pub(crate) config_snapshot: ConfigSnapshot,
493 pub(crate) task: Task,
494}
495
496impl StudyTask {
497 pub(crate) fn identity(&self) -> &str {
499 &self.identity
500 }
501
502 pub(crate) fn label(&self) -> &str {
504 &self.label
505 }
506
507 pub(crate) fn kind(&self) -> TaskKind {
508 self.task.kind()
509 }
510
511 pub(crate) fn kind_name(&self) -> &'static str {
512 self.task.kind_name()
513 }
514
515 pub(crate) fn execution_unit(&self) -> Option<&str> {
517 self.task.execution_unit()
518 }
519
520 pub(crate) fn subject(&self) -> &str {
522 self.task.subject()
523 }
524
525 pub(crate) fn timeout(&self) -> Option<Duration> {
527 self.task.timeout()
528 }
529
530 pub(crate) fn output_ordinal(&self) -> u64 {
531 self.output_ordinal
532 }
533
534 pub(crate) const fn configuration(&self) -> usize {
535 self.configuration
536 }
537
538 pub(crate) fn config_snapshot(&self) -> ConfigSnapshot {
539 self.config_snapshot.clone()
540 }
541
542 pub(crate) fn definition(&self) -> &dyn TaskDefinition {
543 &self.task
544 }
545
546 pub(crate) fn execution_unit_provenance(&self) -> Option<ExecutionUnitTaskProvenance<'_>> {
547 self.task.execution_unit_provenance()
548 }
549
550 pub(crate) fn program_path(&self) -> Option<&Path> {
551 self.task.program_path()
552 }
553
554 pub(crate) fn python_script(&self) -> Option<&Path> {
555 self.task.python_script()
556 }
557
558 pub(crate) fn program_seed_purpose(&self) -> Option<&str> {
559 self.task.program_seed_purpose()
560 }
561
562 pub(crate) fn program_threads(&self) -> usize {
563 self.task
564 .program_threads()
565 .expect("a compiled program task retains its positive thread request")
566 }
567
568 pub(crate) fn is_npy(&self) -> bool {
569 self.task.is_npy()
570 }
571}
572
573impl std::fmt::Debug for StudyTask {
574 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
575 formatter
576 .debug_struct("StudyTask")
577 .field("identity", &self.identity())
578 .field("label", &self.label())
579 .field("kind", &self.kind())
580 .field("subject", &self.subject())
581 .finish_non_exhaustive()
582 }
583}
584
585fn topological_positions(phases: &[StudyPhase]) -> Vec<usize> {
586 fn visit(
587 index: usize,
588 phases: &[StudyPhase],
589 by_name: &std::collections::HashMap<&str, usize>,
590 visited: &mut [bool],
591 positions: &mut Vec<usize>,
592 ) {
593 if visited[index] {
594 return;
595 }
596 for dependency in phases[index].dependencies() {
597 visit(by_name[dependency], phases, by_name, visited, positions);
598 }
599 visited[index] = true;
600 positions.push(index);
601 }
602
603 let by_name = phases
604 .iter()
605 .enumerate()
606 .map(|(index, phase)| (phase.name(), index))
607 .collect::<HashMap<_, _>>();
608 let mut visited = vec![false; phases.len()];
609 let mut positions = Vec::with_capacity(phases.len());
610 for index in 0..phases.len() {
611 visit(index, phases, &by_name, &mut visited, &mut positions);
612 }
613 positions
614}