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