1use 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
18pub 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 pub const fn dependencies(&self) -> &Value {
70 &self.dependencies
71 }
72
73 pub const fn has_master_seed(&self) -> bool {
75 self.master_seed.is_some()
76 }
77
78 pub fn shared_seed(&self, purpose: &str) -> Result<u64, SeedError> {
83 self.seed(SeedScope::Shared, purpose)
84 }
85
86 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#[derive(Debug, Error)]
250#[non_exhaustive]
251pub enum SeedError {
252 #[error("this execution unit requires `seed` in `wf_configs/study.json`")]
254 MissingMasterSeed,
255 #[error("invalid seed {field} `{value}`: it must be nonempty with no surrounding whitespace")]
257 InvalidName {
258 field: &'static str,
260 value: String,
262 },
263 #[error("seed requested for unknown member identity `{identity}`")]
265 UnknownMemberIdentity {
266 identity: String,
268 },
269}
270
271#[derive(Clone, Copy, Debug)]
277pub struct MemberCompletion<'a> {
278 reason: Option<&'a Map<String, Value>>,
279}
280
281impl<'a> MemberCompletion<'a> {
282 pub const fn without_reason() -> Self {
284 Self { reason: None }
285 }
286
287 pub const fn with_reason(reason: &'a Map<String, Value>) -> Self {
289 Self {
290 reason: Some(reason),
291 }
292 }
293
294 pub const fn reason(self) -> Option<&'a Map<String, Value>> {
296 self.reason
297 }
298}
299
300#[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 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 pub const fn identity(self) -> &'a str {
337 self.identity
338 }
339
340 pub const fn state(self) -> &'a SystemState {
342 self.state
343 }
344
345 pub const fn completion(self) -> Option<MemberCompletion<'a>> {
347 self.completion
348 }
349
350 pub const fn target_iteration(self) -> Option<u64> {
352 self.target_iteration
353 }
354}
355
356pub trait ExecutionUnit: Send + Sized + 'static {
371 type Constants: DeserializeOwned + 'static;
373
374 fn standard_state_schema() -> Option<StateSchemaProvider> {
381 None
382 }
383
384 fn preflight(
393 _constants: &Self::Constants,
394 _schema: &SystemStateSchema,
395 ) -> UnitResult<ObservationPlan> {
396 Ok(ObservationPlan::all_fields())
397 }
398
399 fn initialize(
404 constants: Self::Constants,
405 schema: &SystemStateSchema,
406 context: &InitializationContext,
407 ) -> UnitResult<Self>;
408
409 fn member_count(&self) -> usize;
411
412 fn member(&self, index: usize) -> Option<MemberView<'_>>;
418
419 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}