dsir 0.1.1

DSPy-shaped library for programming language models in Rust.
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
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
use anyhow::{Context, Result, anyhow};
use bon::Builder;
use serde::{Deserialize, Serialize};

use crate::evaluate::{MetricOutcome, TypedMetric, average_score};
use crate::optimizer::{
    Optimizer, evaluate_module_with_metric, predictor_names, with_named_predictor,
};
use crate::predictors::Example;
use crate::{BamlType, BamlValue, Facet, Module, Signature};

use super::pareto::ParetoFrontier;

/// A single instruction candidate tracked through GEPA's evolutionary search.
///
/// Carries the instruction text, per-example scores, lineage (parent_id), and
/// generation number. The Pareto frontier selects candidates that aren't dominated
/// on any individual example — not just by average score.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GEPACandidate {
    pub id: usize,
    pub instruction: String,
    pub module_name: String,
    pub example_scores: Vec<f32>,
    pub parent_id: Option<usize>,
    pub generation: usize,
}

impl GEPACandidate {
    pub fn average_score(&self) -> f32 {
        if self.example_scores.is_empty() {
            return 0.0;
        }
        self.example_scores.iter().sum::<f32>() / self.example_scores.len() as f32
    }

    pub fn mutate(&self, new_instruction: String, generation: usize) -> Self {
        Self {
            id: 0,
            instruction: new_instruction,
            module_name: self.module_name.clone(),
            example_scores: Vec::new(),
            parent_id: Some(self.id),
            generation,
        }
    }
}

/// Full report from a [`GEPA`] optimization run.
///
/// Contains the winning candidate, the complete candidate history (if `track_stats`
/// was enabled), budget usage, and optionally the best outputs on the validation set.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GEPAResult {
    /// The candidate with the best average score on the Pareto frontier.
    pub best_candidate: GEPACandidate,
    /// All candidates evaluated (empty unless `track_stats` is enabled).
    pub all_candidates: Vec<GEPACandidate>,
    /// Total evaluation rollouts consumed.
    pub total_rollouts: usize,
    /// Total LM calls consumed (rollouts + candidate generation).
    pub total_lm_calls: usize,
    /// (generation, best_average_score) pairs for plotting convergence.
    pub evolution_history: Vec<(usize, f32)>,
    /// Highest score achieved per validation example across all candidates.
    pub highest_score_achieved_per_val_task: Vec<f32>,
    /// Best outputs on the validation set (only if `track_best_outputs` is enabled).
    pub best_outputs_valset: Option<Vec<BamlValue>>,
    /// Pareto frontier statistics per generation.
    pub frontier_history: Vec<ParetoStatistics>,
}

pub use super::pareto::ParetoStatistics;

/// Genetic-Pareto instruction optimizer with feedback-driven evolution.
///
/// GEPA uses an evolutionary search guided by per-example feedback from your metric.
/// Unlike [`COPRO`](crate::COPRO) which only uses numerical scores, GEPA requires your
/// [`TypedMetric`] to return [`MetricOutcome::with_feedback`] — textual feedback
/// explaining *why* each example scored the way it did. This feedback gets appended
/// to the instruction as a mutation prompt for the next generation, so the quality
/// of your feedback directly determines the quality of GEPA's search.
///
/// The Pareto frontier tracks candidates that aren't dominated on any individual
/// training example, not just by average score. This means GEPA finds instructions
/// that are robust across diverse inputs rather than overfitting to easy examples.
///
/// Only searches instruction space — no demo mutation, no crossover between candidates.
/// Each child has exactly one parent.
///
/// # Hyperparameters
///
/// - **`num_iterations`** (default: 20) — evolutionary generations. More = deeper search.
/// - **`minibatch_size`** (default: 25) — examples per parent evaluation within each
///   generation. Controls exploration vs cost.
/// - **`num_trials`** (default: 10) — **currently unused.** Reserved for multi-child
///   evolution (one child per generation right now). Setting this has no effect.
/// - **`temperature`** (default: 1.0) — **currently unused.** Reserved for mutation
///   diversity control. Setting this has no effect.
/// - **`max_rollouts`** / **`max_lm_calls`** — hard budget caps. Optimization stops
///   when either limit would be exceeded by the next batch.
/// - **`track_stats`** (default: true) — record all candidates and frontier history.
/// - **`track_best_outputs`** (default: false) — re-run the best instruction on the
///   eval set and record outputs.
/// - **`prompt_model`** — optional separate LM for candidate generation.
///
/// # Requires feedback
///
/// GEPA will error if any [`MetricOutcome`] from your metric has `feedback: None`.
/// Use [`MetricOutcome::with_feedback`] or provide a [`FeedbackMetric`](crate::FeedbackMetric).
///
/// # Cost
///
/// Roughly `num_iterations × (minibatch_size + eval_set_size) + initial_eval` LM calls.
/// Budget caps (`max_rollouts`, `max_lm_calls`) prevent runaway costs.
///
/// ```ignore
/// let gepa = GEPA::builder()
///     .num_iterations(20)
///     .max_lm_calls(Some(500))
///     .build();
/// let report = gepa.compile(&mut module, trainset, &feedback_metric).await?;
/// println!("Best score: {:.3}", report.best_candidate.average_score());
/// ```
#[derive(Builder)]
pub struct GEPA {
    /// Evolutionary generations to run.
    #[builder(default = 20)]
    pub num_iterations: usize,

