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