solverforge-solver 0.18.0

Solver engine for SolverForge
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
/* Solver entry point. */

use std::fmt;
use std::hash::Hash;
use std::marker::PhantomData;
use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
use std::time::Duration;

#[cfg(test)]
use std::path::Path;

use solverforge_config::{SolverConfig, TerminationConfig};
use solverforge_core::domain::{PlanningSolution, SolutionDescriptor};
use solverforge_core::score::{ParseableScore, Score};
use solverforge_scoring::{ConstraintSet, Director, ScoreDirector};
use tracing::info;

use crate::builder::{RuntimeExtensionRegistry, Search};
use crate::manager::{SolverRuntime, SolverTerminalReason};
use crate::phase::Phase;
use crate::runtime::compiler::executor::{
    take_runtime_execution_failure, CompiledRuntimePhaseRunner,
};
use crate::runtime::compiler::{compile_runtime_graph, CompiledRuntimeExecutor, RuntimeGraphInput};
use crate::runtime_build_error::{RuntimeBuildError, RuntimeBuildResult};
use crate::scope::{ProgressCallback, SolverProgressKind, SolverProgressRef, SolverScope};
use crate::solver::{NoTermination, Solver};
use crate::stats::{
    format_duration, whole_units_per_second, CandidateTraceExecutionPolicy,
    QualifiedCandidateTraceRunProvenance,
};
use crate::termination::{
    BestScoreTermination, OrTermination, StepCountTermination, Termination, TimeTermination,
    UnimprovedStepCountTermination, UnimprovedTimeTermination,
};

/// Monomorphized termination enum for config-driven solver configurations.
///
/// Avoids repeated branching across termination overloads by capturing the
/// selected termination variant upfront.
pub enum AnyTermination<S: PlanningSolution, D: Director<S>> {
    None(NoTermination),
    Default(OrTermination<(TimeTermination,), S, D>),
    WithBestScore(OrTermination<(TimeTermination, BestScoreTermination<S::Score>), S, D>),
    WithStepCount(OrTermination<(TimeTermination, StepCountTermination), S, D>),
    WithUnimprovedStep(OrTermination<(TimeTermination, UnimprovedStepCountTermination<S>), S, D>),
    WithUnimprovedTime(OrTermination<(TimeTermination, UnimprovedTimeTermination<S>), S, D>),
}

#[derive(Clone)]
pub struct ChannelProgressCallback<S: PlanningSolution> {
    runtime: SolverRuntime<S>,
    _phantom: PhantomData<fn() -> S>,
}

impl<S: PlanningSolution> ChannelProgressCallback<S> {
    fn new(runtime: SolverRuntime<S>) -> Self {
        Self {
            runtime,
            _phantom: PhantomData,
        }
    }
}

impl<S: PlanningSolution> fmt::Debug for ChannelProgressCallback<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ChannelProgressCallback").finish()
    }
}

impl<S: PlanningSolution> ProgressCallback<S> for ChannelProgressCallback<S> {
    fn invoke(&self, progress: SolverProgressRef<'_, S>) {
        match progress.kind {
            SolverProgressKind::Progress => {
                self.runtime.emit_progress(
                    progress.current_score.copied(),
                    progress.best_score.copied(),
                    progress.telemetry.clone(),
                );
            }
            SolverProgressKind::BestSolution => {
                if let (Some(solution), Some(score)) = (progress.solution, progress.best_score) {
                    self.runtime.emit_best_solution(
                        (*solution).clone(),
                        progress.current_score.copied(),
                        *score,
                        progress.telemetry.clone(),
                    );
                }
            }
        }
    }
}

impl<S: PlanningSolution, D: Director<S>> fmt::Debug for AnyTermination<S, D> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::None(_) => write!(f, "AnyTermination::None"),
            Self::Default(_) => write!(f, "AnyTermination::Default"),
            Self::WithBestScore(_) => write!(f, "AnyTermination::WithBestScore"),
            Self::WithStepCount(_) => write!(f, "AnyTermination::WithStepCount"),
            Self::WithUnimprovedStep(_) => write!(f, "AnyTermination::WithUnimprovedStep"),
            Self::WithUnimprovedTime(_) => write!(f, "AnyTermination::WithUnimprovedTime"),
        }
    }
}

