scientific_workflow/task/
unit.rs1use 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::{SystemState, SystemStateSchema};
13
14use super::result::TaskResult;
15
16const SEED_DERIVATION_ALGORITHM: &str = "scientific-workflow.seed.v1";
17
18pub 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 pub const fn has_master_seed(&self) -> bool {
51 self.master_seed.is_some()
52 }
53
54 pub fn shared_seed(&self, purpose: &str) -> Result<u64, SeedError> {
59 self.seed(SeedScope::Shared, purpose)
60 }
61
62 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#[derive(Debug, Error)]
191#[non_exhaustive]
192pub enum SeedError {
193 #[error("this execution unit requires `seed` in `wf_configs/study.json`")]
195 MissingMasterSeed,
196 #[error("invalid seed {field} `{value}`: it must be nonempty with no surrounding whitespace")]
198 InvalidName {
199 field: &'static str,
201 value: String,
203 },
204 #[error("seed requested for unknown member identity `{identity}`")]
206 UnknownMemberIdentity {
207 identity: String,
209 },
210}
211
212#[derive(Clone, Copy, Debug)]
218pub struct MemberCompletion<'a> {
219 reason: Option<&'a Map<String, Value>>,
220}
221
222impl<'a> MemberCompletion<'a> {
223 pub const fn without_reason() -> Self {
225 Self { reason: None }
226 }
227
228 pub const fn with_reason(reason: &'a Map<String, Value>) -> Self {
230 Self {
231 reason: Some(reason),
232 }
233 }
234
235 pub const fn reason(self) -> Option<&'a Map<String, Value>> {
237 self.reason
238 }
239}
240
241#[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 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 pub const fn identity(self) -> &'a str {
278 self.identity
279 }
280
281 pub const fn state(self) -> &'a SystemState {
283 self.state
284 }
285
286 pub const fn completion(self) -> Option<MemberCompletion<'a>> {
288 self.completion
289 }
290
291 pub const fn target_iteration(self) -> Option<u64> {
293 self.target_iteration
294 }
295}
296
297pub trait ExecutionUnit: Send + Sized + 'static {
312 type Constants: DeserializeOwned + 'static;
314
315 fn preflight(
324 _constants: &Self::Constants,
325 _schema: &SystemStateSchema,
326 ) -> TaskResult<ObservationPlan> {
327 Ok(ObservationPlan::all_fields())
328 }
329
330 fn initialize(
335 constants: Self::Constants,
336 schema: &SystemStateSchema,
337 context: &InitializationContext,
338 ) -> TaskResult<Self>;
339
340 fn member_count(&self) -> usize;
342
343 fn member(&self, index: usize) -> Option<MemberView<'_>>;
349
350 fn step(&mut self) -> TaskResult;
356}
357
358#[cfg(test)]
359mod tests {
360 use super::*;
361
362 #[test]
363 fn named_seed_derivation_is_stable_and_request_order_independent() {
364 let first = InitializationContext::new(Some(99), 3, "phase/task", "ensemble");
365 let first_member = first.member_seed("alpha", "initialization").unwrap();
366 let first_shared = first.shared_seed("pairing").unwrap();
367 assert_eq!(first_member, 16_741_472_295_366_384_357);
368 assert_eq!(first_shared, 1_632_703_961_247_452_931);
369
370 let second = InitializationContext::new(Some(99), 3, "phase/task", "ensemble");
371 assert_eq!(second.shared_seed("pairing").unwrap(), first_shared);
372 assert_eq!(
373 second.member_seed("alpha", "initialization").unwrap(),
374 first_member
375 );
376 assert_ne!(
377 second.member_seed("beta", "initialization").unwrap(),
378 first_member
379 );
380
381 let next_replicate = InitializationContext::new(Some(99), 4, "phase/task", "ensemble");
382 assert_ne!(next_replicate.shared_seed("pairing").unwrap(), first_shared);
383 }
384
385 #[test]
386 fn deterministic_units_need_no_master_seed_but_requests_do() {
387 let context = InitializationContext::new(None, 0, "task", "unit");
388 assert!(!context.has_master_seed());
389 assert!(matches!(
390 context.shared_seed("pairing"),
391 Err(SeedError::MissingMasterSeed)
392 ));
393 assert!(context.metadata_for_member("member").is_none());
394 }
395}