1
#![allow(unused)]
2

            
3
use conjure_cp::settings::{
4
    Channelling, Heuristic, Parser, QuantifiedExpander, Rewriter, SolverFamily,
5
};
6
#[path = "../../crates/conjure-cp-cli/src/stats.rs"]
7
mod stats;
8

            
9
pub use self::stats::{
10
    RecordedRuleTraceStats, RecordedRunConfig, RecordedRunStats, RecordedToolStats, TestRunStats,
11
    read_stats_or_default, replace_config_run_stats,
12
};
13

            
14
use self::stats::{deserialise_expected_time, update_canonical_stats, write_canonical_stats};
15
use serde::de::{self, Visitor};
16
use serde::{Deserialize, Serialize};
17
use std::collections::BTreeMap;
18
use std::fmt;
19
use std::fs;
20
use std::io;
21
use std::path::Path;
22
use std::str::FromStr;
23
use std::time::Duration;
24
use toml_edit::{DocumentMut, Item, Table, value};
25
pub const STATS_FILE_NAME: &str = "stats.toml";
26

            
27
4976
pub fn stats_path(test_dir: &Path) -> std::path::PathBuf {
28
4976
    test_dir.join(STATS_FILE_NAME)
29
4976
}
30

            
31
/// Starts a fresh stats snapshot for an exhaustive run.
32
2
pub fn reset_stats_for_run(path: &Path) -> io::Result<()> {
33
2
    write_canonical_stats(path, &TestRunStats::default())
34
2
}
35

            
36
fn read_toml_document_or_empty(path: &Path) -> io::Result<DocumentMut> {
37
    if path.exists() {
38
        let contents = fs::read_to_string(path)?;
39
        if contents.trim().is_empty() {
40
            Ok(DocumentMut::new())
41
        } else {
42
            contents
43
                .parse::<DocumentMut>()
44
                .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
45
        }
46
    } else {
47
        Ok(DocumentMut::new())
48
    }
49
}
50

            
51
fn write_toml_document(path: &Path, document: &DocumentMut) -> io::Result<()> {
52
    let mut contents = document.to_string();
53
    contents.truncate(contents.trim_end_matches('\n').len());
54
    contents.push('\n');
55
    fs::write(path, contents)
56
}
57

            
58
// toml_edit's Index impl panics on missing keys, so use .get() before creating tables.
59
fn ensure_table(document: &mut DocumentMut, key: &str) {
60
    if document.get(key).is_some_and(|item| item.is_table()) {
61
        return;
62
    }
63
    document[key] = Item::Table(Table::new());
64
}
65

            
66
fn ensure_nested_table(document: &mut DocumentMut, keys: &[&str]) {
67
    let (head, tail) = keys.split_first().expect("table path must not be empty");
68
    ensure_table(document, head);
69
    let mut table = document[head].as_table_mut().expect("table exists");
70
    for key in tail {
71
        if table.get(key).is_some_and(|item| item.is_table()) {
72
            table = table[key].as_table_mut().expect("table exists");
73
            continue;
74
        }
75
        table[*key] = Item::Table(Table::new());
76
        table = table[key].as_table_mut().expect("table exists");
77
    }
78
}
79

            
80
16953
fn parse_values<T>(values: &[String]) -> Result<Vec<T>, String>
81
16953
where
82
16953
    T: FromStr<Err = String>,
83
{
84
20169
    values.iter().map(|value| value.parse()).collect()
85
16953
}
86

            
87
14585
fn deserialize_string_or_vec<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
88
14585
where
89
14585
    D: serde::Deserializer<'de>,
90
{
91
    #[derive(Deserialize)]
92
    #[serde(untagged)]
93
    enum StringOrVec {
94
        String(String),
95
        Vec(Vec<String>),
96
    }
97

            
98
14585
    Ok(match StringOrVec::deserialize(deserializer)? {
99
12247
        StringOrVec::String(s) => vec![s],
100
2338
        StringOrVec::Vec(v) => v,
101
    })
102
14585
}
103

            
104
4126
fn default_skip_conjure_validation() -> String {
105
4126
    String::new()
106
4126
}
107

            
108
4343
fn default_skip() -> String {
109
4343
    String::new()
110
4343
}
111

            
112
9049
fn default_minion_discrete_threshold() -> usize {
113
9049
    conjure_cp::settings::DEFAULT_MINION_DISCRETE_THRESHOLD
114
9049
}
115

            
116
1170
fn default_number_of_solutions() -> NumberOfSolutions {
117
1170
    NumberOfSolutions::All
118
1170
}
119

            
120
4362
fn default_keep_intermediate_solutions() -> bool {
121
4362
    false
122
4362
}
123

            
124
2011
fn deserialise_number_of_solutions<'de, D>(deserializer: D) -> Result<NumberOfSolutions, D::Error>
125
2011
where
126
2011
    D: serde::Deserializer<'de>,
