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