kimberlite-oracle 0.9.1

DuckDB-backed analytical-query oracle for Kimberlite differential testing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! # SQL Differential Testing Oracles
//!
//! This crate provides oracle implementations for differential SQL testing,
//! inspired by the Crucible framework and SQLancer research.
//!
//! ## Architecture
//!
//! The `OracleRunner` trait defines a common interface for executing SQL queries
//! against different database engines. Implementations include:
//!
//! - **`DuckDbOracle`**: Executes queries in DuckDB (ground truth oracle)
//! - **`KimberliteOracle`**: Executes queries in Kimberlite (system under test)
//!
//! ## Usage
//!
//! ```rust,ignore
//! use kimberlite_oracle::{OracleRunner, DuckDbOracle, KimberliteOracle};
//!
//! let duckdb = DuckDbOracle::new()?;
//! let kimberlite = KimberliteOracle::new(/* ... */)?;
//!
//! let sql = "SELECT COUNT(*) FROM users WHERE age > 30";
//! let duckdb_result = duckdb.execute(sql)?;
//! let kimberlite_result = kimberlite.execute(sql)?;
//!
//! // Compare results to find bugs
//! assert_eq!(duckdb_result, kimberlite_result);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Differential Testing Strategy
//!
//! Differential testing compares two implementations of the same specification:
//!
//! 1. **Generate** a valid SQL query
//! 2. **Execute** in both DuckDB (reference) and Kimberlite (SUT)
//! 3. **Compare** results byte-by-byte
//! 4. **Report** any discrepancies as bugs
//!
//! **Why DuckDB?**
//! - Battle-tested SQL engine with 99.9% TPC-H compliance
//! - Embedded (no network overhead)
//! - Fast (columnar execution)
//! - Well-documented semantics
//!
//! ## References
//!
//! - Crucible: "Detecting Logic Bugs in DBMS" (154+ bugs found)
//! - SQLancer: Differential testing framework (148+ bugs in nghttp2)
//! - Jepsen: Distributed systems testing methodology

use std::fmt;

use kimberlite_query::QueryResult;

pub mod duckdb;
pub mod kimberlite;

pub use self::duckdb::DuckDbOracle;
pub use self::kimberlite::KimberliteOracle;

// ============================================================================
// Oracle Runner Trait
// ============================================================================

/// Trait for executing SQL queries against a database engine.
///
/// Oracle runners provide a uniform interface for differential testing,
/// allowing us to compare results across different implementations.
pub trait OracleRunner {
    /// Executes a SQL query and returns the result.
    ///
    /// # Arguments
    ///
    /// * `sql` - The SQL query string to execute
    ///
    /// # Returns
    ///
    /// - `Ok(QueryResult)` on successful execution
    /// - `Err(OracleError)` if the query fails or produces an error
    ///
    /// # Guarantees
    ///
    /// - **Deterministic**: Same SQL + same state = same result
    /// - **Isolated**: Queries don't interfere with each other
    /// - **Correct**: Results match SQL standard semantics
    fn execute(&mut self, sql: &str) -> Result<QueryResult, OracleError>;

    /// Resets the oracle to its initial state.
    ///
    /// This clears all tables, drops indexes, and resets sequences.
    /// Used to start fresh between test iterations.
    fn reset(&mut self) -> Result<(), OracleError>;

    /// Returns the name of this oracle (for logging).
    fn name(&self) -> &'static str;
}

// ============================================================================
// Oracle Error Types
// ============================================================================

/// Errors that can occur during oracle execution.
#[derive(Debug, thiserror::Error)]
pub enum OracleError {
    /// SQL syntax error (query is malformed).
    #[error("SQL syntax error: {0}")]
    SyntaxError(String),

    /// Semantic error (query is valid but incorrect, e.g., table not found).
    #[error("Semantic error: {0}")]
    SemanticError(String),

    /// Runtime error (query execution failed).
    #[error("Runtime error: {0}")]
    RuntimeError(String),

