Skip to main content

artifactize_core/store/receipts/
wire.rs

1//! Saved Run and request representations and their wire conversions.
2use crate::store::{self as store, ExecutionOptions, Origin, Producer, Provenance};
3use crate::{
4    config::ProfileKind,
5    types::{
6        Fingerprint, RequestId, RequestStatus, ReuseKey, RunId, RunStatus, SessionId, Timestamp,
7    },
8};
9use serde::{Deserialize, Serialize};
10use std::{
11    collections::{BTreeMap, BTreeSet},
12    path::PathBuf,
13    time::Duration,
14};
15
16mod stored_request_key {
17    use crate::types::RequestKey;
18    use serde::{Deserialize, Deserializer, Serializer};
19
20    pub(super) fn serialize<S: Serializer>(
21        value: &Option<RequestKey>,
22        serializer: S,
23    ) -> Result<S::Ok, S::Error> {
24        match value {
25            Some(key) => serializer.serialize_some(key.as_str()),
26            None => serializer.serialize_none(),
27        }
28    }
29
30    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
31        deserializer: D,
32    ) -> Result<Option<RequestKey>, D::Error> {
33        Ok(Option::<String>::deserialize(deserializer)?.and_then(|raw| raw.parse().ok()))
34    }
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
38#[serde(try_from = "RunWire", into = "RunWire")]
39pub struct Run {
40    pub id: RunId,
41    pub repo_path: PathBuf,
42    /// Optional display metadata; schema 5 Runs written before this remain readable.
43    pub repository: crate::repository::Identity,
44    pub state_dir: PathBuf,
45    pub state: store::RunState,
46    pub modes: crate::runs::RunModes,
47    pub control: Option<crate::runs::Control>,
48    pub request_key: Option<crate::types::RequestKey>,
49    pub request_args_hash: Option<String>,
50    pub origin: Option<crate::runs::Origin>,
51    /// What the requester said it is working on; for people only.
52    pub comment: Option<crate::types::RunComment>,
53    pub created_at: Timestamp,
54    pub selection: crate::project::selection::Selection,
55    pub definitions: store::definitions::Definitions,
56    pub recursive: bool,
57    pub force: bool,
58    pub jobs: Option<usize>,
59    /// Fingerprints computed at once; absent in Runs saved before 0.5.
60    pub fingerprint_jobs: Option<usize>,
61    pub max_executions: Option<u64>,
62    pub executions_started: u64,
63    pub wait_timeout_ms: Option<Duration>,
64    pub wait_timed_out: bool,
65    /// Kinds whose evals only reuse a result; one with nothing to reuse is not executed.
66    pub reuse_only: BTreeSet<ProfileKind>,
67    pub validation: store::Validation,
68    /// Agent backends this Run stopped admitting reviews on, in the order they stopped.
69    pub stopped_backends: Vec<StoppedBackend>,
70    /// Verdicts the Run took from saved results for evals it has no request for, such as the
71    /// dependencies of a partial Run, so readers judge gates on the Run's own evidence.
72    pub evidence: BTreeMap<crate::types::EvalId, crate::types::RequestStatus>,
73}
74
75#[derive(Debug, Clone, Serialize, Deserialize)]
76#[serde(rename_all = "camelCase")]
77struct RunWire {
78    pub id: RunId,
79    #[serde(with = "crate::platform::path_serde")]
80    pub repo_path: PathBuf,
81    /// Optional display metadata; schema 5 Runs written before this remain readable.
82    #[serde(flatten)]
83    pub repository: crate::repository::Identity,
84    #[serde(with = "crate::platform::path_serde")]
85    pub state_dir: PathBuf,
86    #[serde(default, skip_serializing_if = "crate::runs::RunModes::is_default")]
87    pub modes: crate::runs::RunModes,
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub control: Option<crate::runs::Control>,
90    #[serde(
91        default,
92        skip_serializing_if = "Option::is_none",
93        with = "stored_request_key"
94    )]
95    pub request_key: Option<crate::types::RequestKey>,
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub request_args_hash: Option<String>,
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub origin: Option<crate::runs::Origin>,
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub comment: Option<crate::types::RunComment>,
102    pub status: RunStatus,
103    pub created_at: Timestamp,
104    pub completed_at: Option<Timestamp>,
105    pub selection: crate::project::selection::Selection,
106    #[serde(default)]
107    pub definitions: store::definitions::Definitions,
108    #[serde(default)]
109    pub recursive: bool,
110    #[serde(default)]
111    pub force: bool,
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub jobs: Option<usize>,
114    /// Fingerprints computed at once; absent in Runs saved before 0.5.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub fingerprint_jobs: Option<usize>,
117    #[serde(default)]
118    pub max_executions: Option<u64>,
119    #[serde(default)]
120    pub executions_started: u64,
121    #[serde(default, with = "store::wait_timeout")]
122    pub wait_timeout_ms: Option<Duration>,
123    #[serde(default)]
124    pub wait_timed_out: bool,
125    /// Kinds whose evals only reuse a result; one with nothing to reuse is not executed.
126    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
127    pub reuse_only: BTreeSet<ProfileKind>,
128    pub validation: store::Validation,
129    pub error: Option<String>,
130    /// Agent backends this Run stopped admitting reviews on, in the order they stopped.
131    #[serde(default, skip_serializing_if = "Vec::is_empty")]
132    pub stopped_backends: Vec<StoppedBackend>,
133    /// Verdicts the Run took from saved results for evals it has no request for, such as the
134    /// dependencies of a partial Run, so readers judge gates on the Run's own evidence.
135    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
136    pub evidence: BTreeMap<crate::types::EvalId, crate::types::RequestStatus>,
137}
138
139impl TryFrom<RunWire> for Run {
140    type Error = String;
141    fn try_from(wire: RunWire) -> Result<Self, Self::Error> {
142        let state = store::RunState::from_parts(wire.status, wire.completed_at, wire.error)?;
143        Ok(Self {
144            state,
145            modes: wire.modes,
146            control: wire.control,
147            request_key: wire.request_key,
148            request_args_hash: wire.request_args_hash,
149            origin: wire.origin,
150            comment: wire.comment,
151            id: wire.id,
152            repo_path: wire.repo_path,
153            repository: wire.repository,
154            state_dir: wire.state_dir,
155            created_at: wire.created_at,
156            selection: wire.selection,
157            definitions: wire.definitions,
158            recursive: wire.recursive,
159            force: wire.force,
160            jobs: wire.jobs,
161            fingerprint_jobs: wire.fingerprint_jobs,
162            max_executions: wire.max_executions,
163            executions_started: wire.executions_started,
164            wait_timeout_ms: wire.wait_timeout_ms,
165            wait_timed_out: wire.wait_timed_out,
166            reuse_only: wire.reuse_only,
167            validation: wire.validation,
168            stopped_backends: wire.stopped_backends,
169            evidence: wire.evidence,
170        })
171    }
172}
173impl From<Run> for RunWire {
174    fn from(record: Run) -> Self {
175        Self {
176            modes: record.modes.clone(),
177            control: record.control.clone(),
178            request_key: record.request_key.clone(),
179            request_args_hash: record.request_args_hash.clone(),
180            origin: record.origin.clone(),
181            comment: record.comment.clone(),
182            status: record.status(),
183            completed_at: record.completed_at(),
184            error: record.error().map(str::to_owned),
185            id: record.id,
186            repo_path: record.repo_path,
187            repository: record.repository,
188            state_dir: record.state_dir,
189            created_at: record.created_at,
190            selection: record.selection,
191            definitions: record.definitions,
192            recursive: record.recursive,
193            force: record.force,
194            jobs: record.jobs,
195            fingerprint_jobs: record.fingerprint_jobs,
196            max_executions: record.max_executions,
197            executions_started: record.executions_started,
198            wait_timeout_ms: record.wait_timeout_ms,
199            wait_timed_out: record.wait_timed_out,
200            reuse_only: record.reuse_only,
201            validation: record.validation,
202            stopped_backends: record.stopped_backends,
203            evidence: record.evidence,
204        }
205    }
206}
207impl Run {
208    pub fn status(&self) -> RunStatus {
209        self.state.status()
210    }
211    /// Show the Run WAITING_HUMAN while one of its requests, saved with `statuses`, is an
212    /// unsubmitted sign-off, and RUNNING otherwise while it is open.
213    pub(in crate::store) fn show_signoffs(
214        &mut self,
215        mut statuses: impl Iterator<Item = crate::types::RequestStatus>,
216    ) {
217        let open = statuses.any(crate::types::RequestStatus::is_human_wait);
218        self.state = self.state.clone().with_signoffs(open);
219    }
220    pub fn completed_at(&self) -> Option<Timestamp> {
221        self.state.completed_at()
222    }
223    pub fn error(&self) -> Option<&str> {
224        self.state.error()
225    }
226}
227
228/// An Agent backend a Run stopped after an AUTHENTICATION or QUOTA failure, which every
229/// later review on it would repeat.
230#[derive(Debug, Clone, Serialize, Deserialize)]
231#[serde(rename_all = "camelCase")]
232pub struct StoppedBackend {
233    pub backend: crate::config::Backend,
234    pub error_code: crate::types::BackendStopCode,
235    pub eval_id: crate::types::EvalId,
236    pub request_id: RequestId,
237    pub error: String,
238}
239
240#[derive(Debug, Clone, Serialize, Deserialize)]
241#[serde(try_from = "RequestWire", into = "RequestWire")]
242pub struct Request {
243    pub state: store::RequestState,
244    pub id: RequestId,
245    pub run_id: RunId,
246    pub eval_id: crate::types::EvalId,
247    pub target: crate::types::ArtifactName,
248    pub title: String,
249    pub profile: crate::config::StoredProfile,
250    pub requested_profile: crate::config::StoredProfile,
251    pub eval_def_hash: crate::types::DefinitionHash,
252    /// The requested execution options, or a reused result's.
253    pub options: ExecutionOptions,
254    pub execution_id: Option<crate::types::ExecutionId>,
255    pub provenance: Option<Provenance>,
256    /// Usage spent by this request; a reused request spent none.
257    pub usage: Option<Vec<crate::llm::Attempt>>,
258    /// The reused execution's original usage, never counted as spent.
259    pub reused_usage: Option<Vec<crate::llm::Attempt>>,
260    /// The reused result came from the live execution this request waited for, not a
261    /// completed record. Saved only; output reports it as `source.kind` ([`crate::query::source`]).
262    pub joined: bool,
263    /// Who produced a reused result.
264    pub producer: Option<Producer>,
265    /// The Human claimant who submitted a reused result.
266    pub reviewer: Option<crate::types::ReviewerId>,
267    /// The remote store, publisher and publication time of a result reused from a mirror.
268    pub origin: Option<Origin>,
269    /// The Agent review's session id ([`crate::agent::session_id`]), which every request of
270    /// the review sends as its prompt-cache identity. Absent when no Agent review ran, as on
271    /// reuse, and on requests saved before it existed.
272    pub session_id: Option<SessionId>,
273    /// Where the saved conversation behind this request's result lives: its own review's,
274    /// or for a reused result the producing review's. Absent when none was saved.
275    pub session: Option<crate::agent::session::SessionRef>,
276    /// Free-form Human response accompanying the schema-owned answer on this receipt.
277    pub review_notes: Option<String>,
278    pub human_definition: Option<store::HumanDefinition>,
279    pub payload: crate::config::StoredPayload,
280    pub references: BTreeMap<crate::config::ReferenceName, crate::types::ArtifactName>,
281    pub deps: Vec<crate::types::ArtifactName>,
282    pub force: bool,
283    /// The target Artifact's fingerprint.
284    pub fingerprint: Option<Fingerprint>,
285    /// The reuse key; absent without a fingerprint on every Artifact the eval depends on.
286    pub key: Option<ReuseKey>,
287    /// Each Artifact the key covers, with its fingerprint.
288    pub fingerprints: std::collections::BTreeMap<crate::types::ArtifactName, Fingerprint>,
289    pub created_at: Timestamp,
290    pub started_at: Option<Timestamp>,
291    pub cwd: PathBuf,
292    pub run_dir: Option<PathBuf>,
293    pub argv: Option<Vec<String>>,
294    pub child: Option<store::ChildIdentity>,
295    pub blocked_reason: Option<String>,
296    /// Unfulfilled Evals behind this request’s dependency gates.
297    pub blocked_by: Vec<store::Blocker>,
298}
299
300/// What a queued request waits for besides a job slot of its Run.
301#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
302#[serde(tag = "kind", rename_all = "camelCase")]
303pub enum QueueReason {
304    /// A free machine-wide slot of this backend (`limits.json`).
305    Slot { backend: crate::config::Backend },
306}
307
308#[derive(Debug, Clone, Serialize, Deserialize)]
309#[serde(rename_all = "camelCase")]
310struct RequestWire {
311    pub id: RequestId,
312    pub run_id: RunId,
313    pub eval_id: crate::types::EvalId,
314    pub target: crate::types::ArtifactName,
315    pub title: String,
316    pub profile: crate::config::StoredProfile,
317    pub requested_profile: crate::config::StoredProfile,
318    pub eval_def_hash: crate::types::DefinitionHash,
319    /// The requested execution options, or a reused result's.
320    #[serde(default)]
321    pub options: ExecutionOptions,
322    pub execution_id: Option<crate::types::ExecutionId>,
323    pub provenance: Option<Provenance>,
324    /// Usage spent by this request; a reused request spent none.
325    pub usage: Option<Vec<crate::llm::Attempt>>,
326    /// The reused execution's original usage, never counted as spent.
327    #[serde(default, skip_serializing_if = "Option::is_none")]
328    pub reused_usage: Option<Vec<crate::llm::Attempt>>,
329    /// The reused result came from the live execution this request waited for, not a
330    /// completed record. Saved only; output reports it as `source.kind` ([`crate::query::source`]).
331    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
332    pub joined: bool,
333    /// Who produced a reused result.
334    #[serde(default, skip_serializing_if = "Option::is_none")]
335    pub producer: Option<Producer>,
336    /// The Human claimant who submitted a reused result.
337    #[serde(default, skip_serializing_if = "Option::is_none")]
338    pub reviewer: Option<crate::types::ReviewerId>,
339    /// The remote store, publisher and publication time of a result reused from a mirror.
340    #[serde(default, skip_serializing_if = "Option::is_none")]
341    pub origin: Option<Origin>,
342    /// The Agent review's session id ([`crate::agent::session_id`]), which every request of
343    /// the review sends as its prompt-cache identity. Absent when no Agent review ran, as on
344    /// reuse, and on requests saved before it existed.
345    #[serde(default, skip_serializing_if = "Option::is_none")]
346    pub session_id: Option<SessionId>,
347    /// Where the saved conversation behind this request's result lives: its own review's,
348    /// or for a reused result the producing review's. Absent when none was saved.
349    #[serde(default, skip_serializing_if = "Option::is_none")]
350    pub session: Option<crate::agent::session::SessionRef>,
351    #[serde(default, skip_serializing_if = "Option::is_none")]
352    pub review_notes: Option<String>,
353    #[serde(default, skip_serializing_if = "Option::is_none")]
354    pub human_definition: Option<store::HumanDefinition>,
355    pub payload: crate::config::StoredPayload,
356    pub references: BTreeMap<crate::config::ReferenceName, crate::types::ArtifactName>,
357    pub deps: Vec<crate::types::ArtifactName>,
358    #[serde(default)]
359    pub force: bool,
360    /// The target Artifact's fingerprint.
361    #[serde(default)]
362    pub fingerprint: Option<Fingerprint>,
363    /// The reuse key; absent without a fingerprint on every Artifact the eval depends on.
364    #[serde(default)]
365    pub key: Option<ReuseKey>,
366    /// Each Artifact the key covers, with its fingerprint.
367    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
368    pub fingerprints: std::collections::BTreeMap<crate::types::ArtifactName, Fingerprint>,
369    pub status: RequestStatus,
370    pub created_at: Timestamp,
371    pub started_at: Option<Timestamp>,
372    pub completed_at: Option<Timestamp>,
373    #[serde(with = "crate::platform::path_serde")]
374    pub cwd: PathBuf,
375    #[serde(default, with = "crate::platform::path_serde::option")]
376    pub run_dir: Option<PathBuf>,
377    pub argv: Option<Vec<String>>,
378    pub child: Option<store::ChildIdentity>,
379    pub result: Option<store::ExecutionResult>,
380    pub error: Option<String>,
381    pub error_code: Option<crate::types::FailureCode>,
382    pub blocked_reason: Option<String>,
383    /// Unfulfilled Evals behind this request’s dependency gates.
384    #[serde(default, skip_serializing_if = "Vec::is_empty")]
385    pub blocked_by: Vec<store::Blocker>,
386    /// Absent from requests saved before it existed, which read as waiting for a job.
387    #[serde(default, skip_serializing_if = "Option::is_none")]
388    pub queue: Option<QueueReason>,
389}
390
391impl TryFrom<RequestWire> for Request {
392    type Error = String;
393    fn try_from(wire: RequestWire) -> Result<Self, Self::Error> {
394        let mut state = store::RequestState::from_parts(
395            wire.status,
396            wire.result,
397            wire.error,
398            wire.error_code,
399            wire.completed_at,
400        )?;
401        // Old receipts could carry a queue reason on a different state; only queued ones use it.
402        if let store::RequestState::Queued { reason, .. } = &mut state {
403            *reason = wire.queue;
404        }
405        Ok(Self {
406            state,
407            id: wire.id,
408            run_id: wire.run_id,
409            eval_id: wire.eval_id,
410            target: wire.target,
411            title: wire.title,
412            profile: wire.profile,
413            requested_profile: wire.requested_profile,
414            eval_def_hash: wire.eval_def_hash,
415            options: wire.options,
416            execution_id: wire.execution_id,
417            provenance: wire.provenance,
418            usage: wire.usage,
419            reused_usage: wire.reused_usage,
420            joined: wire.joined,
421            producer: wire.producer,
422            reviewer: wire.reviewer,
423            origin: wire.origin,
424            session_id: wire.session_id,
425            session: wire.session,
426            review_notes: wire.review_notes,
427            human_definition: wire.human_definition,
428            payload: wire.payload,
429            references: wire.references,
430            deps: wire.deps,
431            force: wire.force,
432            fingerprint: wire.fingerprint,
433            key: wire.key,
434            fingerprints: wire.fingerprints,
435            created_at: wire.created_at,
436            started_at: wire.started_at,
437            cwd: wire.cwd,
438            run_dir: wire.run_dir,
439            argv: wire.argv,
440            child: wire.child,
441            blocked_reason: wire.blocked_reason,
442            blocked_by: wire.blocked_by,
443        })
444    }
445}
446impl From<Request> for RequestWire {
447    fn from(record: Request) -> Self {
448        Self {
449            queue: record.state.queue_reason().cloned(),
450            status: record.status(),
451            result: record.result().cloned(),
452            error: record.error().map(str::to_owned),
453            error_code: record.error_code(),
454            completed_at: record.completed_at(),
455            id: record.id,
456            run_id: record.run_id,
457            eval_id: record.eval_id,
458            target: record.target,
459            title: record.title,
460            profile: record.profile,
461            requested_profile: record.requested_profile,
462            eval_def_hash: record.eval_def_hash,
463            options: record.options,
464            execution_id: record.execution_id,
465            provenance: record.provenance,
466            usage: record.usage,
467            reused_usage: record.reused_usage,
468            joined: record.joined,
469            producer: record.producer,
470            reviewer: record.reviewer,
471            origin: record.origin,
472            session_id: record.session_id,
473            session: record.session,
474            review_notes: record.review_notes,
475            human_definition: record.human_definition,
476            payload: record.payload,
477            references: record.references,
478            deps: record.deps,
479            force: record.force,
480            fingerprint: record.fingerprint,
481            key: record.key,
482            fingerprints: record.fingerprints,
483            created_at: record.created_at,
484            started_at: record.started_at,
485            cwd: record.cwd,
486            run_dir: record.run_dir,
487            argv: record.argv,
488            child: record.child,
489            blocked_reason: record.blocked_reason,
490            blocked_by: record.blocked_by,
491        }
492    }
493}
494impl Request {
495    pub fn status(&self) -> crate::types::RequestStatus {
496        self.state.status()
497    }
498    pub fn result(&self) -> Option<&store::ExecutionResult> {
499        self.state.result()
500    }
501    pub fn error(&self) -> Option<&str> {
502        self.state.error()
503    }
504    pub fn error_code(&self) -> Option<crate::types::FailureCode> {
505        self.state.error_code()
506    }
507    pub fn completed_at(&self) -> Option<crate::types::Timestamp> {
508        self.state.completed_at()
509    }
510}
511
512#[derive(Debug, Serialize, Deserialize)]
513pub struct RunView {
514    #[serde(flatten)]
515    pub run: Run,
516    pub requests: Vec<std::sync::Arc<Request>>,
517    #[serde(default, skip_serializing_if = "Vec::is_empty")]
518    pub unreadable: Vec<store::Unreadable>,
519}
520
521#[cfg(test)]
522mod tests;