Skip to main content

artifactize_core/runs/
result.rs

1//! Bounded pages derived from a saved Run/request/execution read snapshot, never a second store.
2use super::{Context, State, observe};
3use crate::types::{EvalId, RequestId, RequestStatus, RunId, Sha256Digest};
4use serde::{Deserialize, Serialize, ser::SerializeMap};
5/// Compact findings stay useful within MCP's response bound even with long owner summaries.
6const SUMMARY_CHARS: usize = 512;
7/// Shared page size; interfaces cannot accidentally emit an unbounded findings list.
8pub const PAGE_SIZE: usize = 20;
9/// Leave room for the envelope and MCP's structured-plus-text mirror under 64 KiB.
10const FINDING_BYTES: usize = 24 * 1024;
11#[derive(Debug, Clone, Copy, Serialize)]
12#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
13pub enum RunVerdict {
14    Green,
15    Red,
16    Incomplete,
17    Yellow,
18    Error,
19    Cancelled,
20}
21impl RunVerdict {
22    fn from_state(state: State) -> Option<Self> {
23        match state {
24            State::Green => Some(Self::Green),
25            State::Red => Some(Self::Red),
26            State::Incomplete => Some(Self::Incomplete),
27            State::Yellow => Some(Self::Yellow),
28            State::Error => Some(Self::Error),
29            State::Cancelled => Some(Self::Cancelled),
30            _ => None,
31        }
32    }
33}
34/// The durable Run's outcome, independent of how a surface observed it.
35#[derive(Debug, Serialize)]
36pub struct Completion {
37    pub run: RunId,
38    pub outcome: RunVerdict,
39    /// Total awaiting Review; Run detail lists all requests if the preview is truncated.
40    pub waiting_signoff_count: usize,
41    pub waiting_signoffs: Vec<Signoff>,
42}
43
44#[derive(Debug, Serialize)]
45pub struct Signoff {
46    pub request: RequestId,
47    pub eval: EvalId,
48}
49
50/// Read only the final outcome. Non-YELLOW Runs need no full request snapshot.
51pub async fn completion(context: &Context, id: &RunId) -> Result<Option<Completion>, String> {
52    let observed = observe::status(context, id).await?;
53    let Some(outcome) = RunVerdict::from_state(observed.state) else {
54        return Ok(None);
55    };
56    let mut waiting_signoffs = Vec::new();
57    let mut waiting_signoff_count = 0;
58    if matches!(outcome, RunVerdict::Yellow) {
59        let view = observe::view(context, id).await?;
60        for request in view
61            .requests
62            .iter()
63            .filter(|request| request.status().is_human_wait())
64        {
65            waiting_signoff_count += 1;
66            if waiting_signoffs.len() < PAGE_SIZE {
67                waiting_signoffs.push(Signoff {
68                    request: request.id.clone(),
69                    eval: request.eval_id.clone(),
70                });
71            }
72        }
73    }
74    Ok(Some(Completion {
75        run: observed.run,
76        outcome,
77        waiting_signoff_count,
78        waiting_signoffs,
79    }))
80}
81
82#[derive(Debug, Clone, Serialize, Deserialize)]
83#[serde(try_from = "String", into = "String")]
84pub struct ResultCursor {
85    run: RunId,
86    revision: Sha256Digest,
87    offset: usize,
88}
89impl TryFrom<String> for ResultCursor {
90    type Error = String;
91    fn try_from(value: String) -> Result<Self, String> {
92        let mut parts = value.rsplitn(3, ':');
93        let offset = parts
94            .next()
95            .and_then(|part| part.parse().ok())
96            .ok_or("Invalid result cursor.")?;
97        let revision = parts
98            .next()
99            .ok_or("Invalid result cursor.")?
100            .parse::<Sha256Digest>()
101            .map_err(|_| "Invalid result cursor.")?;
102        let run = parts.next().ok_or("Invalid result cursor.")?.parse()?;
103        Ok(Self {
104            run,
105            revision,
106            offset,
107        })
108    }
109}
110impl From<ResultCursor> for String {
111    fn from(cursor: ResultCursor) -> Self {
112        format!("{}:{}:{}", cursor.run, cursor.revision, cursor.offset)
113    }
114}
115impl std::str::FromStr for ResultCursor {
116    type Err = String;
117    fn from_str(value: &str) -> Result<Self, String> {
118        value.to_owned().try_into()
119    }
120}
121#[derive(Debug, Clone, Serialize)]
122pub struct Finding {
123    pub request: RequestId,
124    pub eval: EvalId,
125    pub state: RequestStatus,
126    pub summary: String,
127}
128/// One result phase owns readiness and verdict. Only GREEN can carry recorded
129/// satisfaction; older GREEN Runs without validation may still lack that proof.
130#[derive(Debug, Clone, Copy)]
131pub enum ResultState {
132    Preparing,
133    Running,
134    Waiting,
135    WaitingHuman,
136    Cancelling,
137    Green { satisfied: bool },
138    Red,
139    Incomplete,
140    Yellow,
141    Error,
142    Cancelled,
143}
144impl ResultState {
145    fn from_observed(state: State, satisfied: bool) -> Self {
146        match state {
147            State::Preparing => Self::Preparing,
148            State::Running => Self::Running,
149            State::Waiting => Self::Waiting,
150            State::WaitingHuman => Self::WaitingHuman,
151            State::Cancelling => Self::Cancelling,
152            State::Green => Self::Green { satisfied },
153            State::Red => Self::Red,
154            State::Incomplete => Self::Incomplete,
155            State::Yellow => Self::Yellow,
156            State::Error => Self::Error,
157            State::Cancelled => Self::Cancelled,
158        }
159    }
160    pub fn state(self) -> State {
161        match self {
162            Self::Preparing => State::Preparing,
163            Self::Running => State::Running,
164            Self::Waiting => State::Waiting,
165            Self::WaitingHuman => State::WaitingHuman,
166            Self::Cancelling => State::Cancelling,
167            Self::Green { .. } => State::Green,
168            Self::Red => State::Red,
169            Self::Incomplete => State::Incomplete,
170            Self::Yellow => State::Yellow,
171            Self::Error => State::Error,
172            Self::Cancelled => State::Cancelled,
173        }
174    }
175}
176#[derive(Debug, Clone)]
177pub struct RunResultPage {
178    pub run: RunId,
179    pub phase: ResultState,
180    pub findings: Vec<Finding>,
181    pub next_cursor: Option<ResultCursor>,
182}
183impl RunResultPage {
184    pub fn state(&self) -> State {
185        self.phase.state()
186    }
187    pub fn ready(&self) -> bool {
188        self.state().is_terminal()
189    }
190    pub fn verdict(&self) -> Option<RunVerdict> {
191        RunVerdict::from_state(self.state())
192    }
193    pub fn satisfied(&self) -> bool {
194        matches!(self.phase, ResultState::Green { satisfied: true })
195    }
196}
197impl Serialize for RunResultPage {
198    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
199        // Preserve the flat CLI/MCP wire format; all status flags are derived here.
200        let mut output = serializer.serialize_map(None)?;
201        output.serialize_entry("run", &self.run)?;
202        output.serialize_entry("state", &self.state())?;
203        output.serialize_entry("ready", &self.ready())?;
204        output.serialize_entry("verdict", &self.verdict())?;
205        output.serialize_entry("satisfied", &self.satisfied())?;
206        output.serialize_entry("findings", &self.findings)?;
207        output.serialize_entry("next_cursor", &self.next_cursor)?;
208        output.end()
209    }
210}
211pub(super) fn finding(request: &crate::store::Request) -> Finding {
212    let summary = if let Some(error) = request.error() {
213        error.to_owned()
214    } else if let Some(summary) = request
215        .result()
216        .and_then(crate::store::ExecutionResult::summary)
217    {
218        summary
219    } else {
220        request.status().to_string()
221    };
222    Finding {
223        request: request.id.clone(),
224        eval: request.eval_id.clone(),
225        state: request.status(),
226        summary: summary.chars().take(SUMMARY_CHARS).collect(),
227    }
228}
229pub async fn result(
230    context: &Context,
231    id: &RunId,
232    cursor: Option<ResultCursor>,
233) -> Result<RunResultPage, String> {
234    let observation = observe::status(context, id).await?;
235    if !observation.state.is_terminal() {
236        if cursor.is_some() {
237            return Err("A running Run has no result cursor.".into());
238        }
239        return Ok(RunResultPage {
240            run: id.clone(),
241            phase: ResultState::from_observed(observation.state, false),
242            findings: Vec::new(),
243            next_cursor: None,
244        });
245    }
246    let state_path = context.state.clone();
247    let run_id = id.clone();
248    let (view, details) = crate::task::joined(
249        tokio::task::spawn_blocking(move || {
250            let mut reader = crate::store::reader::Reader::default();
251            reader.snapshot(&state_path, |db, cache, state| {
252                cache
253                    .selected(db, state, &run_id, true)?
254                    .ok_or_else(|| crate::store::receipts::Error::Invalid("Run not found.".into()))
255            })
256        })
257        .await,
258    )
259    .map_err(|e| e.to_string())??;
260    let state = observe::state(&view.run, &view.requests);
261    let revision =
262        Sha256Digest::of(&serde_json::to_vec(&(&view, &details)).map_err(|e| e.to_string())?);
263    let offset = if let Some(cursor) = cursor {
264        if cursor.run != *id || cursor.revision != revision {
265            return Err("Expired or foreign result cursor.".into());
266        }
267        cursor.offset
268    } else {
269        0
270    };
271    if offset > view.requests.len() {
272        return Err("Invalid result cursor offset.".into());
273    }
274    let findings = if state.is_terminal() {
275        view.requests
276            .iter()
277            .skip(offset)
278            .take(PAGE_SIZE)
279            .map(|request| finding(request))
280            .scan(0, |bytes, finding| {
281                let size = serde_json::to_vec(&finding)
282                    .expect("typed finding serializes")
283                    .len()
284                    + 1;
285                *bytes += size;
286                (*bytes <= FINDING_BYTES).then_some(finding)
287            })
288            .collect::<Vec<_>>()
289    } else {
290        Vec::new()
291    };
292    let next = offset + findings.len();
293    let next_cursor = (state.is_terminal() && next < view.requests.len()).then(|| ResultCursor {
294        run: id.clone(),
295        revision,
296        offset: next,
297    });
298    Ok(RunResultPage {
299        run: id.clone(),
300        phase: ResultState::from_observed(
301            state,
302            view.run.validation.snapshot().is_some_and(|validation| {
303                matches!(validation.satisfied, crate::config::Field::Value(true))
304            }),
305        ),
306        findings,
307        next_cursor,
308    })
309}
310
311#[cfg(test)]
312mod tests;