impl<S: PlanningSolution, D: Director<S>, ProgressCb: ProgressCallback<S>>
    Termination<S, D, ProgressCb> for AnyTermination<S, D>
where
    S::Score: Score,
{
    fn is_terminated(&self, solver_scope: &SolverScope<S, D, ProgressCb>) -> bool {
        match self {
            Self::None(t) => t.is_terminated(solver_scope),
            Self::Default(t) => t.is_terminated(solver_scope),
            Self::WithBestScore(t) => t.is_terminated(solver_scope),
            Self::WithStepCount(t) => t.is_terminated(solver_scope),
            Self::WithUnimprovedStep(t) => t.is_terminated(solver_scope),
            Self::WithUnimprovedTime(t) => t.is_terminated(solver_scope),
        }
    }

    fn install_inphase_limits(&self, solver_scope: &mut SolverScope<S, D, ProgressCb>) {
        match self {
            Self::None(t) => t.install_inphase_limits(solver_scope),
            Self::Default(t) => t.install_inphase_limits(solver_scope),
            Self::WithBestScore(t) => t.install_inphase_limits(solver_scope),
            Self::WithStepCount(t) => t.install_inphase_limits(solver_scope),
            Self::WithUnimprovedStep(t) => t.install_inphase_limits(solver_scope),
            Self::WithUnimprovedTime(t) => t.install_inphase_limits(solver_scope),
        }
    }
}

/// Parsed solver termination policy shared by runtime phase assembly and the
/// top-level termination builder.
///
/// `TerminationConfig` historically chooses the first configured score/work
/// criterion in this order: best score, step count, unimproved steps,
/// unimproved time. A configured time limit is paired with that criterion, or
/// is the policy itself when no other criterion is present. Keeping that
/// precedence here prevents phase assembly from treating an empty or
/// unparsable configuration as a finite solver boundary.
#[derive(Clone, Copy)]
pub(crate) struct ConfiguredTermination<Sc> {
    time_limit: Option<Duration>,
    criterion: Option<ConfiguredTerminationCriterion<Sc>>,
}

#[derive(Clone, Copy)]
enum ConfiguredTerminationCriterion<Sc> {
    BestScore(Sc),
    StepCount(u64),
    UnimprovedStepCount(u64),
    UnimprovedTime(Duration),
}

impl<Sc> ConfiguredTermination<Sc> {
    pub(crate) fn has_effective_limit(&self) -> bool {
        self.time_limit.is_some() || self.criterion.is_some()
    }
}

pub(crate) fn parse_configured_termination<S>(
    config: Option<&TerminationConfig>,
) -> ConfiguredTermination<S::Score>
where
    S: PlanningSolution,
    S::Score: ParseableScore,
{
    let time_limit = config.and_then(TerminationConfig::time_limit);
    let criterion = config.and_then(|config| {
        config
            .best_score_limit
            .as_deref()
            .and_then(|score| S::Score::parse(score).ok())
            .map(ConfiguredTerminationCriterion::BestScore)
            .or_else(|| {
                config
                    .step_count_limit
                    .map(ConfiguredTerminationCriterion::StepCount)
            })
            .or_else(|| {
                config
                    .unimproved_step_count_limit
                    .map(ConfiguredTerminationCriterion::UnimprovedStepCount)
            })
            .or_else(|| {
                config
                    .unimproved_time_limit()
                    .map(ConfiguredTerminationCriterion::UnimprovedTime)
            })
    });
    ConfiguredTermination {
        time_limit,
        criterion,
    }
}

