use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use serde::Deserialize;
use crate::runtime::{
PresentationFailure, RuntimeError, RuntimeEvent, RuntimeObserver, TaskRunKind, TaskRunSummary,
execute_with_observer,
};
use crate::state::{StateTime, SystemState, SystemStateSchema};
use crate::study::Study;
use crate::task::{ExecutionUnit, InitializationContext, MemberCompletion, MemberView, UnitResult};
use super::execution::task_exceeded_timeout;
static TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
pub(crate) fn execute(study: Study) -> Result<super::RunSummary, RuntimeError> {
execute_with_observer(study, || {
crate::ui::UiSession::testing().map_err(|error| Box::new(error) as _)
})
}
#[test]
fn disk_pause_before_admission_can_be_cancelled() {
use std::sync::{Arc, atomic::AtomicUsize};
struct Observer {
control: super::RunControl,
started: Arc<AtomicUsize>,
}
impl RuntimeObserver for Observer {
fn publish(&self, event: RuntimeEvent<'_>) -> Result<(), PresentationFailure> {
if matches!(event, RuntimeEvent::TaskStarted { .. }) {
self.started.fetch_add(1, Ordering::Relaxed);
}
Ok(())
}
fn control(&self) -> super::RunControl {
self.control.clone()
}
fn cancellation_requested(&self) -> Result<bool, PresentationFailure> {
Ok(self.control.disk_paused())
}
fn finish(&self) -> Result<(), PresentationFailure> {
Ok(())
}
}
let project = Project::new(
serde_json::json!({"disk":{"pause_at_percent":0.000001}, "phases":{"run":{"tasks":[{"program":"/bin/true"}]}}}),
serde_json::json!({}),
);
let started = Arc::new(AtomicUsize::new(0));
let error = execute_with_observer(Study::load(project.path()).unwrap(), || {
Ok(Observer {
control: super::RunControl::default(),
started: started.clone(),
})
})
.unwrap_err();
assert!(matches!(error, RuntimeError::ExecutionCancelled));
assert_eq!(started.load(Ordering::Relaxed), 0);
}
#[cfg(unix)]
#[test]
fn cleaning_run_replaces_previous_output_after_preflight() {
let project = Project::new(
serde_json::json!({"phases":{"run":{"tasks":[{"program":"/bin/true"}]}}}),
serde_json::json!({}),
);
let first = execute(Study::load(project.path()).unwrap()).unwrap();
let config = fs::read(project.path().join("wf_configs/study.json")).unwrap();
fs::create_dir_all(project.path().join("output/arbitrary/nested")).unwrap();
fs::write(project.path().join("output/arbitrary/nested/data"), "old").unwrap();
let second = super::execute_with_observer_options(
Study::load(project.path()).unwrap(),
|| crate::ui::UiSession::testing().map_err(|error| Box::new(error) as _),
true,
)
.unwrap();
assert!(!first.output_directory().exists());
assert!(!project.path().join("output/arbitrary").exists());
assert!(second.output_directory().is_dir());
assert_eq!(
fs::read_dir(project.path().join("output")).unwrap().count(),
1
);
assert_eq!(
fs::read(project.path().join("wf_configs/study.json")).unwrap(),
config
);
}
#[test]
#[cfg(unix)]
fn dashboard_startup_failure_preserves_existing_output_before_clean() {
let project = Project::new(
serde_json::json!({"phases":{"run":{"tasks":[{"program":"/bin/true"}]}}}),
serde_json::json!({}),
);
fs::create_dir(project.path().join("output")).unwrap();
let keep = project.path().join("output/keep");
fs::write(&keep, b"previous result").unwrap();
let result = super::execute_with_observer_options::<FailingObserver, _>(
Study::load(project.path()).unwrap(),
|| Err(std::io::Error::other("dashboard already owned").into()),
true,
);
assert!(matches!(result, Err(RuntimeError::Presentation { .. })));
assert_eq!(fs::read(&keep).unwrap(), b"previous result");
assert_eq!(
fs::read_dir(project.path().join("output")).unwrap().count(),
1
);
}
#[test]
#[cfg(unix)]
fn output_creation_failure_aborts_started_observer_without_waiting_for_exit() {
use std::sync::{Arc, atomic::AtomicBool};
struct Observer(Arc<AtomicBool>);
impl RuntimeObserver for Observer {
fn publish(&self, _: RuntimeEvent<'_>) -> Result<(), PresentationFailure> {
Ok(())
}
fn cancellation_requested(&self) -> Result<bool, PresentationFailure> {
Ok(false)
}
fn finish(&self) -> Result<(), PresentationFailure> {
panic!("startup failure must not wait for normal finish")
}
fn abort_startup(&self) -> Result<(), PresentationFailure> {
self.0.store(true, Ordering::Release);
Ok(())
}
}
let project = Project::new(
serde_json::json!({"phases":{"run":{"tasks":[{"program":"/bin/true"}]}}}),
serde_json::json!({}),
);
let aborted = Arc::new(AtomicBool::new(false));
let result = execute_with_observer(Study::load(project.path()).unwrap(), || {
fs::remove_dir(project.path().join("output")).unwrap();
fs::write(project.path().join("output"), b"blocked").unwrap();
Ok(Observer(aborted.clone()))
});
assert!(matches!(result, Err(RuntimeError::OutputScope { .. })));
assert!(aborted.load(Ordering::Acquire));
}
#[test]
#[ignore = "requires the installed coordinated Python 3.14+ companion with the npy extra"]
fn coordinated_npy_handoff_respects_phase_limits_and_worker_modes() {
for (threads, mode) in [(1, "fixed"), (2, "auto")] {
let mut study = execution_unit_study("runtime-ensemble", None);
study["seed"] = 42.into();
study["threads"] = 4.into();
study["phases"]["$npy"] =
serde_json::json!({"after":["run"], "threads":threads, "mode":mode});
let project = Project::new(study, serde_json::json!({"runtime-ensemble":{}}));
let summary = execute(Study::load(project.path()).unwrap()).unwrap();
let task = &summary.replicates()[0].phases()[1].tasks()[0];
let metadata: serde_json::Value = serde_json::from_slice(
&fs::read(task.output_directory().join("program.json")).unwrap(),
)
.unwrap();
assert_eq!(metadata["threads"], threads);
assert!(
metadata["args"]
.as_array()
.unwrap()
.contains(&serde_json::json!(format!("--worker-mode={mode}")))
);
let TaskRunKind::Npy {
processed_directory,
..
} = task.kind()
else {
panic!("expected NPY task")
};
let batch: serde_json::Value =
serde_json::from_slice(&fs::read(processed_directory.join("manifest.json")).unwrap())
.unwrap();
assert_eq!(batch["members"].as_array().unwrap().len(), 2);
}
}
#[test]
#[ignore = "requires the coordinated Python 3.14+ companion with the npy extra"]
fn npy_reuse_requires_current_v3_members_and_verified_array_bytes() {
use sha2::{Digest, Sha256};
let mut study = execution_unit_study("runtime-ensemble", None);
study["seed"] = 42.into();
study["phases"]["$npy"] = serde_json::json!({"after":["run"]});
study["phases"]["consume"] =
serde_json::json!({"after":["$npy"],"tasks":[{"program":"/bin/true"}]});
let project = Project::new(study, serde_json::json!({"runtime-ensemble":{}}));
let first = execute(Study::load(project.path()).unwrap()).unwrap();
let TaskRunKind::Npy {
processed_directory,
..
} = first.replicates()[0].phases()[1].tasks()[0].kind()
else {
panic!("expected NPY result")
};
select_phases(&project, &[2], Some(first.output_directory()));
let reused = execute(Study::load(project.path()).unwrap()).unwrap();
assert!(reused.replicates()[0].phases()[1].was_reused());
let batch_path = processed_directory.join("manifest.json");
let batch_bytes = fs::read(&batch_path).unwrap();
let mut batch: serde_json::Value = serde_json::from_slice(&batch_bytes).unwrap();
batch["format"] = "scientific-workflow-npy-batch.v2".into();
fs::write(&batch_path, serde_json::to_vec(&batch).unwrap()).unwrap();
assert!(matches!(
execute(Study::load(project.path()).unwrap()),
Err(RuntimeError::Reuse { .. })
));
fs::write(&batch_path, &batch_bytes).unwrap();
batch = serde_json::from_slice(&batch_bytes).unwrap();
let member_path = processed_directory.join(batch["members"][0]["manifest"].as_str().unwrap());
let member_bytes = fs::read(&member_path).unwrap();
let mut member: serde_json::Value = serde_json::from_slice(&member_bytes).unwrap();
member["format"] = "scientific-workflow-npy.v2".into();
let changed = serde_json::to_vec(&member).unwrap();
fs::write(&member_path, &changed).unwrap();
let checksum = Sha256::digest(&changed)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
batch["members"][0]["manifest_checksum"] = format!("sha256:{checksum}").into();
fs::write(&batch_path, serde_json::to_vec(&batch).unwrap()).unwrap();
assert!(matches!(
execute(Study::load(project.path()).unwrap()),
Err(RuntimeError::Reuse { .. })
));
fs::write(&member_path, &member_bytes).unwrap();
fs::write(&batch_path, &batch_bytes).unwrap();
member = serde_json::from_slice(&member_bytes).unwrap();
let array = member_path
.parent()
.unwrap()
.join(member["arrays"][0]["path"].as_str().unwrap());
fs::write(array, b"corrupted NPY array").unwrap();
assert!(matches!(
execute(Study::load(project.path()).unwrap()),
Err(RuntimeError::Reuse { .. })
));
assert_eq!(
fs::read_dir(project.path().join("output")).unwrap().count(),
2
);
}
struct Project(PathBuf);
impl Project {
fn new(mut study: serde_json::Value, parameters: serde_json::Value) -> Self {
study
.as_object_mut()
.expect("runtime test study is an object")
.entry("workflow_schema")
.or_insert(1.into());
study
.as_object_mut()
.expect("runtime test study is an object")
.entry("threads")
.or_insert(2.into());
study
.as_object_mut()
.expect("runtime test study is an object")
.entry("compute")
.or_insert_with(|| serde_json::json!({"mode": "auto"}));
let phase_count = study["phases"].as_object().unwrap().len();
study
.as_object_mut()
.unwrap()
.entry("active_phases")
.or_insert_with(|| serde_json::json!((0..phase_count).collect::<Vec<_>>()));
let sequence = TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed);
let root = std::env::temp_dir().join(format!(
"scientific-workflow-runtime-{}-{sequence}",
std::process::id()
));
fs::create_dir_all(root.join("wf_configs/states")).unwrap();
fs::write(
root.join("wf_configs/study.json"),
serde_json::to_vec_pretty(&study).unwrap(),
)
.unwrap();
fs::write(
root.join("wf_configs/parameters.json"),
serde_json::to_vec_pretty(¶meters).unwrap(),
)
.unwrap();
fs::write(
root.join("wf_configs/states/value.json"),
r#"{"fields":[{"name":"value"}]}"#,
)
.unwrap();
Self(root)
}
fn path(&self) -> &Path {
&self.0
}
fn execution_directory(&self) -> PathBuf {
let mut entries = fs::read_dir(self.path().join("output"))
.unwrap()
.map(|entry| entry.unwrap().path())
.collect::<Vec<_>>();
entries.sort();
assert_eq!(entries.len(), 1);
entries.pop().unwrap()
}
#[cfg(unix)]
fn write_executable(&self, name: &str, contents: &str) {
use std::os::unix::fs::PermissionsExt as _;
let path = self.path().join(name);
fs::write(&path, contents).unwrap();
fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
}
}
impl Drop for Project {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PanicConstants {}
struct PanicAfterBeginUnit {
state: SystemState,
}
#[scientific_workflow::execution_unit("runtime-panic-after-begin")]
impl ExecutionUnit for PanicAfterBeginUnit {
const THREAD_COUNT_INVARIANT: bool = true;
type Constants = PanicConstants;
fn initialize(
_constants: Self::Constants,
schema: &SystemStateSchema,
_context: &InitializationContext,
) -> UnitResult<Self> {
let mut state = schema.create_empty_state(StateTime::from_iteration(0));
state.initialize_payload("value", 0_u64)?;
Ok(Self { state })
}
fn member_count(&self) -> usize {
1
}
fn member(&self, index: usize) -> Option<MemberView<'_>> {
(index == 0).then(|| MemberView::new("panic", &self.state, None, None))
}
fn step(&mut self) -> UnitResult {
panic!("runtime panic sentinel")
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SlowConstants {
sleep_ms: u64,
}
struct SlowUnit {
state: SystemState,
sleep: Duration,
}
#[scientific_workflow::execution_unit("runtime-slow")]
impl ExecutionUnit for SlowUnit {
const THREAD_COUNT_INVARIANT: bool = true;
type Constants = SlowConstants;
fn initialize(
constants: Self::Constants,
schema: &SystemStateSchema,
_context: &InitializationContext,
) -> UnitResult<Self> {
let mut state = schema.create_empty_state(StateTime::from_iteration(0));
state.initialize_payload("value", 0_u64)?;
Ok(Self {
state,
sleep: Duration::from_millis(constants.sleep_ms),
})
}
fn member_count(&self) -> usize {
1
}
fn member(&self, index: usize) -> Option<MemberView<'_>> {
(index == 0).then(|| {
MemberView::new(
"slow",
&self.state,
(self.state.time().iteration() == 1).then_some(MemberCompletion::without_reason()),
Some(1),
)
})
}
fn step(&mut self) -> UnitResult {
std::thread::sleep(self.sleep);
*self.state.payload_mut::<u64>("value")? += 1;
self.state.advance_time(None)?;
Ok(())
}
}
struct RuntimeEnsemble {
states: Vec<SystemState>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ThreadPoolConstants {
expected_threads: usize,
}
struct ThreadPoolUnit {
state: SystemState,
expected_threads: usize,
}
#[scientific_workflow::execution_unit("runtime-thread-pool")]
impl ExecutionUnit for ThreadPoolUnit {
const THREAD_COUNT_INVARIANT: bool = true;
type Constants = ThreadPoolConstants;
fn initialize(
constants: Self::Constants,
schema: &SystemStateSchema,
_context: &InitializationContext,
) -> UnitResult<Self> {
ensure_thread_count(constants.expected_threads)?;
let mut state = schema.create_empty_state(StateTime::from_iteration(0));
state.initialize_payload("value", 0_u64)?;
Ok(Self {
state,
expected_threads: constants.expected_threads,
})
}
fn member_count(&self) -> usize {
1
}
fn member(&self, index: usize) -> Option<MemberView<'_>> {
(index == 0).then(|| {
MemberView::new(
"pool",
&self.state,
(self.state.time().iteration() == 1).then_some(MemberCompletion::without_reason()),
Some(1),
)
})
}
fn step(&mut self) -> UnitResult {
ensure_thread_count(self.expected_threads)?;
self.state.advance_time(None)?;
Ok(())
}
}
fn ensure_thread_count(expected: usize) -> UnitResult {
let actual = rayon::current_num_threads();
if actual == expected {
Ok(())
} else {
Err(std::io::Error::other(format!(
"expected {expected} Workflow compute threads, found {actual}"
))
.into())
}
}
#[scientific_workflow::execution_unit("runtime-ensemble")]
impl ExecutionUnit for RuntimeEnsemble {
const THREAD_COUNT_INVARIANT: bool = true;
type Constants = PanicConstants;
fn initialize(
_constants: Self::Constants,
schema: &SystemStateSchema,
context: &InitializationContext,
) -> UnitResult<Self> {
let _ = context.shared_seed("coordination")?;
let _ = context.member_seed("first", "initialization")?;
let _ = context.member_seed("second", "initialization")?;
let mut states = Vec::with_capacity(2);
for initial in [10_u64, 20] {
let mut state = schema.create_empty_state(StateTime::from_iteration(0));
state.initialize_payload("value", initial)?;
states.push(state);
}
Ok(Self { states })
}
fn member_count(&self) -> usize {
self.states.len()
}
fn member(&self, index: usize) -> Option<MemberView<'_>> {
let state = self.states.get(index)?;
Some(MemberView::new(
["first", "second"][index],
state,
(state.time().iteration() >= (index as u64 + 1))
.then_some(MemberCompletion::without_reason()),
Some(index as u64 + 1),
))
}
fn step(&mut self) -> UnitResult {
for (index, state) in self.states.iter_mut().enumerate() {
if state.time().iteration() < index as u64 + 1 {
*state.payload_mut::<u64>("value")? += 1;
state.advance_time(None)?;
}
}
Ok(())
}
}
fn execution_unit_study(execution_unit: &str, timeout_ms: Option<u64>) -> serde_json::Value {
let mut task = serde_json::json!({"execution_unit": execution_unit, "state": "value"});
if let Some(timeout_ms) = timeout_ms {
task["timeout_ms"] = timeout_ms.into();
}
serde_json::json!({
"paths": {"states": {"value": "wf_configs/states/value.json"}},
"phases": {"run": {"tasks": [task]}}
})
}
fn has_task_panic(error: &RuntimeError) -> bool {
match error {
RuntimeError::TaskPanicked { .. } => true,
RuntimeError::Replicate { source, .. } => has_task_panic(source),
_ => false,
}
}
fn has_task_timeout(error: &RuntimeError) -> bool {
match error {
RuntimeError::TaskTimedOut { .. } => true,
RuntimeError::Replicate { source, .. } => has_task_timeout(source),
_ => false,
}
}
fn has_phase_timeout(error: &RuntimeError) -> bool {
match error {
RuntimeError::PhaseTimedOut { .. } => true,
RuntimeError::Replicate { source, .. } => has_phase_timeout(source),
_ => false,
}
}
#[test]
fn runtime_public_results_are_send_and_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<RuntimeError>();
assert_send_sync::<TaskRunSummary>();
}
struct FailingObserver;
impl RuntimeObserver for FailingObserver {
fn publish(&self, _event: RuntimeEvent<'_>) -> Result<(), PresentationFailure> {
Err(std::io::Error::other("test presentation failure").into())
}
fn cancellation_requested(&self) -> Result<bool, PresentationFailure> {
Ok(false)
}
fn finish(&self) -> Result<(), PresentationFailure> {
Ok(())
}
}
#[test]
fn presentation_failures_return_through_the_runtime_error_boundary() {
let project = Project::new(
execution_unit_study("runtime-thread-pool", None),
serde_json::json!({"runtime-thread-pool": {"expected_threads": 2}}),
);
let error = execute_with_observer(Study::load(project.path()).unwrap(), || Ok(FailingObserver))
.unwrap_err();
assert!(matches!(
error,
RuntimeError::Presentation { source }
if source.to_string() == "test presentation failure"
));
}
#[test]
fn an_ensemble_task_persists_and_summarizes_each_member_independently() {
let mut study = execution_unit_study("runtime-ensemble", None);
study["seed"] = 42.into();
let project = Project::new(study, serde_json::json!({"runtime-ensemble": {}}));
let summary = execute(Study::load(project.path()).unwrap()).unwrap();
let task = &summary.replicates()[0].phases()[0].tasks()[0];
let TaskRunKind::ExecutionUnit { members, .. } = task.kind() else {
panic!("expected execution-unit summary");
};
assert_eq!(
members
.iter()
.map(|unit| (unit.identity(), unit.final_iteration()))
.collect::<Vec<_>>(),
[("first", 1), ("second", 2)]
);
for (index, unit) in members.iter().enumerate() {
assert!(
unit.output_directory()
.ends_with(format!("members/member-{index:06}"))
);
let metadata: serde_json::Value = serde_json::from_slice(
&fs::read(unit.output_directory().join("metadata.json")).unwrap(),
)
.unwrap();
assert_eq!(metadata["status"]["state"], "complete");
assert_eq!(metadata["user_metadata"]["workflow"]["member_index"], index);
assert_eq!(metadata["user_metadata"]["workflow"]["threads"], 2);
assert_eq!(
metadata["user_metadata"]["workflow"]["member_identity"],
unit.identity()
);
let derivation = &metadata["user_metadata"]["workflow"]["seed_derivation"];
assert_eq!(derivation["algorithm"], "scientific-workflow.seed.v1");
assert_eq!(derivation["master_seed"], 42);
assert_eq!(derivation["requests"].as_array().unwrap().len(), 2);
assert!(
derivation["requests"]
.as_array()
.unwrap()
.iter()
.any(|request| {
request["scope"] == "shared" && request["purpose"] == "coordination"
})
);
assert!(
derivation["requests"]
.as_array()
.unwrap()
.iter()
.any(|request| {
request["scope"] == "member"
&& request["member_identity"] == unit.identity()
&& request["purpose"] == "initialization"
})
);
}
}
#[test]
fn execution_units_run_inside_the_required_study_pool() {
let mut study = execution_unit_study("runtime-thread-pool", None);
study["threads"] = 3.into();
let project = Project::new(
study,
serde_json::json!({"runtime-thread-pool": {"expected_threads": 3}}),
);
let summary = execute(Study::load(project.path()).unwrap()).unwrap();
let TaskRunKind::ExecutionUnit { members, .. } =
summary.replicates()[0].phases()[0].tasks()[0].kind()
else {
panic!("expected execution-unit summary");
};
let metadata: serde_json::Value = serde_json::from_slice(
&fs::read(members[0].output_directory().join("metadata.json")).unwrap(),
)
.unwrap();
assert_eq!(
metadata["user_metadata"]["workflow"]["compute"]["mode"],
"auto"
);
assert_eq!(
metadata["terminal_metadata"]["compute"]["allocations"][0]["threads"],
3
);
{
let live_log = fs::read_to_string(summary.output_directory().join("log.txt")).unwrap();
assert!(live_log.contains("workflow: started"));
assert!(live_log.contains("workflow: completed"));
}
}
#[test]
fn isolated_execution_units_use_their_fixed_task_pool() {
let mut study = execution_unit_study("runtime-thread-pool", None);
study["threads"] = 4.into();
study["compute"] = serde_json::json!({"mode": "isolated"});
study["phases"]["run"]["tasks"][0]["resources"] = serde_json::json!({"threads": 2});
let project = Project::new(
study,
serde_json::json!({"runtime-thread-pool": {"expected_threads": 2}}),
);
execute(Study::load(project.path()).unwrap()).unwrap();
}
#[cfg(unix)]
#[test]
fn a_seeded_program_receives_only_its_derived_seed_and_persists_the_request() {
let project = Project::new(
serde_json::json!({
"seed": 42,
"phases": {"generate": {"tasks": [{
"program": "seeded-program.sh",
"seed": {"purpose": "target-initial-conditions"},
"resources": {"threads": 2}
}]}}
}),
serde_json::json!({}),
);
project.write_executable(
"seeded-program.sh",
"#!/bin/sh\nprintf '%s' \"$WORKFLOW_TASK_SEED\" > \"$WORKFLOW_TASK_OUTPUT/seed\"\nprintf '%s' \"$WORKFLOW_THREADS\" > \"$WORKFLOW_TASK_OUTPUT/threads\"\nprintf '%s' \"$RAYON_NUM_THREADS\" > \"$WORKFLOW_TASK_OUTPUT/rayon-threads\"\n",
);
let summary = execute(Study::load(project.path()).unwrap()).unwrap();
let output = summary.replicates()[0].phases()[0].tasks()[0].output_directory();
let delivered = fs::read_to_string(output.join("artifacts/seed")).unwrap();
let workflow_threads = fs::read_to_string(output.join("artifacts/threads")).unwrap();
let rayon_threads = fs::read_to_string(output.join("artifacts/rayon-threads")).unwrap();
let metadata: serde_json::Value =
serde_json::from_slice(&fs::read(output.join("program.json")).unwrap()).unwrap();
let request = &metadata["seed_derivation"]["requests"][0];
assert_eq!(
metadata["seed_derivation"]["algorithm"],
"scientific-workflow.seed.v1"
);
assert_eq!(metadata["seed_derivation"]["master_seed"], 42);
assert_eq!(request["scope"], "task");
assert_eq!(request["purpose"], "target-initial-conditions");
assert_eq!(delivered, request["seed"].as_u64().unwrap().to_string());
assert_ne!(delivered, "42");
assert_eq!(workflow_threads, "2");
assert_eq!(rayon_threads, "2");
assert_eq!(metadata["threads"], 2);
}
#[test]
fn completion_timestamp_controls_task_timeout_classification() {
let started = Instant::now();
let timeout = Duration::from_millis(20);
assert!(!task_exceeded_timeout(
started,
started + Duration::from_millis(19),
timeout
));
assert!(task_exceeded_timeout(started, started + timeout, timeout));
}
#[test]
fn inactive_execution_units_remain_planned_but_are_not_run() {
let mut declaration = execution_unit_study("runtime-slow", None);
declaration["phases"]["run"]["tasks"][0]["active"] = false.into();
let project = Project::new(
declaration,
serde_json::json!({"runtime-slow": {"sleep_ms": 0}}),
);
let study = Study::load(project.path()).unwrap();
let planned = study
.plan_summary()
.phases()
.next()
.unwrap()
.tasks()
.next()
.unwrap();
assert!(!planned.is_active());
assert_eq!(planned.output_ordinal(), 0);
let summary = execute(study).unwrap();
assert!(summary.replicates()[0].phases()[0].tasks().is_empty());
assert!(
!summary.replicates()[0]
.output_directory()
.join("task-000000")
.exists()
);
}
#[test]
fn a_panicking_unit_is_reported_and_its_active_recording_is_failed() {
let project = Project::new(
execution_unit_study("runtime-panic-after-begin", None),
serde_json::json!({"runtime-panic-after-begin": {}}),
);
let error = execute(Study::load(project.path()).unwrap()).unwrap_err();
assert!(has_task_panic(&error));
let metadata: serde_json::Value = serde_json::from_slice(
&fs::read(
project
.execution_directory()
.join("replicate-000000/task-000000/metadata.json"),
)
.unwrap(),
)
.unwrap();
assert_eq!(metadata["status"]["state"], "failed");
assert!(
metadata["status"]["message"]
.as_str()
.unwrap()
.contains("runtime panic sentinel")
);
}
#[test]
fn a_task_finishing_after_its_deadline_is_timed_out_and_not_completed() {
let project = Project::new(
execution_unit_study("runtime-slow", Some(20)),
serde_json::json!({"runtime-slow": {"sleep_ms": 80}}),
);
let error = execute(Study::load(project.path()).unwrap()).unwrap_err();
assert!(has_task_timeout(&error));
let metadata: serde_json::Value = serde_json::from_slice(
&fs::read(
project
.execution_directory()
.join("replicate-000000/task-000000/metadata.json"),
)
.unwrap(),
)
.unwrap();
assert_eq!(metadata["status"]["state"], "failed");
}
#[test]
fn a_phase_finishing_after_its_deadline_is_timed_out_and_not_completed() {
let mut study = execution_unit_study("runtime-slow", None);
study["phases"]["run"]["timeout_ms"] = 20.into();
let project = Project::new(study, serde_json::json!({"runtime-slow": {"sleep_ms": 80}}));
let error = execute(Study::load(project.path()).unwrap()).unwrap_err();
assert!(has_phase_timeout(&error));
let metadata: serde_json::Value = serde_json::from_slice(
&fs::read(
project
.execution_directory()
.join("replicate-000000/task-000000/metadata.json"),
)
.unwrap(),
)
.unwrap();
assert_eq!(metadata["status"]["state"], "failed");
}
#[cfg(unix)]
fn replicate_program_project(failure_policy: &str, sibling_sleep: u64) -> Project {
let project = Project::new(
serde_json::json!({
"threads": 3,
"paths": {"states": {}},
"replicates": {
"count": 3,
"scheduling": "parallel",
"failure_policy": failure_policy
},
"phases": {"run": {"tasks": [{"program": "replicate-worker.sh"}]}}
}),
serde_json::json!({}),
);
project.write_executable(
"replicate-worker.sh",
format!(
"#!/bin/sh\ncase \"$WORKFLOW_REPLICATE_ROOT\" in\n *replicate-000000) exit 9 ;;\n *) sleep {sibling_sleep}; printf done > \"$WORKFLOW_TASK_OUTPUT/done\" ;;\nesac\n"
)
.as_str(),
);
project
}
#[cfg(unix)]
#[test]
fn parallel_replicate_fail_fast_cancels_siblings_on_first_observed_failure() {
let project = replicate_program_project("fail_fast", 3);
let started = Instant::now();
let error = execute(Study::load(project.path()).unwrap()).unwrap_err();
assert!(matches!(error, RuntimeError::Replicate { index: 0, .. }));
assert!(started.elapsed() < Duration::from_secs(2));
let execution = project.execution_directory();
for index in 1..=2 {
assert!(
!execution
.join(format!("replicate-{index:06}/task-000000/artifacts/done"))
.exists()
);
}
}
#[cfg(unix)]
#[test]
fn parallel_replicate_finish_all_allows_successful_siblings_to_finish() {
let project = replicate_program_project("finish_all", 0);
let error = execute(Study::load(project.path()).unwrap()).unwrap_err();
assert!(matches!(error, RuntimeError::Replicate { index: 0, .. }));
let execution = project.execution_directory();
for index in 1..=2 {
assert!(
execution
.join(format!("replicate-{index:06}/task-000000/artifacts/done"))
.is_file()
);
}
}
#[cfg(unix)]
fn phase_program_project(failure_policy: &str, sibling_sleep: u64) -> Project {
let project = Project::new(
serde_json::json!({
"paths": {"states": {}},
"phases": {"run": {
"tasks": [
{"program": "phase-fail.sh"},
{"program": "phase-sibling.sh"}
],
"max_concurrency": 2,
"failure_policy": failure_policy
}}
}),
serde_json::json!({}),
);
project.write_executable("phase-fail.sh", "#!/bin/sh\nexit 7\n");
project.write_executable(
"phase-sibling.sh",
format!("#!/bin/sh\nsleep {sibling_sleep}\nprintf done > \"$WORKFLOW_TASK_OUTPUT/done\"\n")
.as_str(),
);
project
}
#[cfg(unix)]
#[test]
fn phase_fail_fast_cancels_an_active_sibling() {
let project = phase_program_project("fail_fast", 3);
let started = Instant::now();
execute(Study::load(project.path()).unwrap()).unwrap_err();
assert!(started.elapsed() < Duration::from_secs(2));
assert!(
!project
.execution_directory()
.join("replicate-000000/task-000001/artifacts/done")
.exists()
);
}
#[cfg(unix)]
#[test]
fn phase_finish_all_allows_an_active_sibling_to_finish() {
let project = phase_program_project("finish_all", 0);
execute(Study::load(project.path()).unwrap()).unwrap_err();
assert!(
project
.execution_directory()
.join("replicate-000000/task-000001/artifacts/done")
.is_file()
);
}
#[cfg(unix)]
fn timing_program_project(scheduling: &str) -> Project {
let project = Project::new(
serde_json::json!({
"paths": {"states": {}},
"replicates": {"count": 2, "scheduling": scheduling},
"phases": {"run": {"tasks": [{"program": "timed.sh"}]}}
}),
serde_json::json!({}),
);
project.write_executable(
"timed.sh",
r#"#!/bin/sh
replicate=$(basename "$WORKFLOW_REPLICATE_ROOT")
: > "$WORKFLOW_PROJECT_ROOT/${replicate}.start"
sleep 0.2
: > "$WORKFLOW_PROJECT_ROOT/${replicate}.end"
"#,
);
project
}
#[cfg(unix)]
fn timing_ranges(path: &Path, prefix: &str) -> Vec<(std::time::SystemTime, std::time::SystemTime)> {
let mut ranges = std::collections::BTreeMap::<
String,
(Option<std::time::SystemTime>, Option<std::time::SystemTime>),
>::new();
for entry in fs::read_dir(path).unwrap() {
let entry = entry.unwrap();
let name = entry.file_name().into_string().unwrap();
let (subject, position) = if let Some(subject) = name.strip_suffix(".start") {
(subject, 0)
} else if let Some(subject) = name.strip_suffix(".end") {
(subject, 1)
} else {
continue;
};
if !subject.starts_with(prefix) {
continue;
}
let modified = entry.metadata().unwrap().modified().unwrap();
let range = ranges.entry(subject.to_owned()).or_default();
if position == 0 {
range.0 = Some(modified);
} else {
range.1 = Some(modified);
}
}
ranges
.into_values()
.map(|(start, end)| (start.unwrap(), end.unwrap()))
.collect()
}
#[cfg(unix)]
#[test]
fn sequential_and_parallel_replicate_policies_have_distinct_admission() {
let sequential = timing_program_project("sequential");
let sequential_summary = execute(Study::load(sequential.path()).unwrap()).unwrap();
assert_eq!(
sequential_summary
.replicates()
.iter()
.map(|replicate| replicate.index())
.collect::<Vec<_>>(),
[0, 1]
);
let sequential_ranges = timing_ranges(sequential.path(), "replicate-");
assert!(sequential_ranges[1].0 >= sequential_ranges[0].1);
let parallel = timing_program_project("parallel");
let parallel_summary = execute(Study::load(parallel.path()).unwrap()).unwrap();
assert_eq!(
parallel_summary
.replicates()
.iter()
.map(|replicate| replicate.index())
.collect::<Vec<_>>(),
[0, 1]
);
let parallel_ranges = timing_ranges(parallel.path(), "replicate-");
let latest_start = parallel_ranges.iter().map(|range| range.0).max().unwrap();
let earliest_end = parallel_ranges.iter().map(|range| range.1).min().unwrap();
assert!(latest_start < earliest_end);
}
#[cfg(unix)]
#[test]
fn external_thread_requests_share_one_budget_across_parallel_replicates() {
let project = Project::new(
serde_json::json!({
"threads": 2,
"replicates": {"count": 2, "scheduling": "parallel"},
"phases": {"run": {"tasks": [{
"program": "timed.sh",
"resources": {"threads": 2}
}]}}
}),
serde_json::json!({}),
);
project.write_executable(
"timed.sh",
r#"#!/bin/sh
replicate=$(basename "$WORKFLOW_REPLICATE_ROOT")
: > "$WORKFLOW_PROJECT_ROOT/${replicate}.start"
sleep 0.2
: > "$WORKFLOW_PROJECT_ROOT/${replicate}.end"
"#,
);
execute(Study::load(project.path()).unwrap()).unwrap();
let ranges = timing_ranges(project.path(), "replicate-");
let latest_start = ranges.iter().map(|range| range.0).max().unwrap();
let earliest_end = ranges.iter().map(|range| range.1).min().unwrap();
assert!(latest_start >= earliest_end);
}
#[cfg(unix)]
#[test]
fn phase_concurrency_respects_start_interval_and_summary_order() {
use std::sync::{Arc, Mutex};
struct AdmissionObserver(Arc<Mutex<Vec<Instant>>>);
impl RuntimeObserver for AdmissionObserver {
fn publish(&self, event: RuntimeEvent<'_>) -> Result<(), PresentationFailure> {
if matches!(event, RuntimeEvent::TaskStarted { .. }) {
self.0.lock().unwrap().push(Instant::now());
}
Ok(())
}
fn cancellation_requested(&self) -> Result<bool, PresentationFailure> {
Ok(false)
}
fn finish(&self) -> Result<(), PresentationFailure> {
Ok(())
}
}
let admissions = Arc::new(Mutex::new(Vec::new()));
let observer_admissions = Arc::clone(&admissions);
let project = Project::new(
serde_json::json!({
"threads": 3,
"paths": {"states": {}},
"phases": {"run": {
"tasks": [
{"program": "phase-timed.sh"},
{"program": "phase-timed.sh"},
{"program": "phase-timed.sh"}
],
"max_concurrency": 3,
"start_interval_ms": 60
}}
}),
serde_json::json!({}),
);
project.write_executable(
"phase-timed.sh",
r#"#!/bin/sh
task=$(basename "$(dirname "$WORKFLOW_TASK_OUTPUT")")
: > "$WORKFLOW_PROJECT_ROOT/${task}.start"
sleep 0.25
: > "$WORKFLOW_PROJECT_ROOT/${task}.end"
"#,
);
let summary = execute_with_observer(Study::load(project.path()).unwrap(), || {
Ok(AdmissionObserver(observer_admissions))
})
.unwrap();
let tasks = summary.replicates()[0].phases()[0].tasks();
assert_eq!(tasks.len(), 3);
assert!(tasks[0].output_directory().ends_with("task-000000"));
assert!(tasks[1].output_directory().ends_with("task-000001"));
assert!(tasks[2].output_directory().ends_with("task-000002"));
let ranges = timing_ranges(project.path(), "task-");
let admissions = admissions.lock().unwrap();
assert_eq!(admissions.len(), 3);
assert!(
admissions
.windows(2)
.all(|pair| pair[1].duration_since(pair[0]) >= Duration::from_millis(60))
);
assert!(ranges[2].0 < ranges[0].1);
}
#[test]
fn pause_freezes_task_and_phase_timeouts_and_start_precedes_progress() {
use std::sync::{Arc, Mutex};
const DEADLINE_MS: u64 = 1000;
const PAUSE: Duration = Duration::from_millis(1200);
struct Observer {
control: crate::runtime::RunControl,
events: Arc<Mutex<Vec<&'static str>>>,
}
impl RuntimeObserver for Observer {
fn control(&self) -> crate::runtime::RunControl {
self.control.clone()
}
fn publish(&self, event: RuntimeEvent<'_>) -> Result<(), PresentationFailure> {
match event {
RuntimeEvent::TaskStarted { .. } => {
self.events.lock().unwrap().push("started");
self.control.pause(true);
let control = self.control.clone();
std::thread::spawn(move || {
std::thread::sleep(PAUSE);
control.pause(false);
});
}
RuntimeEvent::TaskProgress { .. } => {
let mut events = self.events.lock().unwrap();
assert_eq!(events.first(), Some(&"started"));
events.push("progress");
}
_ => {}
}
Ok(())
}
fn cancellation_requested(&self) -> Result<bool, PresentationFailure> {
Ok(false)
}
fn finish(&self) -> Result<(), PresentationFailure> {
Ok(())
}
}
let mut declaration = execution_unit_study("runtime-slow", Some(DEADLINE_MS));
declaration["phases"]["run"]["timeout_ms"] = DEADLINE_MS.into();
let project = Project::new(
declaration,
serde_json::json!({"runtime-slow":{"sleep_ms":5}}),
);
let events = Arc::new(Mutex::new(Vec::new()));
let observed = events.clone();
let started = Instant::now();
execute_with_observer(Study::load(project.path()).unwrap(), || {
Ok(Observer {
control: Default::default(),
events,
})
})
.unwrap();
assert!(started.elapsed() >= PAUSE);
assert!(observed.lock().unwrap().contains(&"progress"));
}
#[test]
#[cfg(unix)]
fn program_diagnostics_are_live_and_raw_logs_are_preserved() {
use std::sync::{Arc, Mutex};
struct Observer(Arc<Mutex<Vec<String>>>);
impl RuntimeObserver for Observer {
fn publish(&self, event: RuntimeEvent<'_>) -> Result<(), PresentationFailure> {
match event {
RuntimeEvent::ProgramLog { message, .. } => {
self.0.lock().unwrap().push(message.into())
}
RuntimeEvent::TaskCompleted { .. } => {
self.0.lock().unwrap().push("TASK COMPLETE".into())
}
_ => {}
}
Ok(())
}
fn cancellation_requested(&self) -> Result<bool, PresentationFailure> {
Ok(false)
}
fn finish(&self) -> Result<(), PresentationFailure> {
Ok(())
}
}
let project = Project::new(
serde_json::json!({"phases":{"run":{"tasks":[{"program":"diagnostics.sh"}]}}}),
serde_json::json!({}),
);
project.write_executable("diagnostics.sh", "#!/bin/sh\nprintf 'stdout sentinel\\n'\nprintf '%s\\n' '@workflow {\"version\":1,\"kind\":\"log\",\"level\":\"warning\",\"message\":\"live sentinel\"}' >&2\nprintf '%s\\n' '@workflow malformed' >&2\nsleep 0.05\n");
let events = Arc::new(Mutex::new(Vec::new()));
let observed = events.clone();
let summary = execute_with_observer(Study::load(project.path()).unwrap(), || {
Ok(Observer(events))
})
.unwrap();
let task = &summary.replicates()[0].phases()[0].tasks()[0];
assert_eq!(
fs::read_to_string(task.output_directory().join("stdout.log")).unwrap(),
"stdout sentinel\n"
);
let stderr = fs::read_to_string(task.output_directory().join("stderr.log")).unwrap();
assert!(stderr.contains("@workflow malformed"));
let events = observed.lock().unwrap();
assert_eq!(events.first().map(String::as_str), Some("live sentinel"));
assert_eq!(events.last().map(String::as_str), Some("TASK COMPLETE"));
assert!(events.iter().any(|e| e.contains("malformed")));
}
#[test]
#[cfg(target_os = "linux")]
fn timeout_stops_a_programs_descendant_process() {
let project = Project::new(
serde_json::json!({"phases":{"run":{"tasks":[{"program":"descendant.sh", "timeout_ms":100}]}}}),
serde_json::json!({}),
);
project.write_executable(
"descendant.sh",
"#!/bin/sh\nsleep 30 &\necho $! > descendant.pid\nwait\n",
);
let error = execute(Study::load(project.path()).unwrap()).unwrap_err();
assert!(has_task_timeout(&error));
let pid = fs::read_to_string(
project
.execution_directory()
.join("replicate-000000/task-000000/artifacts/descendant.pid"),
)
.unwrap();
let status = PathBuf::from(format!("/proc/{}/status", pid.trim()));
let deadline = Instant::now() + Duration::from_secs(1);
loop {
match fs::read_to_string(&status) {
Err(_) => break,
Ok(text)
if text
.lines()
.any(|line| line.starts_with("State:") && line.contains('Z')) =>
{
break;
}
_ if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(5)),
_ => panic!("descendant remains alive: {}", pid.trim()),
}
}
}
fn select_phases(project: &Project, active: &[usize], source: Option<&Path>) {
let path = project.path().join("wf_configs/study.json");
let mut study: serde_json::Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
study["active_phases"] = serde_json::json!(active);
if let Some(source) = source {
study["reuse_from"] = serde_json::json!(source);
} else {
study.as_object_mut().unwrap().remove("reuse_from");
}
fs::write(path, serde_json::to_vec_pretty(&study).unwrap()).unwrap();
}
#[test]
#[cfg(unix)]
fn phase_indices_use_dependency_order_and_reuse_preserves_task_identity_and_paths() {
let project = Project::new(
serde_json::json!({
"active_phases": [0],
"phases": {
"consume": {"after":["prepare"], "tasks":[{"program":"/bin/true"}]},
"prepare": {"tasks":[{"program":"/bin/sh", "args":["-c",
"printf ran >> \"$WORKFLOW_PROJECT_ROOT/starts\"; printf ready > \"$WORKFLOW_TASK_OUTPUT/value\""
]}]}
}
}),
serde_json::json!({}),
);
let study = Study::load(project.path()).unwrap();
let planned = study
.plan_summary()
.phases()
.map(|phase| {
(
phase.index(),
phase.name().to_owned(),
phase.is_active(),
phase.tasks().next().unwrap().identity().to_owned(),
)
})
.collect::<Vec<_>>();
assert_eq!(
(planned[0].0, planned[0].1.as_str(), planned[0].2),
(0, "prepare", true)
);
assert_eq!(
(planned[1].0, planned[1].1.as_str(), planned[1].2),
(1, "consume", false)
);
let first = execute(study).unwrap();
let original = first.replicates()[0].phases()[0].tasks()[0]
.output_directory()
.to_path_buf();
select_phases(&project, &[1], Some(first.output_directory()));
let second = execute(Study::load(project.path()).unwrap()).unwrap();
let reused = &second.replicates()[0].phases()[0];
assert!(reused.was_reused());
assert_eq!(reused.tasks()[0].identity(), planned[0].3);
assert_eq!(reused.tasks()[0].output_directory(), original);
assert!(!second.replicates()[0].phases()[1].was_reused());
assert_eq!(
fs::read_to_string(project.path().join("starts")).unwrap(),
"ran"
);
assert_eq!(
fs::read_to_string(original.join("artifacts/value")).unwrap(),
"ready"
);
select_phases(&project, &[1], Some(second.output_directory()));
let third = execute(Study::load(project.path()).unwrap()).unwrap();
assert_eq!(
third.replicates()[0].phases()[0].tasks()[0].output_directory(),
original
);
assert_eq!(
fs::read_to_string(project.path().join("starts")).unwrap(),
"ran"
);
}
#[test]
#[cfg(unix)]
fn reuse_rejects_missing_failed_or_changed_inputs_before_creating_output() {
let project = Project::new(
serde_json::json!({
"active_phases":[1],
"phases":{
"prepare":{"tasks":[{"program":"/bin/true"}]},
"consume":{"after":["prepare"],"tasks":[{"program":"/bin/true"}]}
}
}),
serde_json::json!({"input":1}),
);
assert!(matches!(
execute(Study::load(project.path()).unwrap()),
Err(RuntimeError::Reuse { .. })
));
assert!(!project.path().join("output").exists());
select_phases(&project, &[0], None);
let first = execute(Study::load(project.path()).unwrap()).unwrap();
select_phases(&project, &[1], Some(first.output_directory()));
fs::write(
project.path().join("wf_configs/parameters.json"),
br#"{"input":2}"#,
)
.unwrap();
assert!(matches!(
execute(Study::load(project.path()).unwrap()),
Err(RuntimeError::Reuse { .. })
));
fs::write(
project.path().join("wf_configs/parameters.json"),
br#"{"input":1}"#,
)
.unwrap();
let metadata = first.replicates()[0].phases()[0].tasks()[0]
.output_directory()
.join("program.json");
let mut value: serde_json::Value =
serde_json::from_slice(&fs::read(&metadata).unwrap()).unwrap();
value["status"] = "failed".into();
fs::write(metadata, serde_json::to_vec(&value).unwrap()).unwrap();
assert!(matches!(
execute(Study::load(project.path()).unwrap()),
Err(RuntimeError::Reuse { .. })
));
assert_eq!(
fs::read_dir(project.path().join("output")).unwrap().count(),
1
);
}
#[test]
#[cfg(unix)]
fn reuse_requires_current_receipts_even_when_legacy_summaries_exist() {
let project = Project::new(
serde_json::json!({
"paths":{"states":{"value":"wf_configs/states/value.json"}},
"phases":{
"simulate":{"tasks":[{"execution_unit":"runtime-slow","state":"value"}]},
"consume":{"after":["simulate"],"tasks":[{"program":"/bin/true"}]}
}
}),
serde_json::json!({"runtime-slow":{"sleep_ms":0}}),
);
let first = execute(Study::load(project.path()).unwrap()).unwrap();
let task = &first.replicates()[0].phases()[0].tasks()[0];
let receipt = task.output_directory().join("workflow-result.json");
let original = fs::read(&receipt).unwrap();
select_phases(&project, &[1], Some(first.output_directory()));
for mode in 0..3 {
if mode < 2 {
let mut value: serde_json::Value = serde_json::from_slice(&original).unwrap();
if mode == 0 {
value["format"] = "scientific-workflow-task-result.v1".into();
} else {
value["inputs"]["config"]
.as_object_mut()
.unwrap()
.remove("checksum");
}
fs::write(&receipt, serde_json::to_vec(&value).unwrap()).unwrap();
} else {
fs::remove_file(&receipt).unwrap();
}
assert!(matches!(
execute(Study::load(project.path()).unwrap()),
Err(RuntimeError::Reuse { .. })
));
assert_eq!(
fs::read_dir(project.path().join("output")).unwrap().count(),
1
);
}
}
#[test]
#[cfg(unix)]
fn reuse_rejects_modified_stored_inputs_for_program_and_execution_unit_tasks() {
for unit in [false, true] {
let producer = if unit {
serde_json::json!({"execution_unit":"runtime-slow","state":"value"})
} else {
serde_json::json!({"program":"/bin/true"})
};
let project = Project::new(
serde_json::json!({
"paths":{"states":{"value":"wf_configs/states/value.json"}},
"phases":{
"prepare":{"tasks":[producer]},
"consume":{"after":["prepare"],"tasks":[{"program":"/bin/true"}]}
}
}),
serde_json::json!({"runtime-slow":{"sleep_ms":0}}),
);
let first = execute(Study::load(project.path()).unwrap()).unwrap();
let output = first.replicates()[0].phases()[0].tasks()[0].output_directory();
select_phases(&project, &[1], Some(first.output_directory()));
for file in ["workflow-config.json", "workflow-dependencies.json"] {
let path = output.join(file);
let original = fs::read(&path).unwrap();
let mut changed = original.clone();
changed.push(b' '); fs::write(&path, changed).unwrap();
assert!(matches!(
execute(Study::load(project.path()).unwrap()),
Err(RuntimeError::Reuse { .. })
));
assert!(
crate::task::project::parameters_from_snapshot::<serde_json::Value>(
&output.join("workflow-config.json"),
None
)
.is_err()
);
assert!(
crate::task::dependencies::Dependencies::load(
&output.join("workflow-dependencies.json")
)
.is_err()
);
assert_eq!(
fs::read_dir(project.path().join("output")).unwrap().count(),
1
);
fs::write(&path, original).unwrap();
}
}
}
#[test]
#[cfg(unix)]
fn reuse_rejects_a_changed_resolved_executable_even_with_the_same_command_name() {
use std::os::unix::fs::symlink;
let project = Project::new(
serde_json::json!({"phases":{
"prepare":{"tasks":[{"program":"producer"}]},
"consume":{"after":["prepare"],"tasks":[{"program":"/bin/true"}]}
}}),
serde_json::json!({}),
);
for (name, executable) in [("a", "/bin/true"), ("b", "/bin/false")] {
fs::create_dir(project.path().join(name)).unwrap();
fs::copy(executable, project.path().join(name).join("producer")).unwrap();
}
let link = project.path().join("producer");
symlink(project.path().join("a/producer"), &link).unwrap();
let first = execute(Study::load(project.path()).unwrap()).unwrap();
fs::remove_file(&link).unwrap();
symlink(project.path().join("b/producer"), &link).unwrap();
select_phases(&project, &[1], Some(first.output_directory()));
let error = execute(Study::load(project.path()).unwrap()).unwrap_err();
assert!(error.to_string().contains("resolved executable differs"));
assert_eq!(
fs::read_dir(project.path().join("output")).unwrap().count(),
1
);
}
#[test]
#[cfg(unix)]
fn python_reuse_ignores_launcher_changes_but_rejects_changed_resolved_scientific_scripts() {
use std::os::unix::fs::symlink;
let project = Project::new(
serde_json::json!({"phases":{
"prepare":{"tasks":[{"python":{"script":"producer.py","environment":{"manager":"system","executable":"/bin/true"}}}]},
"consume":{"after":["prepare"],"tasks":[{"program":"/bin/true"}]}
}}),
serde_json::json!({}),
);
for name in ["a", "b"] {
fs::create_dir(project.path().join(name)).unwrap();
fs::write(
project.path().join(name).join("producer.py"),
b"# scientific entry point\n",
)
.unwrap();
}
let link = project.path().join("producer.py");
symlink(project.path().join("a/producer.py"), &link).unwrap();
let first = execute(Study::load(project.path()).unwrap()).unwrap();
select_phases(&project, &[1], Some(first.output_directory()));
let manifest = project.path().join("wf_configs/study.json");
let mut value: serde_json::Value =
serde_json::from_slice(&fs::read(&manifest).unwrap()).unwrap();
value["phases"]["prepare"]["tasks"][0]["python"]["environment"]["executable"] =
"/bin/false".into();
fs::write(&manifest, serde_json::to_vec(&value).unwrap()).unwrap();
assert!(execute(Study::load(project.path()).unwrap()).is_ok());
fs::remove_file(&link).unwrap();
symlink(project.path().join("b/producer.py"), &link).unwrap();
let error = execute(Study::load(project.path()).unwrap()).unwrap_err();
assert!(
error
.to_string()
.contains("resolved scientific script differs")
);
assert_eq!(
fs::read_dir(project.path().join("output")).unwrap().count(),
2
);
}
#[test]
#[cfg(unix)]
fn reuse_cannot_mix_stale_results_with_rerun_prerequisites() {
let project = Project::new(
serde_json::json!({
"phases":{
"a":{"tasks":[{"program":"/bin/true"}]},
"b":{"after":["a"],"tasks":[{"program":"/bin/true"}]},
"c":{"after":["b"],"tasks":[{"program":"/bin/true"}]}
}
}),
serde_json::json!({}),
);
let first = execute(Study::load(project.path()).unwrap()).unwrap();
select_phases(&project, &[0, 2], Some(first.output_directory()));
assert!(matches!(
execute(Study::load(project.path()).unwrap()),
Err(RuntimeError::Reuse { .. })
));
assert_eq!(
fs::read_dir(project.path().join("output")).unwrap().count(),
1
);
}