127
{
128
2011
    deserializer.deserialize_any(NumberOfSolutionsVisitor)
129
2011
}
130

            
131
struct NumberOfSolutionsVisitor;
132

            
133
impl<'de> Visitor<'de> for NumberOfSolutionsVisitor {
134
    type Value = NumberOfSolutions;
135

            
136
    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
137
        formatter.write_str("a positive integer, the string \"all\", or the string \"skip\"")
138
    }
139

            
140
79
    fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
141
79
    where
142
79
        E: de::Error,
143
    {
144
79
        let value = i32::try_from(value).map_err(|err| {
145
            E::custom(format!(
146
                "number-of-solutions is too large for the solver limit: {err}"
147
            ))
148
        })?;
149

            
150
79
        if value == 0 {
151
            return Err(E::custom(
152
                "number-of-solutions must be positive, or the string \"all\" or \"skip\"",
153
            ));
154
79
        }
155

            
156
79
        Ok(NumberOfSolutions::Limit(value))
157
79
    }
158

            
159
79
    fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
160
79
    where
161
79
        E: de::Error,
162
    {
163
79
        let value = u64::try_from(value).map_err(|_| {
164
            E::custom("number-of-solutions must be positive, or the string \"all\" or \"skip\"")
165
        })?;
166

            
167
79
        self.visit_u64(value)
168
79
    }
169

            
170
1932
    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
171
1932
    where
172
1932
        E: de::Error,
173
    {
174
1932
        match value {
175
1916
            "all" => Ok(NumberOfSolutions::All),
176
16
            "skip" => Ok(NumberOfSolutions::Skip),
177
            _ => Err(E::custom(format!(
178
                "invalid number-of-solutions value '{value}', expected a positive integer, \"all\", or \"skip\""
179
            ))),
180
        }
181
1932
    }
