scientific-workflow 0.18.0

Configuration-driven scientific tasks, typed state, and durable recordings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! Private bounded local workspace facilities and remote chunk spooling.
mod capture_budget;
mod cleanup;
mod process_guard;
use crate::{
    artifact::{ArtifactRef, ArtifactRole},
    storage::Store,
};
pub(crate) use capture_budget::{CaptureBudget, reserve_copy};
pub(crate) use cleanup::{cleanup_completed, remove_sealed_cache};
use fs4::FileExt;
pub(crate) use process_guard::ProcessGuard;
use std::{
    io::{self, Read},
    path::{Path, PathBuf},
    sync::{Arc, Mutex, OnceLock},
};

pub(crate) struct WorkspaceLease {
    pub(crate) root: PathBuf,
    _lock: std::fs::File,
}
impl WorkspaceLease {
    pub(crate) fn create(root: &Path, id: &str) -> io::Result<Self> {
        std::fs::create_dir_all(root)?;
        let root = root.join(id);
        std::fs::create_dir(&root)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700))?;
        }
        let lock = std::fs::OpenOptions::new()
            .write(true)
            .read(true)
            .create_new(true)
            .open(root.join("engine.lock"))?;
        FileExt::try_lock(&lock)?;
        Ok(Self { root, _lock: lock })
    }
}
#[derive(Clone)]
pub(crate) struct TransferContext {
    pub(crate) root: PathBuf,
    pub(crate) store: Store,
    pub(crate) references: Arc<Mutex<std::collections::BTreeMap<PathBuf, ArtifactRef>>>,
    pub(crate) remote: bool,
    pub(crate) max_bytes: u64,
    pub(crate) assertions: Arc<Mutex<std::collections::BTreeMap<String, String>>>,
    pub(crate) manifest: Arc<Mutex<crate::artifact::RunManifest>>,
    pub(crate) observer: Arc<dyn TransferObserver>,
    pub(crate) relocations: Arc<Mutex<Vec<(PathBuf, PathBuf)>>>,
    pub(crate) external_references: Arc<Mutex<std::collections::BTreeMap<PathBuf, ArtifactRef>>>,
}
static TRANSFER: OnceLock<Mutex<Option<TransferContext>>> = OnceLock::new();
pub(crate) fn install(context: Option<TransferContext>) {
    *TRANSFER.get_or_init(|| Mutex::new(None)).lock().unwrap() = context;
}
fn context() -> Option<TransferContext> {
    TRANSFER
        .get_or_init(|| Mutex::new(None))
        .lock()
        .unwrap()
        .clone()
}
pub(crate) fn bytes(root: &Path) -> io::Result<u64> {
    fn scan(root: &Path) -> io::Result<u64> {
        let mut sum = 0u64;
        for entry in std::fs::read_dir(root)? {
            let result = (|| -> io::Result<u64> {
                let entry = entry?;
                let kind = entry.file_type()?;
                if kind.is_symlink() {
                    return Ok(0);
                }
                if kind.is_dir() {
                    scan(&entry.path())
                } else {
                    Ok(entry.metadata()?.len())
                }
            })();
            match result {
                Ok(size) => sum = sum.saturating_add(size),
                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
                Err(error) => return Err(error),
            }
        }
        Ok(sum)
    }
    scan(root)
}
pub(crate) fn check_capacity() -> io::Result<()> {
    if let Some(c) = context()
        && bytes(&c.root)? > c.max_bytes
    {
        return Err(io::Error::other(
            "workspace capacity exceeded; increase runtime.workspace.max_bytes",
        ));
    }
    Ok(())
}
/// Called synchronously at each scientific recording chunk boundary. Uploads
/// apply backpressure to the bounded writer; only verified remote copies evict.
pub(crate) fn commit_chunk(path: &Path) -> io::Result<()> {
    let Some(c) = context().filter(|c| c.remote && path.starts_with(&c.root)) else {
        return Ok(());
    };
    check_capacity()?;
    let key = path
        .strip_prefix(&c.root)
        .unwrap()
        .to_string_lossy()
        .replace('\\', "/");
    let mut attempts = 0u64;
    let mut pressured = false;
    loop {
        match c.store.publish(&key, path, ArtifactRole::Raw) {
            Ok(reference) => {
                if pressured {
                    c.observer.recovered();
                    c.observer.wait_for_resume()?;
                }
                c.references
                    .lock()
                    .unwrap()
                    .insert(path.into(), reference.clone());
                crate::storage::atomic_json(
                    &path.with_extension("wf-object"),
                    &serde_json::json!({"reference":reference,"locator":crate::artifact::ArtifactLocator{storage:c.store.location.clone(),run_id:c.manifest.lock().unwrap().run_id.clone(),prefix:reference.key.clone()}}),
                )?;
                std::fs::remove_file(path)?;
                return Ok(());
            }
            Err(error) => {
                attempts += 1;
                if c.observer.cancelled() {
                    return Err(error);
                }
                if attempts >= 3 && !pressured {
                    pressured = true;
                    c.observer.blocked(&error.to_string());
                }
            }
        }
        std::thread::sleep(std::time::Duration::from_millis((200 * attempts).min(2000)));
    }
}

