1use std::collections::{BTreeMap, BTreeSet};
10use std::error::Error;
11use std::fmt;
12use std::fmt::Write as _;
13use std::fs;
14use std::path::{Path, PathBuf};
15use std::time::Instant;
16
17use serde_json::Value;
18
19use crate::{
20 Grammar, GrammarExpr, GrammarFormat, GrammarOracle, GrammarRule, InferenceOptions,
21 MetricScores, PositiveOnlyOracle, SampleConfig, ScoringMode, emit_gbnf, evaluate, infer_cfg,
22};
23
24pub const DEFAULT_CORPUS_MANIFEST: &str = "benches/corpus-manifest.lino";
26pub const DEFAULT_CORPORA_ROOT: &str = "benches/corpora";
28pub const PUBLISHED_TREEVADA_AVG_F1: f64 = 0.32;
30pub const PUBLISHED_NATGI_AVG_F1: f64 = 0.57;
32pub const D5_REQUIRED_AVG_F1: f64 = PUBLISHED_NATGI_AVG_F1;
34
35#[derive(Clone, Debug, PartialEq, Eq)]
37pub struct CompetitorManifest {
38 pub schema: u64,
40 pub entries: Vec<CorpusManifestEntry>,
42}
43
44#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct CorpusManifestEntry {
47 pub tool: String,
49 pub subject: String,
51 pub source: String,
53 pub commit: String,
55 pub license: String,
57 pub files: usize,
59 pub bytes: u64,
61 pub included: bool,
63 pub exclude_reason: String,
65 pub example_paths: Vec<String>,
67 pub golden: String,
69}
70
71impl CorpusManifestEntry {
72 #[must_use]
74 pub fn id(&self) -> String {
75 format!("{}/{}", self.tool, self.subject)
76 }
77}
78
79#[derive(Clone, Debug, PartialEq, Eq)]
81pub struct SkippedCorpus {
82 pub id: String,
84 pub reason: String,
86}
87
88#[derive(Clone, Debug, PartialEq)]
90pub struct CompetitorRun {
91 pub id: String,
93 pub tool: String,
95 pub subject: String,
97 pub examples: usize,
99 pub scores: MetricScores,
101 pub samples_drawn: usize,
103 pub seed: u64,
105 pub scoring_mode: ScoringMode,
107 pub wall_clock_ms: u128,
109 pub inferred_rules: usize,
111 pub required_f1: f64,
113 pub gbnf_emitted: bool,
115}
116
117#[derive(Clone, Debug, PartialEq, Eq)]
119pub struct SecondaryMetricRow {
120 pub metric: &'static str,
122 pub value: String,
124}
125
126#[derive(Clone, Debug, PartialEq, Eq)]
128pub struct BenchmarkFailure {
129 pub corpus: Option<String>,
131 pub message: String,
133}
134
135impl BenchmarkFailure {
136 fn new(corpus: Option<String>, message: impl Into<String>) -> Self {
137 Self {
138 corpus,
139 message: message.into(),
140 }
141 }
142}
143
144#[derive(Clone, Debug, PartialEq)]
146pub struct CompetitorSuiteReport {
147 pub seed: u64,
149 pub runs: Vec<CompetitorRun>,
151 pub skipped: Vec<SkippedCorpus>,
153 pub secondary: Vec<SecondaryMetricRow>,
155 pub failures: Vec<BenchmarkFailure>,
157}
158
159#[derive(Debug)]
161pub enum BenchmarkError {
162 Io {
164 path: PathBuf,
166 source: std::io::Error,
168 },
169 Json {
171 path: PathBuf,
173 source: serde_json::Error,
175 },
176 Manifest(String),
178}
179
180impl fmt::Display for BenchmarkError {
181 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
182 match self {
183 Self::Io { path, source } => {
184 write!(formatter, "{}: {source}", path.display())
185 }
186 Self::Json { path, source } => {
187 write!(formatter, "{}: {source}", path.display())
188 }
189 Self::Manifest(message) => formatter.write_str(message),
190 }
191 }
192}
193
194impl Error for BenchmarkError {
195 fn source(&self) -> Option<&(dyn Error + 'static)> {
196 match self {
197 Self::Io { source, .. } => Some(source),
198 Self::Json { source, .. } => Some(source),
199 Self::Manifest(_) => None,
200 }
201 }
202}
203
204pub fn run_competitor_suite(
210 config: &SampleConfig,
211) -> Result<CompetitorSuiteReport, BenchmarkError> {
212 run_competitor_suite_from_paths(
213 Path::new(DEFAULT_CORPUS_MANIFEST),
214 Path::new(DEFAULT_CORPORA_ROOT),
215 config,
216 )
217}
218
219pub fn run_competitor_suite_from_paths(
225 manifest_path: &Path,
226 corpora_root: &Path,
227 config: &SampleConfig,
228) -> Result<CompetitorSuiteReport, BenchmarkError> {
229 let manifest = load_manifest(manifest_path)?;
230 let mut report = validate_manifest(&manifest, corpora_root)?;
231 report.seed = config.seed;
232
233 for entry in manifest.entries.iter().filter(|entry| entry.included) {
234 match run_manifest_entry(entry, corpora_root, config) {
235 Ok(run) => {
236 if run.scores.f1 < run.required_f1 {
237 report.failures.push(BenchmarkFailure::new(
238 Some(run.id.clone()),
239 format!(
240 "F1 {:.3} is below required NatGI bar {:.3}",
241 run.scores.f1, run.required_f1
242 ),
243 ));
244 }
245 report.runs.push(run);
246 }
247 Err(message) => {
248 report
249 .failures
250 .push(BenchmarkFailure::new(Some(entry.id()), message));
251 }
252 }
253 }
254
255 if report.runs.is_empty() {
256 report.failures.push(BenchmarkFailure::new(
257 None,
258 "manifest includes no always-on competitor corpus subjects",
259 ));
260 }
261
262 report.secondary = secondary_rows(&report.runs);
263 Ok(report)
264}
265
266pub fn load_manifest(path: &Path) -> Result<CompetitorManifest, BenchmarkError> {
272 let path = crate::resolve_project_data_path(path).map_err(BenchmarkError::Manifest)?;
273 let text = fs::read_to_string(&path).map_err(|source| BenchmarkError::Io {
274 path: path.clone(),
275 source,
276 })?;
277 let value = if path
278 .extension()
279 .is_some_and(|extension| extension == "lino")
280 {
281 crate::read_structured_data_lino(&text)
282 .map_err(|message| BenchmarkError::Manifest(format!("{}: {message}", path.display())))?
283 } else {
284 serde_json::from_str::<Value>(&text).map_err(|source| BenchmarkError::Json {
285 path: path.clone(),
286 source,
287 })?
288 };
289 parse_manifest(&value)
290}
291
292#[must_use]
294pub fn render_competitor_report(report: &CompetitorSuiteReport) -> String {
295 let mut output = String::new();
296 let _ = writeln!(
297 output,
298 "D1/D5 competitor benchmark suite (seed {})",
299 report.seed
300 );
301 let _ = writeln!(
302 output,
303 "Published bars: TreeVada avg F1 ~= {PUBLISHED_TREEVADA_AVG_F1:.2}; NatGI avg F1 ~= {PUBLISHED_NATGI_AVG_F1:.2}"
304 );
305
306 if !report.skipped.is_empty() {
307 let _ = writeln!(output);
308 for skipped in &report.skipped {
309 let _ = writeln!(output, "SKIPPED {}: {}", skipped.id, skipped.reason);
310 }
311 }
312
313 let _ = writeln!(output);
314 let _ = writeln!(
315 output,
316 "| corpus | examples | precision | recall | F1 | required F1 | wall-clock ms | rules | samples |"
317 );
318 let _ = writeln!(output, "|---|---:|---:|---:|---:|---:|---:|---:|---:|");
319 for run in &report.runs {
320 let _ = writeln!(
321 output,
322 "| {} | {} | {:.3} | {:.3} | {:.3} | {:.3} | {} | {} | {} |",
323 run.id,
324 run.examples,
325 run.scores.precision,
326 run.scores.recall,
327 run.scores.f1,
328 run.required_f1,
329 run.wall_clock_ms,
330 run.inferred_rules,
331 run.samples_drawn
332 );
333 }
334
335 let _ = writeln!(output);
336 let _ = writeln!(output, "| secondary metric | value |");
337 let _ = writeln!(output, "|---|---|");
338 for row in &report.secondary {
339 let _ = writeln!(output, "| {} | {} |", row.metric, row.value);
340 }
341
342 if !report.failures.is_empty() {
343 let _ = writeln!(output);
344 let _ = writeln!(output, "Failures:");
345 for failure in &report.failures {
346 match &failure.corpus {
347 Some(corpus) => {
348 let _ = writeln!(output, "- {corpus}: {}", failure.message);
349 }
350 None => {
351 let _ = writeln!(output, "- {}", failure.message);
352 }
353 }
354 }
355 }
356
357 output
358}
359
360fn parse_manifest(value: &Value) -> Result<CompetitorManifest, BenchmarkError> {
361 let object = value
362 .as_object()
363 .ok_or_else(|| BenchmarkError::Manifest("manifest root must be a JSON object".into()))?;
364 let schema = required_u64(object, "schema")?;
365 let corpus = object
366 .get("corpus")
367 .and_then(Value::as_array)
368 .ok_or_else(|| BenchmarkError::Manifest("manifest corpus must be an array".into()))?;
369 let mut entries = Vec::with_capacity(corpus.len());
370 for (index, entry) in corpus.iter().enumerate() {
371 let object = entry.as_object().ok_or_else(|| {
372 BenchmarkError::Manifest(format!("manifest corpus[{index}] must be an object"))
373 })?;
374 entries.push(CorpusManifestEntry {
375 tool: required_string(object, "tool")?,
376 subject: required_string(object, "subject")?,
377 source: required_string(object, "source")?,
378 commit: required_string(object, "commit")?,
379 license: required_string(object, "license")?,
380 files: usize::try_from(required_u64(object, "files")?).map_err(|_| {
381 BenchmarkError::Manifest(format!("manifest corpus[{index}].files overflows usize"))
382 })?,
383 bytes: required_u64(object, "bytes")?,
384 included: required_bool(object, "included")?,
385 exclude_reason: required_string(object, "exclude_reason")?,
386 example_paths: required_string_array(object, "example_paths")?,
387 golden: required_string(object, "golden")?,
388 });
389 }
390
391 Ok(CompetitorManifest { schema, entries })
392}
393
394fn required_string(
395 object: &serde_json::Map<String, Value>,
396 key: &str,
397) -> Result<String, BenchmarkError> {
398 object
399 .get(key)
400 .and_then(Value::as_str)
401 .map(ToOwned::to_owned)
402 .ok_or_else(|| BenchmarkError::Manifest(format!("manifest field `{key}` must be a string")))
403}
404
405fn required_u64(object: &serde_json::Map<String, Value>, key: &str) -> Result<u64, BenchmarkError> {
406 object
407 .get(key)
408 .and_then(Value::as_u64)
409 .ok_or_else(|| BenchmarkError::Manifest(format!("manifest field `{key}` must be a u64")))
410}
411
412fn required_bool(
413 object: &serde_json::Map<String, Value>,
414 key: &str,
415) -> Result<bool, BenchmarkError> {
416 object
417 .get(key)
418 .and_then(Value::as_bool)
419 .ok_or_else(|| BenchmarkError::Manifest(format!("manifest field `{key}` must be a bool")))
420}
421
422fn required_string_array(
423 object: &serde_json::Map<String, Value>,
424 key: &str,
425) -> Result<Vec<String>, BenchmarkError> {
426 object
427 .get(key)
428 .and_then(Value::as_array)
429 .ok_or_else(|| {
430 BenchmarkError::Manifest(format!("manifest field `{key}` must be an array"))
431 })?
432 .iter()
433 .map(|value| {
434 value.as_str().map(ToOwned::to_owned).ok_or_else(|| {
435 BenchmarkError::Manifest(format!("manifest field `{key}` must contain strings"))
436 })
437 })
438 .collect()
439}
440
441fn validate_manifest(
442 manifest: &CompetitorManifest,
443 corpora_root: &Path,
444) -> Result<CompetitorSuiteReport, BenchmarkError> {
445 let mut report = CompetitorSuiteReport {
446 seed: 0,
447 runs: Vec::new(),
448 skipped: Vec::new(),
449 secondary: Vec::new(),
450 failures: Vec::new(),
451 };
452 let mut entries = BTreeMap::<String, &CorpusManifestEntry>::new();
453
454 for entry in &manifest.entries {
455 let id = entry.id();
456 if entries.insert(id.clone(), entry).is_some() {
457 report.failures.push(BenchmarkFailure::new(
458 Some(id.clone()),
459 "duplicate manifest entry",
460 ));
461 }
462
463 if !entry.included {
464 if entry.exclude_reason.trim().is_empty() {
465 report.failures.push(BenchmarkFailure::new(
466 Some(id.clone()),
467 "excluded corpus must provide a non-empty exclude_reason",
468 ));
469 } else {
470 report.skipped.push(SkippedCorpus {
471 id: id.clone(),
472 reason: entry.exclude_reason.clone(),
473 });
474 }
475 }
476
477 let subject_dir = corpora_root.join(&entry.tool).join(&entry.subject);
478 if !subject_dir.is_dir() {
479 report.failures.push(BenchmarkFailure::new(
480 Some(id),
481 format!(
482 "vendored subject directory {} is missing",
483 subject_dir.display()
484 ),
485 ));
486 continue;
487 }
488
489 let (files, bytes) =
490 count_subject_files(&subject_dir).map_err(|source| BenchmarkError::Io {
491 path: subject_dir.clone(),
492 source,
493 })?;
494 if files != entry.files {
495 report.failures.push(BenchmarkFailure::new(
496 Some(id.clone()),
497 format!("manifest files={} but vendored files={files}", entry.files),
498 ));
499 }
500 if bytes != entry.bytes {
501 report.failures.push(BenchmarkFailure::new(
502 Some(id.clone()),
503 format!("manifest bytes={} but vendored bytes={bytes}", entry.bytes),
504 ));
505 }
506
507 if entry.included && entry.example_paths.is_empty() {
508 report.failures.push(BenchmarkFailure::new(
509 Some(id),
510 "included corpus must list at least one example path",
511 ));
512 }
513 }
514
515 for subject in vendored_subjects(corpora_root)? {
516 if !entries.contains_key(&subject) {
517 report.failures.push(BenchmarkFailure::new(
518 Some(subject),
519 "vendored subject is missing from manifest",
520 ));
521 }
522 }
523
524 Ok(report)
525}
526
527fn run_manifest_entry(
528 entry: &CorpusManifestEntry,
529 corpora_root: &Path,
530 config: &SampleConfig,
531) -> Result<CompetitorRun, String> {
532 if entry.golden != "exact_examples" {
533 return Err(format!(
534 "unsupported included golden oracle mode `{}`",
535 entry.golden
536 ));
537 }
538
539 let id = entry.id();
540 let subject_dir = corpora_root.join(&entry.tool).join(&entry.subject);
541 let examples = load_examples(&subject_dir, &entry.example_paths)
542 .map_err(|error| format!("failed to load examples: {error}"))?;
543 if examples.is_empty() {
544 return Err("included corpus loaded no positive examples".into());
545 }
546
547 let start = Instant::now();
548 let inferred = infer_cfg(&examples, &PositiveOnlyOracle, InferenceOptions::default());
549 let golden = exact_examples_grammar(&examples);
550 let oracle = GrammarOracle::new(&golden);
551 let positive_refs = examples.iter().map(String::as_str).collect::<Vec<_>>();
552 let scores = evaluate(
553 &inferred.grammar,
554 &oracle,
555 Some(&golden),
556 &positive_refs,
557 config,
558 )
559 .map_err(|error| format!("D1 evaluation failed: {error}"))?;
560 let samples_drawn = sample_count(&inferred.grammar, &golden, config)
561 .map_err(|error| format!("D1 sample accounting failed: {error}"))?;
562 let gbnf_emitted = emit_gbnf(&inferred.grammar).is_ok_and(|(text, _)| !text.trim().is_empty());
563
564 Ok(CompetitorRun {
565 id,
566 tool: entry.tool.clone(),
567 subject: entry.subject.clone(),
568 examples: examples.len(),
569 scores,
570 samples_drawn,
571 seed: config.seed,
572 scoring_mode: ScoringMode::GoldenGrammar,
573 wall_clock_ms: start.elapsed().as_millis(),
574 inferred_rules: inferred.report.rules,
575 required_f1: D5_REQUIRED_AVG_F1,
576 gbnf_emitted,
577 })
578}
579
580fn sample_count(
581 inferred: &Grammar,
582 golden: &Grammar,
583 config: &SampleConfig,
584) -> Result<usize, crate::EvalError> {
585 let inferred_count = crate::sample(inferred, config)?.len();
586 let golden_count = crate::sample(golden, config)?.len();
587 Ok(inferred_count.saturating_add(golden_count))
588}
589
590fn exact_examples_grammar(examples: &[String]) -> Grammar {
591 let alternatives = examples.iter().map(|example| {
592 if example.is_empty() {
593 GrammarExpr::Empty
594 } else {
595 GrammarExpr::Terminal(example.clone())
596 }
597 });
598 Grammar::new()
599 .with_source_format(GrammarFormat::Inferred)
600 .with_rule(GrammarRule::new(
601 "Root",
602 finish_choice(alternatives.collect()),
603 ))
604 .with_start("Root")
605}
606
607fn finish_choice(alternatives: Vec<GrammarExpr>) -> GrammarExpr {
608 let mut unique = BTreeMap::<String, GrammarExpr>::new();
609 for alternative in alternatives {
610 unique
611 .entry(format!("{alternative:?}"))
612 .or_insert(alternative);
613 }
614
615 match unique.len() {
616 0 => GrammarExpr::Empty,
617 1 => unique
618 .into_values()
619 .next()
620 .expect("one choice alternative must exist"),
621 _ => GrammarExpr::Choice {
622 ordered: false,
623 alternatives: unique.into_values().collect(),
624 },
625 }
626}
627
628fn load_examples(subject_dir: &Path, example_paths: &[String]) -> Result<Vec<String>, String> {
629 let mut files = Vec::new();
630 for relative in example_paths {
631 let path = subject_dir.join(relative);
632 if path.is_file() {
633 files.push(path);
634 } else if path.is_dir() {
635 collect_files(&path, &mut files)
636 .map_err(|error| format!("{}: {error}", path.display()))?;
637 } else {
638 return Err(format!("example path {} is missing", path.display()));
639 }
640 }
641 files.sort();
642 files.dedup();
643
644 files
645 .iter()
646 .map(|path| {
647 fs::read_to_string(path).map_err(|error| format!("{}: {error}", path.display()))
648 })
649 .collect()
650}
651
652fn count_subject_files(path: &Path) -> Result<(usize, u64), std::io::Error> {
653 let mut files = Vec::new();
654 collect_files(path, &mut files)?;
655 let mut bytes = 0u64;
656 for file in &files {
657 bytes = bytes.saturating_add(fs::metadata(file)?.len());
658 }
659 Ok((files.len(), bytes))
660}
661
662fn collect_files(path: &Path, files: &mut Vec<PathBuf>) -> Result<(), std::io::Error> {
663 for entry in fs::read_dir(path)? {
664 let entry = entry?;
665 let path = entry.path();
666 if path.is_dir() {
667 collect_files(&path, files)?;
668 } else if path.is_file() {
669 files.push(path);
670 }
671 }
672 Ok(())
673}
674
675fn vendored_subjects(corpora_root: &Path) -> Result<BTreeSet<String>, BenchmarkError> {
676 let mut subjects = BTreeSet::new();
677 let tools = fs::read_dir(corpora_root).map_err(|source| BenchmarkError::Io {
678 path: corpora_root.to_path_buf(),
679 source,
680 })?;
681 for tool in tools {
682 let tool = tool.map_err(|source| BenchmarkError::Io {
683 path: corpora_root.to_path_buf(),
684 source,
685 })?;
686 let tool_path = tool.path();
687 if !tool_path.is_dir() {
688 continue;
689 }
690 let tool_name = tool.file_name().to_string_lossy().into_owned();
691 for subject in fs::read_dir(&tool_path).map_err(|source| BenchmarkError::Io {
692 path: tool_path.clone(),
693 source,
694 })? {
695 let subject = subject.map_err(|source| BenchmarkError::Io {
696 path: tool_path.clone(),
697 source,
698 })?;
699 let subject_path = subject.path();
700 if subject_path.is_dir() {
701 let subject_name = subject.file_name().to_string_lossy().into_owned();
702 subjects.insert(format!("{tool_name}/{subject_name}"));
703 }
704 }
705 }
706 Ok(subjects)
707}
708
709fn secondary_rows(runs: &[CompetitorRun]) -> Vec<SecondaryMetricRow> {
710 let gbnf_successes = runs.iter().filter(|run| run.gbnf_emitted).count();
711
712 vec![
713 SecondaryMetricRow {
714 metric: "format coverage",
715 value: "n/a (pending B*/C* cross-format coverage aggregation)".to_string(),
716 },
717 SecondaryMetricRow {
718 metric: "round-trip fidelity",
719 value: "n/a (pending F2 fidelity matrix)".to_string(),
720 },
721 SecondaryMetricRow {
722 metric: "GBNF emit",
723 value: format!(
724 "{gbnf_successes}/{} included grammars emitted non-empty GBNF",
725 runs.len()
726 ),
727 },
728 SecondaryMetricRow {
729 metric: "cross-language translation",
730 value: "n/a (pending C6 full metric wiring)".to_string(),
731 },
732 ]
733}