scientific-workflow 0.9.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
//! Generic content-addressed input artifacts inside an execution scope.
//!
//! This module owns immutable artifact publication and integrity verification:
//! deterministic naming, SHA-256 identity computation, deduplicating persistence,
//! descriptor encoding, and strict load-time checks.
//!
//! # Boundary
//!
//! Artifact handling is intentionally limited to bytes. The module does not own
//! execution policy, storage stream formats, task scheduling, or scientific
//! semantics. Callers map descriptors into their own provenance domain and pass
//! them through `ExecutionScope` paths.

use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use thiserror::Error;

use crate::execution::ExecutionScope;

static TEMPORARY_SEQUENCE: AtomicU64 = AtomicU64::new(0);

/// Exact identity and execution-relative location of immutable bytes.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ArtifactDescriptor {
    sha256: String,
    path: String,
}

impl ArtifactDescriptor {
    /// Returns the lowercase SHA-256 identity of the exact bytes.
    pub fn sha256(&self) -> &str {
        &self.sha256
    }

    /// Returns the artifact path relative to its execution directory.
    pub fn path(&self) -> &str {
        &self.path
    }
}

/// Whether publishing created new bytes or reused identical existing bytes.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ArtifactDisposition {
    /// This publication created the destination artifact.
    Created,
    /// Identical bytes already existed and were reused.
    Reused,
}

/// Result of atomically publishing immutable content.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PersistedArtifact {
    descriptor: ArtifactDescriptor,
    disposition: ArtifactDisposition,
}

/// Verified canonical path and exact immutable bytes.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VerifiedArtifact {
    path: PathBuf,
    bytes: Vec<u8>,
}

impl VerifiedArtifact {
    /// Returns the canonical verified filesystem path.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Borrows the bytes whose digest has been verified.
    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Transfers ownership of the verified bytes.
    pub fn into_bytes(self) -> Vec<u8> {
        self.bytes
    }
}

impl PersistedArtifact {
    /// Borrows the immutable identity and relative path.
    pub const fn descriptor(&self) -> &ArtifactDescriptor {
        &self.descriptor
    }

    /// Reports whether this call created or reused the destination.
    pub const fn disposition(&self) -> ArtifactDisposition {
        self.disposition
    }

    /// Transfers ownership of the descriptor.
    pub fn into_descriptor(self) -> ArtifactDescriptor {
        self.descriptor
    }
}

/// Atomically publishes exact bytes beneath `scope/inputs` using their SHA-256.
///
/// `stem` and `extension` describe representation only; callers retain all
/// domain interpretation. Both must be nonempty safe filename fragments.
pub fn persist_artifact(
    scope: &ExecutionScope,
    stem: &str,
    extension: &str,
    bytes: &[u8],
) -> Result<PersistedArtifact, ArtifactError> {
    validate_fragment("stem", stem, true)?;
    validate_fragment("extension", extension, false)?;
    let digest = sha256_hex(bytes);
    let file_name = format!("{stem}-{digest}.{extension}");
    let relative_path = format!("inputs/{file_name}");
    let inputs = scope.directory().join("inputs");
    fs::create_dir_all(&inputs).map_err(|source| ArtifactError::Io {
        operation: "create artifact input directory",
        path: inputs.clone(),
        source,
    })?;
    let destination = inputs.join(file_name);

    if destination.exists() {
        verify_existing(&destination, bytes, &digest)?;
        return Ok(persisted(
            digest,
            relative_path,
            ArtifactDisposition::Reused,
        ));
    }

    let temporary = create_complete_temporary(&inputs, &digest, bytes)?;
    let disposition = match fs::hard_link(&temporary, &destination) {
        Ok(()) => ArtifactDisposition::Created,
        Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => {
            let verification = verify_existing(&destination, bytes, &digest);
            remove_published_temporary(&temporary)?;
            verification?;
            ArtifactDisposition::Reused
        }
        Err(source) => {
            remove_temporary(&temporary);
            return Err(ArtifactError::Io {
                operation: "publish artifact",
                path: destination,
                source,
            });
        }
    };
    if temporary.exists() {
        remove_published_temporary(&temporary)?;
    }
    sync_directory(&inputs)?;
    Ok(persisted(digest, relative_path, disposition))
}

