Skip to main content

lean_ctx/core/eval_ab/
suite.rs

1//! Eval suite + fixtures (#233): the deterministic task definitions an A/B run scores.
2//!
3//! A *suite* is an NDJSON file (one [`Task`] per line, `#`-comments + blank lines allowed).
4//! Each task carries everything the harness needs to (a) assemble context from a workspace,
5//! (b) prompt the pinned model, and (c) score the answer objectively. Two domains are
6//! supported today: free-form [`Domain::Qa`] (scored with EM / F1 / containment) and
7//! [`Domain::Code`] (scored by running a unit-test command against the model output).
8
9use std::path::{Component, Path, PathBuf};
10
11use anyhow::{Context, Result, bail};
12use serde::{Deserialize, Serialize};
13
14use crate::core::benchmark_spec::types::{is_safe_relative_file, is_safe_shell_test};
15
16/// What kind of task this is — selects the scorer and how the model output is interpreted.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "snake_case")]
19pub enum Domain {
20    /// Retrieval-augmented question answering, scored with EM / F1 / containment.
21    Qa,
22    /// Code task, scored by running a unit-test command against the model's output.
23    Code,
24}
25
26impl Domain {
27    /// Stable lowercase label used in digests and reports.
28    pub fn label(self) -> &'static str {
29        match self {
30            Domain::Qa => "qa",
31            Domain::Code => "code",
32        }
33    }
34}
35
36fn is_safe_relative_workspace(value: &str) -> bool {
37    let path = Path::new(value);
38    !value.trim().is_empty()
39        && !value.as_bytes().contains(&0)
40        && !path.is_absolute()
41        && path
42            .components()
43            .all(|component| matches!(component, Component::Normal(_) | Component::CurDir))
44}
45
46/// One scored unit of work. Fixtures are stored as NDJSON (one task per line) so suites are
47/// diff-friendly and stream without loading the whole file into a single JSON value.
48#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
49pub struct Task {
50    /// Stable, unique identifier (used in reports + the determinism digest).
51    pub id: String,
52    /// Selects the scorer and the meaning of the remaining fields.
53    pub domain: Domain,
54    /// Optional evaluation category, added without breaking existing suite files.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub task_class: Option<String>,
57    /// The instruction shown to the model (the "user turn").
58    pub prompt: String,
59    /// Repo / corpus directory the context is assembled from. Safe relative paths resolve
60    /// against the suite file's parent directory.
61    pub workspace: String,
62    /// Query used to retrieve context in the lean-ctx condition. Defaults to `prompt`.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub retrieval_query: Option<String>,
65
66    // --- Domain::Qa --------------------------------------------------------
67    /// Accepted gold answers. Any match counts (EM/F1 take the best over this set).
68    #[serde(default, skip_serializing_if = "Vec::is_empty")]
69    pub answers: Vec<String>,
70
71    // --- Domain::Code ------------------------------------------------------
72    /// File inside a sandbox copy of `workspace` that the model output replaces.
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub target_file: Option<String>,
75    /// Shell command run inside the sandbox; exit code 0 = pass.
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub test_cmd: Option<String>,
78}
79
80impl Task {
81    /// The retrieval query for the lean-ctx condition (falls back to the prompt).
82    pub fn query(&self) -> &str {
83        self.retrieval_query.as_deref().unwrap_or(&self.prompt)
84    }
85
86    /// Absolute workspace directory, resolved against `suite_dir` for relative paths.
87    pub fn workspace_path(&self, suite_dir: &Path) -> PathBuf {
88        let p = Path::new(&self.workspace);
89        if p.is_absolute() {
90            p.to_path_buf()
91        } else {
92            suite_dir.join(p)
93        }
94    }
95
96    /// Canonical workspace constrained to the suite directory.
97    pub(crate) fn resolve_workspace_path(&self, suite_dir: &Path) -> Result<PathBuf> {
98        if let Err(reason) = self.validate() {
99            bail!("invalid task {}: {reason}", self.id);
100        }
101        let root = std::fs::canonicalize(suite_dir)
102            .with_context(|| format!("canonicalizing suite directory {}", suite_dir.display()))?;
103        let workspace = std::fs::canonicalize(root.join(&self.workspace))
104            .with_context(|| format!("canonicalizing workspace {}", self.workspace))?;
105        if !workspace.starts_with(&root) {
106            bail!(
107                "task {}: workspace {} escapes suite directory",
108                self.id,
109                self.workspace
110            );
111        }
112        if !workspace.is_dir() {
113            bail!(
114                "task {}: workspace {} is not a directory",
115                self.id,
116                workspace.display()
117            );
118        }
119        Ok(workspace)
120    }
121
122    /// Validates the per-domain invariants. Returns a human-readable reason on failure.
123    pub(crate) fn validate(&self) -> std::result::Result<(), String> {
124        if self.id.trim().is_empty() {
125            return Err("task id is empty".into());
126        }
127        if self
128            .task_class
129            .as_deref()
130            .is_some_and(|class| class.trim().is_empty())
131        {
132            return Err(format!("task {}: task_class is empty", self.id));
133        }
134        if self.prompt.trim().is_empty() {
135            return Err(format!("task {}: prompt is empty", self.id));
136        }
137        if !is_safe_relative_workspace(&self.workspace) {
138            return Err(format!(
139                "task {}: workspace must be a safe relative path",
140                self.id
141            ));
142        }
143        match self.domain {
144            Domain::Qa => {
145                if self.answers.iter().all(|a| a.trim().is_empty()) {
146                    return Err(format!(
147                        "task {}: qa task has no non-empty answers",
148                        self.id
149                    ));
150                }
151            }
152            Domain::Code => self.validate_code_evaluation()?,
153        }
154        Ok(())
155    }
156
157    /// Validates code-evaluator fields independently of suite-relative workspace parsing.
158    pub(crate) fn validate_code_evaluation(&self) -> std::result::Result<(), String> {
159        if self.domain != Domain::Code {
160            return Err(format!(
161                "task {}: code evaluator requires a code task",
162                self.id
163            ));
164        }
165        if self.target_file.as_deref().unwrap_or("").trim().is_empty() {
166            return Err(format!("task {}: code task needs target_file", self.id));
167        }
168        if !self
169            .target_file
170            .as_deref()
171            .is_some_and(is_safe_relative_file)
172        {
173            return Err(format!(
174                "task {}: target_file must be a safe relative file path",
175                self.id
176            ));
177        }
178        if self.test_cmd.as_deref().unwrap_or("").trim().is_empty() {
179            return Err(format!("task {}: code task needs test_cmd", self.id));
180        }
181        if !self.test_cmd.as_deref().is_some_and(is_safe_shell_test) {
182            return Err(format!(
183                "task {}: test_cmd must be exactly `sh <relative .sh file>`",
184                self.id
185            ));
186        }
187        Ok(())
188    }
189}
190
191/// A loaded, validated suite: the tasks plus the directory used to resolve relative workspaces.
192#[derive(Debug, Clone)]
193pub struct EvalSuite {
194    /// Directory of the suite file (the resolution root for relative workspaces).
195    pub dir: PathBuf,
196    /// Validated tasks in file order.
197    pub tasks: Vec<Task>,
198}
199
200impl EvalSuite {
201    /// Parses + validates an NDJSON suite file.
202    pub fn load(path: &Path) -> Result<Self> {
203        let raw = std::fs::read_to_string(path)
204            .with_context(|| format!("reading suite {}", path.display()))?;
205        let dir = path
206            .parent()
207            .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
208        Self::parse(&raw, dir)
209    }
210
211    /// Pure parser (testable without touching disk for the suite body itself).
212    pub fn parse(raw: &str, dir: PathBuf) -> Result<Self> {
213        let mut tasks = Vec::new();
214        for (lineno, line) in raw.lines().enumerate() {
215            let trimmed = line.trim();
216            if trimmed.is_empty() || trimmed.starts_with('#') {
217                continue;
218            }
219            let task: Task = serde_json::from_str(trimmed)
220                .with_context(|| format!("parsing task on line {}", lineno + 1))?;
221            if let Err(reason) = task.validate() {
222                bail!("invalid task on line {}: {reason}", lineno + 1);
223            }
224            tasks.push(task);
225        }
226        if tasks.is_empty() {
227            bail!("suite contains no tasks");
228        }
229        // Unique ids keep the determinism digest unambiguous.
230        let mut seen = std::collections::HashSet::new();
231        for t in &tasks {
232            if !seen.insert(t.id.as_str()) {
233                bail!("duplicate task id: {}", t.id);
234            }
235        }
236        Ok(Self { dir, tasks })
237    }
238
239    /// Revalidates a suite assembled by callers instead of parsed from NDJSON.
240    pub(crate) fn validate(&self) -> Result<()> {
241        if self.tasks.is_empty() {
242            bail!("suite contains no tasks");
243        }
244        let mut seen = std::collections::HashSet::new();
245        for task in &self.tasks {
246            if let Err(reason) = task.validate() {
247                bail!("invalid task: {reason}");
248            }
249            if !seen.insert(task.id.as_str()) {
250                bail!("duplicate task id: {}", task.id);
251            }
252        }
253        Ok(())
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    fn qa_line() -> &'static str {
262        r#"{"id":"q1","domain":"qa","prompt":"What stores does consolidation write to?","workspace":"corpus","answers":["bm25, graph, knowledge, session"]}"#
263    }
264
265    fn code_line() -> &'static str {
266        r#"{"id":"c1","domain":"code","prompt":"Implement add","workspace":"code","target_file":"solution.sh","test_cmd":"sh test.sh"}"#
267    }
268
269    #[test]
270    fn parses_qa_and_code_skipping_comments_and_blanks() {
271        let raw = format!("# header\n\n{}\n{}\n", qa_line(), code_line());
272        let suite = EvalSuite::parse(&raw, PathBuf::from("/suites")).unwrap();
273        assert_eq!(suite.tasks.len(), 2);
274        assert_eq!(suite.tasks[0].domain, Domain::Qa);
275        assert_eq!(suite.tasks[1].domain, Domain::Code);
276        assert_eq!(suite.tasks[0].query(), suite.tasks[0].prompt);
277        assert_eq!(suite.tasks[0].task_class, None);
278
279        let classified = r#"{"id":"q2","domain":"qa","task_class":"needle_retrieval","prompt":"Find the owner","workspace":"corpus","answers":["registry"]}"#;
280        let classified = EvalSuite::parse(classified, PathBuf::from("/suites")).unwrap();
281        assert_eq!(
282            classified.tasks[0].task_class.as_deref(),
283            Some("needle_retrieval")
284        );
285    }
286
287    #[test]
288    fn relative_workspace_resolves_against_suite_dir() {
289        let suite = EvalSuite::parse(qa_line(), PathBuf::from("/suites")).unwrap();
290        assert_eq!(
291            suite.tasks[0].workspace_path(&suite.dir),
292            PathBuf::from("/suites/corpus")
293        );
294    }
295
296    #[test]
297    fn rejects_qa_without_answers() {
298        let bad = r#"{"id":"q","domain":"qa","prompt":"p","workspace":"w"}"#;
299        assert!(EvalSuite::parse(bad, PathBuf::from(".")).is_err());
300    }
301
302    #[test]
303    fn rejects_code_without_test_cmd() {
304        let bad = r#"{"id":"c","domain":"code","prompt":"p","workspace":"w","target_file":"f"}"#;
305        assert!(EvalSuite::parse(bad, PathBuf::from(".")).is_err());
306    }
307
308    #[test]
309    fn rejects_duplicate_ids() {
310        let raw = format!("{}\n{}", qa_line(), qa_line());
311        assert!(EvalSuite::parse(&raw, PathBuf::from(".")).is_err());
312    }
313
314    #[test]
315    fn rejects_empty_suite() {
316        assert!(EvalSuite::parse("# only comments\n\n", PathBuf::from(".")).is_err());
317    }
318
319    #[test]
320    fn rejects_unsafe_workload_and_code_paths() {
321        for workspace in ["/tmp/outside", "../outside", "nested/../../outside"] {
322            let raw = format!(
323                r#"{{"id":"q","domain":"qa","prompt":"p","workspace":"{workspace}","answers":["a"]}}"#
324            );
325            assert!(EvalSuite::parse(&raw, PathBuf::from(".")).is_err());
326        }
327        for target_file in [
328            "/tmp/solution.sh",
329            "../solution.sh",
330            "nested/../../solution.sh",
331        ] {
332            let raw = format!(
333                r#"{{"id":"c","domain":"code","prompt":"p","workspace":".","target_file":"{target_file}","test_cmd":"sh test.sh"}}"#
334            );
335            assert!(EvalSuite::parse(&raw, PathBuf::from(".")).is_err());
336        }
337        for test_cmd in [
338            "sh ../test.sh",
339            "sh test.sh; touch /tmp/pwned",
340            "cat /etc/passwd",
341        ] {
342            let raw = format!(
343                r#"{{"id":"c","domain":"code","prompt":"p","workspace":".","target_file":"solution.sh","test_cmd":"{test_cmd}"}}"#
344            );
345            assert!(EvalSuite::parse(&raw, PathBuf::from(".")).is_err());
346        }
347    }
348
349    #[test]
350    fn committed_task_class_corpus_parses_without_gold_in_task_metadata() {
351        let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("eval/quality-suite.ndjson");
352        // A mechanism fixture: one synthetic task per class. It proves the harness and
353        // the gold-leak guard, never quality.
354        let suite = EvalSuite::load(&path).expect("committed task-class suite must parse");
355        let expected = [
356            "needle_retrieval",
357            "long_context_qa",
358            "structured_data",
359            "code_understanding",
360            "test_failure_diagnosis",
361            "compiler_output_interpretation",
362            "shell_log_analysis",
363            "config_reasoning",
364            "dependency_tracing",
365            "security_relevant_reasoning",
366        ]
367        .into_iter()
368        .collect::<std::collections::BTreeSet<_>>();
369        let actual = suite
370            .tasks
371            .iter()
372            .filter_map(|task| task.task_class.as_deref())
373            .collect::<std::collections::BTreeSet<_>>();
374        assert_eq!(actual, expected);
375        let normalize = |value: &str| {
376            value
377                .chars()
378                .filter(|character| character.is_alphanumeric())
379                .flat_map(char::to_lowercase)
380                .collect::<String>()
381        };
382
383        for task in &suite.tasks {
384            task.resolve_workspace_path(&suite.dir)
385                .unwrap_or_else(|error| panic!("resolve {}: {error:#}", task.id));
386            for answer in &task.answers {
387                let gold = normalize(answer);
388                if gold.is_empty() {
389                    continue;
390                }
391                let metadata = [
392                    task.id.as_str(),
393                    task.prompt.as_str(),
394                    task.query(),
395                    task.task_class.as_deref().unwrap_or_default(),
396                ];
397                for field in metadata {
398                    assert!(
399                        !normalize(field).contains(&gold),
400                        "gold leaked into task metadata for {}",
401                        task.id
402                    );
403                }
404            }
405        }
406    }
407
408    #[cfg(unix)]
409    #[test]
410    fn canonical_workspace_rejects_symlink_escape() {
411        let root = tempfile::tempdir().unwrap();
412        let suite_root = root.path().join("suite");
413        let outside = tempfile::tempdir().unwrap();
414        std::fs::create_dir_all(&suite_root).unwrap();
415        std::os::unix::fs::symlink(outside.path(), suite_root.join("link")).unwrap();
416        let raw = r#"{"id":"q","domain":"qa","prompt":"p","workspace":"link","answers":["a"]}"#;
417        let suite = EvalSuite::parse(raw, suite_root.clone()).unwrap();
418        assert!(suite.tasks[0].resolve_workspace_path(&suite.dir).is_err());
419    }
420
421    #[test]
422    fn canonical_workspace_preserves_dot_fixture() {
423        let root = tempfile::tempdir().unwrap();
424        let raw = r#"{"id":"q","domain":"qa","prompt":"p","workspace":".","answers":["a"]}"#;
425        let suite = EvalSuite::parse(raw, root.path().to_path_buf()).unwrap();
426        assert_eq!(
427            suite.tasks[0].resolve_workspace_path(&suite.dir).unwrap(),
428            std::fs::canonicalize(root.path()).unwrap()
429        );
430    }
431}