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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::error::{Error, Result};
use crate::model::{round4, Catalog, SCHEMA_VERSION};
use crate::ranker::{RankedTool, Ranker};
/// A single query-to-tool expectation test case.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EvalCase {
/// Unique identifier for reporting regressions.
pub id: String,
/// Natural-language user or agent query.
pub query: String,
/// Primary expected tool name.
pub expected_tool: String,
/// Additional acceptable tool names (counted as hits for Top-1 and Recall@k).
#[serde(default)]
pub acceptable_tools: Vec<String>,
}
impl EvalCase {
fn is_hit(&self, tool_name: &str) -> bool {
tool_name == self.expected_tool || self.acceptable_tools.iter().any(|t| t == tool_name)
}
}
/// Pairwise confusion count showing which wrong tool was picked instead of the expected tool.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConfusionEntry {
/// Expected tool name.
pub expected: String,
/// Tool ranked at Top-1 instead (`"<none>"` if the ranker returned no candidates).
pub predicted: String,
/// Number of queries exhibiting this misrouting.
pub count: usize,
}
/// Detailed failure entry for a single [`EvalCase`] whose Top-1 prediction missed.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EvalFailure {
/// Case identifier.
pub case_id: String,
/// Input query string.
pub query: String,
/// Expected tool name.
pub expected_tool: String,
/// Top-1 predicted tool name, if any.
pub predicted_top1: Option<String>,
/// 1-based rank of the expected tool within `top_k`, or `None` if absent.
pub expected_rank: Option<usize>,
/// Full ranked candidates returned up to `top_k`.
pub ranked_top_k: Vec<RankedTool>,
}
/// Complete evaluation report returned by [`EvalSuite::run`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EvalReport {
/// Report schema version.
pub schema_version: String,
/// Number of evaluated query cases.
pub total_cases: usize,
/// Value of `k` used for Recall@k and ranked candidate lists.
pub top_k: usize,
/// Number of queries whose Top-1 prediction matched.
pub top1_hits: usize,
/// Top-1 selection accuracy (`0.0..=1.0`).
pub top1_accuracy: f32,
/// Number of queries where an expected tool appeared within Top-`k`.
pub topk_hits: usize,
/// Recall@`k` (`0.0..=1.0`).
pub recall_at_k: f32,
/// Mean Reciprocal Rank across all cases (`0.0..=1.0`).
pub mrr: f32,
/// Normalized Discounted Cumulative Gain at `k` (`0.0..=1.0`).
#[serde(default)]
pub ndcg_at_k: f32,
/// Per-expected-tool Top-1 accuracy map (`0.0..=1.0`) for pinpointing low-discoverability tools.
#[serde(default)]
pub per_tool_accuracy: BTreeMap<String, f32>,
/// Aggregated wrong-tool confusion pairs sorted descending by count.
pub confusion_matrix: Vec<ConfusionEntry>,
/// Detailed per-case failure breakdown for all Top-1 misses.
pub failures: Vec<EvalFailure>,
}
impl EvalReport {
/// Serializes this evaluation report as pretty-printed JSON.
pub fn to_json_pretty(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(self)?)
}
/// Serializes this evaluation report as minified single-line JSON for AI agents.
pub fn to_json_compact(&self) -> Result<String> {
Ok(serde_json::to_string(self)?)
}
/// Formats a concise human-readable summary.
pub fn to_text(&self) -> String {
let mut out = String::new();
out.push_str(&format!(
"mcp-vol eval: Top-1 {:.1}% ({}/{}) | Recall@{} {:.1}% ({}/{}) | MRR {:.4} | NDCG@{} {:.4}\n",
self.top1_accuracy * 100.0,
self.top1_hits,
self.total_cases,
self.top_k,
self.recall_at_k * 100.0,
self.topk_hits,
self.total_cases,
self.mrr,
self.top_k,
self.ndcg_at_k,
));
if !self.confusion_matrix.is_empty() {
out.push_str("\nTop confusions:\n");
for c in &self.confusion_matrix {
out.push_str(&format!(
" expected '{}' -> picked '{}' ({}x)\n",
c.expected, c.predicted, c.count
));
}
}
if !self.failures.is_empty() {
out.push_str("\nFailed cases:\n");
for f in &self.failures {
out.push_str(&format!(
" [{}] \"{}\" -> expected '{}', got '{}' (rank={:?})\n",
f.case_id,
f.query,
f.expected_tool,
f.predicted_top1.as_deref().unwrap_or("<none>"),
f.expected_rank
));
}
}
out
}
/// Formats a GitHub-Flavored Markdown summary suitable for Pull Request comments.
pub fn to_markdown(&self) -> String {
let mut out = String::new();
out.push_str("### `mcp-vol` Tool-Selection Evaluation\n\n");
out.push_str("| Metric | Result |\n|---|---:|\n");
out.push_str(&format!(
"| **Top-1 Accuracy** | **{:.1}%** ({}/{}) |\n",
self.top1_accuracy * 100.0,
self.top1_hits,
self.total_cases
));
out.push_str(&format!(
"| **Recall@{}** | **{:.1}%** ({}/{}) |\n",
self.top_k,
self.recall_at_k * 100.0,
self.topk_hits,
self.total_cases
));
out.push_str(&format!("| **MRR** | `{:.4}` |\n", self.mrr));
out.push_str(&format!(
"| **NDCG@{}** | `{:.4}` |\n",
self.top_k, self.ndcg_at_k
));
if !self.confusion_matrix.is_empty() {
out.push_str(
"\n#### Confusion Pairs\n\n| Expected | Picked (Top-1) | Count |\n|---|---|---:|\n",
);
for c in &self.confusion_matrix {
out.push_str(&format!(
"| `{}` | `{}` | {} |\n",
c.expected, c.predicted, c.count
));
}
}
if !self.failures.is_empty() {
out.push_str("\n#### Failed Queries\n\n| Case | Query | Expected | Top-1 | Expected Rank |\n|---|---|---|---|---:|\n");
for f in &self.failures {
out.push_str(&format!(
"| `{}` | {} | `{}` | `{}` | {} |\n",
f.case_id,
f.query.replace('|', "\\|"),
f.expected_tool,
f.predicted_top1.as_deref().unwrap_or("<none>"),
f.expected_rank
.map(|r| format!("#{r}"))
.unwrap_or_else(|| "missed".into())
));
}
}
out
}
}
/// Executable suite of query-to-tool selection assertions runnable in CI.
#[derive(Debug, Clone, Default)]
pub struct EvalSuite {
cases: Vec<EvalCase>,
}
impl EvalSuite {
/// Creates a suite from an iterator of [`EvalCase`].
pub fn new(cases: impl IntoIterator<Item = EvalCase>) -> Self {
Self {
cases: cases.into_iter().collect(),
}
}
/// Parses a suite from either a JSON array `[EvalCase, ...]` or `{ "cases": [...] }`.
pub fn from_json(json: &str) -> Result<Self> {
let value: Value = serde_json::from_str(json)?;
let cases_val = if value.is_array() {
value
} else if let Some(cases) = value.get("cases") {
cases.clone()
} else {
return Err(Error::InvalidEvalSuite(
"expected a JSON array of cases or an object with a `cases` array".into(),
));
};
let cases: Vec<EvalCase> = serde_json::from_value(cases_val)?;
if cases.is_empty() {
return Err(Error::InvalidEvalSuite(
"evaluation suite must contain at least one case".into(),
));
}
Ok(Self { cases })
}
/// Deterministically synthesizes a zero-LLM baseline evaluation suite from a [`Catalog`].
///
/// Produces an intent query and (when parameters exist) a parameter-focused query per tool so
/// AI agents can bootstrap CI routing gates in under 1 ms and immediately surface sibling collisions.
#[must_use]
pub fn generate_baseline(catalog: &Catalog) -> Self {
let mut cases = Vec::new();
for tool in catalog.tools() {
let name_words = crate::text::tokenize_raw(&tool.name);
if name_words.is_empty() {
continue;
}
let humanized_name = name_words.join(" ");
// 1) Primary intent case from first non-redirection description clause (or humanized name).
let intent_query = tool
.description
.as_deref()
.and_then(|d| {
d.split(['.', ';', '\n'])
.map(str::trim)
.find(|clause| {
let low = clause.to_lowercase();
!low.is_empty()
&& !low.contains("instead")
&& !low.contains("do not use")
&& !low.contains("don't use")
})
.map(|clause| {
clause
.replace('`', "")
.split_whitespace()
.take(14)
.collect::<Vec<_>>()
.join(" ")
})
})
.filter(|q| !q.is_empty())
.unwrap_or_else(|| humanized_name.clone());
cases.push(EvalCase {
id: format!("{}_intent", tool.name),
query: intent_query,
expected_tool: tool.name.clone(),
acceptable_tools: Vec::new(),
});
// 2) Parameter-grounded case when the tool exposes input parameters.
let mut param_names: Vec<String> = tool
.required_parameters()
.into_iter()
.map(|p| crate::text::tokenize_raw(p).join(" "))
.filter(|p| !p.is_empty())
.collect();
for p in tool.parameter_names() {
let h = crate::text::tokenize_raw(p).join(" ");
if !h.is_empty() && !param_names.contains(&h) {
param_names.push(h);
}
}
param_names.truncate(3);
if !param_names.is_empty() {
cases.push(EvalCase {
id: format!("{}_params", tool.name),
query: format!("{humanized_name} using {}", param_names.join(", ")),
expected_tool: tool.name.clone(),
acceptable_tools: Vec::new(),
});
}
}
Self { cases }
}
/// Synthesizes hard sibling-disambiguation queries targeting every overlapping pair detected
/// in `catalog` (similarity >= 0.45), testing whether rankers cleanly separate look-alike tools.
#[must_use]
pub fn generate_adversarial(catalog: &Catalog) -> Self {
use std::collections::BTreeSet;
let analysis = crate::collision::analyze_collisions(catalog, 0.45, 0.30);
let mut cases = Vec::new();
let mut seen = BTreeSet::new();
for pair in &analysis.pairs {
if pair.tool_a == pair.tool_b {
continue;
}
let (Some(ta), Some(tb)) = (catalog.get(&pair.tool_a), catalog.get(&pair.tool_b))
else {
continue;
};
for (target, sibling) in [(ta, tb), (tb, ta)] {
let key = format!("{}_vs_{}", target.name, sibling.name);
if !seen.insert(key.clone()) {
continue;
}
let sib_tokens: BTreeSet<String> = crate::text::tokenize_raw(&sibling.name)
.into_iter()
.chain(
sibling
.description
.as_deref()
.map(crate::text::tokenize_raw)
.unwrap_or_default(),
)
.collect();
let mut distinguishing: Vec<String> = crate::text::tokenize_raw(&target.name)
.into_iter()
.chain(
target
.description
.as_deref()
.map(crate::text::tokenize_raw)
.unwrap_or_default(),
)
.filter(|tok| tok.len() >= 3 && !sib_tokens.contains(tok))
.collect();
distinguishing.dedup();
distinguishing.truncate(6);
let query = if distinguishing.is_empty() {
format!(
"{} {}",
pair.shared_terms.join(" "),
crate::text::tokenize_raw(&target.name).join(" ")
)
.trim()
.to_string()
} else {
format!(
"{} {}",
pair.shared_terms
.iter()
.take(3)
.cloned()
.collect::<Vec<_>>()
.join(" "),
distinguishing.join(" ")
)
.trim()
.to_string()
};
cases.push(EvalCase {
id: key,
query,
expected_tool: target.name.clone(),
acceptable_tools: Vec::new(),
});
}
}
// If no pairs exceeded 0.45 (e.g., opposite-polarity CRUD siblings like create_issue vs
// close_issue, or a clean well-separated catalog), contrast each tool against its closest
// lexical neighbor so `gen-eval --adversarial` always emits a valid, challenging suite.
if cases.is_empty() && catalog.len() >= 2 {
let tools = catalog.tools();
let bags: Vec<BTreeSet<String>> = tools
.iter()
.map(|t| {
crate::text::tokenize_raw(&t.name)
.into_iter()
.chain(
t.description
.as_deref()
.map(crate::text::tokenize_raw)
.unwrap_or_default(),
)
.collect()
})
.collect();
for (i, target) in tools.iter().enumerate() {
let mut best_j: Option<(usize, usize)> = None;
for (j, other_bag) in bags.iter().enumerate() {
if i == j {
continue;
}
let shared = bags[i].intersection(other_bag).count();
if best_j.is_none_or(|(_, best_shared)| shared > best_shared) {
best_j = Some((j, shared));
}
}
if let Some((j, _)) = best_j {
let sibling = &tools[j];
let shared: Vec<String> = bags[i]
.intersection(&bags[j])
.filter(|tok| tok.len() >= 3)
.take(3)
.cloned()
.collect();
let mut distinguishing: Vec<String> = crate::text::tokenize_raw(&target.name)
.into_iter()
.chain(
target
.description
.as_deref()
.map(crate::text::tokenize_raw)
.unwrap_or_default(),
)
.filter(|tok| tok.len() >= 3 && !bags[j].contains(tok))
.collect();
distinguishing.dedup();
distinguishing.truncate(6);
let query = format!("{} {}", shared.join(" "), distinguishing.join(" "))
.trim()
.to_string();
let query = if query.is_empty() {
crate::text::tokenize_raw(&target.name).join(" ")
} else {
query
};
cases.push(EvalCase {
id: format!("{}_vs_{}", target.name, sibling.name),
query,
expected_tool: target.name.clone(),
acceptable_tools: Vec::new(),
});
}
}
}
if cases.is_empty() {
return Self::generate_baseline(catalog);
}
Self { cases }
}
/// Serializes this evaluation suite as pretty-printed JSON (`{"cases":[...]}`).
pub fn to_json_pretty(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(
&serde_json::json!({ "cases": self.cases }),
)?)
}
/// Serializes this evaluation suite as minified single-line JSON.
pub fn to_json_compact(&self) -> Result<String> {
Ok(serde_json::to_string(
&serde_json::json!({ "cases": self.cases }),
)?)
}
/// Returns the cases contained in this suite.
pub fn cases(&self) -> &[EvalCase] {
&self.cases
}
/// Evaluates every query against `catalog` using `ranker` and returns accuracy, Recall@k, MRR,
/// NDCG@k, per-tool accuracy, and a confusion matrix.
pub fn run(&self, catalog: &Catalog, ranker: &dyn Ranker, top_k: usize) -> EvalReport {
let k = top_k.max(1);
let total = self.cases.len();
if total == 0 {
return EvalReport {
schema_version: SCHEMA_VERSION.into(),
total_cases: 0,
top_k: k,
top1_hits: 0,
top1_accuracy: 1.0,
topk_hits: 0,
recall_at_k: 1.0,
mrr: 1.0,
ndcg_at_k: 1.0,
per_tool_accuracy: BTreeMap::new(),
confusion_matrix: Vec::new(),
failures: Vec::new(),
};
}
let mut top1_hits = 0usize;
let mut topk_hits = 0usize;
let mut rr_sum = 0.0_f32;
let mut ndcg_sum = 0.0_f32;
let mut per_tool_totals: BTreeMap<String, (usize, usize)> = BTreeMap::new();
let mut confusion: BTreeMap<(String, String), usize> = BTreeMap::new();
let mut failures = Vec::new();
for case in &self.cases {
let ranked = ranker.rank(&case.query, catalog, k);
let predicted_top1 = ranked.first().map(|r| r.tool_name.clone());
let expected_rank = ranked
.iter()
.position(|r| case.is_hit(&r.tool_name))
.map(|idx| idx + 1);
if let Some(rank) = expected_rank {
topk_hits += 1;
rr_sum += 1.0 / (rank as f32);
if rank == 1 {
top1_hits += 1;
}
}
// Compute graded DCG@k / IDCG@k (primary expected = 2, acceptable = 1).
let mut dcg = 0.0_f32;
for (idx, cand) in ranked.iter().enumerate() {
let rel = if cand.tool_name == case.expected_tool {
2.0_f32
} else if case.acceptable_tools.iter().any(|t| t == &cand.tool_name) {
1.0_f32
} else {
0.0_f32
};
if rel > 0.0 {
let denom = ((idx as f32) + 2.0).log2();
dcg += (2.0_f32.powf(rel) - 1.0) / denom;
}
}
let mut ideal_rels = vec![2.0_f32];
ideal_rels.resize(1 + case.acceptable_tools.len(), 1.0_f32);
ideal_rels.truncate(k);
let idcg: f32 = ideal_rels
.into_iter()
.enumerate()
.map(|(idx, rel)| (2.0_f32.powf(rel) - 1.0) / ((idx as f32) + 2.0).log2())
.sum();
if idcg > 0.0 {
ndcg_sum += (dcg / idcg).clamp(0.0, 1.0);
}
let top1_ok = predicted_top1
.as_deref()
.is_some_and(|name| case.is_hit(name));
let entry = per_tool_totals
.entry(case.expected_tool.clone())
.or_insert((0, 0));
entry.1 += 1;
if top1_ok {
entry.0 += 1;
} else {
let pred_label = predicted_top1
.clone()
.unwrap_or_else(|| "<none>".to_string());
*confusion
.entry((case.expected_tool.clone(), pred_label))
.or_insert(0) += 1;
failures.push(EvalFailure {
case_id: case.id.clone(),
query: case.query.clone(),
expected_tool: case.expected_tool.clone(),
predicted_top1,
expected_rank,
ranked_top_k: ranked,
});
}
}
let per_tool_accuracy: BTreeMap<String, f32> = per_tool_totals
.into_iter()
.map(|(tool, (hits, cnt))| (tool, round4(hits as f32 / cnt.max(1) as f32)))
.collect();
let mut confusion_matrix: Vec<ConfusionEntry> = confusion
.into_iter()
.map(|((expected, predicted), count)| ConfusionEntry {
expected,
predicted,
count,
})
.collect();
confusion_matrix.sort_by(|a, b| {
b.count
.cmp(&a.count)
.then_with(|| a.expected.cmp(&b.expected))
.then_with(|| a.predicted.cmp(&b.predicted))
});
EvalReport {
schema_version: SCHEMA_VERSION.into(),
total_cases: total,
top_k: k,
top1_hits,
top1_accuracy: round4(top1_hits as f32 / total as f32),
topk_hits,
recall_at_k: round4(topk_hits as f32 / total as f32),
mrr: round4(rr_sum / total as f32),
ndcg_at_k: round4(ndcg_sum / total as f32),
per_tool_accuracy,
confusion_matrix,
failures,
}
}
}
/// Summary row for a single ranker inside [`RankerComparison`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RankerScoreRow {
/// Human-readable ranker label (e.g., `"bm25"`, `"tfidf"`, `"hybrid"`).
pub ranker: String,
/// Top-1 selection accuracy (`0.0..=1.0`).
pub top1_accuracy: f32,
/// Recall@`k` (`0.0..=1.0`).
pub recall_at_k: f32,
/// Mean Reciprocal Rank (`0.0..=1.0`).
pub mrr: f32,
/// Normalized Discounted Cumulative Gain @ `k` (`0.0..=1.0`).
pub ndcg_at_k: f32,
/// Total Top-1 misses.
pub failure_count: usize,
}
/// Side-by-side multi-ranker A/B comparison returned by [`compare_rankers`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RankerComparison {
/// Schema version.
pub schema_version: String,
/// Number of evaluated queries.
pub total_cases: usize,
/// `top_k` depth evaluated.
pub top_k: usize,
/// Best-performing ranker name (ordered by Top-1 → MRR → NDCG@k).
pub winner: String,
/// Ranked leaderboard of all evaluated rankers.
pub results: Vec<RankerScoreRow>,
}
impl RankerComparison {
/// Serializes this comparison as pretty-printed JSON.
pub fn to_json_pretty(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(self)?)
}
/// Serializes this comparison as minified single-line JSON.
pub fn to_json_compact(&self) -> Result<String> {
Ok(serde_json::to_string(self)?)
}
/// Formats a GitHub-Flavored Markdown comparison table.
pub fn to_markdown(&self) -> String {
let mut out = format!(
"### `mcp-vol` Ranker Comparison ({} cases, top-{}) — Winner: **`{}`**\n\n",
self.total_cases, self.top_k, self.winner
);
out.push_str(&format!(
"| Ranker | Top-1 Accuracy | Recall@{} | MRR | NDCG@{} | Misses |\n",
self.top_k, self.top_k
));
out.push_str("|---|---:|---:|---:|---:|---:|\n");
for row in &self.results {
out.push_str(&format!(
"| `{}` | **{:.1}%** | {:.1}% | `{:.4}` | `{:.4}` | {} |\n",
row.ranker,
row.top1_accuracy * 100.0,
row.recall_at_k * 100.0,
row.mrr,
row.ndcg_at_k,
row.failure_count
));
}
out
}
/// Formats a compact terminal summary.
pub fn to_text(&self) -> String {
let mut out = format!(
"mcp-vol compare-rankers ({} cases, top-{}) | winner: {}\n",
self.total_cases, self.top_k, self.winner
);
for row in &self.results {
out.push_str(&format!(
" {:12} Top-1 {:5.1}% | Recall@{} {:5.1}% | MRR {:.4} | NDCG@{} {:.4} | misses {}\n",
row.ranker,
row.top1_accuracy * 100.0,
self.top_k,
row.recall_at_k * 100.0,
row.mrr,
self.top_k,
row.ndcg_at_k,
row.failure_count
));
}
out
}
}
/// Evaluates multiple named [`Ranker`] implementations side-by-side on the exact same
/// [`EvalSuite`] and [`Catalog`] and identifies the top performer.
#[must_use]
pub fn compare_rankers(
suite: &EvalSuite,
catalog: &Catalog,
rankers: &[(&str, &dyn Ranker)],
top_k: usize,
) -> RankerComparison {
let k = top_k.max(1);
let mut results: Vec<RankerScoreRow> = rankers
.iter()
.map(|(name, ranker)| {
let rep = suite.run(catalog, *ranker, k);
RankerScoreRow {
ranker: (*name).to_string(),
top1_accuracy: rep.top1_accuracy,
recall_at_k: rep.recall_at_k,
mrr: rep.mrr,
ndcg_at_k: rep.ndcg_at_k,
failure_count: rep.failures.len(),
}
})
.collect();
results.sort_by(|a, b| {
b.top1_accuracy
.total_cmp(&a.top1_accuracy)
.then_with(|| b.mrr.total_cmp(&a.mrr))
.then_with(|| b.ndcg_at_k.total_cmp(&a.ndcg_at_k))
.then_with(|| a.ranker.cmp(&b.ranker))
});
let winner = results
.first()
.map(|r| r.ranker.clone())
.unwrap_or_else(|| "<none>".into());
RankerComparison {
schema_version: SCHEMA_VERSION.into(),
total_cases: suite.cases().len(),
top_k: k,
winner,
results,
}
}