    /// Timeout error (query took too long).
    #[error("Timeout after {0}ms")]
    Timeout(u64),

    /// Unsupported feature (query uses SQL features not implemented).
    #[error("Unsupported feature: {0}")]
    Unsupported(String),

    /// Internal error (bug in the oracle implementation).
    #[error("Internal error: {0}")]
    Internal(String),
}

// ============================================================================
// Result Comparison
// ============================================================================

/// Compares two query results for equality.
///
/// # Comparison Rules
///
/// - **Column count**: Must match
/// - **Column names**: Must match (case-sensitive)
/// - **Row count**: Must match
/// - **Row values**: Must match byte-for-byte (including NULLs)
/// - **Row order**: Must match (unless ORDER BY is absent)
///
/// # Returns
///
/// - `Ok(())` if results are identical
/// - `Err(ResultMismatch)` with detailed diagnostic info
pub fn compare_results(
    left: &QueryResult,
    right: &QueryResult,
    left_name: &str,
    right_name: &str,
) -> Result<(), ResultMismatch> {
    // Check column count
    if left.columns.len() != right.columns.len() {
        return Err(ResultMismatch::ColumnCountMismatch {
            left: left.columns.len(),
            right: right.columns.len(),
            left_name: left_name.to_string(),
            right_name: right_name.to_string(),
        });
    }

    // Check column names
    for (i, (left_col, right_col)) in left.columns.iter().zip(right.columns.iter()).enumerate() {
        if left_col.as_str() != right_col.as_str() {
            return Err(ResultMismatch::ColumnNameMismatch {
                column_index: i,
                left: left_col.as_str().to_string(),
                right: right_col.as_str().to_string(),
                left_name: left_name.to_string(),
                right_name: right_name.to_string(),
            });
        }
    }

    // Check row count
    if left.rows.len() != right.rows.len() {
        return Err(ResultMismatch::RowCountMismatch {
            left: left.rows.len(),
            right: right.rows.len(),
            left_name: left_name.to_string(),
            right_name: right_name.to_string(),
        });
    }

    // Check row values
    for (row_idx, (left_row, right_row)) in left.rows.iter().zip(right.rows.iter()).enumerate() {
        if left_row.len() != right_row.len() {
            return Err(ResultMismatch::RowValueCountMismatch {
                row_index: row_idx,
                left: left_row.len(),
                right: right_row.len(),
                left_name: left_name.to_string(),
                right_name: right_name.to_string(),
            });
        }

        for (col_idx, (left_val, right_val)) in left_row.iter().zip(right_row.iter()).enumerate() {
            if left_val != right_val {
                return Err(ResultMismatch::ValueMismatch {
                    row_index: row_idx,
                    column_index: col_idx,
                    left: format!("{left_val:?}"),
                    right: format!("{right_val:?}"),
                    left_name: left_name.to_string(),
                    right_name: right_name.to_string(),
                });
            }
        }
    }

    Ok(())
}

/// Describes a mismatch between two query results.
#[derive(Debug, Clone)]
pub enum ResultMismatch {
    /// Column counts don't match.
    ColumnCountMismatch {
        left: usize,
        right: usize,
        left_name: String,
        right_name: String,
    },

    /// Column names don't match.
    ColumnNameMismatch {
        column_index: usize,
        left: String,
        right: String,
        left_name: String,
        right_name: String,
    },

    /// Row counts don't match.
    RowCountMismatch {
        left: usize,
        right: usize,
        left_name: String,
        right_name: String,
    },

    /// Row value counts don't match (same row has different number of columns).
    RowValueCountMismatch {
        row_index: usize,
        left: usize,
        right: usize,
        left_name: String,
        right_name: String,
    },

    /// Individual cell values don't match.
    ValueMismatch {
        row_index: usize,
        column_index: usize,
        left: String,
        right: String,
        left_name: String,
        right_name: String,
    },
}

