|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +//! Fuzz test for null-aware (`NOT IN`) joins. |
| 19 | +//! |
| 20 | +//! Scalar and multi-column `NOT IN` / `IN` subqueries, which plan as |
| 21 | +//! null-aware hash joins, are compared with `NOT EXISTS` / `EXISTS` |
| 22 | +//! formulations of the same three-valued logic, which do not. Random tables |
| 23 | +//! with NULLs on both sides are swept across batch sizes and partition counts. |
| 24 | +
|
| 25 | +use std::sync::Arc; |
| 26 | + |
| 27 | +use arrow::array::{Int32Array, RecordBatch}; |
| 28 | +use arrow::datatypes::{DataType, Field, Schema}; |
| 29 | +use arrow::util::pretty::pretty_format_batches; |
| 30 | +use datafusion::datasource::MemTable; |
| 31 | +use datafusion::prelude::{SessionConfig, SessionContext}; |
| 32 | +use rand::rngs::StdRng; |
| 33 | +use rand::{Rng, SeedableRng}; |
| 34 | + |
| 35 | +#[tokio::test(flavor = "multi_thread")] |
| 36 | +async fn null_aware_join_matches_reference() { |
| 37 | + for seed in 0..20 { |
| 38 | + let mut rng = StdRng::seed_from_u64(seed); |
| 39 | + let outer = random_table(&mut rng, &["id", "k", "a", "b", "c"]); |
| 40 | + let inner = random_table(&mut rng, &["k", "x", "y", "z"]); |
| 41 | + for target_partitions in [1, 4] { |
| 42 | + for batch_size in [1, 3, 8192] { |
| 43 | + let config = SessionConfig::new() |
| 44 | + .with_target_partitions(target_partitions) |
| 45 | + .with_batch_size(batch_size) |
| 46 | + // Keep multi-partition runs from collapsing to a single |
| 47 | + // partition on these small inputs. |
| 48 | + .set_usize( |
| 49 | + "datafusion.optimizer.hash_join_single_partition_threshold", |
| 50 | + 0, |
| 51 | + ) |
| 52 | + .set_usize( |
| 53 | + "datafusion.optimizer.hash_join_single_partition_threshold_rows", |
| 54 | + 0, |
| 55 | + ); |
| 56 | + let ctx = SessionContext::new_with_config(config); |
| 57 | + ctx.register_table("o", Arc::clone(&outer) as _).unwrap(); |
| 58 | + ctx.register_table("i", Arc::clone(&inner) as _).unwrap(); |
| 59 | + for (query, reference) in cases() { |
| 60 | + let actual = run(&ctx, &query).await; |
| 61 | + let expected = run(&ctx, &reference).await; |
| 62 | + assert_eq!( |
| 63 | + actual, expected, |
| 64 | + "seed={seed} target_partitions={target_partitions} \ |
| 65 | + batch_size={batch_size}\nquery: {query}\nreference: {reference}" |
| 66 | + ); |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +/// Pairs of (query, reference) that must return the same rows. |
| 74 | +fn cases() -> Vec<(String, String)> { |
| 75 | + let mut cases = vec![]; |
| 76 | + // (correlation inside the subquery, the same correlation in the reference) |
| 77 | + for (correlation, reference_correlation) in [ |
| 78 | + ("", ""), |
| 79 | + (" WHERE i.k = o.k", " AND i.k = o.k"), |
| 80 | + (" WHERE i.k < o.k", " AND i.k < o.k"), |
| 81 | + ( |
| 82 | + " WHERE i.k = o.k AND i.z < o.c", |
| 83 | + " AND i.k = o.k AND i.z < o.c", |
| 84 | + ), |
| 85 | + ] { |
| 86 | + // (outer value, subquery output, element-wise equality) |
| 87 | + for (value, output, equal) in [ |
| 88 | + ("o.a", "i.x", "o.a = i.x"), |
| 89 | + ("(o.a, o.b)", "i.x, i.y", "o.a = i.x AND o.b = i.y"), |
| 90 | + ( |
| 91 | + "(o.a, o.b, o.c)", |
| 92 | + "i.x, i.y, i.z", |
| 93 | + "o.a = i.x AND o.b = i.y AND o.c = i.z", |
| 94 | + ), |
| 95 | + ("(o.a, 1)", "i.x, i.y", "o.a = i.x AND 1 = i.y"), |
| 96 | + ] { |
| 97 | + let subquery = format!("SELECT {output} FROM i{correlation}"); |
| 98 | + let matched = format!( |
| 99 | + "EXISTS (SELECT 1 FROM i WHERE ({equal}){reference_correlation})" |
| 100 | + ); |
| 101 | + let unknown = format!( |
| 102 | + "EXISTS (SELECT 1 FROM i WHERE ({equal}) IS NULL{reference_correlation})" |
| 103 | + ); |
| 104 | + let not_in = format!( |
| 105 | + "NOT EXISTS (SELECT 1 FROM i WHERE ({equal}) IS NOT FALSE{reference_correlation})" |
| 106 | + ); |
| 107 | + cases.push(( |
| 108 | + format!("SELECT o.id FROM o WHERE {value} NOT IN ({subquery})"), |
| 109 | + format!("SELECT o.id FROM o WHERE {not_in}"), |
| 110 | + )); |
| 111 | + cases.push(( |
| 112 | + format!("SELECT o.id FROM o WHERE {value} IN ({subquery})"), |
| 113 | + format!("SELECT o.id FROM o WHERE {matched}"), |
| 114 | + )); |
| 115 | + cases.push(( |
| 116 | + format!( |
| 117 | + "SELECT o.id FROM o WHERE {value} NOT IN ({subquery}) OR o.id % 3 = 0" |
| 118 | + ), |
| 119 | + format!("SELECT o.id FROM o WHERE {not_in} OR o.id % 3 = 0"), |
| 120 | + )); |
| 121 | + cases.push(( |
| 122 | + format!("SELECT o.id, {value} NOT IN ({subquery}) AS r FROM o"), |
| 123 | + format!( |
| 124 | + "SELECT o.id, CASE WHEN {matched} THEN false \ |
| 125 | + WHEN {unknown} THEN NULL ELSE true END AS r FROM o" |
| 126 | + ), |
| 127 | + )); |
| 128 | + } |
| 129 | + } |
| 130 | + cases |
| 131 | +} |
| 132 | + |
| 133 | +/// A table of nullable `Int32` columns with values in `0..3`, split into up |
| 134 | +/// to three partitions. A column named `id` holds unique row ids instead. |
| 135 | +fn random_table(rng: &mut StdRng, columns: &[&str]) -> Arc<MemTable> { |
| 136 | + let schema = Arc::new(Schema::new( |
| 137 | + columns |
| 138 | + .iter() |
| 139 | + .map(|name| Field::new(*name, DataType::Int32, true)) |
| 140 | + .collect::<Vec<_>>(), |
| 141 | + )); |
| 142 | + let null_fraction = [0.0, 0.1, 0.3][rng.random_range(0..3)]; |
| 143 | + let mut next_id = 0; |
| 144 | + let partitions = (0..rng.random_range(1..4)) |
| 145 | + .map(|_| { |
| 146 | + let rows = rng.random_range(0..6); |
| 147 | + let arrays = columns |
| 148 | + .iter() |
| 149 | + .map(|name| { |
| 150 | + let values: Int32Array = if *name == "id" { |
| 151 | + (next_id..next_id + rows).map(Some).collect() |
| 152 | + } else { |
| 153 | + (0..rows) |
| 154 | + .map(|_| { |
| 155 | + (!rng.random_bool(null_fraction)) |
| 156 | + .then(|| rng.random_range(0..3)) |
| 157 | + }) |
| 158 | + .collect() |
| 159 | + }; |
| 160 | + Arc::new(values) as _ |
| 161 | + }) |
| 162 | + .collect(); |
| 163 | + next_id += rows; |
| 164 | + vec![RecordBatch::try_new(Arc::clone(&schema), arrays).unwrap()] |
| 165 | + }) |
| 166 | + .collect(); |
| 167 | + Arc::new(MemTable::try_new(schema, partitions).unwrap()) |
| 168 | +} |
| 169 | + |
| 170 | +/// The rows of `sql`, sorted. |
| 171 | +async fn run(ctx: &SessionContext, sql: &str) -> Vec<String> { |
| 172 | + let batches = ctx.sql(sql).await.unwrap().collect().await.unwrap(); |
| 173 | + let formatted = pretty_format_batches(&batches).unwrap().to_string(); |
| 174 | + let mut rows: Vec<String> = formatted |
| 175 | + .lines() |
| 176 | + .filter(|line| line.starts_with('|')) |
| 177 | + .skip(1) |
| 178 | + .map(String::from) |
| 179 | + .collect(); |
| 180 | + rows.sort(); |
| 181 | + rows |
| 182 | +} |
0 commit comments