1
//! Execution statistics shared by the CLI and exhaustive tests.
2

            
3
use serde::{Deserialize, Serialize};
4
use std::fs;
5
use std::io;
6
use std::path::Path;
7

            
8
/// The statistics format selected by an output file's extension.
9
#[derive(Clone, Copy, Debug)]
10
pub enum StatsFormat {
11
    Toml,
12
    Json,
13
}
14

            
15
impl StatsFormat {
16
1799
    pub fn from_path(path: &Path) -> io::Result<Self> {
17
1799
        match path.extension().and_then(|extension| extension.to_str()) {
18
1799
            Some("toml") => Ok(Self::Toml),
19
            Some("json") => Ok(Self::Json),
20
            _ => Err(io::Error::new(
21
                io::ErrorKind::InvalidInput,
22
                "statistics path must have a .toml or .json extension",
23
            )),
24
        }
25
1799
    }
26
}
27

            
28
9
fn quoted_toml_string(value: &str) -> String {
29
9
    toml::Value::String(value.to_string()).to_string()
30
9
}
31

            
32
15
pub fn canonical_float(value: f64) -> String {
33
15
    let rounded = (value * 1_000_000.0).round() / 1_000_000.0;
34
15
    let mut rendered = format!("{rounded:.6}");
35
24
    while rendered.ends_with('0') {
36
9
        rendered.pop();
37
    }
38
15
    if rendered.ends_with('.') {
39
        rendered.push('0');
40
15
    }
41
15
    if rendered == "-0.0" {
42
        "0.0".to_string()
43
    } else {
44
15
        rendered
45
    }
46
15
}
47

            
48
6
fn canonical_rule_key(rule: &str) -> String {
49
6
    if !rule.is_empty()
50
6
        && rule
51
6
            .chars()
52
54
            .all(|character| character.is_ascii_alphanumeric() || matches!(character, '_' | '-'))
53
    {
54
6
        rule.to_string()
55
    } else {
56
        quoted_toml_string(rule)
57
    }
58
6
}
59

            
60
3839
pub(super) fn deserialise_expected_time<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
61
3839
where
62
3839
    D: serde::Deserializer<'de>,
63
{
64
3839
    Option::<u64>::deserialize(deserializer)
65
3839
}
66

            
67
/// Identifies one configured exhaustive-test run.
68
#[derive(Clone, Debug, Eq, PartialEq)]
69
pub struct RecordedRunConfig {
70
    pub parser: String,
71
    pub rewriter: String,
72
    pub comprehension_expander: String,
73
    pub heuristic: String,
74
    pub channelling: String,
75
    pub seed: u64,
76
    pub solver_seed: u32,
77
    pub solver: String,
78
}
79

            
80
13
fn rule_trace_rules_by_count_desc(
81
13
    rules: &std::collections::BTreeMap<String, u64>,
82
13
) -> Vec<(&String, u64)> {
83
13
    let mut sorted_rules: Vec<_> = rules.iter().map(|(rule, count)| (rule, *count)).collect();
84
13
    sorted_rules.sort_by(|(name_a, count_a), (name_b, count_b)| {
85
        count_b.cmp(count_a).then_with(|| name_a.cmp(name_b))
86
    });
87
13
    sorted_rules
88
13
}
89

            
90
/// Recorded exhaustive-run metadata for one test directory.
91
#[derive(Deserialize, Serialize, Debug, Default)]
92
#[serde(default)]
93
#[serde(deny_unknown_fields)]
94
pub struct TestRunStats {
95
    /// Latest observed overall status, such as `ok`, `fail`, or `timeout(N)`.
96
    #[serde(skip_serializing_if = "Option::is_none")]
97
    pub status: Option<String>,
98

            
99
    /// Coarse expected wall time bucket used by MAX_EXPECTED_TIME test selection.
100
    #[serde(
101
        default,
102
        rename = "expected-time",
103
        skip_serializing_if = "Option::is_none",
104
        deserialize_with = "deserialise_expected_time"
105
    )]
106
    pub expected_time: Option<u64>,
