use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt;
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::params::ParamValue;
use crate::types::{Format, Type};
const ALGORITHM: &str = "sha256:";
const RUN_KEY_DOMAIN: &str = "kitchen-run-v2";
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct ContentId(String);
impl ContentId {
pub fn parse(text: &str) -> Result<Self, String> {
let hex = text.strip_prefix(ALGORITHM).unwrap_or("");
if hex.len() == 64 && hex.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()) {
Ok(Self(text.to_string()))
} else {
Err(format!("content id {text:?}: expected sha256:<64 lowercase hex digits>"))
}
}
pub fn from_sha256(digest: &[u8]) -> Self {
Self(format!("{ALGORITHM}{}", to_hex(digest)))
}
pub fn of_bytes(bytes: &[u8]) -> Self {
Self::from_sha256(&Sha256::digest(bytes))
}
pub fn of_json(value: &serde_json::Value) -> Self {
Self::of_bytes(canonical_json(value).as_bytes())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn short(&self) -> &str {
&self.0[ALGORITHM.len()..ALGORITHM.len() + 12]
}
}
impl fmt::Display for ContentId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl TryFrom<String> for ContentId {
type Error = String;
fn try_from(text: String) -> Result<Self, String> {
Self::parse(&text)
}
}
impl From<ContentId> for String {
fn from(id: ContentId) -> String {
id.0
}
}
impl JsonSchema for ContentId {
fn schema_name() -> Cow<'static, str> {
"ContentId".into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({ "type": "string", "pattern": "^sha256:[0-9a-f]{64}$" })
}
}
pub fn to_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
pub fn canonical_json(value: &serde_json::Value) -> String {
use serde_json::Value;
match value {
Value::Object(map) => {
let mut keys: Vec<&String> = map.keys().collect();
keys.sort();
let fields: Vec<String> =
keys.into_iter().map(|k| format!("{}:{}", Value::String(k.clone()), canonical_json(&map[k]))).collect();
format!("{{{}}}", fields.join(","))
}
Value::Array(items) => format!("[{}]", items.iter().map(canonical_json).collect::<Vec<_>>().join(",")),
other => other.to_string(),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct RunKey(String);
impl RunKey {
pub fn of(
op: &str,
version: &str,
params: &BTreeMap<String, ParamValue>,
inputs: &BTreeMap<String, ContentId>,
) -> Self {
let fields = serde_json::json!({
"key": RUN_KEY_DOMAIN,
"op": op,
"version": version,
"params": params,
"inputs": inputs,
});
Self::from_fields(&fields)
}
pub fn from_fields(fields: &serde_json::Value) -> Self {
Self(ContentId::of_json(fields).into())
}
pub fn parse(text: &str) -> Result<Self, String> {
ContentId::parse(text).map(|id| Self(id.into())).map_err(|_| format!("run key {text:?}"))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for RunKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl TryFrom<String> for RunKey {
type Error = String;
fn try_from(text: String) -> Result<Self, String> {
Self::parse(&text)
}
}
impl From<RunKey> for String {
fn from(key: RunKey) -> String {
key.0
}
}
impl JsonSchema for RunKey {
fn schema_name() -> Cow<'static, str> {
"RunKey".into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({ "type": "string", "pattern": "^sha256:[0-9a-f]{64}$" })
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ResultRecord {
pub id: ContentId,
#[serde(rename = "type")]
pub ty: Type,
pub format: Format,
pub size: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub run: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub incomplete: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum RunStatus {
Succeeded,
Failed {
why: String,
},
Cancelled,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct OpRef {
pub id: String,
pub version: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct RunRecord {
pub contract: String,
pub run: String,
pub op: OpRef,
#[serde(default)]
pub params: BTreeMap<String, ParamValue>,
#[serde(default)]
pub inputs: BTreeMap<String, ContentId>,
#[serde(default)]
pub outputs: BTreeMap<String, ContentId>,
pub by: String,
pub via: String,
pub started: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ended: Option<String>,
#[serde(flatten)]
pub status: RunStatus,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub environment: BTreeMap<String, serde_json::Value>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub metrics: BTreeMap<String, serde_json::Value>,
pub run_key: RunKey,
}
impl RunRecord {
pub fn reusable(&self, effects: bool) -> bool {
self.status == RunStatus::Succeeded && !effects
}
}
#[cfg(test)]
mod tests {
use super::*;
fn id(c: char) -> ContentId {
ContentId::parse(&format!("sha256:{}", c.to_string().repeat(64))).unwrap()
}
#[test]
fn ids_parse_and_hash() {
assert!(ContentId::parse("sha256:abc").is_err());
assert!(ContentId::parse(&format!("sha256:{}", "A".repeat(64))).is_err(), "lowercase only");
assert_eq!(
ContentId::of_bytes(b"abc").as_str(),
"sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_eq!(id('a').short(), "aaaaaaaaaaaa");
let a: serde_json::Value = serde_json::from_str(r#"{"b":1,"a":[2,{"d":3,"c":4}]}"#).unwrap();
assert_eq!(canonical_json(&a), r#"{"a":[2,{"c":4,"d":3}],"b":1}"#);
let reordered: serde_json::Value = serde_json::from_str(r#"{"a":[2,{"c":4,"d":3}],"b":1}"#).unwrap();
assert_eq!(ContentId::of_json(&a), ContentId::of_json(&reordered));
}
#[test]
fn the_same_run_has_the_same_key() {
let params: BTreeMap<String, ParamValue> = [("cutoff_hz".to_string(), ParamValue::Number(300.0))].into();
let inputs: BTreeMap<String, ContentId> = [("signal".to_string(), id('a'))].into();
let key = RunKey::of("dspk:highpass", "v1", ¶ms, &inputs);
assert_eq!(key, RunKey::of("dspk:highpass", "v1", ¶ms.clone(), &inputs.clone()));
assert_ne!(key, RunKey::of("dspk:highpass", "v2", ¶ms, &inputs), "a new version runs again");
let other: BTreeMap<String, ContentId> = [("signal".to_string(), id('b'))].into();
assert_ne!(key, RunKey::of("dspk:highpass", "v1", ¶ms, &other));
assert!(RunKey::parse(key.as_str()).is_ok());
}
#[test]
fn run_records_read_and_say_what_may_be_reused() {
let params: BTreeMap<String, ParamValue> = BTreeMap::new();
let inputs: BTreeMap<String, ContentId> = [("signal".to_string(), id('a'))].into();
let record = RunRecord {
contract: crate::CONTRACT_VERSION.into(),
run: "run-1".into(),
op: OpRef { id: "dspk:kilosort".into(), version: "v4".into() },
params: params.clone(),
inputs: inputs.clone(),
outputs: [("sorting".to_string(), id('b'))].into(),
by: "ana".into(),
via: "dsp-kitchen".into(),
started: "2026-11-27T10:00:00Z".into(),
ended: Some("2026-11-27T12:10:00Z".into()),
status: RunStatus::Cancelled,
environment: [("device".to_string(), serde_json::json!("cuda:0"))].into(),
metrics: BTreeMap::new(),
run_key: RunKey::of("dspk:kilosort", "v4", ¶ms, &inputs),
};
let json = serde_json::to_string(&record).unwrap();
assert!(json.contains(r#""status":"cancelled""#), "{json}");
let back: RunRecord = serde_json::from_str(&json).unwrap();
assert_eq!(back, record);
assert!(!record.reusable(false), "a cancelled run is never reused");
let done = RunRecord { status: RunStatus::Succeeded, ..record };
assert!(done.reusable(false));
assert!(!done.reusable(true), "an op with effects is never reused");
let failed: RunStatus = serde_json::from_str(r#"{"status":"failed","why":"out of memory"}"#).unwrap();
assert_eq!(failed, RunStatus::Failed { why: "out of memory".into() });
}
}