1use 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
24const ALGORITHM: &str = "sha256:";
26const RUN_KEY_DOMAIN: &str = "kitchen-run-v2";
28
29#[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 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 pub fn from_sha256(digest: &[u8]) -> Self {
47 Self(format!("{ALGORITHM}{}", to_hex(digest)))
48 }
49
50 pub fn of_bytes(bytes: &[u8]) -> Self {
52 Self::from_sha256(&Sha256::digest(bytes))
53 }
54
55 pub fn of_json(value: &serde_json::Value) -> Self {
57 Self::of_bytes(canonical_json(value).as_bytes())
58 }
59
60 pub fn as_str(&self) -> &str {
62 &self.0
63 }
64
65 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
100pub fn to_hex(bytes: &[u8]) -> String {
102 bytes.iter().map(|b| format!("{b:02x}")).collect()
103}
104
105pub 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#[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 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 pub fn from_fields(fields: &serde_json::Value) -> Self {
149 Self(ContentId::of_json(fields).into())
150 }
151
152 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 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
194pub struct ResultRecord {
195 pub id: ContentId,
197 #[serde(rename = "type")]
199 pub ty: Type,
200 pub format: Format,
202 pub size: u64,
204 #[serde(default, skip_serializing_if = "Option::is_none")]
206 pub run: Option<String>,
207 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
210 pub incomplete: bool,
211}
212
213#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
215#[serde(tag = "status", rename_all = "snake_case")]
216pub enum RunStatus {
217 Succeeded,
219 Failed {
221 why: String,
223 },
224 Cancelled,
226}
227
228#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
230pub struct OpRef {
231 pub id: String,
233 pub version: String,
235}
236
237#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
240pub struct RunRecord {
241 pub contract: String,
243 pub run: String,
245 pub op: OpRef,
247 #[serde(default)]
249 pub params: BTreeMap<String, ParamValue>,
250 #[serde(default)]
252 pub inputs: BTreeMap<String, ContentId>,
253 #[serde(default)]
255 pub outputs: BTreeMap<String, ContentId>,
256 pub by: String,
258 pub via: String,
260 pub started: String,
262 #[serde(default, skip_serializing_if = "Option::is_none")]
264 pub ended: Option<String>,
265 #[serde(flatten)]
267 pub status: RunStatus,
268 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
271 pub environment: BTreeMap<String, serde_json::Value>,
272 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
274 pub metrics: BTreeMap<String, serde_json::Value>,
275 pub run_key: RunKey,
277}
278
279impl RunRecord {
280 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", ¶ms, &inputs);
315 assert_eq!(key, RunKey::of("dspk:highpass", "v1", ¶ms.clone(), &inputs.clone()));
316 assert_ne!(key, RunKey::of("dspk:highpass", "v2", ¶ms, &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", ¶ms, &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", ¶ms, &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}