107

            
108
    /// Metadata recorded for the Conjure plus Savile Row reference run.
109
    #[serde(skip_serializing_if = "RecordedToolStats::is_empty")]
110
    pub conjure: RecordedToolStats,
111

            
112
    /// One measured run per compiled model, including each expanded `x` choice.
113
    pub runs: Vec<RecordedRunStats>,
114
}
115

            
116
/// Flat timing and resolved modelling choices for one actual exhaustive model.
117
#[derive(Deserialize, Serialize, Debug, Default)]
118
#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
119
pub struct RecordedRunStats {
120
    pub parser: String,
121
    pub rewriter: String,
122
    pub comprehension_expander: String,
123
    pub heuristic: String,
124
    pub channelling: String,
125
    pub seed: u64,
126
    pub solver_seed: u32,
127
    pub solver: String,
128
    pub case_name: String,
129
    pub model_index: usize,
130
    /// Full realised choice indices and labels, rather than the replay prefix.
131
    pub choice_path: Vec<usize>,
132
    pub choices: Vec<String>,
133
    /// Distinct representation rules present in the compiled model.
134
    pub representations: Vec<String>,
135
    #[serde(skip_serializing_if = "Option::is_none")]
136
    pub minion_discrete_threshold: Option<usize>,
137
    pub sat_encoding_amo: Vec<String>,
138
    pub sat_encoding_cardinality: Vec<String>,
139
    pub sat_encoding_pb: Vec<String>,
140
    pub sat_encoding_table: Vec<String>,
141
    pub sat_encoding_element: Vec<String>,
142
    pub sat_encoding_alldifferent: Vec<String>,
143
    pub status: String,
144
    /// Zero means all solutions; absent means translation only.
145
    #[serde(skip_serializing_if = "Option::is_none")]
146
    pub solution_limit: Option<i32>,
147
    /// Wall time for parsing, instantiation and rewriting.
148
    #[serde(skip_serializing_if = "Option::is_none")]
149
    pub translation_time: Option<f64>,
150
    /// Wall time for complete solution collection and output.
151
    #[serde(skip_serializing_if = "Option::is_none")]
152
    pub solve_time: Option<f64>,
153
    #[serde(skip_serializing_if = "Option::is_none")]
154
    pub backend_time: Option<f64>,
155
    /// Solver-call wall time, including callbacks and solver-time rewrites.
156
    #[serde(skip_serializing_if = "Option::is_none")]
157
    pub search_time: Option<f64>,
158
    #[serde(skip_serializing_if = "Option::is_none")]
159
    pub solution_processing_time: Option<f64>,
160
    /// Rule counts for this compiled model; written as dotted keys by the canonical writer.
161
    #[serde(skip_serializing_if = "RecordedRuleTraceStats::is_empty")]
162
    pub rule_trace: RecordedRuleTraceStats,
163
}
164

            
165
/// Recorded rule counts for one compiled model.
166
#[derive(Deserialize, Serialize, Debug, Default)]
167
#[serde(default)]
168
#[serde(deny_unknown_fields)]
169
pub struct RecordedRuleTraceStats {
170
    #[serde(rename = "attempts", skip_serializing_if = "Option::is_none")]
171
    pub total_rule_attempts: Option<u64>,
172
    #[serde(rename = "applications", skip_serializing_if = "Option::is_none")]
173
    pub total_rule_applications: Option<u64>,
174
    #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
175
    pub rules: std::collections::BTreeMap<String, u64>,
176
}
177

            
178
impl RecordedRuleTraceStats {
179
26
    fn is_empty(&self) -> bool {
180
26
        self.total_rule_attempts.is_none()
181
14
            && self.total_rule_applications.is_none()
182
14
            && self.rules.is_empty()
183
26
    }
184
}
185

            
186
1791
pub fn read_stats_or_default(path: &Path) -> io::Result<TestRunStats> {
187
1791
    if path.exists() {
188
1790
        let contents = fs::read_to_string(path)?;
189
1790
        match StatsFormat::from_path(path)? {
190
1790
            StatsFormat::Toml => toml::from_str(&contents)
191
                .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)),
192
            StatsFormat::Json => serde_json::from_str(&contents)
193
                .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)),