impl fmt::Display for ResultMismatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ResultMismatch::ColumnCountMismatch {
                left,
                right,
                left_name,
                right_name,
            } => {
                write!(
                    f,
                    "Column count mismatch: {left_name}={left}, {right_name}={right}"
                )
            }
            ResultMismatch::ColumnNameMismatch {
                column_index,
                left,
                right,
                left_name,
                right_name,
            } => {
                write!(
                    f,
                    "Column name mismatch at index {column_index}: {left_name}='{left}', {right_name}='{right}'"
                )
            }
            ResultMismatch::RowCountMismatch {
                left,
                right,
                left_name,
                right_name,
            } => {
                write!(
                    f,
                    "Row count mismatch: {left_name}={left}, {right_name}={right}"
                )
            }
            ResultMismatch::RowValueCountMismatch {
                row_index,
                left,
                right,
                left_name,
                right_name,
            } => {
                write!(
                    f,
                    "Row value count mismatch at row {row_index}: {left_name}={left}, {right_name}={right}"
                )
            }
            ResultMismatch::ValueMismatch {
                row_index,
                column_index,
                left,
                right,
                left_name,
                right_name,
            } => {
                write!(
                    f,
                    "Value mismatch at row {row_index}, column {column_index}: {left_name}={left}, {right_name}={right}"
                )
            }
        }
    }
}

impl std::error::Error for ResultMismatch {}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use kimberlite_query::{ColumnName, Value};

    #[test]
    fn test_compare_results_identical() {
        let result1 = QueryResult {
            columns: vec![ColumnName::from("id"), ColumnName::from("name")],
            rows: vec![
                vec![Value::BigInt(1), Value::Text("Alice".to_string())],
                vec![Value::BigInt(2), Value::Text("Bob".to_string())],
            ],
        };

        let result2 = result1.clone();

        assert!(compare_results(&result1, &result2, "left", "right").is_ok());
    }

    #[test]
    fn test_compare_results_column_count_mismatch() {
        let result1 = QueryResult {
            columns: vec![ColumnName::from("id"), ColumnName::from("name")],
            rows: vec![],
        };

        let result2 = QueryResult {
            columns: vec![ColumnName::from("id")],
            rows: vec![],
        };

        let err = compare_results(&result1, &result2, "left", "right").unwrap_err();
        assert!(matches!(err, ResultMismatch::ColumnCountMismatch { .. }));
    }

    #[test]
    fn test_compare_results_column_name_mismatch() {
        let result1 = QueryResult {
            columns: vec![ColumnName::from("id"), ColumnName::from("name")],
            rows: vec![],
        };

        let result2 = QueryResult {
            columns: vec![ColumnName::from("id"), ColumnName::from("email")],
            rows: vec![],
        };

        let err = compare_results(&result1, &result2, "left", "right").unwrap_err();
        assert!(matches!(err, ResultMismatch::ColumnNameMismatch { .. }));
    }

    #[test]
    fn test_compare_results_row_count_mismatch() {
        let result1 = QueryResult {
            columns: vec![ColumnName::from("id")],
            rows: vec![vec![Value::BigInt(1)], vec![Value::BigInt(2)]],
        };

        let result2 = QueryResult {
            columns: vec![ColumnName::from("id")],
            rows: vec![vec![Value::BigInt(1)]],
        };

        let err = compare_results(&result1, &result2, "left", "right").unwrap_err();
        assert!(matches!(err, ResultMismatch::RowCountMismatch { .. }));
    }

    #[test]
    fn test_compare_results_value_mismatch() {
        let result1 = QueryResult {
            columns: vec![ColumnName::from("id")],
            rows: vec![vec![Value::BigInt(1)]],
        };

        let result2 = QueryResult {
            columns: vec![ColumnName::from("id")],
            rows: vec![vec![Value::BigInt(2)]],
        };

        let err = compare_results(&result1, &result2, "left", "right").unwrap_err();
        assert!(matches!(err, ResultMismatch::ValueMismatch { .. }));
    }
}