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    #[serde(default, skip_serializing_if = "Option::is_none")]
356    pub human_declaration_scope: Option<crate::config::DeclarationScope>,
357    pub payload: crate::config::StoredPayload,
358    pub references: BTreeMap<crate::config::ReferenceName, crate::types::ArtifactName>,
359    pub deps: Vec<crate::types::ArtifactName>,
360    #[serde(default)]
361    pub force: bool,
362    /// The target Artifact's fingerprint.
363    #[serde(default)]
364    pub fingerprint: Option<Fingerprint>,
365    /// The reuse key; absent without a fingerprint on every Artifact the eval depends on.
366    #[serde(default)]
367    pub key: Option<ReuseKey>,
368    /// Each Artifact the key covers, with its fingerprint.
369    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
370    pub fingerprints: std::collections::BTreeMap<crate::types::ArtifactName, Fingerprint>,
371    pub status: RequestStatus,
372    pub created_at: Timestamp,
373    pub started_at: Option<Timestamp>,
374    pub completed_at: Option<Timestamp>,
375    #[serde(with = "crate::platform::path_serde")]
376    pub cwd: PathBuf,
377    #[serde(default, with = "crate::platform::path_serde::option")]
378    pub run_dir: Option<PathBuf>,
379    pub argv: Option<Vec<String>>,
380    pub child: Option<store::ChildIdentity>,
381    pub result: Option<store::ExecutionResult>,
382    pub error: Option<String>,
383    pub error_code: Option<crate::types::FailureCode>,
384    pub blocked_reason: Option<String>,
385    /// Unfulfilled Evals behind this request’s dependency gates.
386    #[serde(default, skip_serializing_if = "Vec::is_empty")]
387    pub blocked_by: Vec<store::Blocker>,
388    /// Absent from requests saved before it existed, which read as waiting for a job.
389    #[serde(default, skip_serializing_if = "Option::is_none")]
390    pub queue: Option<QueueReason>,
391}
392
393impl TryFrom<RequestWire> for Request {
394    type Error = String;
395    fn try_from(mut wire: RequestWire) -> Result<Self, Self::Error> {
396        if let Some(scope) = wire.human_declaration_scope
397            && let Some(definition) = &mut wire.human_definition
398        {
399            definition.declaration_scope = Some(scope);
400        }
401        let mut state = store::RequestState::from_parts(
402            wire.status,
403            wire.result,
404            wire.error,
405            wire.error_code,
406            wire.completed_at,
407        )?;
408        // Old receipts could carry a queue reason on a different state; only queued ones use it.
409        if let store::RequestState::Queued { reason, .. } = &mut state {
410            *reason = wire.queue;
411        }
412        Ok(Self {
413            state,
414            id: wire.id,
415            run_id: wire.run_id,
416            eval_id: wire.eval_id,
417            target: wire.target,
418            title: wire.title,
419            profile: wire.profile,
420            requested_profile: wire.requested_profile,
421            eval_def_hash: wire.eval_def_hash,
422            options: wire.options,
423            execution_id: wire.execution_id,
424            provenance: wire.provenance,
425            usage: wire.usage,
426            reused_usage: wire.reused_usage,
427            joined: wire.joined,
428            producer: wire.producer,
429            reviewer: wire.reviewer,
430            origin: wire.origin,
431            session_id: wire.session_id,
432            session: wire.session,
433            review_notes: wire.review_notes,
434            human_definition: wire.human_definition,
435            payload: wire.payload,
436            references: wire.references,
437            deps: wire.deps,
438            force: wire.force,
439            fingerprint: wire.fingerprint,
440            key: wire.key,
441            fingerprints: wire.fingerprints,
442            created_at: wire.created_at,
443            started_at: wire.started_at,
444            cwd: wire.cwd,
445            run_dir: wire.run_dir,
446            argv: wire.argv,
447            child: wire.child,
448            blocked_reason: wire.blocked_reason,
449            blocked_by: wire.blocked_by,
450        })
451    }
452}
453impl From<Request> for RequestWire {
454    fn from(mut record: Request) -> Self {
455        let human_declaration_scope = record
456            .human_definition
457            .as_mut()
458            .and_then(|definition| definition.declaration_scope.take());
459        Self {
460            queue: record.state.queue_reason().cloned(),
461            status: record.status(),
462            result: record.result().cloned(),
463            error: record.error().map(str::to_owned),
464            error_code: record.error_code(),
465            completed_at: record.completed_at(),
466            id: record.id,
467            run_id: record.run_id,
468            eval_id: record.eval_id,
469            target: record.target,
470            title: record.title,
471            profile: record.profile,
472            requested_profile: record.requested_profile,
473            eval_def_hash: record.eval_def_hash,
474            options: record.options,
475            execution_id: record.execution_id,
476            provenance: record.provenance,
477            usage: record.usage,
478            reused_usage: record.reused_usage,
479            joined: record.joined,
480            producer: record.producer,
481            reviewer: record.reviewer,
482            origin: record.origin,
483            session_id: record.session_id,
484            session: record.session,
485            review_notes: record.review_notes,
486            human_definition: record.human_definition,
487            human_declaration_scope,
488            payload: record.payload,
489            references: record.references,
490            deps: record.deps,
491            force: record.force,
492            fingerprint: record.fingerprint,
493            key: record.key,
494            fingerprints: record.fingerprints,
495            created_at: record.created_at,
496            started_at: record.started_at,
497            cwd: record.cwd,
498            run_dir: record.run_dir,
499            argv: record.argv,
500            child: record.child,
501            blocked_reason: record.blocked_reason,
502            blocked_by: record.blocked_by,
503        }
504    }
505}
506impl Request {
507    pub fn status(&self) -> crate::types::RequestStatus {
508        self.state.status()
509    }
510    pub fn result(&self) -> Option<&store::ExecutionResult> {
511        self.state.result()
512    }
513    pub fn error(&self) -> Option<&str> {
514        self.state.error()
515    }
516    pub fn error_code(&self) -> Option<crate::types::FailureCode> {
517        self.state.error_code()
518    }
519    pub fn completed_at(&self) -> Option<crate::types::Timestamp> {
520        self.state.completed_at()
521    }
522}
523
524#[derive(Debug, Serialize, Deserialize)]
525pub struct RunView {
526    #[serde(flatten)]
527    pub run: Run,
528    pub requests: Vec<std::sync::Arc<Request>>,
529    #[serde(default, skip_serializing_if = "Vec::is_empty")]
530    pub unreadable: Vec<store::Unreadable>,
531}
532
533#[cfg(test)]
534mod tests;