182
}
183

            
184
/// Rounds an observed runtime into the coarse `expected-time` buckets used by test configs,
185
/// such as `1`, `5`, `10`, `30`, `60`, and so on.
186
pub fn round_expected_time(duration: Duration) -> u64 {
187
    let seconds = duration.as_secs_f64();
188

            
189
    if seconds <= 1.0 {
190
        1
191
    } else if seconds <= 5.0 {
192
        5
193
    } else if seconds <= 10.0 {
194
        10
195
    } else {
196
        ((seconds / 30.0).ceil() as u64) * 30
197
    }
198
}
199

            
200
/// Inserts or updates the `expected-time` entry in a test `stats.toml`.
201
1
pub fn upsert_expected_time_stats(path: &Path, expected_time: u64) -> io::Result<()> {
202
1
    update_canonical_stats(path, |stats| stats.expected_time = Some(expected_time))
203
1
}
204

            
205
/// Inserts or updates the `expected-time` entry in a test `config.toml`.
206
///
207
/// Custom tests still keep their expected-time metadata in `config.toml`; exhaustive tests use
208
/// `stats.toml`.
209
pub fn upsert_expected_time_config(path: &Path, expected_time: u64) -> io::Result<()> {
210
    let expected_time = i64::try_from(expected_time).map_err(|err| {
211
        io::Error::new(
212
            io::ErrorKind::InvalidInput,
213
            format!("expected-time is too large to write to TOML: {err}"),
214
        )
215
    })?;
216
    let mut document = read_toml_document_or_empty(path)?;
217
    document["expected-time"] = value(expected_time);
218
    write_toml_document(path, &document)
219
}
220

            
221
/// Inserts or updates the latest observed exhaustive status in a test `stats.toml`.
222
1
pub fn upsert_status_stats(path: &Path, status: &str) -> io::Result<()> {
223
1
    update_canonical_stats(path, |stats| stats.status = Some(status.to_string()))
224
1
}
225

            
226
/// Inserts or updates the latest observed status for one part of an exhaustive test.
227
1
pub fn upsert_tool_status_stats(path: &Path, tool: &str, status: &str) -> io::Result<()> {
228
1
    if tool != "conjure" {
229
        return Err(io::Error::new(
230
            io::ErrorKind::InvalidInput,
231
            format!("'{tool}' does not have shared tool stats"),
232
        ));
233
1
    }
234
1
    update_canonical_stats(path, |stats| {
235
1
        stats.conjure.status = Some(status.to_string());
236
1
    })
237
1
}
238

            
239
/// Timing measurements recorded from one accepted Conjure reference run.
240
#[derive(Clone, Copy, Debug)]
241
pub struct RecordedConjureStats {
242
    /// Wall-clock time of the complete `conjure solve` command, in seconds.
243
    pub conjure_wall_clock_time: f64,
244
    /// Total Conjure plus Savile Row translation time, in seconds.
245
    pub conjure_translation_time: f64,
246
    /// Time spent by Conjure before Savile Row is invoked, in seconds.
247
    pub conjure_driver_translation_time: f64,
248
    /// Time spent by Savile Row during reference translation, in seconds.
249
    pub savilerow_translation_time: f64,
250
    /// Time spent solving the Conjure plus Savile Row reference model, in seconds.
251
    pub conjure_solve_time: f64,
252
}
253

            
254
/// Inserts or updates the recorded Conjure reference timings in a test `stats.toml`.
255
1
pub fn upsert_conjure_timing_stats(path: &Path, stats: RecordedConjureStats) -> io::Result<()> {
256
1
    update_canonical_stats(path, |current| {
257
1
        current.conjure.wall_clock_time = Some(stats.conjure_wall_clock_time);
258
1
        current.conjure.translation_time = Some(stats.conjure_translation_time);
259
1
        current.conjure.conjure_translation_time = Some(stats.conjure_driver_translation_time);
260
1
        current.conjure.savilerow_translation_time = Some(stats.savilerow_translation_time);
261
1
        current.conjure.solve_time = Some(stats.conjure_solve_time);
262
1
    })
263
1
}
264

            
265
/// Solution search limit requested by an exhaustive test.
266
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
267
pub enum NumberOfSolutions {
268
    /// Search for every solution.
269
    All,
270
    /// Stop after the given number of solutions.
271
    Limit(i32),
272
    /// Do not run the solver for this exhaustive test.
273
    Skip,
274
}
275

            
276
impl NumberOfSolutions {
277
    /// Converts the config value into the solver API limit, where `0` means all solutions.
278
378627
    pub fn as_solver_limit(self) -> Option<i32> {
279
378627
        match self {
280
370560
            Self::All => Some(0),
281
7992
            Self::Limit(limit) => Some(limit),
282
75
            Self::Skip => None,
283
        }
284
378627
    }
285
}
286

            
287
/// Per-backend modelling and trace choices for an exhaustive fixture.
288
#[derive(Deserialize, Debug, Default)]
289
#[serde(default, deny_unknown_fields)]
290
pub struct SolverOptions {
291
    /// Override the fixture's modelling heuristic for this backend.
292
    #[serde(deserialize_with = "deserialize_string_or_vec")]
293
    pub heuristic: Vec<String>,
294
    /// Override the fixture's representation-sharing policy for this backend.
295
    #[serde(deserialize_with = "deserialize_string_or_vec")]
296
    pub channelling: Vec<String>,
297
    /// Override the fixture's trace level for this backend.
298
    #[serde(rename = "trace-level")]
299
    pub trace_level: Option<TraceLevel>,
300
}
301

            
302
#[derive(Deserialize, Debug)]
303
#[serde(default)]
304
#[serde(deny_unknown_fields)]
305
pub struct TestConfig {
306
    #[serde(
307
        default,
308
        rename = "parser",
309
        deserialize_with = "deserialize_string_or_vec"
310
    )]
311
    pub parser: Vec<String>, // Stage 1a: list of parsers (tree-sitter or via-conjure)
312

            
313
    #[serde(
314
        default,
315
        rename = "rewriter",
316
        deserialize_with = "deserialize_string_or_vec"
317
    )]
318
    pub rewriter: Vec<String>,
319
    #[serde(
320
        default,
321
        rename = "comprehension-expander",
