Skip to main content

kitchen_contract/
results.rs

1//! Results and run records ([standard §3](../../../standard/spec/03-results.md)).
2//!
3//! - [`ContentId`]: `sha256:` and 64 hex digits, the same bytes giving the same id wherever they
4//!   are (decision 0003). Hashing files and Zarr folders reads them, so it is the runtime's
5//!   (kitchen-store' `identify`); the id itself is the contract's.
6//! - [`canonical_json`]: object keys sorted, no whitespace, so the order fields were written in
7//!   never changes a hash.
8//! - [`ResultRecord`]: a stored result, with its type, format and the run that made it.
9//! - [`RunRecord`]: every run leaves one: which op at which version, its parameters, its inputs
10//!   and outputs by id, who ran it and through what, how it ended.
11//! - [`RunKey`]: what decides a run's result, so an identical run is recognized and reused.
12
13use std::borrow::Cow;
14use std::collections::BTreeMap;
15use std::fmt;
16
17use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
18use serde::{Deserialize, Serialize};
19use sha2::{Digest, Sha256};
20
21use crate::params::ParamValue;
22use crate::types::{Format, Type};
23
24/// Prefix of every id: the algorithm, so another can be added without ambiguity.
25const ALGORITHM: &str = "sha256:";
26/// What every run key's hash starts with: the key format's version.
27const RUN_KEY_DOMAIN: &str = "kitchen-run-v2";
28
29/// A result's content identity: `sha256:<64 lowercase hex digits>`.
30#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
31#[serde(try_from = "String", into = "String")]
32pub struct ContentId(String);
33
34impl ContentId {
35    /// `text` as an id, checked.
36    pub fn parse(text: &str) -> Result<Self, String> {
37        let hex = text.strip_prefix(ALGORITHM).unwrap_or("");
38        if hex.len() == 64 && hex.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()) {
39            Ok(Self(text.to_string()))
40        } else {
41            Err(format!("content id {text:?}: expected sha256:<64 lowercase hex digits>"))
42        }
43    }
44
45    /// The id of a SHA-256 digest (32 bytes).
46    pub fn from_sha256(digest: &[u8]) -> Self {
47        Self(format!("{ALGORITHM}{}", to_hex(digest)))
48    }
49
50    /// The id of `bytes`.
51    pub fn of_bytes(bytes: &[u8]) -> Self {
52        Self::from_sha256(&Sha256::digest(bytes))
53    }
54
55    /// The id of a JSON value: the hash of its canonical form (a pipeline's, a recipe's).
56    pub fn of_json(value: &serde_json::Value) -> Self {
57        Self::of_bytes(canonical_json(value).as_bytes())
58    }
59
60    /// The id as text.
61    pub fn as_str(&self) -> &str {
62        &self.0
63    }
64
65    /// The first 12 hex digits, for names and logs.
66    pub fn short(&self) -> &str {
67        &self.0[ALGORITHM.len()..ALGORITHM.len() + 12]
68    }
69}
70
71impl fmt::Display for ContentId {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.write_str(&self.0)
74    }
75}
76
77impl TryFrom<String> for ContentId {
78    type Error = String;
79    fn try_from(text: String) -> Result<Self, String> {
80        Self::parse(&text)
81    }
82}
83
84impl From<ContentId> for String {
85    fn from(id: ContentId) -> String {
86        id.0
87    }
88}
89
90impl JsonSchema for ContentId {
91    fn schema_name() -> Cow<'static, str> {
92        "ContentId".into()
93    }
94
95    fn json_schema(_: &mut SchemaGenerator) -> Schema {
96        json_schema!({ "type": "string", "pattern": "^sha256:[0-9a-f]{64}$" })
97    }
98}
99
100/// Lowercase hex of `bytes`.
101pub fn to_hex(bytes: &[u8]) -> String {
102    bytes.iter().map(|b| format!("{b:02x}")).collect()
103}
104
105/// `value` as JSON with every object's keys sorted and no whitespace.
106pub fn canonical_json(value: &serde_json::Value) -> String {
107    use serde_json::Value;
108    match value {
109        Value::Object(map) => {
110            let mut keys: Vec<&String> = map.keys().collect();
111            keys.sort();
112            let fields: Vec<String> =
113                keys.into_iter().map(|k| format!("{}:{}", Value::String(k.clone()), canonical_json(&map[k]))).collect();
114            format!("{{{}}}", fields.join(","))
115        }
116        Value::Array(items) => format!("[{}]", items.iter().map(canonical_json).collect::<Vec<_>>().join(",")),
117        other => other.to_string(),
118    }
119}
120
121/// A run's key: `sha256:<hex>`, the hash of what decides its result.
122#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
123#[serde(try_from = "String", into = "String")]
124pub struct RunKey(String);
125
126impl RunKey {
127    /// The key of running op `op` at `version` (its [`OpSpec::version_key`](crate::OpSpec::version_key))
128    /// with `params` (every one, defaults filled) on `inputs` (port → result id). Run options and
129    /// metrics are not in it: they change how fast, not what.
130    pub fn of(
131        op: &str,
132        version: &str,
133        params: &BTreeMap<String, ParamValue>,
134        inputs: &BTreeMap<String, ContentId>,
135    ) -> Self {
136        let fields = serde_json::json!({
137            "key": RUN_KEY_DOMAIN,
138            "op": op,
139            "version": version,
140            "params": params,
141            "inputs": inputs,
142        });
143        Self::from_fields(&fields)
144    }
145
146    /// The key of any JSON `fields` (a tool run's: tool, image, operation, recipe), hashed in
147    /// canonical form.
148    pub fn from_fields(fields: &serde_json::Value) -> Self {
149        Self(ContentId::of_json(fields).into())
150    }
151
152    /// `text` as a key, checked.
153    pub fn parse(text: &str) -> Result<Self, String> {
154        ContentId::parse(text).map(|id| Self(id.into())).map_err(|_| format!("run key {text:?}"))
155    }
156
157    /// The key as text.
158    pub fn as_str(&self) -> &str {
159        &self.0
160    }
161}
162
163impl fmt::Display for RunKey {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        f.write_str(&self.0)
166    }
167}
168
169impl TryFrom<String> for RunKey {
170    type Error = String;
171    fn try_from(text: String) -> Result<Self, String> {
172        Self::parse(&text)
173    }
174}
175
176impl From<RunKey> for String {
177    fn from(key: RunKey) -> String {
178        key.0
179    }
180}
181
182impl JsonSchema for RunKey {
183    fn schema_name() -> Cow<'static, str> {
184        "RunKey".into()
185    }
186
187    fn json_schema(_: &mut SchemaGenerator) -> Schema {
188        json_schema!({ "type": "string", "pattern": "^sha256:[0-9a-f]{64}$" })
189    }
190}
191
192/// A stored result ([standard §3.1](../../../standard/spec/03-results.md)).
193#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
194pub struct ResultRecord {
195    /// Its content id.
196    pub id: ContentId,
197    /// What it is.
198    #[serde(rename = "type")]
199    pub ty: Type,
200    /// How it is encoded.
201    pub format: Format,
202    /// Its size in bytes.
203    pub size: u64,
204    /// The run that made it (`None` for a source the store was given).
205    #[serde(default, skip_serializing_if = "Option::is_none")]
206    pub run: Option<String>,
207    /// Made by a run that was cancelled: usable and exportable, its metadata says *run
208    /// incomplete*, and never reused by run key.
209    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
210    pub incomplete: bool,
211}
212
213/// How a run ended.
214#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
215#[serde(tag = "status", rename_all = "snake_case")]
216pub enum RunStatus {
217    /// Every output written.
218    Succeeded,
219    /// It stopped, and why.
220    Failed {
221        /// Why, said for people.
222        why: String,
223    },
224    /// Cancelled: its outputs so far are kept, marked incomplete.
225    Cancelled,
226}
227
228/// The op a run ran, at which version.
229#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
230pub struct OpRef {
231    /// Its id.
232    pub id: String,
233    /// Its [`OpSpec::version_key`](crate::OpSpec::version_key): `v<n>`, or a script's or recipe's hash.
234    pub version: String,
235}
236
237/// Every run of an op (or a pipeline) leaves one ([standard §3.2](../../../standard/spec/03-results.md)).
238/// Appended, never edited: a correction is a new run.
239#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
240pub struct RunRecord {
241    /// The contract version it was written under ([`CONTRACT_VERSION`](crate::CONTRACT_VERSION)).
242    pub contract: String,
243    /// Its id.
244    pub run: String,
245    /// The op that ran.
246    pub op: OpRef,
247    /// Every parameter, defaults filled.
248    #[serde(default)]
249    pub params: BTreeMap<String, ParamValue>,
250    /// Port → result id (for a source the app reads, the source's id).
251    #[serde(default)]
252    pub inputs: BTreeMap<String, ContentId>,
253    /// Port → result id.
254    #[serde(default)]
255    pub outputs: BTreeMap<String, ContentId>,
256    /// Who: a person.
257    pub by: String,
258    /// Through what: an app, a generated interface, an agent.
259    pub via: String,
260    /// When it started (RFC 3339).
261    pub started: String,
262    /// When it ended (RFC 3339).
263    #[serde(default, skip_serializing_if = "Option::is_none")]
264    pub ended: Option<String>,
265    /// How it ended.
266    #[serde(flatten)]
267    pub status: RunStatus,
268    /// The runtime's and the app's versions, the device, and the run's options (piece size,
269    /// read-ahead, threads, upload mode).
270    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
271    pub environment: BTreeMap<String, serde_json::Value>,
272    /// Time per op, bytes read, moved and written; never part of the run key.
273    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
274    pub metrics: BTreeMap<String, serde_json::Value>,
275    /// What decides its result ([`RunKey::of`]).
276    pub run_key: RunKey,
277}
278
279impl RunRecord {
280    /// Whether its outputs may stand in for an identical later run: it succeeded and its op acts
281    /// on nothing outside the store.
282    pub fn reusable(&self, effects: bool) -> bool {
283        self.status == RunStatus::Succeeded && !effects
284    }
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    fn id(c: char) -> ContentId {
292        ContentId::parse(&format!("sha256:{}", c.to_string().repeat(64))).unwrap()
293    }
294
295    #[test]
296    fn ids_parse_and_hash() {
297        assert!(ContentId::parse("sha256:abc").is_err());
298        assert!(ContentId::parse(&format!("sha256:{}", "A".repeat(64))).is_err(), "lowercase only");
299        assert_eq!(
300            ContentId::of_bytes(b"abc").as_str(),
301            "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
302        );
303        assert_eq!(id('a').short(), "aaaaaaaaaaaa");
304        let a: serde_json::Value = serde_json::from_str(r#"{"b":1,"a":[2,{"d":3,"c":4}]}"#).unwrap();
305        assert_eq!(canonical_json(&a), r#"{"a":[2,{"c":4,"d":3}],"b":1}"#);
306        let reordered: serde_json::Value = serde_json::from_str(r#"{"a":[2,{"c":4,"d":3}],"b":1}"#).unwrap();
307        assert_eq!(ContentId::of_json(&a), ContentId::of_json(&reordered));
308    }
309
310    #[test]
311    fn the_same_run_has_the_same_key() {
312        let params: BTreeMap<String, ParamValue> = [("cutoff_hz".to_string(), ParamValue::Number(300.0))].into();
313        let inputs: BTreeMap<String, ContentId> = [("signal".to_string(), id('a'))].into();
314        let key = RunKey::of("dspk:highpass", "v1", &params, &inputs);
315        assert_eq!(key, RunKey::of("dspk:highpass", "v1", &params.clone(), &inputs.clone()));
316        assert_ne!(key, RunKey::of("dspk:highpass", "v2", &params, &inputs), "a new version runs again");
317        let other: BTreeMap<String, ContentId> = [("signal".to_string(), id('b'))].into();
318        assert_ne!(key, RunKey::of("dspk:highpass", "v1", &params, &other));
319        assert!(RunKey::parse(key.as_str()).is_ok());
320    }
321
322    #[test]
323    fn run_records_read_and_say_what_may_be_reused() {
324        let params: BTreeMap<String, ParamValue> = BTreeMap::new();
325        let inputs: BTreeMap<String, ContentId> = [("signal".to_string(), id('a'))].into();
326        let record = RunRecord {
327            contract: crate::CONTRACT_VERSION.into(),
328            run: "run-1".into(),
329            op: OpRef { id: "dspk:kilosort".into(), version: "v4".into() },
330            params: params.clone(),
331            inputs: inputs.clone(),
332            outputs: [("sorting".to_string(), id('b'))].into(),
333            by: "ana".into(),
334            via: "dsp-kitchen".into(),
335            started: "2026-11-27T10:00:00Z".into(),
336            ended: Some("2026-11-27T12:10:00Z".into()),
337            status: RunStatus::Cancelled,
338            environment: [("device".to_string(), serde_json::json!("cuda:0"))].into(),
339            metrics: BTreeMap::new(),
340            run_key: RunKey::of("dspk:kilosort", "v4", &params, &inputs),
341        };
342        let json = serde_json::to_string(&record).unwrap();
343        assert!(json.contains(r#""status":"cancelled""#), "{json}");
344        let back: RunRecord = serde_json::from_str(&json).unwrap();
345        assert_eq!(back, record);
346        assert!(!record.reusable(false), "a cancelled run is never reused");
347        let done = RunRecord { status: RunStatus::Succeeded, ..record };
348        assert!(done.reusable(false));
349        assert!(!done.reusable(true), "an op with effects is never reused");
350        let failed: RunStatus = serde_json::from_str(r#"{"status":"failed","why":"out of memory"}"#).unwrap();
351        assert_eq!(failed, RunStatus::Failed { why: "out of memory".into() });
352    }
353}