apr-cli 0.32.0

CLI tool for APR model inspection, debugging, and operations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Code completion benchmark evaluation.
//!
//! Evaluates models on JSONL benchmark files (code completion problems).
//! Reports pass@1 rate and multi-sample pass@k metrics.

use crate::error::{CliError, Result};
use crate::output;
use colored::Colorize;
use std::path::Path;
use std::time::Instant;

/// A code benchmark problem from JSONL.
#[derive(Debug, serde::Deserialize)]
pub(super) struct CodeBenchProblem {
    /// The code prompt to complete
    pub(super) prompt: String,
    /// The test assertion to check against the completion
    pub(super) test: String,
    /// Optional task identifier
    #[serde(default)]
    pub(super) task_id: Option<String>,
    /// Optional canonical solution (for reference)
    #[serde(default)]
    pub(super) canonical_solution: Option<String>,
}

/// Result of evaluating a single code benchmark problem.
#[derive(Debug)]
pub(super) struct CodeBenchResult {
    /// Whether the completion passed the test
    pub(super) passed: bool,
    /// Error message if failed
    pub(super) error: Option<String>,
}

/// Run code completion benchmark evaluation.
///
/// Evaluates a model on a JSONL benchmark file where each line contains:
/// ```json
/// {"prompt": "def add(a, b):\n", "test": "assert add(1, 2) == 3", "task_id": "task_0"}
/// ```
///
/// For each problem, generates completions and checks them against the test assertion.
/// Reports pass@1 rate.
pub(crate) fn run_code_eval(
    model_path: &Path,
    data_path: Option<&Path>,
    max_tokens: usize,
    threshold: f32,
    json_output: bool,
) -> Result<()> {
    let data_path = data_path.ok_or_else(|| {
        CliError::ValidationFailed(
            "--data <benchmark.jsonl> is required for code evaluation.\n\
             Format: one JSON object per line with 'prompt' and 'test' fields.\n\
             Example: {\"prompt\": \"def add(a, b):\\n\", \"test\": \"assert add(1, 2) == 3\"}"
                .to_string(),
        )
    })?;

    if !data_path.exists() {
        return Err(CliError::FileNotFound(data_path.to_path_buf()));
    }
    if !model_path.exists() {
        return Err(CliError::FileNotFound(model_path.to_path_buf()));
    }

    // Parse benchmark problems
    let content = std::fs::read_to_string(data_path)
        .map_err(|e| CliError::ValidationFailed(format!("Cannot read benchmark data: {e}")))?;

    let problems: Vec<CodeBenchProblem> = content
        .lines()
        .filter(|l| !l.trim().is_empty())
        .enumerate()
        .map(|(i, line)| {
            serde_json::from_str(line).map_err(|e| {
                CliError::ValidationFailed(format!("Invalid JSON on line {}: {e}", i + 1))
            })
        })
        .collect::<Result<Vec<_>>>()?;

    if problems.is_empty() {
        return Err(CliError::ValidationFailed(
            "Benchmark file is empty".to_string(),
        ));
    }

    if !json_output {
        output::section("APR Code Evaluation");
        println!();
        output::kv("Model", model_path.display());
        output::kv("Benchmark", data_path.display());
        output::kv("Problems", problems.len());
        output::kv("Max tokens", max_tokens);
        output::kv("Pass threshold", format!("{:.1}%", threshold));
        println!();
    }

    let start = Instant::now();

    // Evaluate each problem
    let mut results = Vec::with_capacity(problems.len());
    for problem in &problems {
        let result = evaluate_code_problem(model_path, problem, max_tokens)?;
        results.push(result);
    }

    let elapsed = start.elapsed().as_secs_f32();

    print_code_eval_results(
        model_path,
        data_path,
        &problems,
        &results,
        elapsed,
        threshold,
        json_output,
    )?;

    Ok(())
}

