Skip to main content

artifactize_core/store/executions/
wire.rs

1//! Execution records and their compatible wire format.
2use crate::{
3    config::Profile,
4    process,
5    runtime::Verdict,
6    store,
7    types::{ExecutionStatus, Fingerprint, RequestId, ReuseKey, RunId},
8};
9use serde::{Deserialize, Serialize};
10use std::{collections::BTreeMap, path::PathBuf};
11
12#[derive(Debug, Clone, Serialize, Deserialize)]
13#[serde(rename_all = "camelCase")]
14pub struct Provenance {
15    #[serde(with = "crate::platform::path_serde")]
16    pub repo_path: PathBuf,
17    pub run_id: RunId,
18    pub request_id: RequestId,
19    pub eval_id: crate::types::EvalId,
20    pub eval_def_hash: crate::types::DefinitionHash,
21    pub completed_at: Option<crate::types::Timestamp>,
22    /// For Agent results: the SHA-256 of each tool's `executionPaths` when the review started,
23    /// by tool name and declared path.
24    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
25    pub execution_paths: crate::tools::pins::Pins,
26}
27
28/// One execution and, once GREEN or RED with a key, one record of its key's history. A local
29/// Agent execution holds one of its backend's machine-wide slots while RUNNING.
30#[derive(Debug, Clone, Serialize, Deserialize)]
31#[serde(try_from = "ExecutionWire", into = "ExecutionWire")]
32pub struct Execution {
33    pub state: store::ExecutionState,
34    pub id: crate::types::ExecutionId,
35    /// The reuse key; absent without a fingerprint on every Artifact the eval depends on.
36    pub key: Option<ReuseKey>,
37    /// The target Artifact's fingerprint.
38    pub fingerprint: Option<Fingerprint>,
39    /// Each Artifact the key covers, the target included, with its fingerprint.
40    pub fingerprints: BTreeMap<crate::types::ArtifactName, Fingerprint>,
41    /// Kinds of exactly the Artifacts covered by a new-format reuse key.
42    pub artifact_kinds: BTreeMap<crate::types::ArtifactName, crate::config::ArtifactKind>,
43    pub eval_def_hash: crate::types::DefinitionHash,
44    /// The local process running this execution; absent for one mirrored from a remote
45    /// review store, which no local process owns.
46    pub owner: Option<process::ChildIdentity>,
47    pub profile: crate::config::StoredProfile,
48    /// How this result was produced; never part of the key.
49    pub options: ExecutionOptions,
50    pub usage: Option<Vec<crate::llm::Attempt>>,
51    pub provenance: Provenance,
52    pub started_at: crate::types::Timestamp,
53    pub producer: Option<Producer>,
54    /// The Human claimant who submitted this result.
55    pub reviewer: Option<crate::types::ReviewerId>,
56    /// Set only on executions mirrored from a remote review store.
57    pub origin: Option<Origin>,
58    pub manifest: Option<crate::cache::Manifest>,
59}
60
61#[derive(Debug, Clone, Serialize, Deserialize)]
62#[serde(rename_all = "camelCase")]
63struct ExecutionWire {
64    pub id: crate::types::ExecutionId,
65    /// The reuse key; absent without a fingerprint on every Artifact the eval depends on.
66    #[serde(default)]
67    pub key: Option<ReuseKey>,
68    /// The target Artifact's fingerprint.
69    pub fingerprint: Option<Fingerprint>,
70    /// Each Artifact the key covers, the target included, with its fingerprint.
71    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
72    pub fingerprints: BTreeMap<crate::types::ArtifactName, Fingerprint>,
73    /// Kinds of exactly the Artifacts covered by a new-format reuse key.
74    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
75    pub artifact_kinds: BTreeMap<crate::types::ArtifactName, crate::config::ArtifactKind>,
76    /// Partition Live names out of the old strict enum map for schema-10 readers.
77    #[serde(default, skip_serializing_if = "std::collections::BTreeSet::is_empty")]
78    pub live_artifacts: std::collections::BTreeSet<crate::types::ArtifactName>,
79    pub eval_def_hash: crate::types::DefinitionHash,
80    pub owner_pid: u32,
81    pub owner_start_time: u64,
82    pub status: ExecutionStatus,
83    pub result: Option<store::ExecutionResult>,
84    pub error: Option<String>,
85    pub error_code: Option<crate::types::FailureCode>,
86    pub profile: crate::config::StoredProfile,
87    /// How this result was produced; never part of the key.
88    #[serde(default)]
89    pub options: ExecutionOptions,
90    pub usage: Option<Vec<crate::llm::Attempt>>,
91    pub provenance: Provenance,
92    pub started_at: crate::types::Timestamp,
93    pub completed_at: Option<crate::types::Timestamp>,
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub producer: Option<Producer>,
96    /// The Human claimant who submitted this result.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub reviewer: Option<crate::types::ReviewerId>,
99    /// Set only on executions mirrored from a remote review store.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub origin: Option<Origin>,
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub manifest: Option<crate::cache::Manifest>,
104}
105
106impl TryFrom<ExecutionWire> for Execution {
107    type Error = String;
108    fn try_from(wire: ExecutionWire) -> Result<Self, Self::Error> {
109        if wire
110            .live_artifacts
111            .iter()
112            .any(|name| wire.artifact_kinds.contains_key(name))
113        {
114            return Err(
115                "A saved execution gives one Artifact both a filesystem and Live kind.".into(),
116            );
117        }
118        let state = store::ExecutionState::from_parts(
119            wire.status,
120            wire.result,
121            wire.error,
122            wire.error_code,
123            wire.completed_at,
124        )?;
125        Ok(Self {
126            state,
127            id: wire.id,
128            key: wire.key,
129            fingerprint: wire.fingerprint,
130            fingerprints: wire.fingerprints,
131            artifact_kinds: wire
132                .artifact_kinds
133                .into_iter()
134                .chain(
135                    wire.live_artifacts
136                        .into_iter()
137                        .map(|name| (name, crate::config::ArtifactKind::Live)),
138                )
139                .collect(),
140            eval_def_hash: wire.eval_def_hash,
141            owner: std::num::NonZeroU32::new(wire.owner_pid).map(|pid| process::ChildIdentity {
142                pid: process::ProcessId::from(pid),
143                start_time: wire.owner_start_time,
144            }),
145            profile: wire.profile,
146            options: wire.options,
147            usage: wire.usage,
148            provenance: wire.provenance,
149            started_at: wire.started_at,
150            producer: wire.producer,
151            reviewer: wire.reviewer,
152            origin: wire.origin,
153            manifest: wire.manifest,
154        })
155    }
156}
157impl From<Execution> for ExecutionWire {
158    fn from(record: Execution) -> Self {
159        let owner_pid = record.owner_pid();
160        let owner_start_time = record.owner_start_time();
161        Self {
162            status: record.status(),
163            result: record.result().cloned(),
164            error: record.error().map(str::to_owned),
165            error_code: record.error_code(),
166            completed_at: record.completed_at(),
167            id: record.id,
168            key: record.key,
169            fingerprint: record.fingerprint,
170            fingerprints: record.fingerprints,
171            live_artifacts: record
172                .artifact_kinds
173                .iter()
174                .filter(|(_, kind)| **kind == crate::config::ArtifactKind::Live)
175                .map(|(name, _)| name.clone())
176                .collect(),
177            artifact_kinds: record
178                .artifact_kinds
179                .into_iter()
180                .filter(|(_, kind)| *kind != crate::config::ArtifactKind::Live)
181                .collect(),
182            eval_def_hash: record.eval_def_hash,
183            owner_pid,
184            owner_start_time,
185            profile: record.profile,
186            options: record.options,
187            usage: record.usage,
188            provenance: record.provenance,
189            started_at: record.started_at,
190            producer: record.producer,
191            reviewer: record.reviewer,
192            origin: record.origin,
193            manifest: record.manifest,
194        }
195    }
196}
197impl Execution {
198    pub fn status(&self) -> crate::types::ExecutionStatus {
199        self.state.status()
200    }
201    pub fn result(&self) -> Option<&store::ExecutionResult> {
202        self.state.result()
203    }
204    pub fn error(&self) -> Option<&str> {
205        self.state.error()
206    }
207    pub fn error_code(&self) -> Option<crate::types::FailureCode> {
208        self.state.error_code()
209    }
210    pub fn completed_at(&self) -> Option<crate::types::Timestamp> {
211        self.state.completed_at()
212    }
213    /// The owning process's pid, or 0 for a remote-mirrored execution with no local owner:
214    /// the `owner_pid` SQL column and wire field's sentinel for "no owner", confined to
215    /// this persistence boundary.
216    pub fn owner_pid(&self) -> u32 {
217        self.owner.map_or(0, |owner| owner.pid.get())
218    }
219    /// The owning process's start time, or 0 alongside [`Self::owner_pid`]'s sentinel.
220    pub fn owner_start_time(&self) -> u64 {
221        self.owner.map_or(0, |owner| owner.start_time)
222    }
223}
224
225/// The execution options of a result: stored next to it, never part of its key, so results
226/// from different profiles for the same key reuse each other.
227#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
228#[serde(rename_all = "camelCase")]
229pub struct ExecutionOptions {
230    #[serde(default, skip_serializing_if = "Vec::is_empty")]
231    pub mutex: Vec<crate::config::MutexTag>,
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub backend: Option<crate::config::Backend>,
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub model: Option<crate::config::ModelId>,
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub reasoning: Option<crate::config::Reasoning>,
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    #[serde(with = "crate::config::validation::milliseconds")]
240    pub timeout_ms: Option<std::time::Duration>,
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub max_tool_calls: Option<u64>,
243    #[serde(default, skip_serializing_if = "Option::is_none")]
244    pub max_tokens: Option<u64>,
245    /// The named profile a Run chose instead of the eval's own, which only executions saved
246    /// before profiles chose their settings from the environment record.
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub variant: Option<crate::config::ProfileName>,
249}
250
251impl ExecutionOptions {
252    /// The declared options of an effective profile, as declared (absent means the default).
253    pub fn new(profile: &Profile) -> Self {
254        let mut options = Self::default();
255        match profile {
256            Profile::Agent {
257                backend,
258                model,
259                reasoning,
260                timeout_ms,
261                max_tool_calls,
262                max_tokens,
263            } => {
264                options.backend = Some(backend.clone());
265                options.model = Some(model.clone());
266                options.reasoning = *reasoning;
267                options.timeout_ms = *timeout_ms;
268                options.max_tool_calls = *max_tool_calls;
269                options.max_tokens = *max_tokens;
270            }
271            Profile::Runtime { timeout_ms, .. } => options.timeout_ms = *timeout_ms,
272            Profile::Human {} => {}
273        }
274        options
275    }
276}
277
278/// Who produced an execution: display metadata, never authentication.
279#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
280pub struct Producer {
281    /// `user@host`.
282    pub name: crate::types::ProducerId,
283    /// The producing artifactize version.
284    pub version: String,
285    /// Where an Agent review's saved conversation lives. It travels with remote records,
286    /// which older clients read without it; the conversation itself never leaves the machine.
287    #[serde(default, skip_serializing_if = "Option::is_none")]
288    pub session: Option<crate::agent::session::SessionRef>,
289}
290
291/// The name every producer without a user or host gets.
292const UNKNOWN_PRODUCER: &str = "unknown@unknown";
293
294impl Producer {
295    pub fn current() -> Self {
296        let user = crate::platform::user_name();
297        let host = crate::platform::host_name();
298        let name = format!(
299            "{}@{}",
300            user.as_deref().unwrap_or("unknown"),
301            host.as_deref()
302                .map(str::trim)
303                .filter(|host| !host.is_empty())
304                .unwrap_or("unknown")
305        );
306        // A name is printable and bounded; whatever the system reports is cut to fit.
307        let mut printable: String = name.chars().filter(|c| !c.is_control()).collect();
308        while printable.len() > crate::types::MAX_ID_BYTES {
309            printable.pop();
310        }
311        Self {
312            name: printable
313                .parse()
314                .unwrap_or_else(|_| UNKNOWN_PRODUCER.parse().expect("a valid producer name")),
315            version: env!("CARGO_PKG_VERSION").into(),
316            session: None,
317        }
318    }
319}
320
321/// The remote store, authenticated publisher and server clock of a mirrored execution.
322#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
323#[serde(rename_all = "camelCase")]
324pub struct Origin {
325    pub store: crate::types::StoreUrl,
326    pub publisher: crate::types::TokenName,
327    pub published_at: crate::types::Timestamp,
328}
329
330impl Execution {
331    /// The backend whose machine-wide slot this execution holds while RUNNING: a local Agent
332    /// review's. A mirrored record ran elsewhere.
333    pub(super) fn backend(&self) -> Option<&str> {
334        self.options
335            .backend
336            .as_ref()
337            .map(|backend| backend.as_str())
338            .filter(|_| self.origin.is_none())
339    }
340
341    /// Whether this record completed after `other`, comparing `completedAt` as instants.
342    pub fn completed_after(&self, other: &Execution) -> bool {
343        self.completed_at() > other.completed_at()
344    }
345
346    pub fn verdict(&self) -> Option<Verdict> {
347        match self.status() {
348            ExecutionStatus::Green => Some(Verdict::Green),
349            ExecutionStatus::Red => Some(Verdict::Red),
350            _ => None,
351        }
352    }
353}