Skip to main content

scientific_workflow/task/
unit.rs

1//! Application-owned scientific execution contract.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::sync::{Mutex, MutexGuard};
5
6use serde::de::DeserializeOwned;
7use serde_json::{Map, Value};
8use sha2::{Digest, Sha256};
9use thiserror::Error;
10
11use crate::observation::ObservationPlan;
12use crate::state::{StateSchemaProvider, SystemState, SystemStateSchema};
13
14use super::UnitResult;
15
16pub(crate) const SEED_DERIVATION_ALGORITHM: &str = "scientific-workflow.seed.v1";
17
18/// Immutable dependency results, execution facts, and optional seed derivation.
19///
20/// Workflow creates one context for each execution-unit initialization. A
21/// unit may inspect completed correlated dependencies. A stochastic unit
22/// requests only the named seeds it actually needs; Workflow derives them
23/// without counters or request-order dependence and records successful
24/// requests with the affected member's output metadata.
25pub struct InitializationContext {
26    master_seed: Option<u64>,
27    replicate_ordinal: u64,
28    task_identity: Box<str>,
29    execution_unit_key: Box<str>,
30    dependencies: super::dependencies::Dependencies,
31    requests: Mutex<BTreeMap<SeedRequest, u64>>,
32}
33
34impl InitializationContext {
35    #[cfg(test)]
36    pub(crate) fn new(
37        master_seed: Option<u64>,
38        replicate_ordinal: u64,
39        task_identity: &str,
40        execution_unit_key: &str,
41    ) -> Self {
42        Self::with_dependencies(
43            master_seed,
44            replicate_ordinal,
45            task_identity,
46            execution_unit_key,
47            Value::Array(Vec::new()),
48        )
49    }
50
51    pub(crate) fn with_dependencies(
52        master_seed: Option<u64>,
53        replicate_ordinal: u64,
54        task_identity: &str,
55        execution_unit_key: &str,
56        dependencies: Value,
57    ) -> Self {
58        Self {
59            master_seed,
60            replicate_ordinal,
61            task_identity: task_identity.into(),
62            execution_unit_key: execution_unit_key.into(),
63            dependencies: super::dependencies::Dependencies::from_json(dependencies)
64                .expect("Runtime supplies a validated dependency snapshot"),
65            requests: Mutex::new(BTreeMap::new()),
66        }
67    }
68
69    /// Returns completed summaries from the task's declared dependency phases.
70    pub const fn dependencies(&self) -> &super::dependencies::Dependencies {
71        &self.dependencies
72    }
73
74    /// Returns a named captured external input as a backend-independent selection.
75    pub fn input(&self, name: &str) -> std::io::Result<crate::artifact::ArtifactSet> {
76        super::context::captured_input(name)
77    }
78
79    /// Returns whether `wf_configs/study.json` supplied a master seed.
80    pub const fn has_master_seed(&self) -> bool {
81        self.master_seed.is_some()
82    }
83
84    /// Derives a seed shared by all members in this execution unit.
85    ///
86    /// `purpose` is a stable, nonempty semantic name such as `"pairing"`.
87    /// Repeating the same request returns the same seed and metadata entry.
88    pub fn shared_seed(&self, purpose: &str) -> Result<u64, SeedError> {
89        self.seed(SeedScope::Shared, purpose)
90    }
91
92    /// Derives a seed belonging to one member exposed by this execution unit.
93    ///
94    /// `member_identity` must exactly match that member's [`MemberView`] identity;
95    /// Workflow rejects an initialization that requested a seed for an unknown
96    /// member. `purpose` is a stable, nonempty semantic name such as
97    /// `"initialization"` or `"replacement"`.
98    pub fn member_seed(&self, member_identity: &str, purpose: &str) -> Result<u64, SeedError> {
99        validate_name(member_identity, "member identity")?;
100        self.seed(SeedScope::Member(member_identity.into()), purpose)
101    }
102
103    /// Derives a deliberately shared stream across tasks in this study and replicate.
104    /// Group and purpose are explicit scientific names, retained in the seed ledger.
105    pub fn group_seed(&self, group: &str, purpose: &str) -> Result<u64, SeedError> {
106        validate_name(group, "group")?;
107        self.seed(SeedScope::Group(group.into()), purpose)
108    }
109
110    fn seed(&self, scope: SeedScope, purpose: &str) -> Result<u64, SeedError> {
111        validate_name(purpose, "purpose")?;
112        let master_seed = self.master_seed.ok_or(SeedError::MissingMasterSeed)?;
113        let request = SeedRequest {
114            scope,
115            purpose: purpose.into(),
116        };
117        if let Some(seed) = self.request_ledger().get(&request) {
118            return Ok(*seed);
119        }
120
121        let seed = derive_seed(
122            master_seed,
123            self.replicate_ordinal,
124            &self.task_identity,
125            &self.execution_unit_key,
126            &request.scope,
127            &request.purpose,
128        );
129        self.request_ledger().insert(request, seed);
130        Ok(seed)
131    }
132
133    pub(crate) fn validate_member_identities<'a>(
134        &self,
135        identities: impl IntoIterator<Item = &'a str>,
136    ) -> Result<(), SeedError> {
137        let identities = identities.into_iter().collect::<BTreeSet<_>>();
138        for request in self.request_ledger().keys() {
139            if let SeedScope::Member(identity) = &request.scope
140                && !identities.contains(identity.as_ref())
141            {
142                return Err(SeedError::UnknownMemberIdentity {
143                    identity: identity.to_string(),
144                });
145            }
146        }
147        Ok(())
148    }
149
150    pub(crate) fn metadata_for_member(&self, member_identity: &str) -> Option<Value> {
151        let requests = self
152            .request_ledger()
153            .iter()
154            .filter_map(|(request, seed)| match &request.scope {
155                SeedScope::Group(group) => Some(serde_json::json!({"scope":"study_group","group":group,"purpose":request.purpose,"seed":seed})),
156                SeedScope::Shared => Some(Value::Object(Map::from_iter([
157                    ("scope".to_owned(), "shared".into()),
158                    ("purpose".to_owned(), request.purpose.to_string().into()),
159                    ("seed".to_owned(), (*seed).into()),
160                ]))),
161                SeedScope::Member(identity) if identity.as_ref() == member_identity => {
162                    Some(Value::Object(Map::from_iter([
163                        ("scope".to_owned(), "member".into()),
164                        ("member_identity".to_owned(), identity.to_string().into()),
165                        ("purpose".to_owned(), request.purpose.to_string().into()),
166                        ("seed".to_owned(), (*seed).into()),
167                    ])))
168                }
169                SeedScope::Member(_) => None,
170            })
171            .collect::<Vec<_>>();
172        (!requests.is_empty()).then(|| {
173            Value::Object(Map::from_iter([
174                ("algorithm".to_owned(), SEED_DERIVATION_ALGORITHM.into()),
175                (
176                    "master_seed".to_owned(),
177                    self.master_seed
178                        .expect("a recorded request has a seed")
179                        .into(),
180                ),
181                ("requests".to_owned(), requests.into()),
182            ]))
183        })
184    }
185
186    fn request_ledger(&self) -> MutexGuard<'_, BTreeMap<SeedRequest, u64>> {
187        self.requests
188            .lock()
189            .unwrap_or_else(|error| error.into_inner())
190    }
191}
192
193pub(crate) fn derive_program_seed(
194    master_seed: u64,
195    replicate_ordinal: u64,
196    task_identity: &str,
197    program_kind: &str,
198    purpose: &str,
199) -> u64 {
200    derive_seed(
201        master_seed,
202        replicate_ordinal,
203        task_identity,
204        program_kind,
205        &SeedScope::Shared,
206        purpose,
207    )
208}
209
210fn derive_seed(
211    master_seed: u64,
212    replicate_ordinal: u64,
213    task_identity: &str,
214    workload_key: &str,
215    scope: &SeedScope,
216    purpose: &str,
217) -> u64 {
218    let mut digest = Sha256::new();
219    hash_part(&mut digest, SEED_DERIVATION_ALGORITHM.as_bytes());
220    digest.update(master_seed.to_le_bytes());
221    digest.update(replicate_ordinal.to_le_bytes());
222    if matches!(scope, SeedScope::Group(_)) {
223        hash_part(&mut digest, b"study-shared-group");
224    } else {
225        hash_part(&mut digest, task_identity.as_bytes());
226        hash_part(&mut digest, workload_key.as_bytes());
227    }
228    match scope {
229        SeedScope::Group(group) => {
230            digest.update([2]);
231            hash_part(&mut digest, group.as_bytes());
232        }
233        SeedScope::Shared => digest.update([0]),
234        SeedScope::Member(identity) => {
235            digest.update([1]);
236            hash_part(&mut digest, identity.as_bytes());
237        }
238    }
239    hash_part(&mut digest, purpose.as_bytes());
240    u64::from_le_bytes(digest.finalize()[..8].try_into().expect("SHA-256 prefix"))
241}
242
243fn hash_part(digest: &mut Sha256, bytes: &[u8]) {
244    digest.update((bytes.len() as u64).to_le_bytes());
245    digest.update(bytes);
246}
247
248fn validate_name(value: &str, field: &'static str) -> Result<(), SeedError> {
249    if value.is_empty() || value.trim() != value {
250        return Err(SeedError::InvalidName {
251            field,
252            value: value.to_owned(),
253        });
254    }
255    Ok(())
256}
257
258#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
259struct SeedRequest {
260    scope: SeedScope,
261    purpose: Box<str>,
262}
263
264#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
265enum SeedScope {
266    Group(Box<str>),
267    Shared,
268    Member(Box<str>),
269}
270
271/// Failure to make or validate a deterministic initialization seed request.
272#[derive(Debug, Error)]
273#[non_exhaustive]
274pub enum SeedError {
275    /// The execution unit requested a seed but the study has none.
276    #[error("this execution unit requires `seed` in `wf_configs/study.json`")]
277    MissingMasterSeed,
278    /// A stable seed name was empty or had surrounding whitespace.
279    #[error("invalid seed {field} `{value}`: it must be nonempty with no surrounding whitespace")]
280    InvalidName {
281        /// The invalid semantic field.
282        field: &'static str,
283        /// The rejected value.
284        value: String,
285    },
286    /// A member seed was requested for an identity the unit did not expose.
287    #[error("seed requested for unknown member identity `{identity}`")]
288    UnknownMemberIdentity {
289        /// The requested identity absent from the execution unit.
290        identity: String,
291    },
292}
293
294/// The optional completion declaration for one execution-unit member.
295///
296/// This borrowed value distinguishes an incomplete member from a completed
297/// member with or without a structured reason. The execution unit retains the
298/// reason object; Workflow copies it only when the member first completes.
299#[derive(Clone, Copy, Debug)]
300pub struct MemberCompletion<'a> {
301    reason: Option<&'a Map<String, Value>>,
302}
303
304impl<'a> MemberCompletion<'a> {
305    /// Declares completion without a structured reason.
306    pub const fn without_reason() -> Self {
307        Self { reason: None }
308    }
309
310    /// Declares completion with a borrowed structured JSON reason.
311    pub const fn with_reason(reason: &'a Map<String, Value>) -> Self {
312        Self {
313            reason: Some(reason),
314        }
315    }
316
317    /// Returns the structured reason, when the execution unit supplied one.
318    pub const fn reason(self) -> Option<&'a Map<String, Value>> {
319        self.reason
320    }
321}
322
323/// A borrowed view of one independently stateful member inside an execution unit.
324///
325/// The identity, state owner, and schema allocation must remain stable at the
326/// same member index for the complete execution. `completion` and
327/// `target_iteration` are declarations inspected by Workflow; constructing a
328/// view has no side effects.
329#[derive(Clone, Copy, Debug)]
330pub struct MemberView<'a> {
331    identity: &'a str,
332    state: &'a SystemState,
333    completion: Option<MemberCompletion<'a>>,
334    target_iteration: Option<u64>,
335}
336
337impl<'a> MemberView<'a> {
338    /// Describes one member owned by an [`ExecutionUnit`].
339    ///
340    /// `identity` must be nonempty, contain no surrounding whitespace, and be
341    /// unique within the unit. `state` must remain at the same address and use
342    /// the schema supplied to [`ExecutionUnit::initialize`]. A target, when
343    /// present, must not precede the state's current iteration.
344    pub const fn new(
345        identity: &'a str,
346        state: &'a SystemState,
347        completion: Option<MemberCompletion<'a>>,
348        target_iteration: Option<u64>,
349    ) -> Self {
350        Self {
351            identity,
352            state,
353            completion,
354            target_iteration,
355        }
356    }
357
358    /// Returns the stable identity of this member within its execution unit.
359    pub const fn identity(self) -> &'a str {
360        self.identity
361    }
362
363    /// Borrows this member's directly owned canonical state.
364    pub const fn state(self) -> &'a SystemState {
365        self.state
366    }
367
368    /// Returns completion details, or `None` while the member is incomplete.
369    pub const fn completion(self) -> Option<MemberCompletion<'a>> {
370        self.completion
371    }
372
373    /// Returns this member's optional expected final iteration.
374    pub const fn target_iteration(self) -> Option<u64> {
375        self.target_iteration
376    }
377}
378
379/// One schedulable scientific execution containing one or more members.
380///
381/// Workflow manages every implementation through the same lifecycle and does
382/// not distinguish a standalone unit from a coordinated ensemble. A normal
383/// unit returns one [`MemberView`]; an ensemble returns one view per member and
384/// keeps all internal parallelism, shared inputs, and synchronization private.
385/// Each exposed member owns a distinct [`SystemState`]; Workflow rejects
386/// duplicate state addresses before beginning member recordings.
387///
388/// Member count, index order, identities, state owners, and schema allocations
389/// must remain stable after initialization. One successful [`Self::step`] must
390/// strictly advance at least one incomplete member and must never advance a
391/// member that was already complete. Other incomplete members may wait during a
392/// coordinated step, which permits synchronized ensembles and restored members
393/// at different iterations.
394pub trait ExecutionUnit: Send + Sized + 'static {
395    /// One complete set of constants supplied by Config.
396    type Constants: DeserializeOwned + 'static;
397
398    /// Declares whether changing Rayon worker counts between coordinated steps
399    /// preserves this unit's scientific result.
400    ///
401    /// Automatic compute allocation requires an explicit `true`; the default
402    /// keeps fixed-width numerical units out of dynamically rebalanced runs.
403    const THREAD_COUNT_INVARIANT: bool = false;
404
405    /// Returns the standard static schema supplied for this unit, if any.
406    ///
407    /// StudyPlan uses this provider only when the task omits an explicit project
408    /// `state`. The default requires callers to select a project schema. An
409    /// upstream provider owns the JSON document; this unit merely declares
410    /// that it can receive states using that standard layout.
411    fn standard_state_schema() -> Option<StateSchemaProvider> {
412        None
413    }
414
415    /// Validates unit-owned configuration and defines per-member observations.
416    ///
417    /// All members of one execution unit use the state schema selected by the
418    /// task and this common observation plan. The default records every field
419    /// at every iteration without additional validation. An override owns all
420    /// domain validation that can be performed before initialization; StudyPlan
421    /// trusts a successful result. This preflight operation must not create
422    /// output, initialize the unit, or mutate external state.
423    fn preflight(
424        _constants: &Self::Constants,
425        _schema: &SystemStateSchema,
426    ) -> UnitResult<ObservationPlan> {
427        Ok(ObservationPlan::all_fields())
428    }
429
430    /// Builds a fully initialized standalone unit or ensemble.
431    ///
432    /// Every state subsequently exposed through [`Self::member`] must have been
433    /// created from this exact schema allocation.
434    fn initialize(
435        constants: Self::Constants,
436        schema: &SystemStateSchema,
437        context: &InitializationContext,
438    ) -> UnitResult<Self>;
439
440    /// Returns the stable positive number of independently stateful members.
441    fn member_count(&self) -> usize;
442
443    /// Borrows one member by stable zero-based index.
444    ///
445    /// The method must be side-effect free. Workflow calls it repeatedly before
446    /// and after coordinated steps. An index below [`Self::member_count`] must
447    /// always return `Some`; all other indices must return `None`.
448    fn member(&self, index: usize) -> Option<MemberView<'_>>;
449
450    /// Performs one coordinated scientific transition.
451    ///
452    /// A standalone unit advances itself. An ensemble may advance members in
453    /// parallel or share generated inputs, but it must return only after the
454    /// complete logical step is visible through [`Self::member`].
455    fn step(&mut self) -> UnitResult;
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461
462    #[test]
463    fn named_seed_derivation_is_stable_and_request_order_independent() {
464        let first = InitializationContext::new(Some(99), 3, "phase/task", "ensemble");
465        let first_member = first.member_seed("alpha", "initialization").unwrap();
466        let first_shared = first.shared_seed("pairing").unwrap();
467        assert_eq!(first_member, 16_741_472_295_366_384_357);
468        assert_eq!(first_shared, 1_632_703_961_247_452_931);
469
470        let second = InitializationContext::new(Some(99), 3, "phase/task", "ensemble");
471        assert_eq!(second.shared_seed("pairing").unwrap(), first_shared);
472        assert_eq!(
473            second.member_seed("alpha", "initialization").unwrap(),
474            first_member
475        );
476        assert_ne!(
477            second.member_seed("beta", "initialization").unwrap(),
478            first_member
479        );
480
481        let next_replicate = InitializationContext::new(Some(99), 4, "phase/task", "ensemble");
482        assert_ne!(next_replicate.shared_seed("pairing").unwrap(), first_shared);
483    }
484
485    #[test]
486    fn explicit_group_streams_cross_task_boundaries_and_stay_replicate_scoped() {
487        let a = InitializationContext::new(Some(99), 3, "prepare/a", "a");
488        let b = InitializationContext::new(Some(99), 3, "run/b", "b");
489        assert_eq!(
490            a.group_seed("pair", "initial").unwrap(),
491            b.group_seed("pair", "initial").unwrap()
492        );
493        assert_ne!(
494            a.group_seed("pair", "initial").unwrap(),
495            a.group_seed("pair", "noise").unwrap()
496        );
497        let c = InitializationContext::new(Some(99), 4, "run/b", "b");
498        assert_ne!(
499            a.group_seed("pair", "initial").unwrap(),
500            c.group_seed("pair", "initial").unwrap()
501        );
502    }
503
504    #[test]
505    fn deterministic_units_need_no_master_seed_but_requests_do() {
506        let context = InitializationContext::new(None, 0, "task", "unit");
507        assert!(!context.has_master_seed());
508        assert!(matches!(
509            context.shared_seed("pairing"),
510            Err(SeedError::MissingMasterSeed)
511        ));
512        assert!(context.metadata_for_member("member").is_none());
513    }
514
515    #[test]
516    fn program_seed_derivation_uses_task_kind_purpose_and_replicate() {
517        let seed = derive_program_seed(99, 3, "phase/task", "program", "preparation");
518        assert_eq!(
519            derive_program_seed(99, 3, "phase/task", "program", "preparation"),
520            seed
521        );
522        assert_ne!(
523            derive_program_seed(99, 4, "phase/task", "program", "preparation"),
524            seed
525        );
526        assert_ne!(
527            derive_program_seed(99, 3, "phase/task", "python", "preparation"),
528            seed
529        );
530        assert_ne!(
531            derive_program_seed(99, 3, "phase/task", "program", "analysis"),
532            seed
533        );
534    }
535}