File size: 8,337 Bytes
2109241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18de23f
 
 
 
2109241
 
 
 
 
 
 
 
 
 
 
 
18de23f
 
 
 
 
 
 
 
 
 
 
 
 
 
2109241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a54697
 
 
2109241
 
 
 
 
4a54697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2109241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
//! Filesystem effects supporting immutable project snapshots and atomic updates.

use super::types::{ArtifactIdentity, Manifest, RunInfo, WorkflowError};
use serde::{Serialize, de::DeserializeOwned};
use sha2::{Digest, Sha256};
use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};

/// Compute a stable identity of exact serialized bytes.
pub(super) fn digest(bytes: &[u8]) -> String {
    format!("{:x}", Sha256::digest(bytes))
}

/// Read one file and bind its current bytes.
pub(super) fn file_digest(path: &Path) -> Result<String, WorkflowError> {
    Ok(digest(&fs::read(path)?))
}

/// Decode strict metadata through the receiving type's schema.
pub(super) fn read_json<T: DeserializeOwned>(path: &Path) -> Result<T, WorkflowError> {
    Ok(serde_json::from_slice(&fs::read(path)?)?)
}

/// Atomically replace a single file while its project lock is held.
pub(super) fn atomic_bytes(path: &Path, bytes: &[u8]) -> Result<(), WorkflowError> {
    let parent = path
        .parent()
        .ok_or(WorkflowError::Invalid("file needs a parent directory"))?;
    let mut temporary = tempfile::NamedTempFile::new_in(parent)?;
    temporary.write_all(bytes)?;
    temporary.as_file().sync_all()?;
    temporary.persist(path).map_err(|error| error.error)?;
    File::open(parent)?.sync_all()?;
    Ok(())
}

/// Serialize a complete state before publishing one atomic replacement.
pub(super) fn atomic_json(path: &Path, value: &impl Serialize) -> Result<(), WorkflowError> {
    let mut bytes = serde_json::to_vec_pretty(value)?;
    bytes.push(b'\n');
    atomic_bytes(path, &bytes)
}

/// A short-lived cross-process update lock; a crashed lock needs explicit removal.
pub(super) struct ProjectLock {
    /// Exclusive lockfile claimed by this guard.
    path: PathBuf,
}

impl ProjectLock {
    /// Claim a new lock without blocking the native worker or losing updates.
    pub(super) fn acquire(project: &Path) -> Result<Self, WorkflowError> {
        let path = project.join(".workflow.lock");
        match OpenOptions::new().create_new(true).write(true).open(&path) {
            Ok(mut file) => {
                let guard = Self { path };
                writeln!(file, "{}", std::process::id())?;
                Ok(guard)
            }
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
                Err(WorkflowError::Busy)
            }
            Err(error) => Err(error.into()),
        }
    }
}

impl Drop for ProjectLock {
    /// Release only the path owned by this successful exclusive claim.
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.path);
    }
}

/// Resolve a local existing project to an absolute stable path.
pub(super) fn canonical(project: &Path) -> Result<PathBuf, WorkflowError> {
    Ok(fs::canonicalize(project)?)
}

/// Read the two prediction-defining artifact files.
pub(super) fn identity(model: &Path) -> Result<ArtifactIdentity, WorkflowError> {
    Ok(ArtifactIdentity {
        config_sha256: file_digest(&model.join("config.json"))?,
        weights_sha256: file_digest(&model.join("model.safetensors"))?,
    })
}

/// Reject silent artifact replacement before trusting any associated evidence.
pub(super) fn verify_identity(
    model: &Path,
    expected: &ArtifactIdentity,
) -> Result<(), WorkflowError> {
    if identity(model)? != *expected {
        return Err(WorkflowError::Changed(model.to_path_buf()));
    }
    Ok(())
}