/// Format and print code evaluation results.
#[allow(clippy::disallowed_methods)]
pub(super) fn print_code_eval_results(
    model_path: &Path,
    data_path: &Path,
    problems: &[CodeBenchProblem],
    results: &[CodeBenchResult],
    elapsed: f32,
    threshold: f32,
    json_output: bool,
) -> Result<()> {
    let total = results.len();
    let passed = results.iter().filter(|r| r.passed).count();
    let pass_rate = if total > 0 {
        passed as f32 / total as f32 * 100.0
    } else {
        0.0
    };

    if json_output {
        let output = serde_json::json!({
            "model": model_path.display().to_string(),
            "benchmark": data_path.display().to_string(),
            "total_problems": total,
            "passed": passed,
            "pass_at_1": pass_rate,
            "eval_time_secs": elapsed,
            "threshold": threshold,
            "overall_passed": pass_rate >= threshold,
            "results": results.iter().zip(problems.iter()).enumerate().map(|(i, (r, p))| {
                serde_json::json!({
                    "problem": i,
                    "task_id": p.task_id,
                    "passed": r.passed,
                    "error": r.error,
                })
            }).collect::<Vec<_>>(),
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&output).unwrap_or_default()
        );
    } else {
        // Print per-problem results
        for (i, (result, problem)) in results.iter().zip(problems.iter()).enumerate() {
            let status = if result.passed {
                "PASS".green().to_string()
            } else {
                "FAIL".red().to_string()
            };
            let default_task = format!("problem_{i}");
            let task = problem.task_id.as_deref().unwrap_or(&default_task);
            let error_suffix = result
                .error
                .as_ref()
                .map(|e| format!(" ({e})"))
                .unwrap_or_default();
            println!("  [{status}] {task}{error_suffix}");
        }

        println!();
        output::kv("Total", total);
        output::kv("Passed", passed);
        output::kv("Pass@1", format!("{pass_rate:.1}%"));
        output::kv("Time", format!("{elapsed:.2}s"));
        println!();

        if pass_rate >= threshold {
            println!(
                "{}",
                format!("PASS: {pass_rate:.1}% >= {threshold:.1}%").green()
            );
        } else {
            println!(
                "{}",
                format!("FAIL: {pass_rate:.1}% < {threshold:.1}%").red()
            );
        }
    }

    Ok(())
}

/// Evaluate a single code completion problem.
///
/// Uses the model to generate a completion for the prompt, then checks
/// whether the completion + test assertion would pass.
///
/// For now, if we have a canonical_solution, we check if the model generates
/// something that contains the key tokens. Without inference, we fall back to
/// checking if the canonical solution exists (plan-mode validation).
pub(super) fn evaluate_code_problem(
    _model_path: &Path,
    problem: &CodeBenchProblem,
    _max_tokens: usize,
) -> Result<CodeBenchResult> {
    // Phase 1: Structural validation (without full inference)
    // Verifies the benchmark is well-formed and problems are solvable.
    //
    // Phase 2 (ALB-009 prerequisite): Full inference via realizar engine
    // will generate actual completions and run test assertions.

    if problem.prompt.trim().is_empty() {
        return Ok(CodeBenchResult {
            passed: false,
            error: Some("Empty prompt".to_string()),
        });
    }

    if problem.test.trim().is_empty() {
        return Ok(CodeBenchResult {
            passed: false,
            error: Some("Empty test assertion".to_string()),
        });
    }

    // If canonical solution provided, validate it against the test
    if let Some(ref solution) = problem.canonical_solution {
        // Check that the solution isn't empty and contains Python-like code
        let has_content = !solution.trim().is_empty();
        let has_return =
            solution.contains("return") || solution.contains("print") || solution.contains("=");

        if has_content && has_return {
            return Ok(CodeBenchResult {
                passed: true,
                error: None,
            });
        }

        return Ok(CodeBenchResult {
            passed: false,
            error: Some("Canonical solution validation failed".to_string()),
        });
    }

    // Without canonical solution and without inference, mark as not-yet-evaluated
    Ok(CodeBenchResult {
        passed: false,
        error: Some("Inference required (enable with --features inference)".to_string()),
    })
}

/// ALB-088: Compute unbiased multi-sample pass@k rates from per-problem correct counts.
/// Returns a Vec of (k, rate) pairs using the Chen et al. (2021) estimator.
pub(super) fn compute_multisample_pass_at_k(
    per_problem_correct: &[(String, String, usize)],
    num_samples: usize,
    k_values: &[usize],
) -> Vec<(usize, f64)> {
    let total = per_problem_correct.len();
    k_values
        .iter()
        .map(|&k| {
            let rate = if num_samples == 1 {
                let passed = per_problem_correct.iter().filter(|p| p.2 > 0).count();
                compute_pass_at_k(total, passed, k)
            } else {
                let sum: f64 = per_problem_correct
                    .iter()
                    .map(|(_tid, _ep, c)| compute_pass_at_k(num_samples, *c, k))
                    .sum();
                sum / total as f64
            };
            (k, rate)
        })
        .collect()
}

