Skip to main content

scientific_workflow/engine/
launch.rs

1use crate::protocol::{Outcome, Status};
2use crate::{
3    WorkflowError,
4    artifact::{ArtifactRole, RunManifest, StorageLocation},
5    storage::{Store, atomic_json, run_id},
6    study::StudyPlan,
7    workspace::WorkspaceLease,
8};
9use serde::{Deserialize, Serialize};
10use std::{
11    io,
12    path::{Path, PathBuf},
13    process::{Command, Stdio},
14    time::{Duration, Instant},
15};
16/// Durable identity and local socket of an independent engine process.
17#[derive(Clone, Debug, Serialize, Deserialize)]
18pub struct RunHandle {
19    /// UTC run namespace at the destination.
20    pub run_id: String,
21    /// Unix socket for all live status and controls.
22    pub socket: PathBuf,
23    /// External local workspace, containing the recovery journal.
24    pub workspace: PathBuf,
25    /// Host binding for safe cleanup of disposable local copies.
26    pub host_id: String,
27    /// Authored input folder; execution leaves it unchanged.
28    pub input: PathBuf,
29    /// Authoritative destination; contains credential profile references only.
30    pub storage: StorageLocation,
31}
32impl RunHandle {
33    /// Connects to a live engine without owning its lifecycle.
34    pub fn client(&self) -> io::Result<crate::client::RunClient> {
35        crate::client::RunClient::connect(&self.socket)
36    }
37    /// Waits for a terminal outcome; a stale running snapshot never implies success.
38    pub fn wait(&self) -> io::Result<Status> {
39        match self.client().and_then(|c| c.wait()) {
40            Ok(status) => Ok(status),
41            Err(error) => {
42                let status: Status = Store::open(&self.storage)?
43                    .json(&format!("{}/records/status.json", self.run_id))?;
44                if status.outcome.terminal() {
45                    Ok(status)
46                } else {
47                    Err(error)
48                }
49            }
50        }
51    }
52}
53#[derive(Serialize, Deserialize)]
54pub(super) struct LaunchSpec {
55    pub handle: RunHandle,
56    pub input: PathBuf,
57    pub manifest: RunManifest,
58    pub max_bytes: u64,
59    pub path: std::ffi::OsString,
60}
61pub(crate) fn start(input: &Path) -> Result<RunHandle, WorkflowError> {
62    start_mode(input, false)
63}
64pub(super) fn start_mode(input: &Path, capture_only: bool) -> Result<RunHandle, WorkflowError> {
65    let input = input.canonicalize()?;
66    if input.join("campaign.json").is_file() {
67        let campaign = crate::campaign::CampaignPlan::load(&input)?;
68        campaign.check()?;
69        let software = campaign
70            .declaration
71            .studies
72            .iter()
73            .map(|m| {
74                if m.runner.is_absolute() {
75                    m.runner.clone()
76                } else {
77                    input.join(&m.runner)
78                }
79            })
80            .collect::<Vec<_>>();
81        return start_prepared(
82            &input,
83            campaign.settings,
84            software,
85            Vec::new(),
86            Default::default(),
87            None,
88            "campaign",
89            capture_only,
90        );
91    }
92    let study = StudyPlan::load(&input)?;
93    crate::runtime::check_prerequisites(&study)?;
94    let settings = study.runtime_settings().clone();
95    let verification = study
96        .verification()
97        .map(|v| v.resolve(&input))
98        .transpose()
99        .map_err(crate::study::StudyError::from)?;
100    let mut software = study
101        .phases()
102        .iter()
103        .flat_map(|p| p.tasks())
104        .flat_map(|t| [t.program_path(), t.python_script()].into_iter().flatten())
105        .map(Path::to_path_buf)
106        .collect::<Vec<_>>();
107    if let Some(program) = &verification {
108        software.push(program.program().to_path_buf());
109        if let Some(script) = program.python_script() {
110            software.push(script.to_path_buf());
111        }
112    }
113    let mut python = study
114        .phases()
115        .iter()
116        .flat_map(|p| p.tasks())
117        .filter_map(|t| t.program_declaration())
118        .filter(|p| p.capture_key().is_some())
119        .cloned()
120        .collect::<Vec<_>>();
121    if let Some(program) = verification
122        && program.capture_key().is_some()
123    {
124        python.push(program);
125    }
126    start_prepared(
127        &input,
128        settings,
129        software,
130        python,
131        study.reproduction().clone(),
132        Some(study),
133        "study",
134        capture_only,
135    )
136}
137fn collision_id(id: &str) -> String {
138    let (base, sequence) = id.split_once('-').map_or((id, 0), |(base, sequence)| {
139        (base, sequence.parse::<u64>().unwrap_or(0))
140    });
141    format!("{base}-{:04}", sequence + 1)
142}
143// A reserved run must remain discoverable even when capture or launch fails.
144struct StartupRecord {
145    store: Store,
146    root: PathBuf,
147    manifest: RunManifest,
148    armed: bool,
149}
150impl Drop for StartupRecord {
151    fn drop(&mut self) {
152        if !self.armed {
153            return;
154        }
155        if std::fs::File::open(self.root.join("records/status.json"))
156            .ok()
157            .and_then(|f| serde_json::from_reader::<_, Status>(f).ok())
158            .is_some_and(|s| s.outcome.terminal())
159        {
160            return;
161        }
162        self.manifest.outcome = Outcome::Failed;
163        let status = Status {
164            version: crate::protocol::VERSION,
165            run_id: self.manifest.run_id.clone(),
166            sequence: 0,
167            updated_at: crate::storage::utc_now(),
168            pid: std::process::id(),
169            outcome: Outcome::Failed,
170            pause_reason: None,
171            control: "finished".into(),
172            study: None,
173            tasks: Default::default(),
174            allocations: serde_json::json!({}),
175            message: Some(
176                "capture or engine startup failed; inspect the launch error and retained workspace"
177                    .into(),
178            ),
179            wall_ms: 0,
180            active_ms: 0,
181        };
182        let _ = atomic_json(&self.root.join("records/status.json"), &status);
183        let _ = self.store.put_json(
184            &format!("{}/records/status.json", self.manifest.run_id),
185            &status,
186            &self.root,
187            false,
188        );
189        let _ = self.store.put_json(
190            &format!("{}/manifest.json", self.manifest.run_id),
191            &self.manifest,
192            &self.root,
193            false,
194        );
195        let _ = crate::registry::index_manifest(&self.store, &self.manifest, &self.root);
196    }
197}
198#[allow(clippy::too_many_arguments)]
199fn start_prepared(
200    input: &Path,
201    settings: crate::config::RuntimeSettings,
202    software: Vec<PathBuf>,
203    python: Vec<crate::config::ResolvedProgramTask>,
204    reproduction: crate::config::ReproductionSpecification,
205    expected: Option<StudyPlan>,
206    kind: &str,
207    capture_only: bool,
208) -> Result<RunHandle, WorkflowError> {
209    let store = Store::open(&settings.storage)?;
210    let mut id = run_id();
211    let mut lease;
212    loop {
213        lease = match WorkspaceLease::create(&settings.workspace.root, &id) {
214            Ok(lease) => lease,
215            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
216                id = collision_id(&id);
217                continue;
218            }
219            Err(error) => return Err(error.into()),
220        };
221        let marker = serde_json::json!({"format":"scientific-workflow-reservation.v1","run_id":id});
222        match store.put_json(
223            &format!("{id}/reservation.json"),
224            &marker,
225            &lease.root,
226            true,
227        ) {
228            Ok(()) => break,
229            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
230                id = collision_id(&id);
231            }
232            Err(e) => return Err(e.into()),
233        }
234    }
235    let root = lease.root.clone();
236    let initial = RunManifest {
237        format: "scientific-workflow-run.v1".into(),
238        run_id: id.clone(),
239        kind: kind.into(),
240        scientific_identity: crate::artifact::digest_bytes(b""),
241        artifacts: Default::default(),
242        capture_complete: false,
243        outcome: Outcome::Starting,
244        removed: Vec::new(),
245    };
246    let mut startup = StartupRecord {
247        store: store.clone(),
248        root: root.clone(),
249        manifest: initial,
250        armed: true,
251    };
252    store.put_json(
253        &format!("{id}/manifest.json"),
254        &startup.manifest,
255        &root,
256        false,
257    )?;
258
259    let _budget = crate::workspace::CaptureBudget::new(&root, settings.workspace.max_bytes.get())?;
260    let captured = root.join("inputs");
261    std::fs::create_dir(&captured)?;
262    let mut artifacts = Default::default();
263    crate::provenance::capture_tree(&store, input, "inputs", Some(&captured), &mut artifacts)?;
264    if let Some(expected) = expected {
265        expected
266            .verify_capture(&captured)
267            .map_err(crate::study::StudyError::from)?;
268    }
269    crate::workspace::check_capacity()?;
270    if crate::workspace::bytes(&root)? > settings.workspace.max_bytes.get() {
271        return Err(io::Error::other("captured input exceeds workspace budget").into());
272    }
273    let executable = std::env::current_exe()?.canonicalize()?;
274    let runner = root.join("reproduction/software/runner");
275    crate::provenance::capture_file(
276        &store,
277        &executable,
278        "reproduction/software/runner",
279        Some(&runner),
280        &mut artifacts,
281        ArtifactRole::Reproduction,
282    )?;
283    crate::provenance::capture_libraries(&store, &executable, &root, &mut artifacts)?;
284    let mut python_bindings = std::collections::BTreeMap::new();
285    for program in python {
286        if let Some(key) = program.capture_key()
287            && python_bindings.contains_key(key)
288        {
289            continue;
290        }
291        if let Some((key, value)) =
292            crate::provenance::capture_python(&store, &program, &root, &mut artifacts)?
293        {
294            python_bindings.insert(key, value);
295        }
296    }
297    let mut bindings = std::collections::BTreeMap::new();
298    let numerical = crate::provenance::capture_environment(&reproduction.environment)?;
299    let mut input_bindings = std::collections::BTreeMap::new();
300    for (name, source) in reproduction.inputs {
301        crate::artifact::validate_key(&name)?;
302        let key = format!("reproduction/external-inputs/{name}");
303        if let Some(locator) = settings.input_bindings.get(&name) {
304            let selected = locator.open()?;
305            for reference in selected.references() {
306                let relative = reference
307                    .key
308                    .strip_prefix(&locator.prefix)
309                    .ok_or_else(|| io::Error::other("input reference escapes its selection"))?;
310                let target = format!("{key}{relative}");
311                let copied = store.copy_reference(
312                    &target,
313                    selected.reader(relative.trim_start_matches('/'))?,
314                    reference,
315                    ArtifactRole::Reproduction,
316                )?;
317                artifacts.insert(target, copied);
318            }
319        } else {
320            let source = if source.is_absolute() {
321                source
322            } else {
323                input.join(source)
324            }
325            .canonicalize()?;
326            if source.is_dir() {
327                crate::provenance::capture_tree(&store, &source, &key, None, &mut artifacts)?;
328            } else {
329                crate::provenance::capture_file(
330                    &store,
331                    &source,
332                    &key,
333                    None,
334                    &mut artifacts,
335                    ArtifactRole::Reproduction,
336                )?;
337            }
338        }
339        input_bindings.insert(
340            name,
341            crate::artifact::ArtifactLocator {
342                storage: settings.storage.clone(),
343                run_id: id.clone(),
344                prefix: key,
345            },
346        );
347    }
348    for (i, source) in reproduction.software.into_iter().enumerate() {
349        let source = if source.is_absolute() {
350            source
351        } else {
352            input.join(source)
353        }
354        .canonicalize()?;
355        let key = format!(
356            "reproduction/software/declared-{i}/{}",
357            source
358                .file_name()
359                .ok_or_else(|| io::Error::other("software source requires a file or folder name"))?
360                .to_string_lossy()
361        );
362        let target = root.join(&key);
363        if source.is_dir() {
364            crate::provenance::capture_software_tree(
365                &store,
366                &source,
367                &key,
368                &target,
369                &mut artifacts,
370            )?;
371        } else {
372            crate::provenance::capture_file(
373                &store,
374                &source,
375                &key,
376                Some(&target),
377                &mut artifacts,
378                ArtifactRole::Reproduction,
379            )?;
380            crate::provenance::capture_libraries(&store, &source, &root, &mut artifacts)?;
381        }
382        bindings.insert(source, target);
383    }
384    for source in software {
385        let source = source.canonicalize()?;
386        if source
387            .strip_prefix(input)
388            .is_ok_and(|p| captured.join(p).is_file())
389        {
390            continue;
391        }
392        crate::provenance::capture_libraries(&store, &source, &root, &mut artifacts)?;
393        let digest = crate::artifact::digest_reader(std::fs::File::open(&source)?)?.0;
394        let key = format!(
395            "reproduction/software/{digest}/{}",
396            source.file_name().unwrap().to_string_lossy()
397        );
398        let local = root.join(&key);
399        if let std::collections::btree_map::Entry::Vacant(entry) = bindings.entry(source.clone()) {
400            crate::provenance::capture_file(
401                &store,
402                &source,
403                &key,
404                Some(&local),
405                &mut artifacts,
406                ArtifactRole::Reproduction,
407            )?;
408            entry.insert(local);
409        }
410    }
411    // Retain exact authored inputs; a separate execution view binds external software.
412    let effective = root.join("execution-input");
413    std::fs::create_dir(&effective)?;
414    copy_tree(&captured, &effective)?;
415    let runtime_path = effective.join(if kind == "campaign" {
416        "runtime.json"
417    } else {
418        "wf_configs/runtime.json"
419    });
420    let mut runtime: serde_json::Value =
421        serde_json::from_reader(std::fs::File::open(&runtime_path)?)?;
422    if kind == "study" {
423        runtime["input_bindings"] = serde_json::to_value(&input_bindings)?;
424    }
425    if let Some(environment) = python_bindings.get("standard-npy") {
426        let mut environment = environment.clone();
427        environment.as_object_mut().unwrap().remove("manager");
428        runtime["npy_environment"] = environment;
429    }
430    runtime["workspace"]["root"] = root.join("work").to_string_lossy().into_owned().into();
431    atomic_json(&runtime_path, &runtime)?;
432    if kind == "study" {
433        let path = effective.join("wf_configs/study.json");
434        let mut study: serde_json::Value = serde_json::from_reader(std::fs::File::open(&path)?)?;
435        if let Some(phases) = study["phases"].as_object_mut() {
436            for phase in phases.values_mut() {
437                if let Some(tasks) = phase
438                    .get_mut("tasks")
439                    .and_then(serde_json::Value::as_array_mut)
440                {
441                    for task in tasks {
442                        if let Some(python) = task.get_mut("python") {
443                            let key = crate::config::python_capture_key(python.clone())
444                                .map_err(crate::study::StudyError::from)?;
445                            if let Some(environment) = python_bindings.get(&key) {
446                                python["environment"] = environment.clone();
447                            }
448                        }
449                    }
450                }
451            }
452        }
453        if let Some(python) = study.pointer_mut("/verification/python") {
454            let key = crate::config::python_capture_key(python.clone())
455                .map_err(crate::study::StudyError::from)?;
456            if let Some(environment) = python_bindings.get(&key) {
457                python["environment"] = environment.clone();
458            }
459        }
460        atomic_json(&path, &study)?;
461    }
462    rewrite_paths(
463        &effective.join(if kind == "campaign" {
464            "campaign.json"
465        } else {
466            "wf_configs/study.json"
467        }),
468        &bindings,
469        input,
470        &effective,
471    )?;
472    for file in ["wf_configs/parameters.json", "wf_configs/study.json"] {
473        let path = effective.join(file);
474        if path.exists() {
475            rewrite_paths(&path, &bindings, input, &effective)?;
476        }
477    }
478    crate::provenance::capture_tree(
479        &store,
480        &effective,
481        "reproduction/effective-inputs",
482        None,
483        &mut artifacts,
484    )?;
485    let numerical_path = root.join("reproduction/environment/numerical.json");
486    atomic_json(&numerical_path, &numerical)?;
487    crate::provenance::capture_file(
488        &store,
489        &numerical_path,
490        "reproduction/environment/numerical.json",
491        None,
492        &mut artifacts,
493        ArtifactRole::Reproduction,
494    )?;
495    let environment = serde_json::json!({"os":std::env::consts::OS,"arch":std::env::consts::ARCH,"runner_sha256":crate::artifact::digest_reader(std::fs::File::open(&runner)?)?.0,"software_bindings":bindings,"seed_algorithm":"scientific-workflow.seed.v1"});
496    let environment_path = root.join("reproduction/environment/manifest.json");
497    atomic_json(&environment_path, &environment)?;
498    crate::provenance::capture_file(
499        &store,
500        &environment_path,
501        "reproduction/environment/manifest.json",
502        None,
503        &mut artifacts,
504        ArtifactRole::Reproduction,
505    )?;
506    if kind == "campaign" {
507        super::campaign::capture_members(
508            &store,
509            &root,
510            &effective,
511            &settings.storage,
512            &mut artifacts,
513        )?;
514        if crate::workspace::bytes(&root)? > settings.workspace.max_bytes.get() {
515            return Err(
516                io::Error::other("campaign capture exceeds its explicit workspace budget").into(),
517            );
518        }
519    }
520    let science = artifacts
521        .iter()
522        .filter(|(key, _)| {
523            !key.ends_with("runtime.json")
524                && (!key.starts_with("reproduction/environment/")
525                    || *key == "reproduction/environment/numerical.json")
526                && !key.starts_with("reproduction/effective-inputs/")
527        })
528        .map(|(k, r)| (k.clone(), r.sha256.clone()))
529        .collect::<std::collections::BTreeMap<_, _>>();
530    let scientific_identity = crate::artifact::digest_bytes(&serde_json::to_vec(&science)?);
531    let manifest = RunManifest {
532        format: "scientific-workflow-run.v1".into(),
533        run_id: id.clone(),
534        kind: kind.into(),
535        scientific_identity,
536        artifacts,
537        capture_complete: true,
538        outcome: Outcome::Starting,
539        removed: Vec::new(),
540    };
541    startup.manifest = manifest.clone();
542    store.put_json(&format!("{id}/manifest.json"), &manifest, &root, false)?;
543    crate::registry::index_manifest(&store, &manifest, &root)?;
544    let mut socket = root.join("engine.sock");
545    if socket.as_os_str().len() > 100 {
546        // Campaign workspaces are nested; Unix socket endpoints have a much
547        // shorter platform limit than ordinary paths.
548        let socket_root =
549            std::env::temp_dir().join(format!("workflow-sockets-{}", unsafe { libc::geteuid() }));
550        std::fs::create_dir_all(&socket_root)?;
551        use std::os::unix::fs::{MetadataExt, PermissionsExt};
552        let metadata = std::fs::symlink_metadata(&socket_root)?;
553        if metadata.file_type().is_symlink() || metadata.uid() != unsafe { libc::geteuid() } {
554            return Err(
555                io::Error::other("socket directory must be owned by the current user").into(),
556            );
557        }
558        std::fs::set_permissions(&socket_root, std::fs::Permissions::from_mode(0o700))?;
559        socket = socket_root.join(format!("{id}.sock"));
560        if socket.as_os_str().len() > 100 {
561            return Err(io::Error::other("temporary socket directory is too long").into());
562        }
563    }
564    let handle = RunHandle {
565        run_id: id,
566        workspace: root.clone(),
567        socket,
568        storage: settings.storage,
569        host_id: crate::workspace::host_id(),
570        input: input.into(),
571    };
572    let mut paths = bindings
573        .values()
574        .filter_map(|p| {
575            if p.is_dir() {
576                Some(p.join("bin"))
577            } else {
578                p.parent().map(Path::to_path_buf)
579            }
580        })
581        .collect::<Vec<_>>();
582    paths.extend(std::env::split_paths(
583        &std::env::var_os("PATH").unwrap_or_default(),
584    ));
585    let captured_path = std::env::join_paths(paths).map_err(io::Error::other)?;
586    let spec = LaunchSpec {
587        handle: handle.clone(),
588        input: effective,
589        manifest,
590        max_bytes: settings.workspace.max_bytes.get(),
591        path: captured_path,
592    };
593    atomic_json(&root.join("launch.json"), &spec)?;
594    atomic_json(&root.join("handle.json"), &handle)?;
595    store.put_json(
596        &format!("{}/records/handle.json", handle.run_id),
597        &handle,
598        &root,
599        false,
600    )?;
601    drop(lease);
602    if !capture_only {
603        spawn_prepared(&handle)?;
604    }
605    startup.armed = false;
606    Ok(handle)
607}
608pub(super) fn spawn_prepared(handle: &RunHandle) -> Result<(), WorkflowError> {
609    let root = handle.workspace.clone();
610    let spec: LaunchSpec = serde_json::from_reader(std::fs::File::open(root.join("launch.json"))?)?;
611    let numerical =
612        crate::provenance::read_environment(&root.join("reproduction/environment/numerical.json"))?;
613    let log = std::fs::OpenOptions::new()
614        .create_new(true)
615        .write(true)
616        .open(root.join("engine.log"))?;
617    let mut command = Command::new(root.join("reproduction/software/runner"));
618    command
619        .env("PATH", spec.path)
620        .arg("--workflow-engine")
621        .arg(root.join("launch.json"))
622        .current_dir(&root)
623        .env("WORKFLOW_RUN_HANDLE", root.join("handle.json"))
624        .env("LD_LIBRARY_PATH", root.join("reproduction/libraries"))
625        .env("PYTHONDONTWRITEBYTECODE", "1")
626        .stdin(Stdio::null())
627        .stdout(Stdio::from(log.try_clone()?))
628        .stderr(Stdio::from(log));
629    crate::provenance::apply_environment(&mut command, &numerical);
630    #[cfg(unix)]
631    {
632        use std::os::unix::process::CommandExt;
633        unsafe {
634            command.pre_exec(|| {
635                if libc::setsid() < 0 {
636                    return Err(io::Error::last_os_error());
637                }
638                Ok(())
639            });
640        }
641    }
642    let mut child = command.spawn()?;
643    let started = Instant::now();
644    loop {
645        if handle.client().is_ok() {
646            break;
647        }
648        if let Some(status) = child.try_wait()? {
649            return Err(io::Error::other(format!(
650                "engine failed startup ({status}); inspect {}",
651                root.join("engine.log").display()
652            ))
653            .into());
654        }
655        if started.elapsed() > Duration::from_secs(60) {
656            let _ = child.kill();
657            return Err(
658                io::Error::new(io::ErrorKind::TimedOut, "engine readiness timed out").into(),
659            );
660        }
661        std::thread::sleep(Duration::from_millis(20));
662    }
663    Ok(())
664}
665pub(super) fn copy_tree(from: &Path, to: &Path) -> io::Result<()> {
666    for e in std::fs::read_dir(from)? {
667        let e = e?;
668        let target = to.join(e.file_name());
669        if e.file_type()?.is_dir() {
670            std::fs::create_dir(&target)?;
671            copy_tree(&e.path(), &target)?;
672        } else {
673            crate::workspace::reserve_copy(&target, e.metadata()?.len())?;
674            std::fs::copy(e.path(), target)?;
675        }
676    }
677    Ok(())
678}
679pub(super) fn rewrite_paths(
680    path: &Path,
681    bindings: &std::collections::BTreeMap<PathBuf, PathBuf>,
682    original: &Path,
683    effective: &Path,
684) -> io::Result<()> {
685    fn visit(
686        value: &mut serde_json::Value,
687        bindings: &std::collections::BTreeMap<PathBuf, PathBuf>,
688        original: &Path,
689        effective: &Path,
690    ) {
691        match value {
692            serde_json::Value::String(s) => {
693                let path = Path::new(s);
694                if let Some((source, bound)) = bindings
695                    .iter()
696                    .filter(|(source, _)| path.starts_with(source))
697                    .max_by_key(|(source, _)| source.components().count())
698                {
699                    let relative = path.strip_prefix(source).unwrap();
700                    *s = if relative.as_os_str().is_empty() {
701                        bound.clone()
702                    } else {
703                        bound.join(relative)
704                    }
705                    .to_string_lossy()
706                    .into_owned();
707                } else if let Ok(relative) = path.strip_prefix(original) {
708                    *s = effective.join(relative).to_string_lossy().into_owned();
709                }
710            }
711            serde_json::Value::Object(o) => {
712                for v in o.values_mut() {
713                    visit(v, bindings, original, effective);
714                }
715            }
716            serde_json::Value::Array(a) => {
717                for v in a {
718                    visit(v, bindings, original, effective);
719                }
720            }
721            _ => {}
722        }
723    }
724    let mut value = serde_json::from_slice(&std::fs::read(path)?).map_err(io::Error::other)?;
725    visit(&mut value, bindings, original, effective);
726    atomic_json(path, &value)
727}