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