/// Reads immutable bytes after path-containment and exact-digest verification.
pub fn load_verified_artifact(
    execution_directory: impl AsRef<Path>,
    descriptor: &ArtifactDescriptor,
) -> Result<VerifiedArtifact, ArtifactLoadError> {
    validate_descriptor(descriptor)?;
    let execution_directory =
        fs::canonicalize(execution_directory.as_ref()).map_err(|source| ArtifactLoadError::Io {
            operation: "resolve execution directory",
            path: execution_directory.as_ref().to_path_buf(),
            source,
        })?;
    let relative = Path::new(descriptor.path());
    if relative.as_os_str().is_empty()
        || relative
            .components()
            .any(|component| !matches!(component, Component::Normal(_)))
    {
        return Err(ArtifactLoadError::InvalidDescriptor {
            reason: "artifact path must be a nonempty normalized relative path".to_owned(),
        });
    }
    let unresolved = execution_directory.join(relative);
    let path = fs::canonicalize(&unresolved).map_err(|source| ArtifactLoadError::Io {
        operation: "resolve artifact",
        path: unresolved,
        source,
    })?;
    if !path.starts_with(&execution_directory) {
        return Err(ArtifactLoadError::InvalidDescriptor {
            reason: "artifact path resolves outside the execution directory".to_owned(),
        });
    }
    let bytes = fs::read(&path).map_err(|source| ArtifactLoadError::Io {
        operation: "read artifact",
        path: path.clone(),
        source,
    })?;
    let actual = sha256_hex(&bytes);
    if actual != descriptor.sha256 {
        return Err(ArtifactLoadError::DigestMismatch {
            path,
            expected: descriptor.sha256.clone(),
            actual,
        });
    }
    Ok(VerifiedArtifact { path, bytes })
}

fn persisted(sha256: String, path: String, disposition: ArtifactDisposition) -> PersistedArtifact {
    PersistedArtifact {
        descriptor: ArtifactDescriptor { sha256, path },
        disposition,
    }
}

fn validate_fragment(
    kind: &'static str,
    value: &str,
    allow_hyphen: bool,
) -> Result<(), ArtifactError> {
    let valid = !value.is_empty()
        && value.bytes().all(|byte| {
            byte.is_ascii_alphanumeric() || byte == b'_' || (allow_hyphen && byte == b'-')
        });
    if valid {
        Ok(())
    } else {
        Err(ArtifactError::InvalidFragment {
            kind,
            value: value.to_owned(),
        })
    }
}

fn validate_descriptor(descriptor: &ArtifactDescriptor) -> Result<(), ArtifactLoadError> {
    if descriptor.sha256.len() != 64
        || !descriptor
            .sha256
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
    {
        return Err(ArtifactLoadError::InvalidDescriptor {
            reason: "artifact SHA-256 must contain exactly 64 lowercase hexadecimal digits"
                .to_owned(),
        });
    }
    Ok(())
}

fn create_complete_temporary(
    directory: &Path,
    digest: &str,
    bytes: &[u8],
) -> Result<PathBuf, ArtifactError> {
    for _ in 0..1024 {
        let sequence = TEMPORARY_SEQUENCE.fetch_add(1, Ordering::Relaxed);
        let path = directory.join(format!(
            ".artifact-{digest}-{}-{sequence}.tmp",
            std::process::id()
        ));
        let mut file = match OpenOptions::new().write(true).create_new(true).open(&path) {
            Ok(file) => file,
            Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(source) => {
                return Err(ArtifactError::Io {
                    operation: "create temporary artifact",
                    path,
                    source,
                });
            }
        };
        if let Err(source) = file.write_all(bytes).and_then(|()| file.sync_all()) {
            drop(file);
            remove_temporary(&path);
            return Err(ArtifactError::Io {
                operation: "write temporary artifact",
                path,
                source,
            });
        }
        return Ok(path);
    }
    Err(ArtifactError::TemporaryIdentityExhausted {
        directory: directory.to_path_buf(),
    })
}

