Skip to main content

unitype_runtime/
conform.rs

1//! Checking that the proofs of one proposition agree.
2//!
3//! A proposition with several proofs is only useful if they all prove the *same*
4//! thing. The type system gets part of the way — every proof is held to the
5//! signature at the boundary — but a signature says what shape comes back, not
6//! what is in it. `sort` and `reverse` have the same type.
7//!
8//! So the rest is done by running them against the same inputs and comparing.
9//! Where an expected answer is given, every proof is held to it; where none is,
10//! the proofs are held to each other, which catches a disagreement without
11//! anyone having to know which side is right.
12//!
13//! # What is being compared
14//!
15//! Values, not text. Two encoders that write the same number differently, or
16//! the same object with its keys in a different order, agree — and would look
17//! like they disagreed if this compared what they printed.
18
19use std::collections::BTreeMap;
20
21use serde::{Deserialize, Serialize};
22use unitype_core::QualifiedName;
23use unitype_core::ir::Type;
24use unitype_core::value::Value;
25
26use crate::dispatch::{Dispatcher, Policy};
27use crate::implementation::ImplId;
28
29/// The vector-file format this build reads.
30pub const SUITE_VERSION: &str = "1.0";
31
32/// One case: what to pass, and what should come back.
33#[derive(Clone, Debug, Serialize, Deserialize)]
34pub struct Vector {
35    /// What this case is called, so a failure can be talked about.
36    pub name: String,
37    /// The arguments, in declaration order.
38    pub args: Vec<serde_json::Value>,
39    /// What should come back.
40    ///
41    /// Left out, the proofs are compared against each other instead. That is
42    /// worth doing on its own: it finds a disagreement without anyone having to
43    /// work out the right answer first.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub expect: Option<serde_json::Value>,
46}
47
48/// A set of cases for one proposition.
49#[derive(Clone, Debug, Serialize, Deserialize)]
50pub struct Suite {
51    /// The format version.
52    #[serde(default = "default_version")]
53    pub version: String,
54    /// The proposition being checked.
55    pub signature: QualifiedName,
56    /// How close two floats have to be to count as equal.
57    ///
58    /// Zero means exactly. Anything else is an admission that two languages
59    /// will not agree to the last bit, which for floating point is usually
60    /// true and always worth stating rather than assuming.
61    #[serde(default)]
62    pub float_tolerance: f64,
63    /// The cases.
64    pub vectors: Vec<Vector>,
65}
66
67fn default_version() -> String {
68    SUITE_VERSION.to_string()
69}
70
71/// What became of one proof on one case.
72#[derive(Clone, Debug, PartialEq)]
73pub enum Answer {
74    /// It ran and produced this.
75    Value(Value),
76    /// It ran and failed.
77    Failed(String),
78    /// It could not be run here.
79    Skipped(String),
80}
81
82impl Answer {
83    /// The value, if there is one.
84    pub fn value(&self) -> Option<&Value> {
85        match self {
86            Answer::Value(v) => Some(v),
87            _ => None,
88        }
89    }
90
91    /// A short description, for a report.
92    pub fn summary(&self) -> String {
93        match self {
94            Answer::Value(v) => v.to_json_string().unwrap_or_else(|_| "<unwritable>".into()),
95            Answer::Failed(why) => format!("failed: {why}"),
96            Answer::Skipped(why) => format!("skipped: {why}"),
97        }
98    }
99}
100
101/// How one case went.
102#[derive(Clone, Debug)]
103pub struct Case {
104    /// The case's name.
105    pub name: String,
106    /// What each proof said.
107    pub answers: BTreeMap<ImplId, Answer>,
108    /// Proofs grouped by what they said, so a disagreement shows its sides.
109    pub agreement: Vec<Vec<ImplId>>,
110    /// Whether every proof that ran said the same thing.
111    pub agreed: bool,
112    /// Proofs that disagreed with the expected answer, where one was given.
113    pub wrong: Vec<ImplId>,
114}
115
116/// How a whole suite went.
117#[derive(Clone, Debug)]
118pub struct Report {
119    /// The proposition checked.
120    pub signature: QualifiedName,
121    /// Every proof that took part.
122    pub proofs: Vec<ImplId>,
123    /// Each case.
124    pub cases: Vec<Case>,
125}
126
127impl Report {
128    /// Whether every case came out with everyone agreeing.
129    pub fn agreed(&self) -> bool {
130        self.cases.iter().all(|c| c.agreed && c.wrong.is_empty())
131    }
132
133    /// The cases where something disagreed.
134    pub fn disagreements(&self) -> Vec<&Case> {
135        self.cases
136            .iter()
137            .filter(|c| !c.agreed || !c.wrong.is_empty())
138            .collect()
139    }
140}
141
142/// Why a suite could not be run.
143#[derive(thiserror::Error, Debug)]
144pub enum ConformError {
145    /// The file was not a suite.
146    #[error("invalid vector file: {0}")]
147    Malformed(#[from] serde_json::Error),
148    /// The suite is from a version this build does not read.
149    #[error("this vector file is version {found}; this build reads {expected}")]
150    Version {
151        /// What it said.
152        found: String,
153        /// What this build knows.
154        expected: &'static str,
155    },
156    /// The proposition is not in the workspace.
157    #[error("`{0}` is not a proposition in this workspace")]
158    UnknownSignature(QualifiedName),
159    /// Nothing proves it, so there is nothing to compare.
160    #[error("nothing proves `{0}`, so there is nothing to compare")]
161    NoProofs(QualifiedName),
162    /// A case's arguments were not what the signature takes.
163    #[error("case `{name}`: {detail}")]
164    BadVector {
165        /// The case.
166        name: String,
167        /// What was wrong.
168        detail: String,
169    },
170}
171
172impl Suite {
173    /// Reads a suite.
174    pub fn from_json(text: &str) -> Result<Self, ConformError> {
175        let suite: Suite = serde_json::from_str(text)?;
176        if suite.version != SUITE_VERSION {
177            return Err(ConformError::Version {
178                found: suite.version,
179                expected: SUITE_VERSION,
180            });
181        }
182        Ok(suite)
183    }
184}
185
186/// Runs every proof of a proposition against every case.
187pub async fn run(dispatcher: &Dispatcher, suite: &Suite) -> Result<Report, ConformError> {
188    let ws = dispatcher.workspace();
189    let Some(sig) = ws.sig(&suite.signature) else {
190        return Err(ConformError::UnknownSignature(suite.signature.clone()));
191    };
192
193    // Every proof, not the one a policy would pick: the whole point is to try
194    // them all.
195    let proofs: Vec<ImplId> = dispatcher
196        .candidates(&suite.signature, &Policy::Default)
197        .iter()
198        .map(|i| i.id.clone())
199        .collect();
200    if proofs.is_empty() {
201        return Err(ConformError::NoProofs(suite.signature.clone()));
202    }
203
204    let expected_type = match &sig.ret {
205        Type::Future { of } => (**of).clone(),
206        other => other.clone(),
207    };
208
209    let mut cases = Vec::with_capacity(suite.vectors.len());
210    for vector in &suite.vectors {
211        // Arguments are read against the parameters, so a case is written the
212        // way the data is written rather than the way a decoder guesses.
213        if vector.args.len() != sig.params.len() {
214            return Err(ConformError::BadVector {
215                name: vector.name.clone(),
216                detail: format!(
217                    "`{}` takes {} argument(s), but this gives {}",
218                    suite.signature,
219                    sig.params.len(),
220                    vector.args.len()
221                ),
222            });
223        }
224        let mut args = Vec::with_capacity(vector.args.len());
225        for (param, given) in sig.params.iter().zip(&vector.args) {
226            args.push(
227                ws.read(given, &param.ty)
228                    .map_err(|e| ConformError::BadVector {
229                        name: vector.name.clone(),
230                        detail: format!("argument `{}`: {e}", param.name),
231                    })?,
232            );
233        }
234
235        let expected = match &vector.expect {
236            Some(json) => {
237                Some(
238                    ws.read(json, &expected_type)
239                        .map_err(|e| ConformError::BadVector {
240                            name: vector.name.clone(),
241                            detail: format!("the expected answer is not a `{expected_type}`: {e}"),
242                        })?,
243                )
244            }
245            None => None,
246        };
247
248        let mut answers: BTreeMap<ImplId, Answer> = BTreeMap::new();
249        for id in &proofs {
250            let answer = match dispatcher
251                .call(&suite.signature, args.clone(), &Policy::Pinned(id.clone()))
252                .await
253            {
254                Ok(invocation) => Answer::Value(invocation.value),
255                Err(error) => {
256                    // A machine without Python is not a disagreement between
257                    // proofs, so it is set aside rather than counted as one.
258                    if unavailable(&error) {
259                        Answer::Skipped(error.to_string())
260                    } else {
261                        Answer::Failed(error.to_string())
262                    }
263                }
264            };
265            answers.insert(id.clone(), answer);
266        }
267
268        let agreement = group(&answers, suite.float_tolerance);
269        let wrong: Vec<ImplId> = match &expected {
270            Some(want) => answers
271                .iter()
272                .filter(|(_, answer)| match answer {
273                    Answer::Value(got) => !alike(got, want, suite.float_tolerance),
274                    Answer::Skipped(_) => false,
275                    Answer::Failed(_) => true,
276                })
277                .map(|(id, _)| id.clone())
278                .collect(),
279            None => Vec::new(),
280        };
281
282        cases.push(Case {
283            name: vector.name.clone(),
284            agreed: agreement.len() <= 1,
285            agreement,
286            wrong,
287            answers,
288        });
289    }
290
291    Ok(Report {
292        signature: suite.signature.clone(),
293        proofs,
294        cases,
295    })
296}
297
298/// Whether a failure was the environment's rather than the proof's.
299pub(crate) fn unavailable(error: &crate::error::DispatchError) -> bool {
300    match error {
301        crate::error::DispatchError::Exec { source, .. } => source.is_environmental(),
302        crate::error::DispatchError::Unusable { .. }
303        | crate::error::DispatchError::NoneAvailable { .. } => true,
304        _ => false,
305    }
306}
307
308/// Proofs grouped by what they said. More than one group is a disagreement.
309fn group(answers: &BTreeMap<ImplId, Answer>, tolerance: f64) -> Vec<Vec<ImplId>> {
310    let mut groups: Vec<(Value, Vec<ImplId>)> = Vec::new();
311    for (id, answer) in answers {
312        // Something that did not run has no opinion, so it is not a side.
313        let Answer::Value(value) = answer else {
314            continue;
315        };
316        match groups
317            .iter_mut()
318            .find(|(seen, _)| alike(seen, value, tolerance))
319        {
320            Some((_, members)) => members.push(id.clone()),
321            None => groups.push((value.clone(), vec![id.clone()])),
322        }
323    }
324    groups.into_iter().map(|(_, members)| members).collect()
325}
326
327/// Whether two values say the same thing.
328///
329/// Compared as values rather than as text, so that two encoders which write a
330/// number differently, or an object with its keys in another order, still
331/// agree. Floats are compared within whatever slack the suite allows, because
332/// two languages computing the same thing will not always land on the same bit.
333pub fn alike(a: &Value, b: &Value, tolerance: f64) -> bool {
334    match (a, b) {
335        (Value::Float(x), Value::Float(y)) => {
336            x == y || (tolerance > 0.0 && (x - y).abs() <= tolerance)
337        }
338        // A whole number and the same number written as a float are the same
339        // number, which is the sort of thing languages differ about.
340        (Value::Int(x), Value::Float(y)) | (Value::Float(y), Value::Int(x)) => {
341            let x = *x as f64;
342            x == *y || (tolerance > 0.0 && (x - y).abs() <= tolerance)
343        }
344        (Value::List(x), Value::List(y)) | (Value::Tuple(x), Value::Tuple(y)) => {
345            x.len() == y.len() && x.iter().zip(y).all(|(p, q)| alike(p, q, tolerance))
346        }
347        (Value::Record(x), Value::Record(y)) => {
348            // Key order is not information.
349            x.len() == y.len()
350                && x.iter()
351                    .all(|(k, v)| y.get(k).is_some_and(|other| alike(v, other, tolerance)))
352        }
353        (Value::Map(x), Value::Map(y)) => {
354            x.len() == y.len()
355                && x.iter().all(|(k, v)| {
356                    y.iter()
357                        .any(|(k2, v2)| alike(k, k2, tolerance) && alike(v, v2, tolerance))
358                })
359        }
360        (Value::Variant { tag: a, value: x }, Value::Variant { tag: b, value: y }) => {
361            a == b && alike(x, y, tolerance)
362        }
363        _ => a == b,
364    }
365}
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370    use std::sync::Arc;
371    use unitype_core::check::check_workspace;
372    use unitype_core::{BigO, Ident, ImplProfile, Workspace};
373
374    use crate::implementation::Implementation;
375    use crate::registry::Registry;
376
377    const WS: &str = r#"{"universes":[{"name":"demo","functions":[
378        {"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"}]}]}"#;
379
380    fn ints(value: &Value) -> Vec<i64> {
381        let Value::List(items) = value else {
382            return Vec::new();
383        };
384        items.iter().filter_map(Value::as_int).collect()
385    }
386
387    fn list(items: &[i64]) -> serde_json::Value {
388        serde_json::json!(items)
389    }
390
391    /// A dispatcher with the proofs named, each behaving as its name suggests.
392    fn dispatcher(proofs: &[&str]) -> Dispatcher {
393        let ws =
394            Arc::new(check_workspace(Workspace::from_json(WS).expect("reads")).expect("checks"));
395        let mut registry = Registry::new();
396
397        registry.register_native_sync("sorts", |args| {
398            let mut items = ints(&args[0]);
399            items.sort_unstable();
400            Ok(Value::List(items.into_iter().map(Value::Int).collect()))
401        });
402        registry.register_native_sync("also_sorts", |args| {
403            // The same answer by a different route.
404            let mut items = ints(&args[0]);
405            for i in 0..items.len() {
406                for j in 0..items.len().saturating_sub(i + 1) {
407                    if items[j] > items[j + 1] {
408                        items.swap(j, j + 1);
409                    }
410                }
411            }
412            Ok(Value::List(items.into_iter().map(Value::Int).collect()))
413        });
414        registry.register_native_sync("reverses", |args| {
415            // The right *type*, the wrong answer — which is exactly what a
416            // signature cannot catch.
417            let mut items = ints(&args[0]);
418            items.reverse();
419            Ok(Value::List(items.into_iter().map(Value::Int).collect()))
420        });
421        registry.register_native_sync("gives_up", |_| {
422            Err(crate::ExecError::Failed {
423                id: "gives_up".into(),
424                message: "not today".into(),
425            })
426        });
427
428        for entry in proofs {
429            registry
430                .register(Implementation::new(
431                    *entry,
432                    "demo::sort".parse().unwrap(),
433                    Ident::new("here").unwrap(),
434                    *entry,
435                    ImplProfile::new(BigO::ON, BigO::ON),
436                ))
437                .expect("registers");
438        }
439        Dispatcher::new(ws, Arc::new(registry))
440    }
441
442    fn suite(vectors: Vec<Vector>) -> Suite {
443        Suite {
444            version: SUITE_VERSION.into(),
445            signature: "demo::sort".parse().unwrap(),
446            float_tolerance: 0.0,
447            vectors,
448        }
449    }
450
451    fn case(name: &str, input: &[i64], expect: Option<&[i64]>) -> Vector {
452        Vector {
453            name: name.into(),
454            args: vec![list(input)],
455            expect: expect.map(list),
456        }
457    }
458
459    #[tokio::test]
460    async fn proofs_that_agree_are_reported_as_agreeing() {
461        let report = run(
462            &dispatcher(&["sorts", "also_sorts"]),
463            &suite(vec![
464                case("already in order", &[1, 2, 3], None),
465                case("backwards", &[3, 2, 1], None),
466            ]),
467        )
468        .await
469        .expect("runs");
470
471        assert!(report.agreed(), "{:?}", report.disagreements());
472        assert_eq!(report.proofs.len(), 2);
473    }
474
475    #[tokio::test]
476    async fn a_proof_of_the_wrong_thing_is_caught_where_the_type_could_not_catch_it() {
477        // `reverse` has exactly the type `sort` has. Nothing about the
478        // signature separates them; only running both does.
479        let report = run(
480            &dispatcher(&["sorts", "reverses"]),
481            &suite(vec![case("backwards", &[3, 1, 2], None)]),
482        )
483        .await
484        .expect("runs");
485
486        assert!(!report.agreed());
487        let disagreement = report.disagreements()[0];
488        assert_eq!(
489            disagreement.agreement.len(),
490            2,
491            "there should be two sides: {:?}",
492            disagreement.agreement
493        );
494    }
495
496    #[tokio::test]
497    async fn an_input_they_happen_to_agree_on_does_not_hide_a_disagreement_elsewhere() {
498        // Sorting and reversing agree on a single-element list. A suite with
499        // only that case would pass, which is why the report is per case.
500        let report = run(
501            &dispatcher(&["sorts", "reverses"]),
502            &suite(vec![
503                case("one thing", &[7], None),
504                case("several", &[3, 1, 2], None),
505            ]),
506        )
507        .await
508        .expect("runs");
509
510        assert!(report.cases[0].agreed, "they do agree about this one");
511        assert!(!report.cases[1].agreed, "and disagree about this one");
512        assert!(!report.agreed());
513    }
514
515    #[tokio::test]
516    async fn an_expected_answer_holds_every_proof_to_it() {
517        let report = run(
518            &dispatcher(&["sorts", "reverses"]),
519            &suite(vec![case("backwards", &[3, 1, 2], Some(&[1, 2, 3]))]),
520        )
521        .await
522        .expect("runs");
523
524        let wrong: Vec<String> = report.cases[0]
525            .wrong
526            .iter()
527            .map(ToString::to_string)
528            .collect();
529        assert_eq!(wrong, ["reverses"], "the right one should not be blamed");
530    }
531
532    #[tokio::test]
533    async fn a_proof_that_fails_is_a_disagreement_with_an_expected_answer() {
534        let report = run(
535            &dispatcher(&["sorts", "gives_up"]),
536            &suite(vec![case("anything", &[2, 1], Some(&[1, 2]))]),
537        )
538        .await
539        .expect("runs");
540
541        assert_eq!(report.cases[0].wrong.len(), 1);
542        assert!(matches!(
543            report.cases[0].answers[&ImplId::new("gives_up")],
544            Answer::Failed(_)
545        ));
546    }
547
548    #[tokio::test]
549    async fn a_proposition_nothing_proves_says_so_rather_than_passing_vacuously() {
550        let ws =
551            Arc::new(check_workspace(Workspace::from_json(WS).expect("reads")).expect("checks"));
552        let empty = Dispatcher::new(ws, Arc::new(Registry::new()));
553        assert!(matches!(
554            run(&empty, &suite(vec![case("anything", &[1], None)])).await,
555            Err(ConformError::NoProofs(_))
556        ));
557    }
558
559    #[tokio::test]
560    async fn a_case_with_the_wrong_arguments_is_reported_before_anything_runs() {
561        let bad = Suite {
562            vectors: vec![Vector {
563                name: "wrong shape".into(),
564                args: vec![serde_json::json!("not a list")],
565                expect: None,
566            }],
567            ..suite(vec![])
568        };
569        assert!(matches!(
570            run(&dispatcher(&["sorts"]), &bad).await,
571            Err(ConformError::BadVector { .. })
572        ));
573    }
574
575    #[test]
576    fn a_suite_reads_the_way_someone_would_write_one() {
577        let suite = Suite::from_json(
578            r#"{"signature":"demo::sort",
579                "vectors":[
580                    {"name":"backwards","args":[[3,1,2]],"expect":[1,2,3]},
581                    {"name":"empty","args":[[]]}]}"#,
582        )
583        .expect("reads");
584
585        assert_eq!(suite.signature.to_string(), "demo::sort");
586        assert_eq!(suite.vectors.len(), 2);
587        assert!(
588            suite.vectors[1].expect.is_none(),
589            "a case may leave the answer to the proofs"
590        );
591    }
592
593    #[test]
594    fn a_suite_from_a_later_version_is_refused_rather_than_guessed_at() {
595        assert!(matches!(
596            Suite::from_json(r#"{"version":"9.9","signature":"demo::sort","vectors":[]}"#),
597            Err(ConformError::Version { .. })
598        ));
599    }
600
601    #[test]
602    fn two_encoders_writing_the_same_thing_differently_still_agree() {
603        assert!(alike(&Value::Int(2), &Value::Float(2.0), 0.0));
604        assert!(alike(
605            &Value::record([("a", Value::Int(1)), ("b", Value::Int(2))]),
606            &Value::record([("b", Value::Int(2)), ("a", Value::Int(1))]),
607            0.0,
608        ));
609    }
610
611    #[test]
612    fn floats_agree_within_whatever_slack_was_allowed() {
613        let a = Value::Float(0.1 + 0.2);
614        let b = Value::Float(0.3);
615        assert!(!alike(&a, &b, 0.0), "exactly means exactly");
616        assert!(alike(&a, &b, 1e-9), "and this is the honest amount");
617    }
618}