pub(crate) trait TransferObserver: Send + Sync {
    fn blocked(&self, reason: &str);
    fn recovered(&self);
    fn cancelled(&self) -> bool;
    fn wait_for_resume(&self) -> io::Result<()>;
}

pub(crate) fn open_file(path: &Path) -> io::Result<Box<dyn Read + Send>> {
    let relocated = relocate(path);
    let path = relocated.as_path();
    if let Ok(file) = std::fs::File::open(path) {
        return Ok(Box::new(file));
    }
    if let Some(c) = context()
        && let Some(reference) = c.references.lock().unwrap().get(path)
    {
        return c.store.read_verified(reference);
    }
    let pointer = path.with_extension("wf-object");
    if pointer.is_file() {
        let value: serde_json::Value =
            serde_json::from_reader(std::fs::File::open(pointer)?).map_err(io::Error::other)?;
        let locator = serde_json::from_value(value["locator"].clone()).map_err(io::Error::other)?;
        let reference =
            serde_json::from_value(value["reference"].clone()).map_err(io::Error::other)?;
        return crate::artifact::open_reference(&locator, &reference);
    }
    Err(io::Error::new(
        io::ErrorKind::NotFound,
        "local file or verified remote chunk unavailable",
    ))
}
pub(crate) fn remote_references() -> Vec<(PathBuf, ArtifactRef)> {
    context()
        .map(|c| {
            c.references
                .lock()
                .unwrap()
                .iter()
                .map(|(p, r)| (p.clone(), r.clone()))
                .collect()
        })
        .unwrap_or_default()
}

