Skip to main content

graphrt_eval/
capture.rs

1//! What one run of the system under test produced, and the views assertions
2//! read from it: the output, the tool-call trajectory and retrieval hits.
3
4use graphrt_core::Event;
5use graphrt_core::event::Usage;
6use serde::{Deserialize, Serialize};
7use serde_json::{Map, Value as Json};
8
9/// How a run ended.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
11#[serde(rename_all = "snake_case")]
12pub enum RunStatus {
13    #[default]
14    Succeeded,
15    Failed,
16    Aborted,
17    Paused,
18}
19
20/// Everything recorded about one run.
21#[derive(Clone, Debug, Default)]
22#[non_exhaustive]
23pub struct RunCapture {
24    pub run_id: String,
25    pub status: RunStatus,
26    pub error: Option<String>,
27    pub error_type: Option<String>,
28    /// The workflow outputs (end node outputs).
29    pub outputs: Map<String, Json>,
30    /// The streamed answer text (answer nodes), empty when there is none.
31    pub answer: String,
32    pub usage: Usage,
33    /// Wall time of the run in milliseconds, measured by the harness.
34    pub latency_ms: u64,
35    /// The run's events, without `node_chunk` events (their text is in `answer`
36    /// and the node outputs).
37    pub events: Vec<Event>,
38}
39
40/// One tool call made by an agent node.
41#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
42#[non_exhaustive]
43pub struct ToolCallRecord {
44    /// Node that made the call.
45    pub node_id: String,
46    pub id: String,
47    /// Name the model called (the tool's exposed name).
48    pub name: String,
49    /// Tool provider and tool name, when the agent's `tool_calls` log has them.
50    #[serde(default, skip_serializing_if = "String::is_empty")]
51    pub provider: String,
52    #[serde(default, skip_serializing_if = "String::is_empty")]
53    pub tool: String,
54    pub arguments: Json,
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub is_error: Option<bool>,
57}
58
59impl ToolCallRecord {
60    /// Whether `pattern` (with `*` wildcards) names this call: the exposed name,
61    /// the tool name or `provider/tool`, as in the agent's `require_approval`.
62    pub fn matches(&self, pattern: &str) -> bool {
63        use crate::glob::matches;
64        matches(pattern, &self.name)
65            || (!self.tool.is_empty() && matches(pattern, &self.tool))
66            || (!self.provider.is_empty() && matches(pattern, &format!("{}/{}", self.provider, self.tool)))
67    }
68}
69
70/// One retrieved chunk from a `knowledge-retrieval` node.
71#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
72#[non_exhaustive]
73pub struct RetrievalHit {
74    pub node_id: String,
75    /// Chunk id.
76    pub id: String,
77    pub document_id: String,
78    pub score: Option<f64>,
79    /// The chunk text (judges get it as `contexts`).
80    #[serde(default, skip_serializing_if = "String::is_empty")]
81    pub content: String,
82}
83
84impl RetrievalHit {
85    /// Whether this hit is the labelled document or chunk `label`.
86    pub fn is(&self, label: &str) -> bool {
87        self.document_id == label || self.id == label
88    }
89}
90
91impl RunCapture {
92    /// Build a capture from a run's events (chunk events are dropped).
93    pub fn from_events(events: Vec<Event>, answer: String, latency_ms: u64) -> Self {
94        let mut capture = Self { answer, latency_ms, ..Self::default() };
95        for event in &events {
96            match event {
97                Event::RunStarted { run_id, .. } => capture.run_id.clone_from(run_id),
98                Event::RunSucceeded { outputs, usage, .. } => {
99                    capture.status = RunStatus::Succeeded;
100                    capture.outputs = outputs.iter().map(|(k, v)| (k.clone(), v.to_json())).collect();
101                    capture.usage = *usage;
102                }
103                Event::RunFailed { error, error_type, usage, .. } => {
104                    capture.status = RunStatus::Failed;
105                    capture.error = Some(error.clone());
106                    capture.error_type = Some(error_type.clone());
107                    capture.usage = *usage;
108                }
109                Event::RunAborted { reason, .. } => {
110                    capture.status = RunStatus::Aborted;
111                    capture.error = Some(reason.clone());
112                    capture.error_type = Some("aborted".into());
113                }
114                Event::RunPaused { reasons, .. } => {
115                    capture.status = RunStatus::Paused;
116                    let kinds: Vec<&str> = reasons.iter().map(|r| r.kind.as_str()).collect();
117                    capture.error = Some(format!("the run paused ({})", kinds.join(", ")));
118                    capture.error_type = Some("paused".into());
119                }
120                _ => {}
121            }
122        }
123        capture.events = events.into_iter().filter(|e| !matches!(e, Event::NodeChunk { .. })).collect();
124        capture
125    }
126
127    /// The main output assertions check by default: the answer text when the
128    /// workflow streamed one, else the single output value, else the outputs object.
129    pub fn output(&self) -> Json {
130        if !self.answer.is_empty() {
131            return Json::String(self.answer.clone());
132        }
133        match (self.outputs.len(), self.outputs.values().next()) {
134            (1, Some(only)) => only.clone(),
135            _ => Json::Object(self.outputs.clone()),
136        }
137    }
138
139    /// The object paths are resolved against: `output`, `answer`, `outputs`,
140    /// `usage`, `latency_ms`, `status`, `error`, plus `vars` from the test.
141    pub fn subject_root(&self, vars: &Map<String, Json>) -> Json {
142        serde_json::json!({
143            "output": self.output(),
144            "answer": self.answer,
145            "outputs": self.outputs,
146            "usage": self.usage,
147            "latency_ms": self.latency_ms,
148            "status": self.status,
149            "error": self.error,
150            "vars": vars,
151        })
152    }
153
154    /// Every tool call in the order the agents announced them (`tool_call`
155    /// progress events), enriched with the provider and tool name from the
156    /// agent's `tool_calls` output.
157    pub fn tool_calls(&self) -> Vec<ToolCallRecord> {
158        let mut calls = Vec::new();
159        for event in &self.events {
160            match event {
161                Event::NodeProgress { node_id, name, data, .. } if name == "tool_call" => {
162                    let data = data.to_json();
163                    calls.push(ToolCallRecord {
164                        node_id: node_id.to_string(),
165                        id: text(&data, "id"),
166                        name: text(&data, "name"),
167                        arguments: data.get("arguments").cloned().unwrap_or(Json::Null),
168                        ..ToolCallRecord::default()
169                    });
170                }
171                Event::NodeSucceeded { node_id, outputs, .. } => {
172                    let Some(log) = outputs.get("tool_calls").map(graphrt_core::Value::to_json) else { continue };
173                    for entry in log.as_array().into_iter().flatten() {
174                        let name = text(entry, "name");
175                        let pending = calls
176                            .iter_mut()
177                            .find(|c| c.node_id == node_id.as_ref() && c.name == name && c.is_error.is_none());
178                        if let Some(call) = pending {
179                            call.provider = text(entry, "provider");
180                            call.tool = text(entry, "tool");
181                            call.is_error = entry.get("is_error").and_then(Json::as_bool);
182                        }
183                    }
184                }
185                _ => {}
186            }
187        }
188        calls
189    }
190
191    /// Number of agent steps (model turns: `agent_step` progress events).
192    pub fn agent_steps(&self) -> usize {
193        self.progress_count("agent_step")
194    }
195
196    /// Number of node executions that finished (succeeded or failed).
197    pub fn node_executions(&self) -> usize {
198        self.events.iter().filter(|e| matches!(e, Event::NodeSucceeded { .. } | Event::NodeFailed { .. })).count()
199    }
200
201    fn progress_count(&self, wanted: &str) -> usize {
202        self.events.iter().filter(|e| matches!(e, Event::NodeProgress { name, .. } if name == wanted)).count()
203    }
204
205    /// Hits of every `knowledge-retrieval` node, in rank order (nodes in the
206    /// order they finished).
207    pub fn retrieval_hits(&self) -> Vec<RetrievalHit> {
208        let mut retrieval_execs = std::collections::HashSet::new();
209        let mut hits = Vec::new();
210        for event in &self.events {
211            match event {
212                Event::NodeStarted { exec_id, kind, .. } if kind.as_ref() == "knowledge-retrieval" => {
213                    retrieval_execs.insert(exec_id.clone());
214                }
215                Event::NodeSucceeded { node_id, exec_id, outputs, .. } if retrieval_execs.contains(exec_id) => {
216                    let Some(result) = outputs.get("result").map(graphrt_core::Value::to_json) else { continue };
217                    for hit in result.as_array().into_iter().flatten() {
218                        hits.push(RetrievalHit {
219                            node_id: node_id.to_string(),
220                            id: text(hit, "id"),
221                            document_id: text(hit, "document_id"),
222                            score: hit.get("score").and_then(Json::as_f64),
223                            content: text(hit, "content"),
224                        });
225                    }
226                }
227                _ => {}
228            }
229        }
230        hits
231    }
232}
233
234fn text(value: &Json, key: &str) -> String {
235    match value.get(key) {
236        Some(Json::String(s)) => s.clone(),
237        Some(Json::Null) | None => String::new(),
238        Some(other) => other.to_string(),
239    }
240}