    /// Examples per parent evaluation within each generation.
    #[builder(default = 25)]
    pub minibatch_size: usize,

    /// **Currently unused.** Reserved for multi-child evolution (one child per
    /// generation right now). Setting this has no effect.
    #[builder(default = 10)]
    pub num_trials: usize,

    /// **Currently unused.** Reserved for mutation diversity control.
    /// Setting this has no effect.
    #[builder(default = 1.0)]
    pub temperature: f32,

    /// Record all candidates and frontier history in the report.
    #[builder(default = true)]
    pub track_stats: bool,

    /// Re-run the best instruction on the eval set and record outputs.
    #[builder(default = false)]
    pub track_best_outputs: bool,

    /// Hard cap on total evaluation rollouts.
    pub max_rollouts: Option<usize>,
    /// Hard cap on total LM calls (rollouts + generation).
    pub max_lm_calls: Option<usize>,
    /// Optional separate LM for candidate generation.
    pub prompt_model: Option<crate::LM>,
}

impl GEPA {
    fn would_exceed_budget(current: usize, batch_cost: usize, max_budget: Option<usize>) -> bool {
        max_budget.is_some_and(|max| current.saturating_add(batch_cost) > max)
    }

    fn set_instruction<M>(module: &mut M, module_name: &str, instruction: String) -> Result<()>
    where
        M: for<'a> Facet<'a>,
    {
        with_named_predictor(module, module_name, |predictor| {
            predictor.set_instruction(instruction);
            Ok(())
        })
    }

    async fn evaluate_candidate<S, M, MT>(
        &self,
        module: &mut M,
        module_name: &str,
        instruction: &str,
        examples: &[Example<S>],
        metric: &MT,
    ) -> Result<Vec<MetricOutcome>>
    where
        S: Signature,
        S::Input: Clone,
        M: Module<Input = S::Input> + for<'a> Facet<'a>,
        MT: TypedMetric<S, M>,
    {
        let original_state =
            with_named_predictor(module, module_name, |predictor| Ok(predictor.dump_state()))?;

        Self::set_instruction(module, module_name, instruction.to_string())?;
        let evaluation = evaluate_module_with_metric(&*module, examples, metric).await;

        match evaluation {
            Ok(outcomes) => {
                with_named_predictor(module, module_name, |predictor| {
                    predictor.load_state(original_state.clone())
                })?;
                Ok(outcomes)
            }
            Err(eval_err) => {
                if let Err(restore_err) = with_named_predictor(module, module_name, |predictor| {
                    predictor.load_state(original_state)
                }) {
                    return Err(anyhow!(
                        "candidate evaluation failed: {eval_err}; failed to restore predictor state: {restore_err}"
                    ));
                }
                Err(eval_err)
            }
        }
    }

    fn require_feedback(
        outcomes: &[MetricOutcome],
        module_name: &str,
        generation: usize,
    ) -> Result<()> {
        if outcomes.iter().any(|o| o.feedback.is_none()) {
            return Err(anyhow!(
                "GEPA requires feedback for every evaluated example (module=`{module_name}`, generation={generation})"
            ));
        }
        Ok(())
    }