pub(crate) fn commit_task(
    directory: &Path,
    processed: Option<&Path>,
    roles: &crate::artifact::ArtifactDeclarations,
) -> io::Result<()> {
    let Some(c) = context().filter(|c| directory.starts_with(&c.root)) else {
        return Ok(());
    };
    for (name, relative) in &roles.shared_inputs {
        let path = directory.join(relative);
        let mut inventory = Vec::new();
        fn content(
            path: &Path,
            root: &Path,
            inventory: &mut Vec<(String, String)>,
        ) -> io::Result<()> {
            if path.is_file() {
                inventory.push((
                    path.strip_prefix(root)
                        .unwrap_or(path)
                        .to_string_lossy()
                        .into_owned(),
                    crate::artifact::digest_reader(std::fs::File::open(path)?)?.0,
                ));
            } else {
                for e in std::fs::read_dir(path)? {
                    content(&e?.path(), root, inventory)?;
                }
            }
            Ok(())
        }
        content(&path, &path, &mut inventory)?;
        inventory.sort();
        let digest = crate::artifact::digest_bytes(
            &serde_json::to_vec(&inventory).map_err(io::Error::other)?,
        );
        let mut assertions = c.assertions.lock().unwrap();
        if let Some(expected) = assertions.get(name) {
            if expected != &digest {
                return Err(io::Error::other(format!(
                    "shared input assertion '{name}' failed: actual scientific contents differ"
                )));
            }
        } else {
            assertions.insert(name.clone(), digest);
        }
    }
    let role_list = roles
        .reproduction
        .iter()
        .map(|p| (p, ArtifactRole::Reproduction))
        .chain(roles.raw.iter().map(|p| (p, ArtifactRole::Raw)))
        .chain(roles.processed.iter().map(|p| (p, ArtifactRole::Processed)))
        .collect::<Vec<_>>();
    for (relative, _) in &role_list {
        let path = directory.join(relative);
        if !path.exists() {
            return Err(io::Error::other(format!(
                "declared artifact is missing: {relative}"
            )));
        }
    }
    fn walk(
        c: &TransferContext,
        base: &Path,
        dir: &Path,
        roles: &[(&String, ArtifactRole)],
        default: ArtifactRole,
    ) -> io::Result<()> {
        if !dir.exists() {
            return Ok(());
        }
        for e in std::fs::read_dir(dir)? {
            let e = e?;
            let path = e.path();
            if e.file_type()?.is_symlink() {
                return Err(io::Error::other("task output contains symlink"));
            }
            if e.file_type()?.is_dir() {
                walk(c, base, &path, roles, default)?;
            } else {
                if path.extension().is_some_and(|e| e == "wf-object") {
                    continue;
                }
                let relative = path
                    .strip_prefix(base)
                    .unwrap()
                    .to_string_lossy()
                    .replace('\\', "/");
                let role = roles
                    .iter()
                    .find(|(p, _)| relative == p.as_str() || relative.starts_with(&format!("{p}/")))
                    .map(|(_, r)| *r)
                    .unwrap_or_else(|| {
                        if [
                            "workflow-result.json",
                            "workflow-config.json",
                            "workflow-dependencies.json",
                            "workflow-inputs.json",
                            "program.json",
                        ]
                        .contains(&relative.as_str())
                            || (relative.ends_with("/metadata.json")
                                && !relative.starts_with("artifacts/"))
                        {
                            ArtifactRole::Record
                        } else {
                            default
                        }
                    });
                let key = path
                    .strip_prefix(&c.root)
                    .unwrap()
                    .to_string_lossy()
                    .replace('\\', "/");
                let reference = c.store.publish(&key, &path, role)?;
                c.references.lock().unwrap().insert(path, reference);
            }
        }
        Ok(())
    }
    walk(&c, directory, directory, &role_list, ArtifactRole::Raw)?;
    if let Some(path) = processed {
        walk(&c, path, path, &[], ArtifactRole::Processed)?;
    }
    // Publish inventory before the completion receipt; a receipt is never evidence
    // for local-only output. The final run manifest later incorporates these refs.
    let refs = c
        .references
        .lock()
        .unwrap()
        .values()
        .cloned()
        .chain(c.external_references.lock().unwrap().values().cloned())
        .collect::<Vec<_>>();
    let task_id = crate::artifact::digest_bytes(
        directory
            .strip_prefix(&c.root)
            .unwrap()
            .to_string_lossy()
            .as_bytes(),
    );
    let handle: serde_json::Value =
        serde_json::from_reader(std::fs::File::open(c.root.join("handle.json"))?)
            .map_err(io::Error::other)?;
    let id = handle["run_id"]
        .as_str()
        .ok_or_else(|| io::Error::other("missing run identity"))?;
    c.store.put_json(
        &format!("{id}/records/task-{task_id}.json"),
        &refs,
        &c.root,
        false,
    )?;
    let mut manifest = c
        .manifest
        .lock()
        .map_err(|_| io::Error::other("manifest lock poisoned"))?;
    for reference in refs {
        manifest.artifacts.insert(reference.key.clone(), reference);
    }
    c.store
        .put_json(&format!("{id}/manifest.json"), &*manifest, &c.root, false)?;
    Ok(())
}

