Skip to main content

crisol_core/data/
conformance.rs

1//! The implementation-independent conformance suite for data backends (SWAP-04).
2//!
3//! A new backend (native Arrow, `f32` columns, a remote source) implements
4//! [`Conformance`] and calls [`run`]. The suite checks schema reporting, paging,
5//! bounds, slicing, and null handling without knowing how the backend stores data.
6//!
7//! ```
8//! use crisol_core::data::conformance::run;
9//! use crisol_core::data::MemorySource;
10//!
11//! run::<MemorySource>().expect("the in-memory backend conforms");
12//! ```
13
14use std::ops::Range;
15
16use super::column::{CellValue, Column, ColumnType};
17use super::dataset::Dataset;
18use super::source::{ColumnSchema, DataSource};
19
20/// A backend that can produce its own fixture.
21///
22/// The fixture must have three rows: `x = [1.0, 2.0, 3.0]`, `n = [1, 2, 3]`, and
23/// `label = ["a", "b", "c"]`, with the middle `x` invalid (null).
24/// # Example
25///
26/// ```
27/// use crisol_core::data::conformance::Conformance;
28/// ```
29pub trait Conformance: DataSource {
30    /// Build the fixture described by the trait documentation.
31    fn fixture() -> Self;
32}
33
34/// One failure from the suite.
35#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
36#[non_exhaustive]
37/// # Example
38///
39/// ```
40/// use crisol_core::data::conformance::ConformanceError;
41/// ```
42pub enum ConformanceError {
43    /// The schema does not have the expected shape.
44    #[error("schema: {0}")]
45    Schema(String),
46    /// A row count is wrong.
47    #[error("row count: expected {expected}, got {actual}")]
48    RowCount {
49        /// Expected rows.
50        expected: usize,
51        /// Actual rows.
52        actual: usize,
53    },
54    /// A page did not have the expected values.
55    #[error("page: {0}")]
56    Page(String),
57    /// A range that should fail did not.
58    #[error("range {0:?} was accepted")]
59    RangeAccepted(Range<usize>),
60    /// The backend could not read a valid range.
61    #[error("read: {0}")]
62    Read(String),
63}
64
65/// Run the full suite against a backend.
66///
67/// # Errors
68/// With the first failed expectation.
69// spec: SWAP-04
70/// # Example
71///
72/// ```
73/// use crisol_core::data::conformance::run;
74/// ```
75pub fn run<Impl: Conformance>() -> Result<(), ConformanceError> {
76    let source = Impl::fixture();
77    check_schema(source.schema())?;
78    if source.row_count() != 3 {
79        return Err(ConformanceError::RowCount {
80            expected: 3,
81            actual: source.row_count(),
82        });
83    }
84    let all = source
85        .read_range(0..3)
86        .map_err(|error| ConformanceError::Read(error.to_string()))?;
87    if all.row_count() != 3 {
88        return Err(ConformanceError::Page(format!(
89            "expected 3 rows, got {}",
90            all.row_count()
91        )));
92    }
93    if all.column(0).map(Column::kind) != Some(ColumnType::Float) {
94        return Err(ConformanceError::Schema("x is not a float column".to_owned()));
95    }
96    if all.cell(1, 0) != CellValue::Null {
97        return Err(ConformanceError::Page("the middle x is not null".to_owned()));
98    }
99    let page = source
100        .read_range(1..3)
101        .map_err(|error| ConformanceError::Read(error.to_string()))?;
102    if page.row_count() != 2 || page.cell(0, 1) != CellValue::Int(2) || page.cell(1, 2) != CellValue::Text("c") {
103        return Err(ConformanceError::Page("the 1..3 page is wrong".to_owned()));
104    }
105    for range in [2..9, 3..4] {
106        if source.read_range(range.clone()).is_ok() {
107            return Err(ConformanceError::RangeAccepted(range));
108        }
109    }
110    let (start, end) = (4, 2);
111    if source.read_range(start..end).is_ok() {
112        return Err(ConformanceError::RangeAccepted(start..end));
113    }
114    Ok(())
115}
116
117fn check_schema(schema: &[ColumnSchema]) -> Result<(), ConformanceError> {
118    let expected = [
119        ("x", ColumnType::Float),
120        ("n", ColumnType::Int),
121        ("label", ColumnType::Text),
122    ];
123    if schema.len() != expected.len() {
124        return Err(ConformanceError::Schema(format!(
125            "expected {} columns, got {}",
126            expected.len(),
127            schema.len()
128        )));
129    }
130    for (column, (name, kind)) in schema.iter().zip(expected) {
131        if column.name != name || column.kind != kind {
132            return Err(ConformanceError::Schema(format!(
133                "expected {name}:{kind:?}, got {}:{:?}",
134                column.name, column.kind
135            )));
136        }
137    }
138    Ok(())
139}
140
141#[cfg(feature = "polars")]
142impl Conformance for super::polars::PolarsSource {
143    fn fixture() -> Self {
144        super::polars::conformance_fixture()
145    }
146}
147
148impl Conformance for super::source::MemorySource {
149    fn fixture() -> Self {
150        let data = Dataset::from_columns([
151            Column::floats("x", vec![1.0, 0.0, 3.0]).with_validity([true, false, true]),
152            Column::ints("n", vec![1, 2, 3]),
153            Column::text("label", ["a", "b", "c"]),
154        ]);
155        Self::new(data)
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[cfg(feature = "polars")]
164    #[test]
165    fn the_polars_backend_conforms() {
166        run::<super::super::polars::PolarsSource>().expect("Polars conforms");
167    }
168
169    #[test]
170    fn the_memory_backend_conforms() {
171        run::<super::super::source::MemorySource>().expect("conforms");
172    }
173
174    #[test]
175    fn an_invalid_range_is_reported() {
176        let error = ConformanceError::RangeAccepted(2..9);
177        assert!(error.to_string().contains("2..9"));
178    }
179
180    #[test]
181    fn a_bad_schema_is_reported() {
182        let error = super::check_schema(&[ColumnSchema::new("x", ColumnType::Float)]).expect_err("bad");
183        assert!(matches!(error, ConformanceError::Schema(_)));
184    }
185}