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-v2\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 profile variant),
20/// the eval's id and title, and tool views stay out.
21pub fn eval_definition_hash(eval: &EvalDeclaration) -> crate::types::DefinitionHash {
22    let kind = match &eval.profile() {
23        Profile::Agent { .. } => "agent",
24        Profile::Human {} => "human",
25        Profile::Runtime { .. } => "runtime",
26    };
27    let mut criteria = json!({
28        "kind": kind,
29        "payload": eval.payload(),
30        "passSchema": eval.pass_schema(),
31        "failSchema": eval.fail_schema(),
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    if let Profile::Runtime { command, args, .. } = &eval.profile() {
38        criteria["command"] = json!(command);
39        criteria["args"] = json!(args);
40    }
41    criteria.sort_all_objects();
42    content::hex(&Sha256::digest(
43        serde_json::to_vec(&criteria).expect("evaluation criteria is JSON"),
44    ))
45    .parse()
46    .expect("a SHA-256 digest in hex is a definition hash")
47}
48
49/// An eval's reuse key: `hash(evaluation criteria, sorted (name, fingerprint) of the Artifacts it
50/// depends on)`.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Key {
53    pub value: crate::types::ReuseKey,
54    pub eval_def_hash: crate::types::DefinitionHash,
55    /// Each Artifact the eval depends on, its target included, with its fingerprint.
56    pub fingerprints: BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>,
57    pub artifact_kinds: BTreeMap<crate::types::ArtifactName, crate::config::ArtifactKind>,
58}
59
60/// Why an eval has no reuse key: an Artifact it depends on declares `fingerprint: false`.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum Unkeyed {
63    /// The eval's own target.
64    Target,
65    /// A child or referenced Artifact.
66    Dependency(ArtifactName),
67    /// Runtime observations of external state always execute.
68    LiveObservation(ArtifactName),
69    /// A Live input has no observed-state snapshot.
70    LiveUnobserved(ArtifactName),
71}
72
73/// Key inputs: the target, every part it is made of, and the Artifacts the eval names.
74/// Composition is recursive; references stay one hop and grant no additional tool access.
75pub fn dependencies<'a>(config: &'a RepoConfig, eval: &'a Eval) -> BTreeSet<&'a ArtifactName> {
76    std::iter::once(&eval.target)
77        .chain(config.descendants(&eval.target))
78        .chain(&eval.deps)
79        .collect()
80}
81
82/// Restrict fingerprint preparation to the required Eval key inputs.
83pub(crate) fn fingerprint_targets<'a>(
84    config: &'a RepoConfig,
85    required: &BTreeSet<&'a ArtifactName>,
86) -> BTreeSet<&'a ArtifactName> {
87    config
88        .evals
89        .iter()
90        .filter(|eval| required.contains(&eval.target))
91        .flat_map(|eval| dependencies(config, eval))
92        .collect()
93}
94
95/// A Live input is an observation boundary, not a file. Composition counts as coverage too.
96pub(crate) fn live_input<'a>(config: &'a RepoConfig, eval: &'a Eval) -> Option<&'a ArtifactName> {
97    dependencies(config, eval)
98        .into_iter()
99        .find(|name| config.artifacts[*name].kind() == crate::config::ArtifactKind::Live)
100}
101
102/// The reuse key of an Eval definition hash over these fingerprints.
103pub fn key(
104    eval_def_hash: &crate::types::DefinitionHash,
105    fingerprints: &BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>,
106) -> crate::types::ReuseKey {
107    let mut digest = Sha256::new();
108    digest.update(format!("{REUSE_KEY_FORMAT_PREFIX}eval {eval_def_hash}\n"));
109    // Names are identifiers and fingerprints never contain spaces or line breaks.
110    for (name, fingerprint) in fingerprints {
111        digest.update(format!("artifact {name} {fingerprint}\n"));
112    }
113    content::hex(&digest.finalize())
114        .parse()
115        .expect("SHA-256 is a reuse key")
116}
117
118/// Scope kinds distinguish file/folder observation without coupling reuse to repo paths.
119pub fn key_with_kinds(
120    eval_def_hash: &crate::types::DefinitionHash,
121    fingerprints: &BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>,
122    kinds: &BTreeMap<crate::types::ArtifactName, crate::config::ArtifactKind>,
123) -> crate::types::ReuseKey {
124    if kinds.is_empty() {
125        return key(eval_def_hash, fingerprints);
126    }
127    let mut digest = Sha256::new();
128    digest.update(KIND_KEY_FORMAT_PREFIX);
129    digest.update(key(eval_def_hash, fingerprints).as_bytes());
130    digest.update(serde_json::to_vec(kinds).expect("Artifact kinds are JSON"));
131    content::hex(&digest.finalize())
132        .parse()
133        .expect("SHA-256 is a reuse key")
134}
135
136/// Versioned composition format over the complete, kind-aware input map. The map already
137/// contains each part once; no content is rehashed and no persistence schema changes.
138pub(crate) fn parts_key(value: &crate::types::ReuseKey) -> crate::types::ReuseKey {
139    let mut digest = Sha256::new();
140    digest.update(PARTS_KEY_FORMAT_PREFIX);
141    digest.update(value.as_bytes());
142    content::hex(&digest.finalize())
143        .parse()
144        .expect("SHA-256 is a reuse key")
145}
146
147/// The eval's reuse key from prepared fingerprints. Without a fingerprint on every Artifact
148/// it depends on, the eval has no key, so it is never reused or published.
149pub fn eval_key(
150    config: &RepoConfig,
151    eval: &Eval,
152    fingerprints: &BTreeMap<&ArtifactName, PreparedFingerprint>,
153) -> Result<Key, Unkeyed> {
154    if matches!(eval.declaration.profile(), Profile::Runtime { .. })
155        && let Some(id) = live_input(config, eval)
156    {
157        return Err(Unkeyed::LiveObservation(id.clone()));
158    }
159    if !fingerprints.contains_key(&eval.target) {
160        return Err(
161            if config.artifacts[&eval.target].kind() == crate::config::ArtifactKind::Live {
162                Unkeyed::LiveUnobserved(eval.target.clone())
163            } else {
164                Unkeyed::Target
165            },
166        );
167    }
168    let values = dependencies(config, eval)
169        .into_iter()
170        .map(|id| {
171            let fingerprint = fingerprints.get(id).ok_or_else(|| {
172                if config.artifacts[id].kind() == crate::config::ArtifactKind::Live {
173                    Unkeyed::LiveUnobserved(id.clone())
174                } else {
175                    Unkeyed::Dependency(id.clone())
176                }
177            })?;
178            Ok((id.clone(), fingerprint.value.clone()))
179        })
180        .collect::<Result<BTreeMap<_, _>, Unkeyed>>()?;
181    let eval_def_hash = eval_definition_hash(&eval.declaration);
182    let artifact_kinds = values
183        .keys()
184        .map(|id| (id.clone(), config.artifacts[id].kind()))
185        .collect();
186    let value = key_with_kinds(&eval_def_hash, &values, &artifact_kinds);
187    let value = if config.artifacts[&eval.target].parts.is_empty() {
188        value
189    } else {
190        parts_key(&value)
191    };
192    Ok(Key {
193        value,
194        eval_def_hash,
195        fingerprints: values,
196        artifact_kinds,
197    })
198}
199
200/// Keys of every eval whose dependency Artifacts were all prepared, by eval id.
201pub fn eval_keys<'a>(
202    config: &'a RepoConfig,
203    fingerprints: &BTreeMap<&ArtifactName, PreparedFingerprint>,
204) -> BTreeMap<&'a crate::types::EvalId, Key> {
205    config
206        .evals
207        .iter()
208        .filter_map(|eval| Some((&eval.id, eval_key(config, eval, fingerprints).ok()?)))
209        .collect()
210}