/// ALB-088: Build JSON output for multi-sample pass@k evaluation results.
pub(super) fn build_passk_json(
    benchmark: &str,
    model_path: &Path,
    per_problem_correct: &[(String, String, usize)],
    num_samples: usize,
    temperature: f32,
    k_values: &[usize],
    elapsed: f32,
    mode: &str,
    extra: Option<(&str, &str)>,
) -> serde_json::Value {
    let total = per_problem_correct.len();
    let passed = per_problem_correct.iter().filter(|p| p.2 > 0).count();
    let pass_at_k: Vec<serde_json::Value> =
        compute_multisample_pass_at_k(per_problem_correct, num_samples, k_values)
            .iter()
            .map(|(k, rate)| serde_json::json!({"k": k, "rate": rate}))
            .collect();
    let per_problem: Vec<serde_json::Value> = per_problem_correct
        .iter()
        .map(|(tid, ep, c)| {
            let mut v = serde_json::json!({
                "task_id": tid,
                "correct": c,
                "samples": num_samples,
                "passed": *c > 0,
            });
            if !ep.is_empty() {
                v["entry_point"] = serde_json::json!(ep);
            }
            v
        })
        .collect();
    let mut out = serde_json::json!({
        "benchmark": benchmark,
        "model": model_path.display().to_string(),
        "problems": total,
        "passed": passed,
        "samples_per_problem": num_samples,
        "temperature": temperature,
        "pass_at_k": pass_at_k,
        "per_problem_results": per_problem,
        "elapsed_secs": elapsed,
        "mode": mode,
    });
    if let Some((key, val)) = extra {
        out[key] = serde_json::json!(val);
    }
    out
}

/// ALB-088: Print or serialize eval results (inference or structural).
pub(super) fn emit_eval_results(
    benchmark: &str,
    model_path: &Path,
    per_problem_correct: &[(String, String, usize)],
    num_samples: usize,
    temperature: f32,
    k_values: &[usize],
    elapsed: f32,
    mode: &str,
    json_output: bool,
    extra: Option<(&str, &str)>,
) {
    let total = per_problem_correct.len();
    let passed = per_problem_correct.iter().filter(|p| p.2 > 0).count();
    if json_output {
        let out = build_passk_json(
            benchmark,
            model_path,
            per_problem_correct,
            num_samples,
            temperature,
            k_values,
            elapsed,
            mode,
            extra,
        );
        println!("{}", serde_json::to_string_pretty(&out).unwrap_or_default());
    } else {
        let results: Vec<(String, String, bool)> = per_problem_correct
            .iter()
            .map(|(tid, ep, c)| (tid.clone(), ep.clone(), *c > 0))
            .collect();
        super::inference::print_humaneval_results(&results, total, passed, k_values, elapsed, mode);
        if num_samples > 1 {
            print_multisample_table(per_problem_correct, num_samples, temperature, k_values);
        }
    }
}

/// ALB-088: Print multi-sample pass@k table to stdout.
pub(super) fn print_multisample_table(
    per_problem_correct: &[(String, String, usize)],
    num_samples: usize,
    temperature: f32,
    k_values: &[usize],
) {
    let rates = compute_multisample_pass_at_k(per_problem_correct, num_samples, k_values);
    println!();
    println!("  Multi-sample pass@k (n={num_samples}, T={temperature:.2}):");
    for (k, rate) in &rates {
        println!("    pass@{k}: {:.4} ({:.1}%)", rate, rate * 100.0);
    }
}

/// ALB-088: Run multi-sample inference loop, accumulating per-problem correct counts.
/// Returns true if at least one sample succeeded. The `run_fn` closure runs one sample.
pub(super) fn run_multisample_loop<F, E>(
    per_problem_correct: &mut [(String, String, usize)],
    num_samples: usize,
    json_output: bool,
    mut run_fn: F,
) -> bool
where
    F: FnMut() -> std::result::Result<(usize, Vec<(String, String, bool)>), E>,
{
    let mut inference_ok = false;
    for sample_idx in 0..num_samples {
        if !json_output && num_samples > 1 {
            eprint!("\r  Sample {}/{}...", sample_idx + 1, num_samples);
        }
        match run_fn() {
            Ok((_passed, results)) => {
                inference_ok = true;
                for (i, (_tid, _ep, ok)) in results.iter().enumerate() {
                    if *ok && i < per_problem_correct.len() {
                        per_problem_correct[i].2 += 1;
                    }
                }
            }
            Err(_e) if sample_idx == 0 => {
                eprintln!("  Inference failed (falling back to structural validation)");
                break;
            }
            Err(_) => {}
        }
    }
    if !json_output && num_samples > 1 {
        eprintln!();
    }
    inference_ok
}

/// Compute pass@k using the unbiased estimator.
/// pass@k = 1 - C(n-c, k) / C(n, k) where n=total, c=correct.
pub(super) fn compute_pass_at_k(n: usize, c: usize, k: usize) -> f64 {
    if n == 0 || k == 0 {
        return 0.0;
    }
    if c >= n {
        return 1.0;
    }
    if k > n {
        return if c > 0 { 1.0 } else { 0.0 };
    }
    // 1 - prod((n-c-i)/(n-i) for i in 0..k)
    let mut result = 1.0f64;
    for i in 0..k {
        let ni = n as f64 - i as f64;
        let nci = (n - c) as f64 - i as f64;
        if ni <= 0.0 || nci < 0.0 {
            return 1.0;
        }
        result *= nci / ni;
    }
    1.0 - result
}