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