194
        }
195
    } else {
196
1
        Ok(TestRunStats::default())
197
    }
198
1791
}
199

            
200
/// Recorded status and timings for one implementation in a test config.
201
#[derive(Deserialize, Serialize, Debug, Default)]
202
#[serde(default)]
203
#[serde(deny_unknown_fields)]
204
pub struct RecordedToolStats {
205
    /// Latest observed status, such as `ok`, `fail`, or `timeout(N)`.
206
    #[serde(skip_serializing_if = "Option::is_none")]
207
    pub status: Option<String>,
208

            
209
    /// Translation time in seconds.
210
    #[serde(rename = "translation-time", skip_serializing_if = "Option::is_none")]
211
    pub translation_time: Option<f64>,
212

            
213
    /// Solver time in seconds.
214
    #[serde(rename = "solve-time", skip_serializing_if = "Option::is_none")]
215
    pub solve_time: Option<f64>,
216

            
217
    /// Wall-clock time of the complete tool command, in seconds, when available.
218
    #[serde(rename = "wall-clock-time", skip_serializing_if = "Option::is_none")]
219
    pub wall_clock_time: Option<f64>,
220

            
221
    /// Conjure-only translation time in seconds, when available.
222
    #[serde(
223
        rename = "conjure-translation-time",
224
        skip_serializing_if = "Option::is_none"
225
    )]
226
    pub conjure_translation_time: Option<f64>,
227

            
228
    /// Savile Row translation time in seconds, when available.
229
    #[serde(
230
        rename = "savilerow-translation-time",
231
        skip_serializing_if = "Option::is_none"
232
    )]
233
    pub savilerow_translation_time: Option<f64>,