/// Builds a termination from config, returning both the termination and the time limit.
pub fn build_termination<S, C>(
    config: &SolverConfig,
    default_secs: u64,
) -> (AnyTermination<S, ScoreDirector<S, C>>, Option<Duration>)
where
    S: PlanningSolution,
    S::Score: Score + ParseableScore,
    C: ConstraintSet<S, S::Score>,
{
    let ConfiguredTermination {
        time_limit: configured_time_limit,
        criterion,
    } = parse_configured_termination::<S>(config.termination.as_ref());
    let fallback_time_limit = Duration::from_secs(default_secs);

    let (termination, effective_time_limit) = match criterion {
        Some(ConfiguredTerminationCriterion::BestScore(target)) => {
            let effective_time_limit = configured_time_limit.unwrap_or(fallback_time_limit);
            let time = TimeTermination::new(effective_time_limit);
            (
                AnyTermination::WithBestScore(OrTermination::new((
                    time,
                    BestScoreTermination::new(target),
                ))),
                Some(effective_time_limit),
            )
        }
        Some(ConfiguredTerminationCriterion::StepCount(step_limit)) => {
            let effective_time_limit = configured_time_limit.unwrap_or(fallback_time_limit);
            let time = TimeTermination::new(effective_time_limit);
            (
                AnyTermination::WithStepCount(OrTermination::new((
                    time,
                    StepCountTermination::new(step_limit),
                ))),
                Some(effective_time_limit),
            )
        }
        Some(ConfiguredTerminationCriterion::UnimprovedStepCount(unimproved_step_limit)) => {
            let effective_time_limit = configured_time_limit.unwrap_or(fallback_time_limit);
            let time = TimeTermination::new(effective_time_limit);
            (
                AnyTermination::WithUnimprovedStep(OrTermination::new((
                    time,
                    UnimprovedStepCountTermination::<S>::new(unimproved_step_limit),
                ))),
                Some(effective_time_limit),
            )
        }
        Some(ConfiguredTerminationCriterion::UnimprovedTime(unimproved_time)) => {
            let effective_time_limit = configured_time_limit.unwrap_or(fallback_time_limit);
            let time = TimeTermination::new(effective_time_limit);
            (
                AnyTermination::WithUnimprovedTime(OrTermination::new((
                    time,
                    UnimprovedTimeTermination::<S>::new(unimproved_time),
                ))),
                Some(effective_time_limit),
            )
        }
        None => configured_time_limit.map_or_else(
            || (AnyTermination::None(NoTermination), None),
            |limit| {
                let time = TimeTermination::new(limit);
                (
                    AnyTermination::Default(OrTermination::new((time,))),
                    Some(limit),
                )
            },
        ),
    };

    (termination, effective_time_limit)
}

