1use std::collections::HashSet;
28use std::io::{BufRead, BufReader, BufWriter, Write};
29use std::path::Path;
30
31use serde::{Deserialize, Serialize};
32
33use crate::error::{EvalError, Result};
34use crate::report::EvaluationResult;
35use crate::schema::EvalCase;
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct AnnotationRecord {
40 pub case_id: String,
42 pub input: String,
44 pub expected_response: Option<String>,
46 pub actual_response: Option<String>,
48 pub verdict: Option<HumanVerdict>,
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct HumanVerdict {
55 pub score: f64,
57 pub reasoning: String,
59 pub annotator_id: String,
61}
62
63pub struct AnnotationStore;
65
66impl AnnotationStore {
67 pub fn export(
80 cases: &[EvalCase],
81 results: &[EvaluationResult],
82 output_path: impl AsRef<Path>,
83 ) -> Result<()> {
84 let file = std::fs::File::create(output_path.as_ref()).map_err(|e| {
85 EvalError::AnnotationError(format!(
86 "failed to create annotation file '{}': {e}",
87 output_path.as_ref().display()
88 ))
89 })?;
90 let mut writer = BufWriter::new(file);
91
92 for case in cases {
93 let input = case
95 .conversation
96 .iter()
97 .map(|turn| turn.user_content.get_text())
98 .collect::<Vec<_>>()
99 .join("\n");
100
101 let expected_response = case
103 .conversation
104 .last()
105 .and_then(|turn| turn.final_response.as_ref())
106 .map(|content| content.get_text());
107
108 let actual_response = results
110 .iter()
111 .find(|r| r.eval_id == case.eval_id)
112 .and_then(|r| r.turn_results.last())
113 .and_then(|tr| tr.actual_response.clone());
114
115 let record = AnnotationRecord {
116 case_id: case.eval_id.clone(),
117 input,
118 expected_response,
119 actual_response,
120 verdict: None,
121 };
122
123 let line = serde_json::to_string(&record).map_err(|e| {
124 EvalError::AnnotationError(format!(
125 "failed to serialize annotation record for case '{}': {e}",
126 case.eval_id
127 ))
128 })?;
129
130 writeln!(writer, "{line}").map_err(|e| {
131 EvalError::AnnotationError(format!("failed to write annotation line: {e}"))
132 })?;
133 }
134
135 writer.flush().map_err(|e| {
136 EvalError::AnnotationError(format!("failed to flush annotation file: {e}"))
137 })?;
138
139 Ok(())
140 }
141
142 pub fn import(
158 path: impl AsRef<Path>,
159 valid_case_ids: &HashSet<String>,
160 ) -> Result<(Vec<AnnotationRecord>, Vec<String>)> {
161 let file = std::fs::File::open(path.as_ref()).map_err(|e| {
162 EvalError::AnnotationError(format!(
163 "failed to open annotation file '{}': {e}",
164 path.as_ref().display()
165 ))
166 })?;
167 let reader = BufReader::new(file);
168
169 let mut records = Vec::new();
170 let mut warnings = Vec::new();
171
172 for (line_num, line_result) in reader.lines().enumerate() {
173 let line = line_result.map_err(|e| {
174 EvalError::AnnotationError(format!("failed to read line {}: {e}", line_num + 1))
175 })?;
176
177 let trimmed = line.trim();
179 if trimmed.is_empty() {
180 continue;
181 }
182
183 let record: AnnotationRecord = serde_json::from_str(trimmed).map_err(|e| {
184 EvalError::AnnotationError(format!(
185 "failed to parse annotation at line {}: {e}",
186 line_num + 1
187 ))
188 })?;
189
190 if valid_case_ids.contains(&record.case_id) {
191 records.push(record);
192 } else {
193 warnings.push(format!(
194 "unmatched case_id '{}' at line {}",
195 record.case_id,
196 line_num + 1
197 ));
198 }
199 }
200
201 Ok((records, warnings))
202 }
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208 use crate::report::EvaluationResult;
209 use crate::schema::{ContentData, EvalCase, Turn};
210 use std::collections::HashMap;
211 use std::time::Duration;
212 use tempfile::NamedTempFile;
213
214 fn make_case(id: &str, input: &str, expected: Option<&str>) -> EvalCase {
215 let mut conversation = vec![Turn {
216 invocation_id: format!("inv_{id}"),
217 user_content: ContentData::text(input),
218 final_response: expected.map(ContentData::model_response),
219 intermediate_data: None,
220 expected_vision: None,
221 }];
222
223 if expected.is_none() {
225 conversation[0].final_response = None;
226 }
227
228 EvalCase {
229 eval_id: id.to_string(),
230 description: String::new(),
231 conversation,
232 session_input: Default::default(),
233 tags: vec![],
234 metadata: None,
235 }
236 }
237
238 fn make_result(id: &str) -> EvaluationResult {
239 EvaluationResult::passed(id, HashMap::new(), Duration::from_millis(50))
240 }
241
242 #[test]
243 fn test_export_creates_jsonl_file() {
244 let cases = vec![
245 make_case("case_1", "Hello", Some("Hi there")),
246 make_case("case_2", "How are you?", None),
247 ];
248 let results = vec![make_result("case_1"), make_result("case_2")];
249
250 let tmp = NamedTempFile::new().unwrap();
251 let path = tmp.path().to_path_buf();
252
253 AnnotationStore::export(&cases, &results, &path).unwrap();
254
255 let content = std::fs::read_to_string(&path).unwrap();
256 let lines: Vec<&str> = content.lines().collect();
257 assert_eq!(lines.len(), 2);
258
259 let record: AnnotationRecord = serde_json::from_str(lines[0]).unwrap();
261 assert_eq!(record.case_id, "case_1");
262 assert_eq!(record.input, "Hello");
263 assert_eq!(record.expected_response, Some("Hi there".to_string()));
264 assert!(record.verdict.is_none());
265
266 let record: AnnotationRecord = serde_json::from_str(lines[1]).unwrap();
268 assert_eq!(record.case_id, "case_2");
269 assert_eq!(record.input, "How are you?");
270 assert_eq!(record.expected_response, None);
271 assert!(record.verdict.is_none());
272 }
273
274 #[test]
275 fn test_import_valid_records() {
276 let tmp = NamedTempFile::new().unwrap();
277 let path = tmp.path().to_path_buf();
278
279 let records = [
280 AnnotationRecord {
281 case_id: "case_1".to_string(),
282 input: "Hello".to_string(),
283 expected_response: Some("Hi".to_string()),
284 actual_response: Some("Hey".to_string()),
285 verdict: Some(HumanVerdict {
286 score: 0.9,
287 reasoning: "Good response".to_string(),
288 annotator_id: "reviewer_1".to_string(),
289 }),
290 },
291 AnnotationRecord {
292 case_id: "case_2".to_string(),
293 input: "Bye".to_string(),
294 expected_response: None,
295 actual_response: None,
296 verdict: None,
297 },
298 ];
299
300 let content: String = records
302 .iter()
303 .map(|r| serde_json::to_string(r).unwrap())
304 .collect::<Vec<_>>()
305 .join("\n");
306 std::fs::write(&path, content).unwrap();
307
308 let valid_ids: HashSet<String> =
309 ["case_1", "case_2"].iter().map(|s| s.to_string()).collect();
310 let (imported, warnings) = AnnotationStore::import(&path, &valid_ids).unwrap();
311
312 assert_eq!(imported.len(), 2);
313 assert!(warnings.is_empty());
314 assert_eq!(imported[0].case_id, "case_1");
315 assert!(imported[0].verdict.is_some());
316 assert_eq!(imported[0].verdict.as_ref().unwrap().score, 0.9);
317 }
318
319 #[test]
320 fn test_import_unmatched_case_ids_produce_warnings() {
321 let tmp = NamedTempFile::new().unwrap();
322 let path = tmp.path().to_path_buf();
323
324 let record = AnnotationRecord {
325 case_id: "unknown_case".to_string(),
326 input: "test".to_string(),
327 expected_response: None,
328 actual_response: None,
329 verdict: None,
330 };
331
332 let content = serde_json::to_string(&record).unwrap();
333 std::fs::write(&path, content).unwrap();
334
335 let valid_ids: HashSet<String> = ["case_1"].iter().map(|s| s.to_string()).collect();
336 let (imported, warnings) = AnnotationStore::import(&path, &valid_ids).unwrap();
337
338 assert!(imported.is_empty());
339 assert_eq!(warnings.len(), 1);
340 assert!(warnings[0].contains("unknown_case"));
341 }
342
343 #[test]
344 fn test_import_malformed_json_returns_error() {
345 let tmp = NamedTempFile::new().unwrap();
346 let path = tmp.path().to_path_buf();
347
348 std::fs::write(&path, "not valid json\n").unwrap();
349
350 let valid_ids: HashSet<String> = HashSet::new();
351 let result = AnnotationStore::import(&path, &valid_ids);
352
353 assert!(result.is_err());
354 let err = result.unwrap_err();
355 assert!(err.to_string().contains("annotation"));
356 }
357
358 #[test]
359 fn test_import_skips_empty_lines() {
360 let tmp = NamedTempFile::new().unwrap();
361 let path = tmp.path().to_path_buf();
362
363 let record = AnnotationRecord {
364 case_id: "case_1".to_string(),
365 input: "hello".to_string(),
366 expected_response: None,
367 actual_response: None,
368 verdict: None,
369 };
370
371 let line = serde_json::to_string(&record).unwrap();
372 let content = format!("\n{line}\n\n");
373 std::fs::write(&path, content).unwrap();
374
375 let valid_ids: HashSet<String> = ["case_1"].iter().map(|s| s.to_string()).collect();
376 let (imported, warnings) = AnnotationStore::import(&path, &valid_ids).unwrap();
377
378 assert_eq!(imported.len(), 1);
379 assert!(warnings.is_empty());
380 }
381
382 #[test]
383 fn test_export_import_round_trip() {
384 let cases = vec![
385 make_case("rt_1", "What is Rust?", Some("A systems programming language")),
386 make_case("rt_2", "Tell me a joke", Some("Why did the crab cross the road?")),
387 ];
388 let results = vec![make_result("rt_1"), make_result("rt_2")];
389
390 let tmp = NamedTempFile::new().unwrap();
391 let path = tmp.path().to_path_buf();
392
393 AnnotationStore::export(&cases, &results, &path).unwrap();
395
396 let valid_ids: HashSet<String> = cases.iter().map(|c| c.eval_id.clone()).collect();
398 let (imported, warnings) = AnnotationStore::import(&path, &valid_ids).unwrap();
399
400 assert!(warnings.is_empty());
401 assert_eq!(imported.len(), 2);
402
403 assert_eq!(imported[0].case_id, "rt_1");
405 assert_eq!(imported[0].input, "What is Rust?");
406 assert_eq!(
407 imported[0].expected_response,
408 Some("A systems programming language".to_string())
409 );
410
411 assert_eq!(imported[1].case_id, "rt_2");
412 assert_eq!(imported[1].input, "Tell me a joke");
413 assert_eq!(
414 imported[1].expected_response,
415 Some("Why did the crab cross the road?".to_string())
416 );
417 }
418
419 #[test]
420 fn test_export_nonexistent_directory_returns_error() {
421 let cases = vec![make_case("c1", "hi", None)];
422 let results = vec![];
423
424 let result =
425 AnnotationStore::export(&cases, &results, "/nonexistent/dir/annotations.jsonl");
426 assert!(result.is_err());
427 let err = result.unwrap_err();
428 assert!(err.to_string().contains("annotation"));
429 }
430
431 #[test]
432 fn test_import_nonexistent_file_returns_error() {
433 let valid_ids: HashSet<String> = HashSet::new();
434 let result = AnnotationStore::import("/nonexistent/file.jsonl", &valid_ids);
435 assert!(result.is_err());
436 let err = result.unwrap_err();
437 assert!(err.to_string().contains("annotation"));
438 }
439}