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