Skip to main content

artifactize_core/cache/
key.rs

1//! Pure Eval criteria hashes, dependency coverage, and reuse keys.
2
3use super::{PreparedFingerprint, content};
4use crate::config::{ArtifactName, Eval, EvalDeclaration, Profile, RepoConfig};
5use serde_json::json;
6use sha2::{Digest, Sha256};
7use std::collections::{BTreeMap, BTreeSet};
8
9/// Domain-separated kind-aware key format; changes invalidate persisted cache keys.
10const KIND_KEY_FORMAT_PREFIX: &[u8] = b"artifactize-kind-key-v1\n";
11/// Composition keys have new coverage semantics. Invalidate old whole results even when
12/// their eval already named every part. Stored rows need no migration: old keys miss naturally.
13const PARTS_KEY_FORMAT_PREFIX: &[u8] = b"artifactize-parts-key-v1\n";
14/// Domain-separate and version the reuse-key hash input, including its terminating newline.
15/// Changing these bytes invalidates existing reuse keys; this is not a config/session/DB version.
16const REUSE_KEY_FORMAT_PREFIX: &str = "artifactize-key-v3\n";
17
18/// Hash the evaluation criteria: what is asked and how the answer is judged, never how the eval
19/// is executed. Execution options (backend, model, reasoning, limits, the named profile), the
20/// eval's id and title, a runtime eval's instruction and tool views stay out.
21pub fn eval_definition_hash(eval: &EvalDeclaration) -> crate::types::DefinitionHash {
22    let mut criteria = match &eval.profile() {
23        Profile::Agent { .. } => json!({"kind": "agent", "payload": eval.payload()}),
24        Profile::Human {} => json!({"kind": "human", "payload": eval.payload()}),
25        // A runtime eval's verdict is its command's exit code; its prose instruction is not.
26        Profile::Runtime { command, args, .. } => json!({
27            "kind": "runtime",
28            "command": command,
29            "args": args,
30            "inputs": eval.inputs(),
31        }),
32    };
33    // Only an Agent eval declares a bar, so other evals keep their criteria hashes.
34    if let Some(red_at) = eval.red_at() {
35        criteria["redAt"] = json!(red_at);
36    }
37    criteria.sort_all_objects();
38    content::hex(&Sha256::digest(
39        serde_json::to_vec(&criteria).expect("evaluation criteria is JSON"),
40    ))
41    .parse()
42    .expect("a SHA-256 digest in hex is a definition hash")
43}
44
45/// An eval's reuse key: `hash(evaluation criteria, sorted (name, fingerprint) of the Artifacts it
46/// depends on)`.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct Key {
49    pub value: crate::types::ReuseKey,
50    pub eval_def_hash: crate::types::DefinitionHash,
51    /// Each Artifact the eval depends on, its target included, with its fingerprint.
52    pub fingerprints: BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>,
53    pub artifact_kinds: BTreeMap<crate::types::ArtifactName, crate::config::ArtifactKind>,
54}
55
56/// Why an eval has no reuse key: an Artifact it depends on declares `fingerprint: false`.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum Unkeyed {
59    /// The eval's own target.
60    Target,
61    /// A child or referenced Artifact.
62    Dependency(ArtifactName),
63    /// Runtime observations of external state always execute.
64    LiveObservation(ArtifactName),
65    /// A Live input has no observed-state snapshot.
66    LiveUnobserved(ArtifactName),
67}
68
69/// Key inputs: the target, every part it is made of, and the Artifacts the eval names.
70/// Composition is recursive; references stay one hop and grant no additional tool access.
71pub fn dependencies<'a>(config: &'a RepoConfig, eval: &'a Eval) -> BTreeSet<&'a ArtifactName> {
72    std::iter::once(&eval.target)
73        .chain(config.descendants(&eval.target))
74        .chain(&eval.deps)
75        .collect()
76}
77
78/// A Live input is an observation boundary, not a file. Composition counts as coverage too.
79pub(crate) fn live_input<'a>(config: &'a RepoConfig, eval: &'a Eval) -> Option<&'a ArtifactName> {
80    dependencies(config, eval)
81        .into_iter()
82        .find(|name| config.artifacts[*name].kind() == crate::config::ArtifactKind::Live)
83}
84
85/// The reuse key of an Eval definition hash over these fingerprints.
86pub fn key(
87    eval_def_hash: &crate::types::DefinitionHash,
88    fingerprints: &BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>,
89) -> crate::types::ReuseKey {
90    let mut digest = Sha256::new();
91    digest.update(format!("{REUSE_KEY_FORMAT_PREFIX}eval {eval_def_hash}\n"));
92    // Names are identifiers and fingerprints never contain spaces or line breaks.
93    for (name, fingerprint) in fingerprints {
94        digest.update(format!("artifact {name} {fingerprint}\n"));
95    }
96    content::hex(&digest.finalize())
97        .parse()
98        .expect("SHA-256 is a reuse key")
99}
100
101/// Scope kinds distinguish file/folder observation without coupling reuse to repo paths.
102pub fn key_with_kinds(
103    eval_def_hash: &crate::types::DefinitionHash,
104    fingerprints: &BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>,
105    kinds: &BTreeMap<crate::types::ArtifactName, crate::config::ArtifactKind>,
106) -> crate::types::ReuseKey {
107    if kinds.is_empty() {
108        return key(eval_def_hash, fingerprints);
109    }
110    let mut digest = Sha256::new();
111    digest.update(KIND_KEY_FORMAT_PREFIX);
112    digest.update(key(eval_def_hash, fingerprints).as_bytes());
113    digest.update(serde_json::to_vec(kinds).expect("Artifact kinds are JSON"));
114    content::hex(&digest.finalize())
115        .parse()
116        .expect("SHA-256 is a reuse key")
117}
118
119/// Versioned composition format over the complete, kind-aware input map. The map already
120/// contains each part once; no content is rehashed and no persistence schema changes.
121pub(crate) fn parts_key(value: &crate::types::ReuseKey) -> crate::types::ReuseKey {
122    let mut digest = Sha256::new();
123    digest.update(PARTS_KEY_FORMAT_PREFIX);
124    digest.update(value.as_bytes());
125    content::hex(&digest.finalize())
126        .parse()
127        .expect("SHA-256 is a reuse key")
128}
129
130/// The eval's reuse key from prepared fingerprints. Without a fingerprint on every Artifact
131/// it depends on, the eval has no key, so it is never reused or published.
132pub fn eval_key(
133    config: &RepoConfig,
134    eval: &Eval,
135    fingerprints: &BTreeMap<&ArtifactName, PreparedFingerprint>,
136) -> Result<Key, Unkeyed> {
137    if matches!(eval.declaration.profile(), Profile::Runtime { .. })
138        && let Some(id) = live_input(config, eval)
139    {
140        return Err(Unkeyed::LiveObservation(id.clone()));
141    }
142    if !fingerprints.contains_key(&eval.target) {
143        return Err(
144            if config.artifacts[&eval.target].kind() == crate::config::ArtifactKind::Live {
145                Unkeyed::LiveUnobserved(eval.target.clone())
146            } else {
147                Unkeyed::Target
148            },
149        );
150    }
151    let values = dependencies(config, eval)
152        .into_iter()
153        .map(|id| {
154            let fingerprint = fingerprints.get(id).ok_or_else(|| {
155                if config.artifacts[id].kind() == crate::config::ArtifactKind::Live {
156                    Unkeyed::LiveUnobserved(id.clone())
157                } else {
158                    Unkeyed::Dependency(id.clone())
159                }
160            })?;
161            Ok((id.clone(), fingerprint.value.clone()))
162        })
163        .collect::<Result<BTreeMap<_, _>, Unkeyed>>()?;
164    let eval_def_hash = eval_definition_hash(&eval.declaration);
165    let artifact_kinds = values
166        .keys()
167        .map(|id| (id.clone(), config.artifacts[id].kind()))
168        .collect();
169    let value = key_with_kinds(&eval_def_hash, &values, &artifact_kinds);
170    let value = if config.artifacts[&eval.target].parts.is_empty() {
171        value
172    } else {
173        parts_key(&value)
174    };
175    Ok(Key {
176        value,
177        eval_def_hash,
178        fingerprints: values,
179        artifact_kinds,
180    })
181}
182
183/// Keys of every eval whose dependency Artifacts were all prepared, by eval id.
184pub fn eval_keys<'a>(
185    config: &'a RepoConfig,
186    fingerprints: &BTreeMap<&ArtifactName, PreparedFingerprint>,
187) -> BTreeMap<&'a crate::types::EvalId, Key> {
188    config
189        .evals
190        .iter()
191        .filter_map(|eval| Some((&eval.id, eval_key(config, eval, fingerprints).ok()?)))
192        .collect()
193}