/// Records the termination policy the configured runtime actually installed.
///
/// This deliberately derives its time guard from `build_termination`'s
/// returned effective limit rather than from the input TOML.  In particular,
/// a score/work criterion without an explicit time limit gets the configured
/// entrypoint's fallback guard, and that injected guard is material to both
/// bounded-work and fixed-budget comparisons.
pub(crate) fn configured_execution_policy<S>(
    config: &SolverConfig,
    default_secs: u64,
    effective_time_limit: Option<Duration>,
) -> CandidateTraceExecutionPolicy
where
    S: PlanningSolution,
    S::Score: ParseableScore + std::fmt::Display,
{
    let configured = parse_configured_termination::<S>(config.termination.as_ref());
    let configured_time_limit = configured.time_limit;
    let criterion = configured.criterion;
    let fallback_time_limit = Duration::from_secs(default_secs);

    let time_limit_source = match (configured_time_limit, effective_time_limit) {
        (Some(_), Some(_)) => "configured",
        (None, Some(_)) if criterion.is_some() => "configured_entrypoint_fallback",
        (None, Some(_)) => "internal",
        (_, None) => "not_installed",
    };
    let mut attributes = vec![
        ("entrypoint".to_string(), "configured_runtime".to_string()),
        (
            "configured_time_limit_ns".to_string(),
            configured_time_limit.map_or_else(|| "none".to_string(), duration_nanos),
        ),
        (
            "configured_entrypoint_default_time_limit_ns".to_string(),
            duration_nanos(fallback_time_limit),
        ),
        (
            "effective_time_limit_ns".to_string(),
            effective_time_limit.map_or_else(|| "none".to_string(), duration_nanos),
        ),
        (
            "time_limit_source".to_string(),
            time_limit_source.to_string(),
        ),
    ];

    match criterion {
        Some(ConfiguredTerminationCriterion::BestScore(target)) => {
            attributes.push(("criterion".to_string(), "best_score".to_string()));
            attributes.push(("criterion_target".to_string(), target.to_string()));
            attributes.push((
                "termination_composition".to_string(),
                "time_or_best_score".to_string(),
            ));
        }
        Some(ConfiguredTerminationCriterion::StepCount(limit)) => {
            attributes.push(("criterion".to_string(), "step_count".to_string()));
            attributes.push(("criterion_target".to_string(), limit.to_string()));
            attributes.push((
                "termination_composition".to_string(),
                "time_or_step_count".to_string(),
            ));
        }
        Some(ConfiguredTerminationCriterion::UnimprovedStepCount(limit)) => {
            attributes.push(("criterion".to_string(), "unimproved_step_count".to_string()));
            attributes.push(("criterion_target".to_string(), limit.to_string()));
            attributes.push((
                "termination_composition".to_string(),
                "time_or_unimproved_step_count".to_string(),
            ));
        }
        Some(ConfiguredTerminationCriterion::UnimprovedTime(limit)) => {
            attributes.push(("criterion".to_string(), "unimproved_time".to_string()));
            attributes.push(("criterion_target_ns".to_string(), duration_nanos(limit)));
            attributes.push((
                "termination_composition".to_string(),
                "time_or_unimproved_time".to_string(),
            ));
        }
        None if effective_time_limit.is_some() => {
            attributes.push(("criterion".to_string(), "none".to_string()));
            attributes.push((
                "termination_composition".to_string(),
                "time_only".to_string(),
            ));
        }
        None => {
            attributes.push(("criterion".to_string(), "none".to_string()));
            attributes.push((
                "termination_composition".to_string(),
                "unbounded".to_string(),
            ));
        }
    }

    CandidateTraceExecutionPolicy::known("solverforge.execution_policy", attributes)
}

fn duration_nanos(duration: Duration) -> String {
    duration.as_nanos().to_string()
}

pub fn log_solve_start(
    entity_count: usize,
    element_count: Option<usize>,
    candidate_count: Option<usize>,
) {
    match (element_count, candidate_count) {
        (Some(element_count), None) => {
            info!(
                event = "solve_start",
                entity_count = entity_count,
                element_count = element_count,
                solve_shape = "list",
            );
        }
        (None, Some(candidate_count)) => {
            info!(
                event = "solve_start",
                entity_count = entity_count,
                candidate_count = candidate_count,
                solve_shape = "scalar",
            );
        }
        _ => {
            panic!(
                "log_solve_start requires exactly one solve scale: list elements or scalar candidates"
            );
        }
    }
}

#[cfg(test)]
fn load_solver_config_from(path: impl AsRef<Path>) -> SolverConfig {
    SolverConfig::load(path).unwrap_or_default()
}