322
        deserialize_with = "deserialize_string_or_vec"
323
    )]
324
    pub comprehension_expander: Vec<String>,
325
    #[serde(
326
        default,
327
        rename = "heuristic",
328
        deserialize_with = "deserialize_string_or_vec"
329
    )]
330
    pub heuristic: Vec<String>,
331
    #[serde(
332
        default,
333
        rename = "channelling",
334
        deserialize_with = "deserialize_string_or_vec"
335
    )]
336
    pub channelling: Vec<String>,
337
    #[serde(default, rename = "seed")]
338
    pub seed: u64,
339
    #[serde(default, rename = "solver-seed")]
340
    pub solver_seed: u32,
341
    #[serde(
342
        default,
343
        rename = "solver",
344
        deserialize_with = "deserialize_string_or_vec"
345
    )]
346
    pub solver: Vec<String>,
347

            
348
    /// Backend-specific modelling and trace overrides.
349
    #[serde(default, rename = "solver-options")]
350
    pub solver_options: BTreeMap<String, SolverOptions>,
351

            
352
    #[serde(
353
        default,
354
        rename = "extra-rule-sets",
355
        deserialize_with = "deserialize_string_or_vec"
356
    )]
357
    pub extra_rule_sets: Vec<String>,
358

            
359
    #[serde(
360
        default = "default_minion_discrete_threshold",
361
        rename = "minion-discrete-threshold"
362
    )]
363
    pub minion_discrete_threshold: usize,
364

            
365
    #[serde(
366
        default = "default_skip_conjure_validation",
367
        rename = "skip-conjure-validation"
368
    )]
369
    pub skip_conjure_validation: String,
370

            
371
    #[serde(
372
        default = "default_number_of_solutions",
373
        rename = "number-of-solutions",
374
        deserialize_with = "deserialise_number_of_solutions"
375
    )]
376
    pub number_of_solutions: NumberOfSolutions,
377

            
378
    #[serde(
379
        default = "default_keep_intermediate_solutions",
380
        rename = "keep-intermediate-solutions"
381
    )]
382
    pub keep_intermediate_solutions: bool,
383

            
384
    /// How much of the rule trace each run records. See [`TraceLevel`].
385
    #[serde(default, rename = "trace-level")]
386
    pub trace_level: TraceLevel,
387

            
388
    /// Empty `skip` runs the test; a non-empty string ignores it and records why.
389
    #[serde(default = "default_skip")]
390
    pub skip: String,
391

            
392
    #[serde(
393
        default,
394
        rename = "expected-time",
395
        deserialize_with = "deserialise_expected_time"
396
    )]
397
    pub expected_time: Option<u64>,