pub(crate) fn file_size(path: &Path) -> io::Result<u64> {
    let relocated = relocate(path);
    let path = relocated.as_path();
    if let Ok(metadata) = std::fs::metadata(path) {
        return Ok(metadata.len());
    }
    if let Some(c) = context()
        && let Some(reference) = c.references.lock().unwrap().get(path)
    {
        return Ok(reference.bytes);
    }
    let pointer: serde_json::Value =
        serde_json::from_reader(std::fs::File::open(path.with_extension("wf-object"))?)
            .map_err(io::Error::other)?;
    pointer["reference"]["bytes"]
        .as_u64()
        .ok_or_else(|| io::Error::other("invalid workspace object reference"))
}
pub(crate) fn locator_for(path: &Path) -> Option<crate::artifact::ArtifactLocator> {
    for root in path.ancestors() {
        let handle = root.join("handle.json");
        if handle.is_file() {
            let value: serde_json::Value =
                serde_json::from_reader(std::fs::File::open(handle).ok()?).ok()?;
            return Some(crate::artifact::ArtifactLocator {
                storage: serde_json::from_value(value["storage"].clone()).ok()?,
                run_id: value["run_id"].as_str()?.into(),
                prefix: path
                    .strip_prefix(root)
                    .ok()?
                    .to_string_lossy()
                    .replace('\\', "/"),
            });
        }
    }
    None
}

pub(crate) fn relocate(path: &Path) -> PathBuf {
    if let Some(c) = context()
        && let Some((old, new)) = c
            .relocations
            .lock()
            .unwrap()
            .iter()
            .filter(|(old, _)| path.starts_with(old))
            .max_by_key(|(old, _)| old.components().count())
    {
        return new.join(path.strip_prefix(old).unwrap());
    }
    path.to_path_buf()
}
pub(crate) fn add_relocation(old: PathBuf, new: PathBuf) {
    if let Some(c) = context() {
        c.relocations.lock().unwrap().push((old, new));
    }
}
pub(crate) fn add_reference(path: PathBuf, reference: ArtifactRef) {
    if let Some(c) = context() {
        c.external_references
            .lock()
            .unwrap()
            .insert(path, reference);
    }
}
pub(crate) fn external_references() -> Vec<(PathBuf, ArtifactRef)> {
    context()
        .map(|c| {
            c.external_references
                .lock()
                .unwrap()
                .iter()
                .map(|(p, r)| (p.clone(), r.clone()))
                .collect()
        })
        .unwrap_or_default()
}
pub(crate) fn capture_identity() -> Option<std::collections::BTreeMap<String, String>> {
    context().map(|c| {
        c.manifest
            .lock()
            .unwrap()
            .artifacts
            .iter()
            .filter(|(key, _)| {
                (key.starts_with("inputs/") && !key.starts_with("inputs/wf_configs/"))
                    || *key == "reproduction/environment/numerical.json"
                    || [
                        "reproduction/software/",
                        "reproduction/libraries/",
                        "reproduction/python/",
                        "reproduction/external-inputs/",
                    ]
                    .iter()
                    .any(|p| key.starts_with(p))
            })
            .map(|(key, r)| (key.clone(), r.sha256.clone()))
            .collect()
    })
}

pub(crate) fn host_id() -> String {
    let mut identity = std::fs::read("/etc/machine-id")
        .unwrap_or_else(|_| std::env::var("HOSTNAME").unwrap_or_default().into_bytes());
    identity.extend_from_slice(
        std::fs::read_link("/proc/self/ns/pid")
            .unwrap_or_default()
            .as_os_str()
            .as_encoded_bytes(),
    );
    crate::artifact::digest_bytes(&identity)
}