/// Validate all immutable project source identities on every public operation.
pub(super) fn manifest(project: &Path) -> Result<Manifest, WorkflowError> {
    let manifest: Manifest = read_json(&project.join("project.json"))?;
    if !matches!(manifest.format_version, 1 | 2)
        || (manifest.format_version == 1 && manifest.task_suite.is_some())
        || (manifest.format_version == 2 && manifest.task_suite.is_none())
    {
        return Err(WorkflowError::Invalid("unsupported project version"));
    }
    verify_identity(&project.join("baseline"), &manifest.baseline)?;
    for (name, expected) in [
        ("training.json", &manifest.training_sha256),
        ("evaluation.json", &manifest.evaluation_sha256),
    ] {
        let path = project.join("frozen").join(name);
        if file_digest(&path)? != *expected {
            return Err(WorkflowError::Changed(path));
        }
    }
    if let Some(tasks) = &manifest.task_suite {
        for (name, expected) in [
            ("emacs-tasks.json", &tasks.tasks_sha256),
            ("emacs-task-runner.el", &tasks.runner_sha256),
        ] {
            let path = project.join("frozen").join(name);
            if file_digest(&path)? != *expected {
                return Err(WorkflowError::Changed(path));
            }
        }
        if !tasks.emacs.is_absolute() || tasks.timeout_seconds == 0 {
            return Err(WorkflowError::Invalid("invalid frozen task runtime"));
        }
    }
    Ok(manifest)
}

/// Reject path components masquerading as generated run identifiers.
pub(super) fn run_directory(project: &Path, id: &str) -> Result<PathBuf, WorkflowError> {
    if !id.starts_with("run-")
        || !id
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
    {
        return Err(WorkflowError::Invalid("invalid run identifier"));
    }
    Ok(project.join("runs").join(id))
}

/// Load a run record whose embedded paths cannot escape its project.
pub(super) fn read_run(project: &Path, id: &str) -> Result<RunInfo, WorkflowError> {
    let directory = run_directory(project, id)?;
    let run: RunInfo = read_json(&directory.join("run.json"))?;
    if run.id != id
        || run.model != directory.join("model")
        || run
            .finalized_model
            .as_ref()
            .is_some_and(|path| path != &project.join("finalized").join(id))
    {
        return Err(WorkflowError::Invalid("run identity or path mismatch"));
    }
    if file_digest(&directory.join("training.json"))? != run.training_data_sha256 {
        return Err(WorkflowError::Changed(directory.join("training.json")));
    }
    if file_digest(&directory.join("examples.json"))? != run.generation {
        return Err(WorkflowError::Changed(directory.join("examples.json")));
    }
    Ok(run)
}

/// Copy only prediction artifacts into a newly claimed immutable directory.
pub(super) fn copy_model(
    source: &Path,
    destination: &Path,
) -> Result<ArtifactIdentity, WorkflowError> {
    let before = identity(source)?;
    fs::create_dir(destination)?;
    for name in ["config.json", "model.safetensors"] {
        fs::copy(source.join(name), destination.join(name))?;
    }
    if source.join("catalog.json").is_file() {
        fs::copy(source.join("catalog.json"), destination.join("catalog.json"))?;
    }
    verify_identity(source, &before)?;
    verify_identity(destination, &before)?;
    Ok(before)
}

/// Resolve the active open `ActionCatalog` if `project/baseline` is a bi-encoder artifact.
pub(super) fn project_catalog(
    project: &Path,
) -> Result<Option<crate::catalog::ActionCatalog>, WorkflowError> {
    let baseline = project.join("baseline");
    if !crate::engine::is_biencoder_artifact(&baseline)? {
        return Ok(None);
    }
    let root_cat = project.join("catalog.json");
    if root_cat.is_file() {
        return Ok(Some(crate::catalog::ActionCatalog::load_or_builtin(&root_cat)?));
    }
    Ok(Some(crate::catalog::ActionCatalog::load_or_builtin(
        &baseline.join("catalog.json"),
    )?))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_copy_of_a_newer_source_cannot_satisfy_the_frozen_artifact_identity()
    -> Result<(), WorkflowError> {
        let directory = tempfile::tempdir()?;
        let source = directory.path().join("source");
        fs::create_dir(&source)?;
        fs::write(source.join("config.json"), "configuration")?;
        fs::write(source.join("model.safetensors"), "original weights")?;
        let frozen = identity(&source)?;
        fs::write(source.join("model.safetensors"), "replacement weights")?;
        let staged = directory.path().join("staged");
        copy_model(&source, &staged)?;
        assert!(matches!(
            verify_identity(&staged, &frozen),
            Err(WorkflowError::Changed(_))
        ));
        Ok(())
    }
}