    fn summarize_feedback(outcomes: &[MetricOutcome]) -> String {
        let mut lines = Vec::new();
        for (idx, outcome) in outcomes.iter().enumerate() {
            if let Some(feedback) = &outcome.feedback {
                lines.push(format!(
                    "{}: score={:.3}; {}",
                    idx + 1,
                    outcome.score,
                    feedback.feedback
                ));
            }
        }
        lines.join("\n")
    }

    async fn collect_best_outputs<S, M>(
        module: &M,
        eval_set: &[Example<S>],
    ) -> Result<Vec<BamlValue>>
    where
        S: Signature,
        S::Input: Clone,
        M: Module<Input = S::Input>,
        M::Output: BamlType,
    {
        let mut outputs = Vec::with_capacity(eval_set.len());
        for example in eval_set {
            let input = example.input.clone();
            let predicted = module.call(input).await.map_err(|err| anyhow!("{err}"))?;
            outputs.push(predicted.into_inner().to_baml_value());
        }
        Ok(outputs)
    }

    /// Runs GEPA with an explicit validation set separate from the trainset.
    ///
    /// When `valset` is `Some`, initial evaluation and child scoring use the validation
    /// set, while parent re-evaluation uses the trainset minibatch. When `None`, the
    /// trainset serves both roles.
    ///
    /// # Errors
    ///
    /// - No optimizable predictors found
    /// - Any metric evaluation returns `feedback: None`
    /// - LM call failure during evaluation
    pub async fn compile_with_valset<S, M, MT>(
        &self,
        module: &mut M,
        trainset: Vec<Example<S>>,
        valset: Option<Vec<Example<S>>>,
        metric: &MT,
    ) -> Result<GEPAResult>
    where
        S: Signature,
        S::Input: Clone,
        M: Module<Input = S::Input> + for<'a> Facet<'a>,
        MT: TypedMetric<S, M>,
    {
        let eval_set = valset.as_deref().unwrap_or(&trainset);

        let predictor_names = predictor_names(module)?;

        if predictor_names.is_empty() {
            return Err(anyhow!("no optimizable predictors found"));
        }

        let mut frontier = ParetoFrontier::new();
        let mut total_lm_calls = 0usize;
        let mut total_rollouts = 0usize;

        for module_name in &predictor_names {
            if Self::would_exceed_budget(total_lm_calls, eval_set.len(), self.max_lm_calls)
                || Self::would_exceed_budget(total_rollouts, eval_set.len(), self.max_rollouts)
            {
                break;
            }

            let instruction = {
                with_named_predictor(module, module_name, |predictor| Ok(predictor.instruction()))?
            };

            let outcomes = self
                .evaluate_candidate::<S, _, _>(module, module_name, &instruction, eval_set, metric)
                .await?;
            total_lm_calls = total_lm_calls.saturating_add(outcomes.len());
            total_rollouts = total_rollouts.saturating_add(outcomes.len());
            Self::require_feedback(&outcomes, module_name, 0)?;

            let scores: Vec<f32> = outcomes.iter().map(|o| o.score).collect();
            let candidate = GEPACandidate {
                id: 0,
                instruction,
                module_name: module_name.clone(),
                example_scores: scores.clone(),
                parent_id: None,
                generation: 0,
            };
            frontier.add_candidate(candidate, &scores);
        }

        let mut all_candidates = Vec::new();
        let mut evolution_history = Vec::new();
        let mut frontier_history = Vec::new();

        for generation in 0..self.num_iterations {
            if let Some(max_rollouts) = self.max_rollouts
                && total_rollouts >= max_rollouts
            {
                break;
            }

            if let Some(max_lm_calls) = self.max_lm_calls
                && total_lm_calls >= max_lm_calls
            {
                break;
            }

            let parent = frontier
                .sample_proportional_to_coverage()
                .context("failed to sample from frontier")?
                .clone();

            let minibatch_end = trainset.len().min(self.minibatch_size.max(1));
            let minibatch = &trainset[..minibatch_end];

            if Self::would_exceed_budget(total_lm_calls, minibatch.len(), self.max_lm_calls)
                || Self::would_exceed_budget(total_rollouts, minibatch.len(), self.max_rollouts)
            {
                break;
            }

            let parent_outcomes = self
                .evaluate_candidate::<S, _, _>(
                    module,
                    &parent.module_name,
                    &parent.instruction,
                    minibatch,
                    metric,
                )
                .await?;
            total_lm_calls = total_lm_calls.saturating_add(parent_outcomes.len());
            Self::require_feedback(&parent_outcomes, &parent.module_name, generation)?;

            let feedback_summary = Self::summarize_feedback(&parent_outcomes);
            let parent_score = average_score(&parent_outcomes);
            total_rollouts += parent_outcomes.len();

            if Self::would_exceed_budget(total_lm_calls, eval_set.len(), self.max_lm_calls)
                || Self::would_exceed_budget(total_rollouts, eval_set.len(), self.max_rollouts)
            {
                break;
            }

            let child_instruction = format!(
                "{}\n\n[GEPA gen {}] Improve based on feedback:\n{}\n(Parent score {:.3})",
                parent.instruction,
                generation + 1,
                feedback_summary,
                parent_score,
            );

            let child = parent.mutate(child_instruction, generation + 1);

            let child_outcomes = self
                .evaluate_candidate::<S, _, _>(
                    module,
                    &child.module_name,
                    &child.instruction,
                    eval_set,
                    metric,
                )
                .await?;
            total_lm_calls = total_lm_calls.saturating_add(child_outcomes.len());
            Self::require_feedback(&child_outcomes, &child.module_name, generation + 1)?;

            let child_scores: Vec<f32> = child_outcomes.iter().map(|o| o.score).collect();
            total_rollouts += child_scores.len();

            let mut child = child;
            child.example_scores = child_scores.clone();
            let _added = frontier.add_candidate(child.clone(), &child_scores);

            if self.track_stats {
                all_candidates.push(child);
                let best_avg = frontier
                    .best_by_average()
                    .map(|c| c.average_score())
                    .unwrap_or(0.0);
                evolution_history.push((generation, best_avg));
                frontier_history.push(frontier.statistics());
            }
        }

        let best_candidate = frontier
            .best_by_average()
            .cloned()
            .context("no candidates available on Pareto frontier")?;

        Self::set_instruction(
            module,
            &best_candidate.module_name,
            best_candidate.instruction.clone(),
        )?;

        let highest_score_achieved_per_val_task = if frontier.is_empty() {
            Vec::new()
        } else {
            let mut highs = vec![f32::MIN; eval_set.len()];
            for candidate in frontier.candidates() {
                for (idx, score) in candidate.example_scores.iter().enumerate() {
                    if idx < highs.len() {
                        highs[idx] = highs[idx].max(*score);
                    }
                }
            }
            highs
        };

        let best_outputs_valset = if self.track_best_outputs {
            if Self::would_exceed_budget(total_lm_calls, eval_set.len(), self.max_lm_calls)
                || Self::would_exceed_budget(total_rollouts, eval_set.len(), self.max_rollouts)
            {
                tracing::debug!(
                    eval_examples = eval_set.len(),
                    total_lm_calls,
                    total_rollouts,
                    max_lm_calls = ?self.max_lm_calls,
                    max_rollouts = ?self.max_rollouts,
                    "skipping best output collection because budget would be exceeded"
                );
                None
            } else {
                let outputs = Self::collect_best_outputs::<S, _>(module, eval_set).await?;
                total_lm_calls = total_lm_calls.saturating_add(eval_set.len());
                total_rollouts = total_rollouts.saturating_add(eval_set.len());
                Some(outputs)
            }
        } else {
            None
        };

        Ok(GEPAResult {
            best_candidate,
            all_candidates,
            total_rollouts,
            total_lm_calls,
            evolution_history,
            highest_score_achieved_per_val_task,
            best_outputs_valset,
            frontier_history,
        })
    }
}