/// Runs one configured model through the immutable runtime graph compiler and
/// retained compiled runner.
///
/// `build_search` creates the one descriptor-resolved declaration consumed by
/// the compiled graph. Every model, including a zero-work model, follows this
/// one lifecycle; the public API never exposes a graph, prepared source
/// catalog, or phase-builder fallback.
#[allow(clippy::too_many_arguments)]
pub fn try_run_solver_with_config_and_search<S, C, V, DM, IDM, Declaration, BuildSearch>(
    solution: S,
    constraints: C,
    descriptor: SolutionDescriptor,
    entity_count_by_descriptor: fn(&S, usize) -> usize,
    runtime: SolverRuntime<S>,
    config: SolverConfig,
    default_time_limit_secs: u64,
    log_scale: fn(&S),
    qualified_candidate_trace_provenance: Option<QualifiedCandidateTraceRunProvenance>,
    build_search: BuildSearch,
) -> RuntimeBuildResult<S>
where
    S: PlanningSolution + Clone + Send + Sync + 'static,
    S::Score: Score + Copy + Ord + ParseableScore,
    C: ConstraintSet<S, S::Score>,
    V: Clone + Copy + PartialEq + Eq + Hash + Into<usize> + Send + Sync + fmt::Debug + 'static,
    DM: crate::heuristic::selector::nearby_list_change::CrossEntityDistanceMeter<S>
        + Clone
        + Send
        + Sync
        + fmt::Debug
        + 'static,
    IDM: crate::heuristic::selector::nearby_list_change::CrossEntityDistanceMeter<S>
        + Clone
        + Send
        + Sync
        + fmt::Debug
        + 'static,
    Declaration: Search<S, V, DM, IDM>,
    Declaration::Extensions: RuntimeExtensionRegistry<S, V, DM, IDM>,
    BuildSearch: FnOnce(&SolverConfig, SolutionDescriptor) -> RuntimeBuildResult<Declaration>,
{
    try_run_solver_with_config_and_search_request(
        solution,
        constraints,
        descriptor,
        entity_count_by_descriptor,
        runtime,
        config,
        default_time_limit_secs,
        log_scale,
        qualified_candidate_trace_provenance,
        build_search,
    )
}

#[allow(clippy::too_many_arguments)]
fn try_run_solver_with_config_and_search_request<S, C, V, DM, IDM, Declaration, BuildSearch>(
    solution: S,
    constraints: C,
    descriptor: SolutionDescriptor,
    entity_count_by_descriptor: fn(&S, usize) -> usize,
    runtime: SolverRuntime<S>,
    config: SolverConfig,
    default_time_limit_secs: u64,
    log_scale: fn(&S),
    qualified_candidate_trace_provenance: Option<QualifiedCandidateTraceRunProvenance>,
    build_search: BuildSearch,
) -> RuntimeBuildResult<S>
where
    S: PlanningSolution + Clone + Send + Sync + 'static,
    S::Score: Score + Copy + Ord + ParseableScore,
    C: ConstraintSet<S, S::Score>,
    V: Clone + Copy + PartialEq + Eq + Hash + Into<usize> + Send + Sync + fmt::Debug + 'static,
    DM: crate::heuristic::selector::nearby_list_change::CrossEntityDistanceMeter<S>
        + Clone
        + Send
        + Sync
        + fmt::Debug
        + 'static,
    IDM: crate::heuristic::selector::nearby_list_change::CrossEntityDistanceMeter<S>
        + Clone
        + Send
        + Sync
        + fmt::Debug
        + 'static,
    Declaration: Search<S, V, DM, IDM>,
    Declaration::Extensions: RuntimeExtensionRegistry<S, V, DM, IDM>,
    BuildSearch: FnOnce(&SolverConfig, SolutionDescriptor) -> RuntimeBuildResult<Declaration>,
{
    try_run_solver_with_candidate_trace_request(
        solution,
        constraints,
        descriptor,
        entity_count_by_descriptor,
        runtime,
        config,
        default_time_limit_secs,
        log_scale,
        qualified_candidate_trace_provenance,
        move |config, descriptor| {
            let declaration = build_search(config, descriptor.clone())?;
            let (context, extensions) = declaration.into_runtime_parts();
            let graph = compile_runtime_graph(config, RuntimeGraphInput::new(context, extensions))
                .map_err(|error| {
                    let message = error.to_string();
                    RuntimeBuildError::Compilation {
                        path: error.path,
                        message,
                    }
                })?;
            let executor = CompiledRuntimeExecutor::new(graph);
            CompiledRuntimePhaseRunner::try_new(&executor)
        },
    )
}

