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::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: super::dependencies::Dependencies,
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: super::dependencies::Dependencies::from_json(dependencies)
64 .expect("Runtime supplies a validated dependency snapshot"),
65 requests: Mutex::new(BTreeMap::new()),
66 }
67 }
68
69 pub const fn dependencies(&self) -> &super::dependencies::Dependencies {
71 &self.dependencies
72 }
73
74 pub fn input(&self, name: &str) -> std::io::Result<crate::artifact::ArtifactSet> {
76 super::context::captured_input(name)
77 }
78
79 pub const fn has_master_seed(&self) -> bool {
81 self.master_seed.is_some()
82 }
83
84 pub fn shared_seed(&self, purpose: &str) -> Result<u64, SeedError> {
89 self.seed(SeedScope::Shared, purpose)
90 }
91
92 pub fn member_seed(&self, member_identity: &str, purpose: &str) -> Result<u64, SeedError> {
99 validate_name(member_identity, "member identity")?;
100 self.seed(SeedScope::Member(member_identity.into()), purpose)
101 }
102
103 pub fn group_seed(&self, group: &str, purpose: &str) -> Result<u64, SeedError> {
106 validate_name(group, "group")?;
107 self.seed(SeedScope::Group(group.into()), purpose)
108 }
109
110 fn seed(&self, scope: SeedScope, purpose: &str) -> Result<u64, SeedError> {
111 validate_name(purpose, "purpose")?;
112 let master_seed = self.master_seed.ok_or(SeedError::MissingMasterSeed)?;
113 let request = SeedRequest {
114 scope,
115 purpose: purpose.into(),
116 };
117 if let Some(seed) = self.request_ledger().get(&request) {
118 return Ok(*seed);
119 }
120
121 let seed = derive_seed(
122 master_seed,
123 self.replicate_ordinal,
124 &self.task_identity,
125 &self.execution_unit_key,
126 &request.scope,
127 &request.purpose,
128 );
129 self.request_ledger().insert(request, seed);
130 Ok(seed)
131 }
132
133 pub(crate) fn validate_member_identities<'a>(
134 &self,
135 identities: impl IntoIterator<Item = &'a str>,
136 ) -> Result<(), SeedError> {
137 let identities = identities.into_iter().collect::<BTreeSet<_>>();
138 for request in self.request_ledger().keys() {
139 if let SeedScope::Member(identity) = &request.scope
140 && !identities.contains(identity.as_ref())
141 {
142 return Err(SeedError::UnknownMemberIdentity {
143 identity: identity.to_string(),
144 });
145 }
146 }
147 Ok(())
148 }
149
150 pub(crate) fn metadata_for_member(&self, member_identity: &str) -> Option<Value> {
151 let requests = self
152 .request_ledger()
153 .iter()
154 .filter_map(|(request, seed)| match &request.scope {
155 SeedScope::Group(group) => Some(serde_json::json!({"scope":"study_group","group":group,"purpose":request.purpose,"seed":seed})),
156 SeedScope::Shared => Some(Value::Object(Map::from_iter([
157 ("scope".to_owned(), "shared".into()),
158 ("purpose".to_owned(), request.purpose.to_string().into()),
159 ("seed".to_owned(), (*seed).into()),
160 ]))),
161 SeedScope::Member(identity) if identity.as_ref() == member_identity => {
162 Some(Value::Object(Map::from_iter([
163 ("scope".to_owned(), "member".into()),
164 ("member_identity".to_owned(), identity.to_string().into()),
165 ("purpose".to_owned(), request.purpose.to_string().into()),
166 ("seed".to_owned(), (*seed).into()),
167 ])))
168 }
169 SeedScope::Member(_) => None,
170 })
171 .collect::<Vec<_>>();
172 (!requests.is_empty()).then(|| {
173 Value::Object(Map::from_iter([
174 ("algorithm".to_owned(), SEED_DERIVATION_ALGORITHM.into()),
175 (
176 "master_seed".to_owned(),
177 self.master_seed
178 .expect("a recorded request has a seed")
179 .into(),
180 ),
181 ("requests".to_owned(), requests.into()),
182 ]))
183 })
184 }
185
186 fn request_ledger(&self) -> MutexGuard<'_, BTreeMap<SeedRequest, u64>> {
187 self.requests
188 .lock()
189 .unwrap_or_else(|error| error.into_inner())
190 }
191}
192
193pub(crate) fn derive_program_seed(
194 master_seed: u64,
195 replicate_ordinal: u64,
196 task_identity: &str,
197 program_kind: &str,
198 purpose: &str,
199) -> u64 {
200 derive_seed(
201 master_seed,
202 replicate_ordinal,
203 task_identity,
204 program_kind,
205 &SeedScope::Shared,
206 purpose,
207 )
208}
209
210fn derive_seed(
211 master_seed: u64,
212 replicate_ordinal: u64,
213 task_identity: &str,
214 workload_key: &str,
215 scope: &SeedScope,
216 purpose: &str,
217) -> u64 {
218 let mut digest = Sha256::new();
219 hash_part(&mut digest, SEED_DERIVATION_ALGORITHM.as_bytes());
220 digest.update(master_seed.to_le_bytes());
221 digest.update(replicate_ordinal.to_le_bytes());
222 if matches!(scope, SeedScope::Group(_)) {
223 hash_part(&mut digest, b"study-shared-group");
224 } else {
225 hash_part(&mut digest, task_identity.as_bytes());
226 hash_part(&mut digest, workload_key.as_bytes());
227 }
228 match scope {
229 SeedScope::Group(group) => {
230 digest.update([2]);
231 hash_part(&mut digest, group.as_bytes());
232 }
233 SeedScope::Shared => digest.update([0]),
234 SeedScope::Member(identity) => {
235 digest.update([1]);
236 hash_part(&mut digest, identity.as_bytes());
237 }
238 }
239 hash_part(&mut digest, purpose.as_bytes());
240 u64::from_le_bytes(digest.finalize()[..8].try_into().expect("SHA-256 prefix"))
241}
242
243fn hash_part(digest: &mut Sha256, bytes: &[u8]) {
244 digest.update((bytes.len() as u64).to_le_bytes());
245 digest.update(bytes);
246}
247
248fn validate_name(value: &str, field: &'static str) -> Result<(), SeedError> {
249 if value.is_empty() || value.trim() != value {
250 return Err(SeedError::InvalidName {
251 field,
252 value: value.to_owned(),
253 });
254 }
255 Ok(())
256}
257
258#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
259struct SeedRequest {
260 scope: SeedScope,
261 purpose: Box<str>,
262}
263
264#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
265enum SeedScope {
266 Group(Box<str>),
267 Shared,
268 Member(Box<str>),
269}
270
271#[derive(Debug, Error)]
273#[non_exhaustive]
274pub enum SeedError {
275 #[error("this execution unit requires `seed` in `wf_configs/study.json`")]
277 MissingMasterSeed,
278 #[error("invalid seed {field} `{value}`: it must be nonempty with no surrounding whitespace")]
280 InvalidName {
281 field: &'static str,
283 value: String,
285 },
286 #[error("seed requested for unknown member identity `{identity}`")]
288 UnknownMemberIdentity {
289 identity: String,
291 },
292}
293
294#[derive(Clone, Copy, Debug)]
300pub struct MemberCompletion<'a> {
301 reason: Option<&'a Map<String, Value>>,
302}
303
304impl<'a> MemberCompletion<'a> {
305 pub const fn without_reason() -> Self {
307 Self { reason: None }
308 }
309
310 pub const fn with_reason(reason: &'a Map<String, Value>) -> Self {
312 Self {
313 reason: Some(reason),
314 }
315 }
316
317 pub const fn reason(self) -> Option<&'a Map<String, Value>> {
319 self.reason
320 }
321}
322
323#[derive(Clone, Copy, Debug)]
330pub struct MemberView<'a> {
331 identity: &'a str,
332 state: &'a SystemState,
333 completion: Option<MemberCompletion<'a>>,
334 target_iteration: Option<u64>,
335}
336
337impl<'a> MemberView<'a> {
338 pub const fn new(
345 identity: &'a str,
346 state: &'a SystemState,
347 completion: Option<MemberCompletion<'a>>,
348 target_iteration: Option<u64>,
349 ) -> Self {
350 Self {
351 identity,
352 state,
353 completion,
354 target_iteration,
355 }
356 }
357
358 pub const fn identity(self) -> &'a str {
360 self.identity
361 }
362
363 pub const fn state(self) -> &'a SystemState {
365 self.state
366 }
367
368 pub const fn completion(self) -> Option<MemberCompletion<'a>> {
370 self.completion
371 }
372
373 pub const fn target_iteration(self) -> Option<u64> {
375 self.target_iteration
376 }
377}
378
379pub trait ExecutionUnit: Send + Sized + 'static {
395 type Constants: DeserializeOwned + 'static;
397
398 const THREAD_COUNT_INVARIANT: bool = false;
404
405 fn standard_state_schema() -> Option<StateSchemaProvider> {
412 None
413 }
414
415 fn preflight(
424 _constants: &Self::Constants,
425 _schema: &SystemStateSchema,
426 ) -> UnitResult<ObservationPlan> {
427 Ok(ObservationPlan::all_fields())
428 }
429
430 fn initialize(
435 constants: Self::Constants,
436 schema: &SystemStateSchema,
437 context: &InitializationContext,
438 ) -> UnitResult<Self>;
439
440 fn member_count(&self) -> usize;
442
443 fn member(&self, index: usize) -> Option<MemberView<'_>>;
449
450 fn step(&mut self) -> UnitResult;
456}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
461
462 #[test]
463 fn named_seed_derivation_is_stable_and_request_order_independent() {
464 let first = InitializationContext::new(Some(99), 3, "phase/task", "ensemble");
465 let first_member = first.member_seed("alpha", "initialization").unwrap();
466 let first_shared = first.shared_seed("pairing").unwrap();
467 assert_eq!(first_member, 16_741_472_295_366_384_357);
468 assert_eq!(first_shared, 1_632_703_961_247_452_931);
469
470 let second = InitializationContext::new(Some(99), 3, "phase/task", "ensemble");
471 assert_eq!(second.shared_seed("pairing").unwrap(), first_shared);
472 assert_eq!(
473 second.member_seed("alpha", "initialization").unwrap(),
474 first_member
475 );
476 assert_ne!(
477 second.member_seed("beta", "initialization").unwrap(),
478 first_member
479 );
480
481 let next_replicate = InitializationContext::new(Some(99), 4, "phase/task", "ensemble");
482 assert_ne!(next_replicate.shared_seed("pairing").unwrap(), first_shared);
483 }
484
485 #[test]
486 fn explicit_group_streams_cross_task_boundaries_and_stay_replicate_scoped() {
487 let a = InitializationContext::new(Some(99), 3, "prepare/a", "a");
488 let b = InitializationContext::new(Some(99), 3, "run/b", "b");
489 assert_eq!(
490 a.group_seed("pair", "initial").unwrap(),
491 b.group_seed("pair", "initial").unwrap()
492 );
493 assert_ne!(
494 a.group_seed("pair", "initial").unwrap(),
495 a.group_seed("pair", "noise").unwrap()
496 );
497 let c = InitializationContext::new(Some(99), 4, "run/b", "b");
498 assert_ne!(
499 a.group_seed("pair", "initial").unwrap(),
500 c.group_seed("pair", "initial").unwrap()
501 );
502 }
503
504 #[test]
505 fn deterministic_units_need_no_master_seed_but_requests_do() {
506 let context = InitializationContext::new(None, 0, "task", "unit");
507 assert!(!context.has_master_seed());
508 assert!(matches!(
509 context.shared_seed("pairing"),
510 Err(SeedError::MissingMasterSeed)
511 ));
512 assert!(context.metadata_for_member("member").is_none());
513 }
514
515 #[test]
516 fn program_seed_derivation_uses_task_kind_purpose_and_replicate() {
517 let seed = derive_program_seed(99, 3, "phase/task", "program", "preparation");
518 assert_eq!(
519 derive_program_seed(99, 3, "phase/task", "program", "preparation"),
520 seed
521 );
522 assert_ne!(
523 derive_program_seed(99, 4, "phase/task", "program", "preparation"),
524 seed
525 );
526 assert_ne!(
527 derive_program_seed(99, 3, "phase/task", "python", "preparation"),
528 seed
529 );
530 assert_ne!(
531 derive_program_seed(99, 3, "phase/task", "program", "analysis"),
532 seed
533 );
534 }
535}