impl Optimizer for GEPA {
    type Report = GEPAResult;

    async fn compile<S, M, MT>(
        &self,
        module: &mut M,
        trainset: Vec<Example<S>>,
        metric: &MT,
    ) -> Result<Self::Report>
    where
        S: Signature,
        S::Input: Clone,
        M: Module<Input = S::Input> + for<'a> Facet<'a>,
        MT: TypedMetric<S, M>,
    {
        self.compile_with_valset::<S, _, _>(module, trainset, None, metric)
            .await
    }
}

impl GEPA {
    /// Dynamic GEPA over [`DynModule`] Facet leaves (requires feedback-capable metric).
    pub async fn compile_dyn<M, MT>(
        &self,
        module: &mut M,
        trainset: Vec<crate::data::example::Example>,
        metric: &MT,
    ) -> Result<GEPAResult>
    where
        M: crate::predictors::DynModule + for<'a> Facet<'a>,
        MT: crate::evaluate::DynMetric,
    {
        use crate::evaluate::{average_score, evaluate_dyn_trainset, input_only};
        use crate::optimizer::dyn_compile::ensure_predictors;
        use crate::optimizer::pareto::ParetoFrontier;

        let names = ensure_predictors(module)?;
        let module_name = names[0].clone();
        let eval_set = &trainset;
        let mut frontier = ParetoFrontier::new();
        let mut all_candidates = Vec::new();
        let mut evolution_history = Vec::new();
        let mut frontier_history = Vec::new();
        let mut total_rollouts = 0usize;
        let mut total_lm_calls = 0usize;

        let base_instruction =
            with_named_predictor(module, &module_name, |p| Ok(p.instruction()))?;
        Self::set_instruction(module, &module_name, base_instruction.clone())?;
        let initial = evaluate_dyn_trainset(module, eval_set, metric).await?;
        total_rollouts += initial.len();
        total_lm_calls += initial.len();
        for outcome in &initial {
            if outcome.feedback.is_none() {
                return Err(anyhow!(
                    "GEPA compile_dyn requires MetricOutcome feedback on every example"
                ));
            }
        }
        let scores: Vec<f32> = initial.iter().map(|o| o.score).collect();
        let candidate = GEPACandidate {
            id: 0,
            instruction: base_instruction,
            module_name: module_name.clone(),
            example_scores: scores.clone(),
            parent_id: None,
            generation: 0,
        };
        frontier.add_candidate(candidate.clone(), &scores);
        all_candidates.push(candidate);

        let iterations = self.num_iterations.max(self.num_trials.min(self.num_iterations));
        for generation in 0..iterations {
            if Self::would_exceed_budget(total_rollouts, self.minibatch_size, self.max_rollouts)
                || Self::would_exceed_budget(total_lm_calls, self.minibatch_size, self.max_lm_calls)
            {
                break;
            }
            let parent = frontier
                .best_by_average()
                .cloned()
                .context("empty frontier")?;
            let feedback_bits: String = initial
                .iter()
                .filter_map(|o| o.feedback.as_ref().map(|f| f.feedback.clone()))
                .take(3)
                .collect::<Vec<_>>()
                .join(" | ");
            let temperature_note = if self.temperature != 1.0 {
                format!(" temperature={}", self.temperature)
            } else {
                String::new()
            };
            let child_instruction = format!(
                "{}\n\nImprove based on feedback:{temperature_note} {}",
                parent.instruction, feedback_bits
            );
            let proposals = crate::optimizer::propose::propose_instructions_with_hint(
                &child_instruction,
                "improved instruction",
                3,
                self.prompt_model.as_ref(),
            )
            .await?;
            let child_instruction = proposals
                .into_iter()
                .nth(1)
                .unwrap_or(child_instruction);

            Self::set_instruction(module, &module_name, child_instruction.clone())?;
            let minibatch_end = eval_set.len().min(self.minibatch_size.max(1));
            let outcomes =
                evaluate_dyn_trainset(module, &eval_set[..minibatch_end], metric).await?;
            total_rollouts += outcomes.len();
            total_lm_calls += outcomes.len();
            for outcome in &outcomes {
                if outcome.feedback.is_none() {
                    return Err(anyhow!("GEPA compile_dyn requires feedback outcomes"));
                }
            }
            let child_scores: Vec<f32> = outcomes.iter().map(|o| o.score).collect();
            let child = GEPACandidate {
                id: generation + 1,
                instruction: child_instruction,
                module_name: module_name.clone(),
                example_scores: child_scores.clone(),
                parent_id: Some(parent.id),
                generation: generation + 1,
            };
            frontier.add_candidate(child.clone(), &child_scores);
            if self.track_stats {
                all_candidates.push(child);
                evolution_history.push((
                    generation,
                    frontier
                        .best_by_average()
                        .map(|c| c.average_score())
                        .unwrap_or(0.0),
                ));
                frontier_history.push(frontier.statistics());
            }
        }

        let best_candidate = frontier
            .best_by_average()
            .cloned()
            .context("no candidates on frontier")?;
        Self::set_instruction(
            module,
            &best_candidate.module_name,
            best_candidate.instruction.clone(),
        )?;

        let best_outputs_valset = if self.track_best_outputs {
            let mut outs = Vec::new();
            for example in eval_set {
                let predicted = module
                    .call(input_only(example))
                    .await
                    .map_err(|err| anyhow!("{err}"))?;
                outs.push(crate::BamlValue::Map(
                    predicted
                        .into_inner()
                        .data
                        .into_iter()
                        .map(|(k, v)| {
                            (
                                k,
                                crate::BamlValue::try_from(v)
                                    .unwrap_or(crate::BamlValue::Null),
                            )
                        })
                        .collect(),
                ));
            }
            Some(outs)
        } else {
            None
        };

        let _ = average_score;
        Ok(GEPAResult {
            best_candidate,
            all_candidates: if self.track_stats {
                all_candidates
            } else {
                Vec::new()
            },
            total_rollouts,
            total_lm_calls,
            evolution_history,
            highest_score_achieved_per_val_task: Vec::new(),
            best_outputs_valset,
            frontier_history,
        })
    }
}

