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 selected `profileVariants` entry; absent for the declared profile.
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub variant: Option<crate::config::ProfileVariantName>,
248}
249
250impl ExecutionOptions {
251    /// The declared options of an effective profile, as declared (absent means the default).
252    pub fn new(profile: &Profile, variant: Option<&crate::config::ProfileVariantName>) -> Self {
253        let mut options = Self {
254            variant: variant.cloned(),
255            ..Self::default()
256        };
257        match profile {
258            Profile::Agent {
259                backend,
260                model,
261                reasoning,
262                timeout_ms,
263                max_tool_calls,
264                max_tokens,
265            } => {
266                options.backend = Some(backend.clone());
267                options.model = Some(model.clone());
268                options.reasoning = *reasoning;
269                options.timeout_ms = *timeout_ms;
270                options.max_tool_calls = *max_tool_calls;
271                options.max_tokens = *max_tokens;
272            }
273            Profile::Runtime { timeout_ms, .. } => options.timeout_ms = *timeout_ms,
274            Profile::Human {} => {}
275        }
276        options
277    }
278}
279
280/// Who produced an execution: display metadata, never authentication.
281#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
282pub struct Producer {
283    /// `user@host`.
284    pub name: crate::types::ProducerId,
285    /// The producing artifactize version.
286    pub version: String,
287    /// Where an Agent review's saved conversation lives. It travels with remote records,
288    /// which older clients read without it; the conversation itself never leaves the machine.
289    #[serde(default, skip_serializing_if = "Option::is_none")]
290    pub session: Option<crate::agent::session::SessionRef>,
291}
292
293/// The name every producer without a user or host gets.
294const UNKNOWN_PRODUCER: &str = "unknown@unknown";
295
296impl Producer {
297    pub fn current() -> Self {
298        let user = crate::platform::user_name();
299        let host = crate::platform::host_name();
300        let name = format!(
301            "{}@{}",
302            user.as_deref().unwrap_or("unknown"),
303            host.as_deref()
304                .map(str::trim)
305                .filter(|host| !host.is_empty())
306                .unwrap_or("unknown")
307        );
308        // A name is printable and bounded; whatever the system reports is cut to fit.
309        let mut printable: String = name.chars().filter(|c| !c.is_control()).collect();
310        while printable.len() > crate::types::MAX_ID_BYTES {
311            printable.pop();
312        }
313        Self {
314            name: printable
315                .parse()
316                .unwrap_or_else(|_| UNKNOWN_PRODUCER.parse().expect("a valid producer name")),
317            version: env!("CARGO_PKG_VERSION").into(),
318            session: None,
319        }
320    }
321}
322
323/// The remote store, authenticated publisher and server clock of a mirrored execution.
324#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
325#[serde(rename_all = "camelCase")]
326pub struct Origin {
327    pub store: crate::types::StoreUrl,
328    pub publisher: crate::types::TokenName,
329    pub published_at: crate::types::Timestamp,
330}
331
332impl Execution {
333    /// The backend whose machine-wide slot this execution holds while RUNNING: a local Agent
334    /// review's. A mirrored record ran elsewhere.
335    pub(super) fn backend(&self) -> Option<&str> {
336        self.options
337            .backend
338            .as_ref()
339            .map(|backend| backend.as_str())
340            .filter(|_| self.origin.is_none())
341    }
342
343    /// Whether this record completed after `other`, comparing `completedAt` as instants.
344    pub fn completed_after(&self, other: &Execution) -> bool {
345        self.completed_at() > other.completed_at()
346    }
347
348    pub fn verdict(&self) -> Option<Verdict> {
349        match self.status() {
350            ExecutionStatus::Green => Some(Verdict::Green),
351            ExecutionStatus::Red => Some(Verdict::Red),
352            _ => None,
353        }
354    }
355}