234
}
235

            
236
impl RecordedToolStats {
237
11
    fn is_empty(&self) -> bool {
238
11
        self.status.is_none()
239
7
            && self.translation_time.is_none()
240
7
            && self.solve_time.is_none()
241
7
            && self.wall_clock_time.is_none()
242
7
            && self.conjure_translation_time.is_none()
243
7
            && self.savilerow_translation_time.is_none()
244
11
    }
245
}
246

            
247
/// Replace this configuration's model rows, removing stale portfolio entries.
248
5
pub fn replace_config_run_stats(
249
5
    path: &Path,
250
5
    config: &RecordedRunConfig,
251
5
    rows: Vec<RecordedRunStats>,
252
5
) -> io::Result<()> {
253
5
    update_canonical_stats(path, |stats| {
254
7
        stats.runs.retain(|row| {
255
7
            !(row.parser == config.parser
256
7
                && row.rewriter == config.rewriter
257
7
                && row.comprehension_expander == config.comprehension_expander
258
7
                && row.heuristic == config.heuristic
259
7
                && row.channelling == config.channelling
260
7
                && row.seed == config.seed
261
7
                && row.solver_seed == config.solver_seed
262
4
                && row.solver == config.solver)
263
7
        });
264
5
        stats.runs.extend(rows);
265
8
        stats.runs.sort_by(|a, b| {
266
8
            (
267
8
                &a.parser,
268
8
                &a.rewriter,
269
8
                &a.comprehension_expander,
270
8
                &a.heuristic,
271
8
                &a.channelling,
272
8
                a.seed,
273
8
                a.solver_seed,
274
8
                &a.solver,
275
8
                a.model_index,
276
8
            )
277
8
                .cmp(&(
278
8
                    &b.parser,
279
8
                    &b.rewriter,
280
8
                    &b.comprehension_expander,
281
8
                    &b.heuristic,
282
8
                    &b.channelling,
283
8
                    b.seed,
284
8
                    b.solver_seed,
285
8
                    &b.solver,
286
8
                    b.model_index,
287
8
                ))
288
8
        });
289
5
    })
290
5
}
291

            
292
9
pub fn update_canonical_stats(
293
9
    path: &Path,
294
9
    update: impl FnOnce(&mut TestRunStats),
295
9
) -> io::Result<()> {
296
9
    let mut stats = read_stats_or_default(path)?;
297
9
    update(&mut stats);
298
9
    write_stats(path, &stats)
299
9
}
300

            
301
/// Write the same statistics schema as TOML or JSON, selected by the extension.
302
9
pub fn write_stats(path: &Path, stats: &TestRunStats) -> io::Result<()> {
303
9
    match StatsFormat::from_path(path)? {
304
9
        StatsFormat::Toml => write_canonical_stats(path, stats),
305
        StatsFormat::Json => {
306
            let contents = serde_json::to_string_pretty(stats)
307
                .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
308
            fs::write(path, format!("{contents}\n"))
309
        }
310
    }
311
9
}
312

            
313
20
fn push_optional_float(contents: &mut String, key: &str, value: Option<f64>) {
314
20
    if let Some(value) = value {
315
15
        contents.push_str(key);
316
15
        contents.push_str(" = ");
317
15
        contents.push_str(&canonical_float(value));
318
15
        contents.push('\n');
319
5
    }
320
20
}
321

            
322
11
pub fn write_canonical_stats(path: &Path, stats: &TestRunStats) -> io::Result<()> {
323
11
    let mut contents = String::new();
324

            
325
11
    if let Some(expected_time) = stats.expected_time {
326
6
        contents.push_str(&format!("expected-time = {expected_time}\n"));
327
5
    }
328
11
    if let Some(status) = &stats.status {
329
5
        contents.push_str(&format!("status = {}\n", quoted_toml_string(status)));
330
6
    }
331

            
332
11
    let conjure = &stats.conjure;
333
11
    if !conjure.is_empty() {
334
4
        if !contents.is_empty() {
335
4
            contents.push('\n');
336
        }
337
4
        contents.push_str("[conjure]\n");
338
4
        if let Some(status) = &conjure.status {
339
4
            contents.push_str(&format!("status = {}\n", quoted_toml_string(status)));
340
        }
341
4
        push_optional_float(&mut contents, "wall-clock-time", conjure.wall_clock_time);
342
4
        push_optional_float(&mut contents, "translation-time", conjure.translation_time);
343
4
        push_optional_float(
344
4
            &mut contents,
345
4
            "conjure-translation-time",
346
4
            conjure.conjure_translation_time,
347
4
        );
348
4
        push_optional_float(
349
4
            &mut contents,
350
4
            "savilerow-translation-time",
351
4
            conjure.savilerow_translation_time,
352
4
        );
353
4
        push_optional_float(&mut contents, "solve-time", conjure.solve_time);
354
7
    }
355

            
356
11
    for run in &stats.runs {
357
13
        contents.push_str("\n[[runs]]\n");
358
        let rendered =
359
13
            toml::to_string(run).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
360
13
        let mut document: toml_edit::DocumentMut = rendered
361
13
            .parse()
362
            .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
363
        // Keep the canonical dotted rule keys below, while the shared data type
364
        // serializes rule counts normally for JSON and its schema.
365
13
        document.remove("rule-trace");
366
13
        contents.push_str(document.to_string().trim_end());
367
13
        contents.push('\n');
368

            
369
13
        if run.rule_trace.total_rule_attempts.is_some()
370
7
            || run.rule_trace.total_rule_applications.is_some()
371
7
            || !run.rule_trace.rules.is_empty()
372
        {
373
6
            contents.push('\n');
374
7
        }
375
13
        if let Some(attempts) = run.rule_trace.total_rule_attempts {
376
6
            contents.push_str(&format!("rule-trace.attempts = {attempts}\n"));
377
7
        }
378
13
        if let Some(applications) = run.rule_trace.total_rule_applications {
379
6
            contents.push_str(&format!("rule-trace.applications = {applications}\n"));
380
7
        }
381
13
        for (rule, count) in rule_trace_rules_by_count_desc(&run.rule_trace.rules) {
382
6
            contents.push_str(&format!(
383
6
                "rule-trace.rules.{} = {count}\n",
384
6
                canonical_rule_key(rule)
385
6
            ));
386
        }
387
    }
388

            
389
11
    fs::write(path, contents)
390
11
}