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/// Restrict fingerprint preparation to the required Eval key inputs.
79pub(crate) fn fingerprint_targets<'a>(
80    config: &'a RepoConfig,
81    required: &BTreeSet<&'a ArtifactName>,
82) -> BTreeSet<&'a ArtifactName> {
83    config
84        .evals
85        .iter()
86        .filter(|eval| required.contains(&eval.target))
87        .flat_map(|eval| dependencies(config, eval))
88        .collect()
89}
90
91/// A Live input is an observation boundary, not a file. Composition counts as coverage too.
92pub(crate) fn live_input<'a>(config: &'a RepoConfig, eval: &'a Eval) -> Option<&'a ArtifactName> {
93    dependencies(config, eval)
94        .into_iter()
95        .find(|name| config.artifacts[*name].kind() == crate::config::ArtifactKind::Live)
96}
97
98/// The reuse key of an Eval definition hash over these fingerprints.
99pub fn key(
100    eval_def_hash: &crate::types::DefinitionHash,
101    fingerprints: &BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>,
102) -> crate::types::ReuseKey {
103    let mut digest = Sha256::new();
104    digest.update(format!("{REUSE_KEY_FORMAT_PREFIX}eval {eval_def_hash}\n"));
105    // Names are identifiers and fingerprints never contain spaces or line breaks.
106    for (name, fingerprint) in fingerprints {
107        digest.update(format!("artifact {name} {fingerprint}\n"));
108    }
109    content::hex(&digest.finalize())
110        .parse()
111        .expect("SHA-256 is a reuse key")
112}
113
114/// Scope kinds distinguish file/folder observation without coupling reuse to repo paths.
115pub fn key_with_kinds(
116    eval_def_hash: &crate::types::DefinitionHash,
117    fingerprints: &BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>,
118    kinds: &BTreeMap<crate::types::ArtifactName, crate::config::ArtifactKind>,
119) -> crate::types::ReuseKey {
120    if kinds.is_empty() {
121        return key(eval_def_hash, fingerprints);
122    }
123    let mut digest = Sha256::new();
124    digest.update(KIND_KEY_FORMAT_PREFIX);
125    digest.update(key(eval_def_hash, fingerprints).as_bytes());
126    digest.update(serde_json::to_vec(kinds).expect("Artifact kinds are JSON"));
127    content::hex(&digest.finalize())
128        .parse()
129        .expect("SHA-256 is a reuse key")
130}
131
132/// Versioned composition format over the complete, kind-aware input map. The map already
133/// contains each part once; no content is rehashed and no persistence schema changes.
134pub(crate) fn parts_key(value: &crate::types::ReuseKey) -> crate::types::ReuseKey {
135    let mut digest = Sha256::new();
136    digest.update(PARTS_KEY_FORMAT_PREFIX);
137    digest.update(value.as_bytes());
138    content::hex(&digest.finalize())
139        .parse()
140        .expect("SHA-256 is a reuse key")
141}
142
143/// The eval's reuse key from prepared fingerprints. Without a fingerprint on every Artifact
144/// it depends on, the eval has no key, so it is never reused or published.
145pub fn eval_key(
146    config: &RepoConfig,
147    eval: &Eval,
148    fingerprints: &BTreeMap<&ArtifactName, PreparedFingerprint>,
149) -> Result<Key, Unkeyed> {
150    if matches!(eval.declaration.profile(), Profile::Runtime { .. })
151        && let Some(id) = live_input(config, eval)
152    {
153        return Err(Unkeyed::LiveObservation(id.clone()));
154    }
155    if !fingerprints.contains_key(&eval.target) {
156        return Err(
157            if config.artifacts[&eval.target].kind() == crate::config::ArtifactKind::Live {
158                Unkeyed::LiveUnobserved(eval.target.clone())
159            } else {
160                Unkeyed::Target
161            },
162        );
163    }
164    let values = dependencies(config, eval)
165        .into_iter()
166        .map(|id| {
167            let fingerprint = fingerprints.get(id).ok_or_else(|| {
168                if config.artifacts[id].kind() == crate::config::ArtifactKind::Live {
169                    Unkeyed::LiveUnobserved(id.clone())
170                } else {
171                    Unkeyed::Dependency(id.clone())
172                }
173            })?;
174            Ok((id.clone(), fingerprint.value.clone()))
175        })
176        .collect::<Result<BTreeMap<_, _>, Unkeyed>>()?;
177    let eval_def_hash = eval_definition_hash(&eval.declaration);
178    let artifact_kinds = values
179        .keys()
180        .map(|id| (id.clone(), config.artifacts[id].kind()))
181        .collect();
182    let value = key_with_kinds(&eval_def_hash, &values, &artifact_kinds);
183    let value = if config.artifacts[&eval.target].parts.is_empty() {
184        value
185    } else {
186        parts_key(&value)
187    };
188    Ok(Key {
189        value,
190        eval_def_hash,
191        fingerprints: values,
192        artifact_kinds,
193    })
194}
195
196/// Keys of every eval whose dependency Artifacts were all prepared, by eval id.
197pub fn eval_keys<'a>(
198    config: &'a RepoConfig,
199    fingerprints: &BTreeMap<&ArtifactName, PreparedFingerprint>,
200) -> BTreeMap<&'a crate::types::EvalId, Key> {
201    config
202        .evals
203        .iter()
204        .filter_map(|eval| Some((&eval.id, eval_key(config, eval, fingerprints).ok()?)))
205        .collect()
206}