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