#[cfg(test)]
mod tests {
    use anyhow::{Result, anyhow};

    use super::*;
    use crate::evaluate::{MetricOutcome, TypedMetric};
    use crate::{CallMetadata, Predict, PredictError, Predicted, Signature};

    #[derive(Signature, Clone, Debug)]
    struct GepaStateSig {
        #[input]
        prompt: String,

        #[output]
        answer: String,
    }

    #[derive(facet::Facet)]
    #[facet(crate = facet)]
    struct GepaStateModule {
        predictor: Predict<GepaStateSig>,
    }

    impl Module for GepaStateModule {
        type Input = GepaStateSigInput;
        type Output = GepaStateSigOutput;

        async fn forward(
            &self,
            input: GepaStateSigInput,
        ) -> Result<Predicted<GepaStateSigOutput>, PredictError> {
            Ok(Predicted::new(
                GepaStateSigOutput {
                    answer: input.prompt,
                },
                CallMetadata::default(),
            ))
        }
    }

    struct AlwaysFailMetric;

    impl TypedMetric<GepaStateSig, GepaStateModule> for AlwaysFailMetric {
        async fn evaluate(
            &self,
            _example: &Example<GepaStateSig>,
            _prediction: &Predicted<GepaStateSigOutput>,
        ) -> Result<MetricOutcome> {
            Err(anyhow!("metric failure"))
        }
    }

    fn eval_set() -> Vec<Example<GepaStateSig>> {
        vec![Example::new(
            GepaStateSigInput {
                prompt: "one".to_string(),
            },
            GepaStateSigOutput {
                answer: "one".to_string(),
            },
        )]
    }

    #[tokio::test]
    async fn evaluate_candidate_restores_state_when_metric_errors() {
        let optimizer = GEPA::builder().num_iterations(1).minibatch_size(1).build();
        let mut module = GepaStateModule {
            predictor: Predict::<GepaStateSig>::builder()
                .instruction("seed-instruction")
                .build(),
        };

        let err = optimizer
            .evaluate_candidate::<GepaStateSig, _, _>(
                &mut module,
                "predictor",
                "candidate instruction",
                &eval_set(),
                &AlwaysFailMetric,
            )
            .await
            .expect_err("candidate evaluation should propagate metric failure");
        assert!(err.to_string().contains("metric failure"));

        let instruction = with_named_predictor(&mut module, "predictor", |predictor| {
            Ok(predictor.instruction())
        })
        .expect("predictor lookup should succeed");
        assert_eq!(instruction, "seed-instruction");
    }
}