fn verify_existing(path: &Path, expected: &[u8], digest: &str) -> Result<(), ArtifactError> {
    let actual = fs::read(path).map_err(|source| ArtifactError::Io {
        operation: "read existing artifact",
        path: path.to_path_buf(),
        source,
    })?;
    if actual == expected {
        Ok(())
    } else {
        Err(ArtifactError::DigestCollision {
            digest: digest.to_owned(),
            path: path.to_path_buf(),
        })
    }
}

fn sha256_hex(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);
    let mut encoded = String::with_capacity(digest.len() * 2);
    for byte in digest {
        use std::fmt::Write as _;
        write!(encoded, "{byte:02x}").expect("writing into a String cannot fail");
    }
    encoded
}

fn sync_directory(path: &Path) -> Result<(), ArtifactError> {
    File::open(path)
        .and_then(|directory| directory.sync_all())
        .map_err(|source| ArtifactError::Io {
            operation: "synchronize artifact input directory",
            path: path.to_path_buf(),
            source,
        })
}

fn remove_temporary(path: &Path) {
    let _ = fs::remove_file(path);
}

fn remove_published_temporary(path: &Path) -> Result<(), ArtifactError> {
    fs::remove_file(path).map_err(|source| ArtifactError::Io {
        operation: "remove temporary artifact",
        path: path.to_path_buf(),
        source,
    })
}

/// Failure while validating or publishing an immutable artifact.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ArtifactError {
    /// A filename fragment is empty or contains unsafe characters.
    #[error("invalid artifact {kind} `{value}`")]
    InvalidFragment {
        /// Kind of fragment, such as `stem` or `extension`.
        kind: &'static str,
        /// Rejected fragment value.
        value: String,
    },
    /// A filesystem operation failed during publication.
    #[error("failed to {operation} at `{path}`")]
    Io {
        /// Stable description of the attempted operation.
        operation: &'static str,
        /// Filesystem path affected by the operation.
        path: PathBuf,
        /// Underlying operating-system failure.
        #[source]
        source: std::io::Error,
    },
    /// Existing bytes at a digest-derived path do not match the digest input.
    #[error("artifact digest collision for `{digest}` at `{path}`")]
    DigestCollision {
        /// SHA-256 identity whose destination was occupied.
        digest: String,
        /// Conflicting artifact path.
        path: PathBuf,
    },
    /// All bounded attempts to allocate a unique temporary path collided.
    #[error("could not allocate a temporary artifact beneath `{directory}`")]
    TemporaryIdentityExhausted {
        /// Directory in which allocation was attempted.
        directory: PathBuf,
    },
}

/// Failure while locating or verifying a persisted artifact.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ArtifactLoadError {
    /// Descriptor contents are malformed or escape the execution directory.
    #[error("invalid artifact descriptor: {reason}")]
    InvalidDescriptor {
        /// Contextual descriptor violation.
        reason: String,
    },
    /// A filesystem operation failed during loading.
    #[error("failed to {operation} at `{path}`")]
    Io {
        /// Stable description of the attempted operation.
        operation: &'static str,
        /// Filesystem path affected by the operation.
        path: PathBuf,
        /// Underlying operating-system failure.
        #[source]
        source: std::io::Error,
    },
    /// Loaded bytes do not have the descriptor's declared digest.
    #[error("artifact `{path}` has SHA-256 `{actual}`, but metadata declares `{expected}`")]
    DigestMismatch {
        /// Canonical path of the loaded artifact.
        path: PathBuf,
        /// SHA-256 digest declared by the descriptor.
        expected: String,
        /// SHA-256 digest calculated from the loaded bytes.
        actual: String,
    },
}