Skip to main content

artifactize_core/
remote.rs

1//! Shared remote review store records: what leaves this machine and how it is mirrored back.
2
3mod push;
4mod pushed;
5mod session;
6pub use push::{Push, push, push_with_clock};
7pub use pushed::{Pushed, recent as recent_pushes, recent_at as recent_pushes_at};
8pub(crate) use session::REFRESH as REFRESH_INTERVAL;
9pub use session::Session;
10
11use std::{collections::BTreeMap, path::PathBuf};
12
13use serde::{Deserialize, Serialize};
14
15use crate::store::{Execution, ExecutionOptions, Origin, Producer, Provenance};
16
17/// Record schema version: 2 since records carry the 0.5 reuse key.
18pub const SCHEMA: u32 = 2;
19/// Bound network/storage cost of reduced records, which omit large captured execution output.
20pub const MAX_SUMMARY_BYTES: usize = 256 * 1024;
21/// Full records must fit the same per-entry budget as the local reusable cache.
22pub const MAX_FULL_BYTES: usize = crate::store::history::MAX_ENTRY_BYTES;
23
24/// One record of a reuse key's history; the store keeps every record and returns the latest.
25///
26/// A summary carries no argv, captured output or repository path. A full record additionally
27/// carries the saved `execution` as is; one an earlier artifactize published may still hold
28/// its `toolCalls`, which readers ignore. The server stamps `publisher`
29/// and `publishedAt`.
30#[derive(Debug, Clone, Serialize, Deserialize)]
31#[serde(rename_all = "camelCase", deny_unknown_fields)]
32pub struct Record {
33    pub schema: u32,
34    pub key: crate::types::ReuseKey,
35    pub eval_def_hash: crate::types::DefinitionHash,
36    /// Each Artifact the key covers, with its fingerprint.
37    pub fingerprints: BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>,
38    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
39    pub artifact_kinds: BTreeMap<crate::types::ArtifactName, crate::config::ArtifactKind>,
40    pub verdict: crate::types::ExecutionStatus,
41    pub eval_id: crate::types::EvalId,
42    pub run_id: crate::types::RunId,
43    pub request_id: crate::types::RequestId,
44    pub execution_id: crate::types::ExecutionId,
45    pub profile: crate::config::StoredProfile,
46    #[serde(default)]
47    pub options: ExecutionOptions,
48    /// An Agent result's tool `executionPaths` pins.
49    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
50    pub execution_paths: crate::tools::pins::Pins,
51    pub result: crate::store::ExecutionResult,
52    pub usage: Option<Vec<crate::llm::Attempt>>,
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub reviewer: Option<crate::types::ReviewerId>,
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub producer: Option<Producer>,
57    pub started_at: crate::types::Timestamp,
58    pub completed_at: crate::types::Timestamp,
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub execution: Option<Box<Execution>>,
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub publisher: Option<crate::types::TokenName>,
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub published_at: Option<crate::types::Timestamp>,
65}
66
67impl Record {
68    /// Project a completed local GREEN/RED result with a key; `full` keeps the execution.
69    pub fn new(execution: &Execution, full: bool) -> Result<Self, String> {
70        let (Some(key), Some(_), Some(completed_at), Some(result)) = (
71            &execution.key,
72            execution.verdict(),
73            &execution.completed_at(),
74            execution.result(),
75        ) else {
76            return Err("Only completed GREEN/RED results with a reuse key are shared.".into());
77        };
78        if execution.origin.is_some() {
79            return Err("Mirrored results are never published again.".into());
80        }
81        let (result, usage) = if full {
82            (result.clone(), execution.usage.clone())
83        } else {
84            (
85                summary_result(&execution.profile, result),
86                summary_usage(execution.usage.as_ref()),
87            )
88        };
89        let record = Self {
90            schema: SCHEMA,
91            key: key.clone(),
92            eval_def_hash: execution.eval_def_hash.clone(),
93            fingerprints: execution.fingerprints.clone(),
94            artifact_kinds: execution.artifact_kinds.clone(),
95            verdict: execution.status(),
96            eval_id: execution.provenance.eval_id.clone(),
97            run_id: execution.provenance.run_id.clone(),
98            request_id: execution.provenance.request_id.clone(),
99            execution_id: execution.id.clone(),
100            profile: execution.profile.clone(),
101            options: execution.options.clone(),
102            execution_paths: execution.provenance.execution_paths.clone(),
103            result,
104            usage,
105            reviewer: execution.reviewer.clone(),
106            producer: execution.producer.clone(),
107            started_at: execution.started_at,
108            completed_at: *completed_at,
109            execution: full.then(|| Box::new(execution.clone())),
110            publisher: None,
111            published_at: None,
112        };
113        record.validate()?;
114        Ok(record)
115    }
116
117    /// Check shape, the key against its fingerprints, and size limits; never trusts the
118    /// record's verdict.
119    pub fn validate(&self) -> Result<(), String> {
120        let keyed = crate::cache::key_with_kinds(
121            &self.eval_def_hash,
122            &self.fingerprints,
123            &self.artifact_kinds,
124        );
125        // Leaf and composition formats both prove the exact input map. Their distinct
126        // keys prevent pre-composition results from answering a whole's new requests.
127        let valid_key = keyed == self.key
128            || (!self.artifact_kinds.is_empty() && crate::cache::parts_key(&keyed) == self.key);
129        let valid = self.schema == SCHEMA
130            && valid_hash(&self.key)
131            && valid_hash(&self.eval_def_hash)
132            && !self.fingerprints.is_empty()
133            && self.fingerprints.iter().all(|(name, fingerprint)| {
134                crate::config::artifact_name(name, "Artifact name").is_ok()
135                    && valid_fingerprint(fingerprint)
136            })
137            && (self.artifact_kinds.is_empty()
138                || self.artifact_kinds.keys().eq(self.fingerprints.keys()))
139            && valid_key
140            && matches!(
141                self.verdict,
142                crate::types::ExecutionStatus::Green | crate::types::ExecutionStatus::Red
143            )
144            && self.result.verdict().as_str() == self.verdict.as_str()
145            && self.execution_id.valid_wire()
146            && valid_session(self.producer.as_ref())
147            && self.execution.as_ref().is_none_or(|execution| {
148                valid_session(execution.producer.as_ref())
149                    && execution.key.as_ref() == Some(&self.key)
150                    && execution.eval_def_hash == self.eval_def_hash
151                    && execution.fingerprints == self.fingerprints
152                    && execution.artifact_kinds == self.artifact_kinds
153                    && execution.status() == self.verdict
154                    && execution.profile == self.profile
155                    && execution.origin.is_none()
156            });
157        if !valid {
158            return Err("Invalid remote review record.".into());
159        }
160        let limit = if self.execution.is_some() {
161            MAX_FULL_BYTES
162        } else {
163            MAX_SUMMARY_BYTES
164        };
165        if serde_json::to_vec(self).map_err(|e| e.to_string())?.len() > limit {
166            return Err(format!("Remote review record exceeds {limit} bytes."));
167        }
168        Ok(())
169    }
170
171    /// Rebuild a self-contained execution for the local cache, marked with its origin.
172    pub fn mirror(self, store: &str) -> Result<Execution, String> {
173        self.validate()?;
174        let (Some(publisher), Some(published_at)) = (self.publisher, self.published_at) else {
175            return Err("Remote review record has no server publisher.".into());
176        };
177        let id = self.execution_id.remote_mirror()?;
178        let mut execution = match self.execution {
179            Some(execution) => *execution,
180            None => Execution {
181                id: id.clone(),
182                key: Some(self.key),
183                // The target is the eval id's Artifact part.
184                fingerprint: self
185                    .eval_id
186                    .rsplit_once('/')
187                    .and_then(|(target, _)| self.fingerprints.get(target))
188                    .cloned(),
189                fingerprints: self.fingerprints,
190                artifact_kinds: self.artifact_kinds,
191                eval_def_hash: self.eval_def_hash.clone(),
192                owner: None,
193                state: crate::store::ExecutionState::Completed {
194                    result: self.result,
195                    at: self.completed_at,
196                },
197                profile: self.profile,
198                options: self.options,
199                usage: self.usage,
200                provenance: Provenance {
201                    repo_path: PathBuf::new(),
202                    run_id: self.run_id,
203                    request_id: self.request_id,
204                    eval_id: self.eval_id,
205                    eval_def_hash: self.eval_def_hash,
206                    completed_at: Some(self.completed_at),
207                    execution_paths: self.execution_paths,
208                },
209                started_at: self.started_at,
210                producer: self.producer,
211                reviewer: self.reviewer,
212                origin: None,
213                manifest: None,
214            },
215        };
216        execution.id = id;
217        execution.origin = Some(Origin {
218            store: store.parse()?,
219            publisher,
220            published_at,
221        });
222        Ok(execution)
223    }
224}
225
226fn summary_result(
227    profile: &crate::config::StoredProfile,
228    result: &crate::store::ExecutionResult,
229) -> crate::store::ExecutionResult {
230    if profile.kind() == crate::config::ProfileKind::Runtime
231        && let crate::store::ExecutionResult::Runtime(runtime) = result
232    {
233        return crate::store::ExecutionResult::Runtime(runtime.summary());
234    }
235    result.clone()
236}
237
238fn summary_usage(usage: Option<&Vec<crate::llm::Attempt>>) -> Option<Vec<crate::llm::Attempt>> {
239    let attempts = usage?;
240    Some(
241        attempts
242            .iter()
243            .map(|attempt| crate::llm::Attempt {
244                turn: attempt.turn,
245                attempt: attempt.attempt,
246                usage: attempt.usage.clone(),
247                error: None,
248                error_code: None,
249            })
250            .collect(),
251    )
252}
253
254pub(crate) fn valid_fingerprint(value: &str) -> bool {
255    value.parse::<crate::types::Fingerprint>().is_ok()
256}
257
258pub(crate) fn valid_hash(value: &str) -> bool {
259    value.len() == crate::types::SHA256_HEX_BYTES
260        && value
261            .bytes()
262            .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
263}
264
265#[cfg(test)]
266#[test]
267fn sha256_hash_wire_format_keeps_exact_width_and_lowercase() {
268    // SHA-256's published wire width is independent of the implementation's limit.
269    assert!(valid_hash(
270        "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
271    ));
272    for hash in [
273        "a".repeat(63),
274        "a".repeat(65),
275        "A".repeat(64),
276        "g".repeat(64),
277    ] {
278        assert!(!valid_hash(&hash), "{hash}");
279    }
280}
281
282/// A producer's session reference, if any, names its conversation in bounded, printable
283/// fields. It is a pointer back to the producing machine; no conversation is ever published.
284fn valid_session(producer: Option<&Producer>) -> bool {
285    producer
286        .and_then(|producer| producer.session.as_ref())
287        .is_none_or(crate::agent::session::SessionRef::valid)
288}