Skip to main content

optimization_job_api/
spec.rs

1//! The job envelope `optimization.job/0.1`: its types and rules, its input
2//! files, and the [`Request`] that also accepts the legacy format (the
3//! guide's section [Envelope](https://github.com/dietmarwo/optimization-jobs/blob/main/docs/job-api.md#envelope)).
4use crate::{Result, coded, legacy, storage};
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7use std::{
8    collections::BTreeSet,
9    fs,
10    path::{Component, Path},
11};
12
13/// The schema version of the job envelope, the value of
14/// [`JobSpec::schema_version`].
15pub const SCHEMA: &str = "optimization.job/0.1";
16/// The worker protocol of this build. It adds the result contract 0.2
17/// (evidence, refutations, objective bounds and the infeasibility and
18/// certified claims) to the process protocol of 0.1.
19pub const PROTOCOL: &str = "optimization.worker/0.2";
20/// Worker protocols the runner accepts. Every 0.1 result record is a valid
21/// 0.2 record, so 0.1 workers keep working; a 0.1 runner rejects 0.2 workers
22/// at registration instead of failing on their journals.
23pub const PROTOCOLS: [&str; 2] = ["optimization.worker/0.1", PROTOCOL];
24/// True if the runner accepts a worker that describes itself with `protocol`.
25pub fn protocol_supported(protocol: &Value) -> bool {
26    protocol.as_str().is_some_and(|p| PROTOCOLS.contains(&p))
27}
28/// The largest input file, 64 MiB.
29pub const MAX_INPUT_BYTES: u64 = 64 * 1024 * 1024;
30
31/// The CPU slots of a job: `outer_workers * inner_threads <= cpu_slots <= 1024`
32/// (the guide's section [Eight CPU slots](https://github.com/dietmarwo/optimization-jobs/blob/main/docs/job-api.md#eight-cpu-slots)).
33#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
34#[serde(deny_unknown_fields)]
35pub struct Resources {
36    /// Slots the runner reserves for the whole attempt.
37    pub cpu_slots: usize,
38    /// Tasks solved at the same time.
39    pub outer_workers: usize,
40    /// Numerical threads of each task.
41    pub inner_threads: usize,
42}
43/// The time limits of a job.
44#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
45#[serde(deny_unknown_fields)]
46pub struct Limits {
47    /// Execution time after which the worker stops its tasks: positive and
48    /// at most one year (31,536,000 seconds).
49    pub wall_time_seconds: f64,
50    /// Time between the wall-time deadline and killing the worker, 0 to
51    /// 86,400 seconds.
52    pub grace_seconds: f64,
53}
54/// A named input file of a job: an LP model, or data a registered model reads.
55#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
56#[serde(deny_unknown_fields)]
57pub struct Input {
58    /// The unique [safe name](safe_name) the worker looks the file up by
59    /// ([`JobSpec::input_bytes`]).
60    pub name: String,
61    /// The path, relative to the submitted specification; `inputs/NAME` in
62    /// an attempt directory.
63    pub file: String,
64    /// The lowercase hexadecimal SHA-256 of the file, checked on every read.
65    pub sha256: String,
66}
67/// A job envelope `optimization.job/0.1` (the guide's section [Envelope](https://github.com/dietmarwo/optimization-jobs/blob/main/docs/job-api.md#envelope)).
68#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
69#[serde(deny_unknown_fields)]
70pub struct JobSpec {
71    /// Exactly [`SCHEMA`].
72    pub schema_version: String,
73    /// The caller-chosen idempotency key, 1 to 200 bytes. [`JobSpec::digest`]
74    /// excludes it.
75    pub request_key: String,
76    /// The ID of the registered worker that runs the job.
77    pub worker: String,
78    /// The worker profile the payload follows, such as `lp-ip.solve/1`.
79    pub payload_schema: String,
80    /// The profile's options (model, algorithm and budget) as a JSON object.
81    /// The worker rejects unknown fields.
82    pub payload: Value,
83    /// The CPU slots of the job.
84    pub resources: Resources,
85    /// The time limits of the job.
86    pub limits: Limits,
87    /// Input files, at most 16; empty for a model without data.
88    #[serde(default)]
89    pub inputs: Vec<Input>,
90    /// Filled by the worker during validation, never inferred by the runner.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub task_count: Option<usize>,
93}
94/// True for a plain name of 1 to 80 bytes of ASCII letters, digits, `-`, `_`
95/// and `.`, other than `.` and `..`. Worker IDs and the names of inputs,
96/// artifacts and work counters are safe names.
97pub fn safe_name(s: &str) -> bool {
98    !s.is_empty()
99        && s.len() <= 80
100        && s.bytes()
101            .all(|c| c.is_ascii_alphanumeric() || b"-_.".contains(&c))
102        && s != "."
103        && s != ".."
104}
105impl JobSpec {
106    /// Checks the envelope's rules without reading a file: the schema
107    /// version, the request key and worker name, `outer_workers *
108    /// inner_threads <= cpu_slots <= 1024`, the time limits, at most 1,000,000
109    /// tasks and 16 inputs, and inputs with unique names, contained relative
110    /// paths and lowercase SHA-256 values.
111    pub fn validate(&self) -> Result<()> {
112        if self.schema_version != SCHEMA
113            || self.request_key.is_empty()
114            || self.request_key.len() > 200
115            || !safe_name(&self.worker)
116            || self.payload_schema.is_empty()
117            || !self.payload.is_object()
118        {
119            return Err("invalid job envelope, schema, request_key or worker".into());
120        }
121        let r = &self.resources;
122        if r.cpu_slots == 0
123            || r.cpu_slots > 1024
124            || r.outer_workers == 0
125            || r.inner_threads == 0
126            || r.outer_workers
127                .checked_mul(r.inner_threads)
128                .is_none_or(|n| n > r.cpu_slots)
129        {
130            return Err(
131                "resources require 1 <= outer_workers * inner_threads <= cpu_slots <= 1024".into(),
132            );
133        }
134        if !self.limits.wall_time_seconds.is_finite()
135            || !(0.0..=31_536_000.0).contains(&self.limits.wall_time_seconds)
136            || self.limits.wall_time_seconds == 0.0
137            || !self.limits.grace_seconds.is_finite()
138            || !(0.0..=86400.0).contains(&self.limits.grace_seconds)
139        {
140            return Err("invalid wall time or grace".into());
141        }
142        if self.task_count.is_some_and(|n| n == 0 || n > 1_000_000) || self.inputs.len() > 16 {
143            return Err("invalid task/input count".into());
144        }
145        let mut names = BTreeSet::new();
146        for i in &self.inputs {
147            if !safe_name(&i.name)
148                || !names.insert(&i.name)
149                || i.sha256.len() != 64
150                || !i
151                    .sha256
152                    .bytes()
153                    .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
154                || i.file.is_empty()
155                || Path::new(&i.file)
156                    .components()
157                    .any(|c| !matches!(c, Component::Normal(_) | Component::CurDir))
158                || !Path::new(&i.file)
159                    .components()
160                    .any(|c| matches!(c, Component::Normal(_)))
161            {
162                return Err("input requires unique safe name, relative contained path and lowercase SHA-256".into());
163            }
164        }
165        Ok(())
166    }
167    /// The `spec_digest` that identifies the experiment: the SHA-256 of the
168    /// specification without its request key.
169    pub fn digest(&self) -> Result<String> {
170        let mut v = serde_json::to_value(self)?;
171        v.as_object_mut().unwrap().remove("request_key");
172        Ok(storage::digest(&serde_json::to_vec(&v)?))
173    }
174    /// The bytes of the input named `name`, read relative to `base` and
175    /// checked by [`checked_input`].
176    pub fn input_bytes(&self, base: &Path, name: &str) -> Result<Vec<u8>> {
177        let input = self
178            .inputs
179            .iter()
180            .find(|i| i.name == name)
181            .ok_or("missing model input")?;
182        checked_input(base, input)
183    }
184}
185/// Reads `input` relative to `base`. Fails if its path leaves `base`, also
186/// through a symbolic link, if the file exceeds [`MAX_INPUT_BYTES`], or if its
187/// SHA-256 differs from `input.sha256`.
188pub fn checked_input(base: &Path, input: &Input) -> Result<Vec<u8>> {
189    let base = fs::canonicalize(base)?;
190    let path = fs::canonicalize(base.join(&input.file))?;
191    if !path.starts_with(&base) || !path.is_file() || fs::metadata(&path)?.len() > MAX_INPUT_BYTES {
192        return Err("input escapes directory or exceeds 64 MiB".into());
193    }
194    // The bounded read also covers a file that grows after the metadata check.
195    use std::io::Read;
196    let mut bytes = Vec::new();
197    fs::File::open(path)?
198        .take(MAX_INPUT_BYTES + 1)
199        .read_to_end(&mut bytes)?;
200    if bytes.len() as u64 > MAX_INPUT_BYTES || storage::digest(&bytes) != input.sha256 {
201        return Err("input SHA-256 mismatch or oversized input".into());
202    }
203    Ok(bytes)
204}
205/// Copies the inputs of `s` from `from` into `to/inputs`, each checked by
206/// [`checked_input`] and synced, and points each input's `file` at its copy.
207pub fn stage_inputs(s: &mut JobSpec, from: &Path, to: &Path) -> Result<()> {
208    fs::create_dir_all(to.join("inputs"))?;
209    for i in &mut s.inputs {
210        let bytes = checked_input(from, i)?;
211        i.file = format!("inputs/{}", i.name);
212        let path = to.join(&i.file);
213        fs::write(&path, bytes)?;
214        fs::File::open(path)?.sync_all()?;
215    }
216    fs::File::open(to.join("inputs"))?.sync_all()?;
217    Ok(())
218}
219/// A submitted job, in the current envelope or in the legacy format.
220#[derive(Clone, Debug, Serialize)]
221#[serde(untagged)]
222pub enum Request {
223    /// An `fcmaes.job/0.1` job, resolved by [`legacy::JobSpec::resolve`].
224    Legacy(legacy::JobSpec),
225    /// An `optimization.job/0.1` job, checked by [`JobSpec::validate`].
226    Job(JobSpec),
227}
228impl Request {
229    /// Parses and validates a submitted job; every failure is `invalid_job`.
230    pub fn parse(bytes: &[u8]) -> Result<Self> {
231        Self::parse_unchecked(bytes).map_err(|e| coded("invalid_job", e.to_string()))
232    }
233    fn parse_unchecked(bytes: &[u8]) -> Result<Self> {
234        let v: Value = serde_json::from_slice(bytes)?;
235        match v["schema_version"].as_str() {
236            Some("fcmaes.job/0.1") => Ok(Self::Legacy(
237                serde_json::from_value::<legacy::JobSpec>(v)?.resolve()?,
238            )),
239            Some(SCHEMA) => {
240                let s: JobSpec = serde_json::from_value(v)?;
241                s.validate()?;
242                Ok(Self::Job(s))
243            }
244            _ => Err("unsupported job schema".into()),
245        }
246    }
247    /// The caller's idempotency key.
248    pub fn request_key(&self) -> &str {
249        match self {
250            Self::Legacy(s) => &s.request_key,
251            Self::Job(s) => &s.request_key,
252        }
253    }
254    /// The worker ID; `native` for a legacy job.
255    pub fn worker(&self) -> &str {
256        match self {
257            Self::Legacy(_) => "native",
258            Self::Job(s) => &s.worker,
259        }
260    }
261    /// The CPU slots the job reserves: `cpu_slots`, or `execution.workers`
262    /// for a legacy job.
263    pub fn slots(&self) -> usize {
264        match self {
265            Self::Legacy(s) => s.execution.workers,
266            Self::Job(s) => s.resources.cpu_slots,
267        }
268    }
269    /// The wall-time limit in seconds.
270    pub fn wall(&self) -> f64 {
271        match self {
272            Self::Legacy(s) => s.budget.wall_time_seconds,
273            Self::Job(s) => s.limits.wall_time_seconds,
274        }
275    }
276    /// The grace period after the wall-time limit, in seconds.
277    pub fn grace(&self) -> f64 {
278        match self {
279            Self::Legacy(s) => s.budget.grace_seconds,
280            Self::Job(s) => s.limits.grace_seconds,
281        }
282    }
283    /// The job's `spec_digest`, which excludes the request key.
284    pub fn digest(&self) -> Result<String> {
285        match self {
286            Self::Legacy(s) => s.digest(),
287            Self::Job(s) => s.digest(),
288        }
289    }
290    /// Writes the job as JSON to `path`, atomically.
291    pub fn save(&self, path: &Path) -> Result<()> {
292        Ok(storage::write_atomic_json(path, self)?)
293    }
294}