398
}
399

            
400
/// The rule trace recorded by each exhaustive run.
401
#[derive(Deserialize, Debug, Default, Clone, Copy, PartialEq, Eq)]
402
#[serde(rename_all = "lowercase")]
403
pub enum TraceLevel {
404
    /// Disable rule trace snapshots and aggregate counts.
405
    None,
406
    /// Write the human-readable trace of every rule application and compare it with the
407
    /// expected snapshot.
408
    #[default]
409
    Full,
410
    /// Count rule applications in memory and record only the totals in `stats.toml`. Much
411
    /// cheaper for large fixtures, at the cost of the trace snapshot.
412
    Aggregate,
413
}
414

            
415
impl Default for TestConfig {
416
4682
    fn default() -> Self {
417
4682
        Self {
418
4682
            skip: String::new(),
419
4682
            parser: vec!["tree-sitter".to_string(), "via-conjure".to_string()],
420
4682
            rewriter: vec!["optimised".to_string()],
421
4682
            comprehension_expander: vec!["auto".to_string()],
422
4682
            heuristic: vec!["x".to_string()],
423
4682
            channelling: vec!["no".to_string()],
424
4682
            seed: 0,
425
4682
            solver_seed: 0,
426
            // How a model is expressed for a solver -- which SAT integer encoding, which Z3
427
            // integer theory -- is a representation choice, so the `x` heuristic above enumerates
428
            // those combinations rather than them being separate solvers here.
429
4682
            solver: vec!["minion".to_string(), "sat".to_string(), "z3".to_string()],
430
4682
            solver_options: BTreeMap::new(),
431
4682
            extra_rule_sets: Vec::new(),
432
4682
            minion_discrete_threshold: default_minion_discrete_threshold(),
433
4682
            skip_conjure_validation: String::new(),
434
4682
            number_of_solutions: NumberOfSolutions::All,
435
4682
            keep_intermediate_solutions: false,
436
4682
            trace_level: TraceLevel::Full,
437
4682
            expected_time: None,
438
4682
        }
439
4682
    }
440
}
441

            
442
impl TestConfig {
443
    /// Complete searches share one golden across all configurations.
444
1779
    pub fn uses_shared_solution_snapshot(&self) -> bool {
445
1779
        matches!(self.number_of_solutions, NumberOfSolutions::All)
446
1779
    }
447

            
448
    /// Empty `skip-conjure-validation` runs Conjure reference validation during accept.
449
1779
    pub fn should_skip_conjure_validation(&self) -> bool {
450
1779
        !self.skip_conjure_validation.is_empty()
451
1779
    }
452

            
453
    /// Empty `skip` runs the test; a non-empty string ignores it.
454
    pub fn should_skip(&self) -> bool {
455
        !self.skip.is_empty()
456
    }
457

            
458
2024
    pub fn skip_reason(&self) -> Option<&str> {
459
2024
        if self.skip.is_empty() {
460
2000
            None
461
        } else {
462
24
            Some(self.skip.as_str())
463
        }
464
2024
    }
465

            
466
2274
    pub fn configured_parsers(&self) -> Result<Vec<Parser>, String> {
467
2274
        parse_values(&self.parser)
468
2274
    }
469

            
470
1779
    pub fn configured_rewriters(&self) -> Result<Vec<Rewriter>, String> {
471
1779
        if self.rewriter.is_empty() {
472
            return Err("setting 'rewriter' has no values".to_string());
473
1779
        }
474

            
475
1779
        parse_values(&self.rewriter)
476
1779
    }
477

            
478
1779
    pub fn configured_comprehension_expanders(&self) -> Result<Vec<QuantifiedExpander>, String> {
479
1779
        let values = if self.comprehension_expander.is_empty() {
480
            vec!["auto".to_string()]
481
        } else {
482
1779
            self.comprehension_expander.clone()
483
        };
484

            
485
1779
        parse_values(&values)
486
1779
    }
487

            
488
2910
    pub fn configured_heuristics(&self) -> Result<Vec<Heuristic>, String> {
489
2910
        let values = if self.heuristic.is_empty() {
490
1035
            vec!["x".to_string()]
491
        } else {
492
1875
            self.heuristic.clone()
493
        };
494
2910
        parse_values(&values)
495
2910
    }
496

            
497
2934
    pub fn configured_channelling(&self) -> Result<Vec<Channelling>, String> {
498
2934
        let values = if self.channelling.is_empty() {
499
1254
            vec!["no".to_string()]
500
        } else {
501
1680
            self.channelling.clone()
502
        };
503
2934
        let configured: Vec<Channelling> = parse_values(&values)?;
504
2934
        if configured.contains(&Channelling::Yes) {
505
            return Err("setting 'channelling=yes' is not supported yet".to_string());
506
2934
        }
507
2934
        Ok(configured)
508
2934
    }
509

            
510
    /// Resolve a backend's trace level, inheriting the fixture default when omitted.
511
4671
    pub fn configured_trace_level_for(&self, solver: SolverFamily) -> TraceLevel {
512
4671
        self.solver_options
513
4671
            .get(&solver.as_str())
514
1764
            .and_then(|options| options.trace_level)
515
4671
            .unwrap_or(self.trace_level)
516
4671
    }
517

            
518
    /// Resolve a backend's heuristic while retaining the fixture default for other backends.
519
4671
    pub fn configured_heuristics_for(
520
4671
        &self,
521
4671
        solver: SolverFamily,
522
4671
    ) -> Result<Vec<Heuristic>, String> {
523
4671
        match self.solver_options.get(&solver.as_str()) {
524
1764
            Some(options) if !options.heuristic.is_empty() => parse_values(&options.heuristic),
525
2910
            _ => self.configured_heuristics(),
526
        }
527
4671
    }
528

            
529
    /// Resolve a backend's channelling policy while retaining the fixture default elsewhere.
530
4671
    pub fn configured_channelling_for(
531
4671
        &self,
532
4671
        solver: SolverFamily,
533
4671
    ) -> Result<Vec<Channelling>, String> {
534
4671
        let configured = match self.solver_options.get(&solver.as_str()) {
535
1764
            Some(options) if !options.channelling.is_empty() => parse_values(&options.channelling)?,
536
2934
            _ => self.configured_channelling()?,
537
        };
538
4671
        if configured.contains(&Channelling::Yes) {
539
            return Err("setting 'channelling=yes' is not supported yet".to_string());
540
4671
        }
541
4671
        Ok(configured)
542
4671
    }
543

            
544
1779
    pub fn configured_solvers(&self) -> Result<Vec<SolverFamily>, String> {
545
1779
        for name in self.solver_options.keys() {
546
1761
            name.parse::<SolverFamily>()?;
547
        }
548
1779
        parse_values(&self.solver)
549
1779
    }
550

            
551
    pub fn uses_smt_solver(&self) -> bool {
552
        self.solver.iter().any(|solver| solver == "z3")
553
    }
554
}
555

            
556
#[cfg(test)]
557
mod tests {
558
    use super::*;
559

            
560
    #[test]
561
1
    fn records_runs_in_the_canonical_shape() {
562
1
        let temp_dir = tempfile::tempdir().unwrap();
563
1
        let path = temp_dir.path().join(STATS_FILE_NAME);
564
1
        reset_stats_for_run(&path).unwrap();
565
1
        upsert_expected_time_stats(&path, 1).unwrap();
566
1
        upsert_status_stats(&path, "ok").unwrap();
567
1
        upsert_tool_status_stats(&path, "conjure", "ok").unwrap();
568

            
569
1
        upsert_conjure_timing_stats(
570
1
            &path,
571
1
            RecordedConjureStats {
572
1
                conjure_wall_clock_time: 0.572383542,
573
1
                conjure_translation_time: 0.572305542,
574
1
                conjure_driver_translation_time: 0.566305542,
575
1
                savilerow_translation_time: 0.006,
576
1
                conjure_solve_time: 0.000078,
577
1
            },
578
1
        )
579
1
        .unwrap();
580

            
581
1
        for (solver, translation_time) in [("minion", 1.0), ("sat-log", 2.0)] {
582
2
            let config = RecordedRunConfig {
583
2
                parser: "tree-sitter".to_string(),
584
2
                rewriter: "optimised".to_string(),
585
2
                comprehension_expander: "auto".to_string(),
586
2
                heuristic: "x".to_string(),
587
2
                channelling: "no".to_string(),
588
2
                seed: 0,
589
2
                solver_seed: 0,
590
2
                solver: solver.to_string(),
591
2
            };
592
2
            let rows = (0..2)
593
                .map(|model_index| RecordedRunStats {
594
4
                    parser: config.parser.clone(),
595
4
                    rewriter: config.rewriter.clone(),
596
4
                    comprehension_expander: config.comprehension_expander.clone(),
597
4
                    heuristic: config.heuristic.clone(),
598
4
                    channelling: config.channelling.clone(),
599
4
                    solver: config.solver.clone(),
600
4
                    case_name: format!("tree-sitter-auto-model-{model_index:03}"),
601
4
                    model_index,
602
4
                    choice_path: vec![model_index],
603
4
                    choices: vec![format!("choice-{model_index}")],
604
4
                    status: "ok".to_owned(),
605
4
                    translation_time: Some(translation_time),
606
4
                    solve_time: Some(3.0),
607
4
                    rule_trace: RecordedRuleTraceStats {
608
4
                        total_rule_attempts: Some(4),
609
4
                        total_rule_applications: Some(model_index as u64 + 1),
610
4
                        rules: BTreeMap::from([("rule_name".to_owned(), model_index as u64 + 1)]),
611
4
                    },
612
4
                    ..RecordedRunStats::default()
613
4
                })
614
                .collect();
615
2
            replace_config_run_stats(&path, &config, rows).unwrap();
616
        }
617

            
618
1
        let contents = fs::read_to_string(&path).unwrap();
619
1
        let document: toml::Value = toml::from_str(&contents).unwrap();
620
1
        assert!(document.get("model-runs").is_none());
621
1
        assert_eq!(document["runs"].as_array().unwrap().len(), 4);
622
1
        assert_eq!(
623
1
            document["conjure"]["wall-clock-time"].as_float(),
624
1
            Some(0.572384)
625
        );
626
1
        let stats = read_stats_or_default(&path).unwrap();
627
1
        assert_eq!(stats.expected_time, Some(1));
628
1
        for (index, run) in stats.runs.iter().enumerate() {
629
4
            assert_eq!(run.model_index, index % 2);
630
4
            assert_eq!(run.choice_path, vec![index % 2]);
631
4
            assert_eq!(
632
4
                run.rule_trace.total_rule_applications,
633
4
                Some((index % 2) as u64 + 1)
634
            );
635
4
            assert_eq!(run.rule_trace.rules["rule_name"], (index % 2) as u64 + 1);
636
4
            assert_eq!(
637
4
                run.translation_time,
638
4
                Some(if index < 2 { 1.0 } else { 2.0 })
639
            );
640
        }
641
1
    }
642

            
643
    #[test]
644
1
    fn replacing_a_portfolio_preserves_other_configurations_and_partial_failures() {
645
1
        let temp_dir = tempfile::tempdir().unwrap();
646
1
        let path = temp_dir.path().join(STATS_FILE_NAME);
647
1
        let config = RecordedRunConfig {
648
1
            parser: "tree-sitter".to_owned(),
649
1
            solver: "minion".to_owned(),
650
1
            rewriter: "optimised".to_owned(),
651
1
            comprehension_expander: "auto".to_owned(),
652
1
            heuristic: "x".to_owned(),
653
1
            channelling: "no".to_owned(),
654
1
            seed: 42,
655
1
            solver_seed: 7,
656
1
        };
657
        let row = |model_index| RecordedRunStats {
658
4
            parser: config.parser.clone(),
659
4
            solver: config.solver.clone(),
660
4
            rewriter: config.rewriter.clone(),
661
4
            comprehension_expander: config.comprehension_expander.clone(),
662
4
            heuristic: config.heuristic.clone(),
663
4
            channelling: config.channelling.clone(),
664
4
            seed: config.seed,
665
4
            solver_seed: config.solver_seed,
666
4
            model_index,
667
4
            status: "ok".to_owned(),
668
4
            ..RecordedRunStats::default()
669
4
        };
670
1
        replace_config_run_stats(&path, &config, vec![row(1), row(0)]).unwrap();
671
1
        let other_config = RecordedRunConfig {
672
1
            solver_seed: 8,
673
1
            ..config.clone()
674
1
        };
675
1
        replace_config_run_stats(
676
1
            &path,
677
1
            &other_config,
678
1
            vec![RecordedRunStats {
679
1
                solver_seed: 8,
680
1
                ..row(0)
681
1
            }],
682
1
        )
683
1
        .unwrap();
684
1
        let mut failed = row(0);
685
1
        failed.status = "fail".to_owned();
686
1
        failed.translation_time = Some(1.25);
687
1
        replace_config_run_stats(&path, &config, vec![failed]).unwrap();
688
1
        let stats = read_stats_or_default(&path).unwrap();
689
1
        assert_eq!(stats.runs.len(), 2);
690
1
        assert_eq!(stats.runs[0].seed, 42);
691
1
        assert_eq!(stats.runs[0].solver_seed, 7);
692
1
        assert_eq!(stats.runs[0].status, "fail");
693
1
        assert_eq!(stats.runs[0].translation_time, Some(1.25));
694
1
        assert_eq!(stats.runs[0].solve_time, None);
695
1
        assert_eq!(stats.runs[1].solver_seed, 8);
696
1
        assert_eq!(stats.runs[1].status, "ok");
697
1
    }
698

            
699
    #[test]
700
1
    fn resetting_stats_discards_the_previous_snapshot() {
701
1
        let temp_dir = tempfile::tempdir().unwrap();
702
1
        let path = temp_dir.path().join(STATS_FILE_NAME);
703
1
        fs::write(
704
1
            &path,
705
1
            "status = \"fail\"\n\n[[runs]]\ncomprehension-expander = \"native\"\nstatus = \"fail\"\n",
706
1
        )
707
1
        .unwrap();
708

            
709
1
        let previous = read_stats_or_default(&path).unwrap();
710
1
        assert_eq!(previous.runs[0].solver, "");
711

            
712
1
        reset_stats_for_run(&path).unwrap();
713

            
714
1
        assert_eq!(fs::read_to_string(path).unwrap(), "");
715
1
    }
716
}