Skip to main content

optimization_job_api/
artifact.rs

1//! Artifacts: files of a job attempt that agents may read through the runner
2//! (`jobs artifact`, MCP `get_artifact`), during the run and after it.
3//!
4//! `results` (the result journal) is built in. A worker adds its own files,
5//! such as an evaluation log or a warm-start snapshot, by declaring them with
6//! [`declare`] before it first writes them. Declarations are checked records
7//! in `artifacts.jsonl` of the attempt directory, so workers in any language
8//! can write them, and a runner that predates them simply ignores the file.
9//! The final manifest lists every declared file that exists, and
10//! `runner.artifact_index` records its format, size and SHA-256 when the
11//! attempt is sealed.
12use crate::{Result, coded, safe_name, storage};
13use serde::{Deserialize, Serialize};
14use serde_json::{Map, Value, json};
15use std::{
16    collections::BTreeSet,
17    fs,
18    io::{self, BufRead, Read},
19    path::Path,
20};
21
22/// The declarations of an attempt: checked records, version 1.
23pub const DECLARATIONS: &str = "artifacts.jsonl";
24const LOCK: &str = "artifacts.lock";
25/// The built-in artifact: the result journal `results.jsonl`.
26pub const RESULTS: &str = "results";
27/// Artifact formats.
28///
29/// - `records`: an append-only journal of checked records, written with
30///   [`storage::append_checked`] (any record version). Readable while the
31///   job runs (complete records only) and in pages of records.
32/// - `json`: one JSON document, replaced atomically with
33///   [`storage::write_atomic_json`]. Read whole.
34pub const FORMATS: [&str; 2] = ["records", "json"];
35/// Files of the runner and the SDK in an attempt directory. No artifact may
36/// use them; nor a name that starts with `.` or ends with `.lock` or `.tmp`.
37pub const RESERVED: [&str; 22] = [
38    "artifacts.jsonl",
39    "artifacts.lock",
40    "cancel.lock",
41    "cancel.request",
42    "child_finished",
43    "containment.unknown",
44    "events.jsonl",
45    "inputs",
46    "job.json",
47    "job.lock",
48    "provenance.json",
49    "request.json",
50    "resolved.json",
51    "results.jsonl",
52    "retries.jsonl",
53    "run.json",
54    "stderr.log",
55    "stdout.log",
56    "submitted.json",
57    "worker",
58    "worker-process.json",
59    "worker.lock",
60];
61/// Declarations per attempt.
62pub const MAX_DECLARATIONS: usize = 4096;
63/// Bytes of a description.
64pub const MAX_DESCRIPTION: usize = 200;
65/// What one runner call returns inline: the whole content of an artifact,
66/// or the records of one page.
67pub const INLINE_CAP: usize = 1 << 20;
68/// Records of one page at most.
69pub const MAX_PAGE: usize = 10_000;
70
71/// A file a worker declares in its attempt directory.
72#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
73#[serde(deny_unknown_fields)]
74pub struct Declaration {
75    /// Name agents use (`jobs artifact ID NAME`); unique in the attempt.
76    pub name: String,
77    /// File name in the attempt directory, no path.
78    pub file: String,
79    /// One of [`FORMATS`].
80    pub format: String,
81    /// The task that writes it, if one does.
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub task_id: Option<usize>,
84    /// What it holds and what it is for, for agents.
85    #[serde(default, skip_serializing_if = "String::is_empty")]
86    pub description: String,
87}
88
89impl Declaration {
90    /// A journal of checked records (see [`FORMATS`]).
91    pub fn records(name: impl Into<String>, file: impl Into<String>) -> Self {
92        Self {
93            name: name.into(),
94            file: file.into(),
95            format: "records".into(),
96            task_id: None,
97            description: String::new(),
98        }
99    }
100    /// A JSON document replaced atomically (see [`FORMATS`]).
101    pub fn json(name: impl Into<String>, file: impl Into<String>) -> Self {
102        Self {
103            format: "json".into(),
104            ..Self::records(name, file)
105        }
106    }
107    /// Ties the artifact to task `task_id`.
108    pub fn task(mut self, task_id: usize) -> Self {
109        self.task_id = Some(task_id);
110        self
111    }
112    /// Sets the description, at most 200 bytes.
113    pub fn describe(mut self, description: impl Into<String>) -> Self {
114        self.description = description.into();
115        self
116    }
117    /// The rules of a declaration, independent of other declarations.
118    pub fn check(&self) -> std::result::Result<(), String> {
119        let file = self.file.as_str();
120        if !safe_name(&self.name) || self.name == RESULTS {
121            return Err(format!("invalid or reserved artifact name {:?}", self.name));
122        }
123        if !safe_name(file)
124            || RESERVED.contains(&file)
125            || file.starts_with('.')
126            || file.ends_with(".lock")
127            || file.ends_with(".tmp")
128        {
129            return Err(format!(
130                "artifact {}: invalid or reserved file name {file:?}",
131                self.name
132            ));
133        }
134        if !FORMATS.contains(&self.format.as_str()) {
135            return Err(format!(
136                "artifact {}: unknown format {:?}",
137                self.name, self.format
138            ));
139        }
140        if self.description.len() > MAX_DESCRIPTION || self.description.contains(char::is_control) {
141            return Err(format!(
142                "artifact {}: description over {MAX_DESCRIPTION} bytes or with control characters",
143                self.name
144            ));
145        }
146        Ok(())
147    }
148}
149
150/// Declares an artifact of the attempt in `dir`, the attempt directory a
151/// worker's `prepare` receives as `base`. Declare it in `solve`, before the
152/// first write, so agents can read it while the job runs; never in `prepare`,
153/// which also runs for validation. Repeating an identical declaration is a
154/// no-op; another declaration of the same name or file is an error. Safe to
155/// call from concurrent tasks.
156pub fn declare(dir: &Path, declaration: &Declaration) -> Result<()> {
157    declaration.check()?;
158    let _lock = storage::lock(&dir.join(LOCK))?;
159    let existing = declarations(dir)?;
160    if let Some(old) = existing.iter().find(|d| d.name == declaration.name) {
161        if old == declaration {
162            return Ok(());
163        }
164        return Err(format!(
165            "artifact {} is already declared differently",
166            declaration.name
167        )
168        .into());
169    }
170    if existing.iter().any(|d| d.file == declaration.file) {
171        return Err(format!("file {} is already declared", declaration.file).into());
172    }
173    if existing.len() >= MAX_DECLARATIONS {
174        return Err(format!("more than {MAX_DECLARATIONS} artifacts declared").into());
175    }
176    storage::append_checked(&dir.join(DECLARATIONS), 1, declaration)?;
177    Ok(())
178}
179
180/// The declarations of the attempt in `dir`, in declaration order; none if
181/// there are none. A declaration that breaks the rules, or a second
182/// declaration of a name or file, makes them all untrusted: an error.
183pub fn declarations(dir: &Path) -> Result<Vec<Declaration>> {
184    let path = dir.join(DECLARATIONS);
185    if !path.exists() {
186        return Ok(vec![]);
187    }
188    let list: Vec<Declaration> =
189        storage::read_checked(&path, 1).map_err(|e| format!("{DECLARATIONS}: {e}"))?;
190    let (mut names, mut files) = (BTreeSet::new(), BTreeSet::new());
191    for d in &list {
192        d.check().map_err(|e| format!("{DECLARATIONS}: {e}"))?;
193        if !names.insert(&d.name) || !files.insert(&d.file) {
194            return Err(format!("{DECLARATIONS}: {} or its file declared twice", d.name).into());
195        }
196    }
197    if list.len() > MAX_DECLARATIONS {
198        return Err(format!("{DECLARATIONS}: more than {MAX_DECLARATIONS} artifacts").into());
199    }
200    Ok(list)
201}
202
203/// Every artifact of the attempt: `results` first, then the declarations.
204/// Files that do not exist (yet) are included.
205pub fn all(dir: &Path) -> Result<Vec<Declaration>> {
206    let mut list = vec![results()];
207    list.extend(declarations(dir)?);
208    Ok(list)
209}
210
211fn results() -> Declaration {
212    Declaration::records(RESULTS, "results.jsonl")
213        .describe("The result journal: one checked record per completed task")
214}
215
216/// [`all`], or `results` alone and the error when the declarations are
217/// broken: what a running attempt serves.
218pub fn all_or_results(dir: &Path) -> (Vec<Declaration>, Vec<String>) {
219    match all(dir) {
220        Ok(list) => (list, vec![]),
221        Err(e) => (vec![results()], vec![e.to_string()]),
222    }
223}
224
225fn entry(d: &Declaration) -> Map<String, Value> {
226    let mut e = Map::new();
227    e.insert("file".into(), json!(d.file));
228    e.insert("format".into(), json!(d.format));
229    if let Some(task) = d.task_id {
230        e.insert("task_id".into(), json!(task));
231    }
232    if !d.description.is_empty() {
233        e.insert("description".into(), json!(d.description));
234    }
235    e
236}
237
238/// The artifact index of a running attempt, for `jobs get`: every artifact
239/// whose file exists, with its current size, and the problems found (a broken
240/// declaration file leaves `results` alone).
241pub fn progress(dir: &Path) -> (Value, Vec<String>) {
242    let (list, errors) = all_or_results(dir);
243    let mut index = Map::new();
244    for d in list {
245        if let Ok(meta) = fs::symlink_metadata(dir.join(&d.file))
246            && meta.is_file()
247        {
248            let mut e = entry(&d);
249            e.insert("bytes".into(), json!(meta.len()));
250            index.insert(d.name.clone(), Value::Object(e));
251        }
252    }
253    (Value::Object(index), errors)
254}
255
256/// The manifest's view of the artifacts when an attempt is sealed: the
257/// `artifacts` map (name to file), `runner.artifact_index` (format, size,
258/// SHA-256, task, description) and the problems found. Only regular files
259/// that exist are listed; a broken declaration file lists `results` alone.
260/// An artifact problem never fails the attempt: its results stand.
261pub fn sealed(dir: &Path) -> (Value, Value, Vec<String>) {
262    let (list, mut errors) = all_or_results(dir);
263    let (mut files, mut index) = (Map::new(), Map::new());
264    for d in list {
265        let path = dir.join(&d.file);
266        match fs::symlink_metadata(&path) {
267            Ok(meta) if meta.is_file() => {}
268            Err(e) if e.kind() == io::ErrorKind::NotFound => continue,
269            Ok(_) => {
270                errors.push(format!(
271                    "artifact {}: {} is not a regular file",
272                    d.name, d.file
273                ));
274                continue;
275            }
276            Err(e) => {
277                errors.push(format!("artifact {}: {e}", d.name));
278                continue;
279            }
280        }
281        let (bytes, sha256) = match digest_file(&path) {
282            Ok(digest) => digest,
283            Err(e) => {
284                errors.push(format!("artifact {}: {e}", d.name));
285                continue;
286            }
287        };
288        let mut e = entry(&d);
289        e.insert("bytes".into(), json!(bytes));
290        e.insert("sha256".into(), json!(sha256));
291        files.insert(d.name.clone(), json!(d.file));
292        index.insert(d.name, Value::Object(e));
293    }
294    (Value::Object(files), Value::Object(index), errors)
295}
296
297/// Size and SHA-256 of a file, read in blocks.
298pub fn digest_file(path: &Path) -> Result<(u64, String)> {
299    use sha2::{Digest, Sha256};
300    let mut file = fs::File::open(path)?;
301    let mut hasher = Sha256::new();
302    let mut buffer = vec![0u8; 1 << 16];
303    let mut bytes = 0u64;
304    loop {
305        let n = file.read(&mut buffer)?;
306        if n == 0 {
307            break;
308        }
309        bytes += n as u64;
310        hasher.update(&buffer[..n]);
311    }
312    Ok((bytes, format!("{:x}", hasher.finalize())))
313}
314
315/// The whole content of an artifact, at most [`INLINE_CAP`] bytes. A
316/// `records` artifact is read up to its last complete line, so a record
317/// being appended is never cut.
318pub fn content(path: &Path, format: &str) -> Result<Value> {
319    let size = fs::metadata(path)?.len();
320    if size > INLINE_CAP as u64 {
321        return Err(coded(
322            "artifact_too_large",
323            format!(
324                "the artifact has {size} bytes, over the {INLINE_CAP}-byte inline cap; {}",
325                if format == "records" {
326                    "read it in pages with offset and limit"
327                } else {
328                    "read the file in the job directory"
329                }
330            ),
331        ));
332    }
333    let mut data = fs::read(path)?;
334    if format == "records" {
335        data.truncate(data.iter().rposition(|b| *b == b'\n').map_or(0, |i| i + 1));
336    }
337    let sha256 = storage::digest(&data);
338    let bytes = data.len();
339    let text = String::from_utf8(data).map_err(|_| "artifact is not UTF-8 text")?;
340    Ok(json!({"format":format,"bytes":bytes,"sha256":sha256,"content":text}))
341}
342
343/// Records `offset..offset + limit` of a `records` artifact: the payloads of
344/// complete records whose checksums hold, at most [`INLINE_CAP`] bytes of
345/// payload (always at least one record). `next_offset` is where the next
346/// page starts; `available` counts the complete records now in the file,
347/// which a running job may extend.
348///
349/// A record is a newline-terminated, non-blank line; a final line without
350/// its newline is still being written and does not count. The file is read
351/// once as a stream: records before `offset` are only counted, and only the
352/// page's records are parsed and checked, so a page costs one pass over the
353/// bytes and memory for the page alone, however long the artifact is.
354pub fn page(path: &Path, offset: usize, limit: usize) -> Result<Value> {
355    if !(1..=MAX_PAGE).contains(&limit) {
356        return Err(coded(
357            "invalid_command",
358            format!("limit must lie in 1..={MAX_PAGE}"),
359        ));
360    }
361    let mut reader = io::BufReader::with_capacity(1 << 16, fs::File::open(path)?);
362    let mut line = Vec::new();
363    let (mut index, mut size, mut full) = (0usize, 0usize, false);
364    let mut records = Vec::new();
365    loop {
366        line.clear();
367        if reader.read_until(b'\n', &mut line)? == 0 || line.last() != Some(&b'\n') {
368            break;
369        }
370        if line.iter().all(u8::is_ascii_whitespace) {
371            continue;
372        }
373        if index >= offset && records.len() < limit && !full {
374            let envelope: storage::Envelope = serde_json::from_slice(&line)
375                .map_err(|e| format!("record {index} of the artifact is no checked record: {e}"))?;
376            if envelope.checksum != storage::digest(envelope.payload_json.as_bytes()) {
377                return Err(format!("record {index} of the artifact fails its checksum").into());
378            }
379            if size + envelope.payload_json.len() > INLINE_CAP {
380                if records.is_empty() {
381                    return Err(coded(
382                        "artifact_too_large",
383                        format!(
384                            "record {index} alone exceeds the {INLINE_CAP}-byte inline cap; read the file in the job directory"
385                        ),
386                    ));
387                }
388                full = true;
389            } else {
390                size += envelope.payload_json.len();
391                records.push(serde_json::from_str::<Value>(&envelope.payload_json)?);
392            }
393        }
394        index += 1;
395    }
396    let next = offset.min(index) + records.len();
397    Ok(
398        json!({"format":"records","offset":offset,"records":records,"next_offset":next,"available":index}),
399    )
400}