#[allow(clippy::too_many_arguments)]
fn try_run_solver_with_candidate_trace_request<S, C, Runner, BuildRunner>(
    solution: S,
    constraints: C,
    descriptor: SolutionDescriptor,
    entity_count_by_descriptor: fn(&S, usize) -> usize,
    runtime: SolverRuntime<S>,
    config: SolverConfig,
    default_time_limit_secs: u64,
    log_scale: fn(&S),
    qualified_candidate_trace_provenance: Option<QualifiedCandidateTraceRunProvenance>,
    build_runner: BuildRunner,
) -> RuntimeBuildResult<S>
where
    S: PlanningSolution,
    S::Score: Score + ParseableScore,
    C: ConstraintSet<S, S::Score>,
    Runner: Phase<S, ScoreDirector<S, C>, ChannelProgressCallback<S>> + Send + std::fmt::Debug,
    BuildRunner: FnOnce(&SolverConfig, &SolutionDescriptor) -> RuntimeBuildResult<Runner>,
{
    log_scale(&solution);
    let director = ScoreDirector::with_descriptor(
        solution,
        constraints,
        descriptor.clone(),
        entity_count_by_descriptor,
    );

    let (termination, time_limit) = build_termination::<S, C>(&config, default_time_limit_secs);
    let execution_policy =
        configured_execution_policy::<S>(&config, default_time_limit_secs, time_limit);

    let callback = ChannelProgressCallback::new(runtime);

    let runner = match build_runner(&config, &descriptor) {
        Ok(runner) => runner,
        Err(error) => {
            runtime.emit_failed(error.to_string());
            return Err(error);
        }
    };
    let mut solver = Solver::new((runner,))
        .with_config(config.clone())
        .with_candidate_trace_execution_policy(execution_policy)
        .with_termination(termination)
        .with_runtime(runtime)
        .with_progress_callback(callback);
    if let Some(provenance) = qualified_candidate_trace_provenance {
        solver = solver.with_qualified_candidate_trace_run_provenance(provenance);
    }
    if let Some(time_limit) = time_limit {
        solver = solver.with_time_limit(time_limit);
    }

    let result = match catch_unwind(AssertUnwindSafe(|| {
        solver.with_terminate(runtime.cancel_flag()).solve(director)
    })) {
        Ok(result) => result,
        Err(payload) => match take_runtime_execution_failure(payload) {
            Ok(error) => {
                runtime.emit_failed(error.to_string());
                return Err(error);
            }
            Err(payload) => resume_unwind(payload),
        },
    };

    let crate::solver::SolveResult {
        solution,
        current_score,
        best_score: final_score,
        terminal_reason,
        stats,
    } = result;
    let final_telemetry = stats.snapshot();
    let final_move_speed = whole_units_per_second(stats.moves_evaluated, stats.elapsed());
    match terminal_reason {
        SolverTerminalReason::Completed | SolverTerminalReason::TerminatedByConfig => {
            runtime.emit_completed(
                solution.clone(),
                current_score,
                final_score,
                final_telemetry,
                terminal_reason,
            );
        }
        SolverTerminalReason::Cancelled => {
            runtime.emit_cancelled(current_score, Some(final_score), final_telemetry);
        }
        SolverTerminalReason::Failed => unreachable!("solver completion cannot report failure"),
    }

    info!(
        event = "solve_end",
        score = %final_score,
        steps = stats.step_count,
        moves_generated = stats.moves_generated,
        moves_evaluated = stats.moves_evaluated,
        moves_accepted = stats.moves_accepted,
        score_calculations = stats.score_calculations,
        generation_time = %format_duration(stats.generation_time()),
        evaluation_time = %format_duration(stats.evaluation_time()),
        moves_speed = final_move_speed,
        acceptance_rate = format!("{:.1}%", stats.acceptance_rate() * 100.0),
    );
    Ok(solution)
}

#[cfg(test)]
#[path = "run_tests.rs"]
mod tests;