|
| 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 | +//! End-to-end tests: the dynamic filters of the hash join, TopK and |
| 19 | +//! aggregate operators arrive at the Parquet scan as *optional* conjuncts of |
| 20 | +//! its [`PhysicalFilter`], and the query results do not change. |
| 21 | +//! |
| 22 | +//! [`PhysicalFilter`]: datafusion_physical_expr::filter::PhysicalFilter |
| 23 | +
|
| 24 | +use std::sync::Arc; |
| 25 | + |
| 26 | +use arrow::array::{Int64Array, RecordBatch}; |
| 27 | +use arrow::util::pretty::pretty_format_batches; |
| 28 | +use arrow_schema::{DataType, Field, Schema}; |
| 29 | +use datafusion::datasource::physical_plan::ParquetSource; |
| 30 | +use datafusion::datasource::source::DataSourceExec; |
| 31 | +use datafusion::physical_plan::{ExecutionPlan, collect}; |
| 32 | +use datafusion::prelude::{ParquetReadOptions, SessionConfig, SessionContext}; |
| 33 | +use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion}; |
| 34 | +use datafusion_datasource::file_scan_config::FileScanConfig; |
| 35 | +use insta::assert_snapshot; |
| 36 | +use parquet::arrow::ArrowWriter; |
| 37 | +use tempfile::TempDir; |
| 38 | + |
| 39 | +/// Write `columns` as a single-file Parquet table `name` and register it. |
| 40 | +async fn register_table( |
| 41 | + ctx: &SessionContext, |
| 42 | + dir: &TempDir, |
| 43 | + name: &str, |
| 44 | + columns: Vec<(&str, Vec<i64>)>, |
| 45 | +) { |
| 46 | + let schema = Arc::new(Schema::new( |
| 47 | + columns |
| 48 | + .iter() |
| 49 | + .map(|(name, _)| Field::new(*name, DataType::Int64, false)) |
| 50 | + .collect::<Vec<_>>(), |
| 51 | + )); |
| 52 | + let arrays = columns |
| 53 | + .into_iter() |
| 54 | + .map(|(_, values)| Arc::new(Int64Array::from(values)) as _) |
| 55 | + .collect(); |
| 56 | + let batch = RecordBatch::try_new(Arc::clone(&schema), arrays).unwrap(); |
| 57 | + let path = dir.path().join(format!("{name}.parquet")); |
| 58 | + let file = std::fs::File::create(&path).unwrap(); |
| 59 | + let mut writer = ArrowWriter::try_new(file, schema, None).unwrap(); |
| 60 | + writer.write(&batch).unwrap(); |
| 61 | + writer.close().unwrap(); |
| 62 | + ctx.register_parquet(name, path.to_str().unwrap(), ParquetReadOptions::default()) |
| 63 | + .await |
| 64 | + .unwrap(); |
| 65 | +} |
| 66 | + |
| 67 | +/// A context with a small `build` table (`k` in 1..=3) and a larger `probe` |
| 68 | +/// table (`k` in 0..100, `v = 10 * k`). |
| 69 | +async fn context() -> (SessionContext, TempDir) { |
| 70 | + let config = SessionConfig::new() |
| 71 | + .set_bool("datafusion.execution.parquet.pushdown_filters", true) |
| 72 | + .with_target_partitions(2); |
| 73 | + let ctx = SessionContext::new_with_config(config); |
| 74 | + let dir = TempDir::new().unwrap(); |
| 75 | + register_table(&ctx, &dir, "build", vec![("k", vec![1, 2, 3])]).await; |
| 76 | + let k: Vec<i64> = (0..100).collect(); |
| 77 | + let v = k.iter().map(|k| k * 10).collect(); |
| 78 | + register_table(&ctx, &dir, "probe", vec![("k", k), ("v", v)]).await; |
| 79 | + (ctx, dir) |
| 80 | +} |
| 81 | + |
| 82 | +/// The conjuncts of the filter of each Parquet scan in `plan`, with their |
| 83 | +/// optional flag. |
| 84 | +fn scan_conjuncts(plan: &Arc<dyn ExecutionPlan>) -> Vec<Vec<(String, bool)>> { |
| 85 | + let mut scans = vec![]; |
| 86 | + plan.apply(|node| { |
| 87 | + if let Some(source) = node |
| 88 | + .downcast_ref::<DataSourceExec>() |
| 89 | + .and_then(|exec| exec.data_source().downcast_ref::<FileScanConfig>()) |
| 90 | + .and_then(|config| config.file_source().downcast_ref::<ParquetSource>()) |
| 91 | + { |
| 92 | + scans.push( |
| 93 | + source |
| 94 | + .physical_filter() |
| 95 | + .conjuncts() |
| 96 | + .iter() |
| 97 | + .map(|c| (c.to_string(), c.is_optional())) |
| 98 | + .collect(), |
| 99 | + ); |
| 100 | + } |
| 101 | + Ok(TreeNodeRecursion::Continue) |
| 102 | + }) |
| 103 | + .unwrap(); |
| 104 | + scans |
| 105 | +} |
| 106 | + |
| 107 | +/// Plan and run `sql`. Return the conjuncts of each Parquet scan and the |
| 108 | +/// formatted result. |
| 109 | +async fn run(sql: &str) -> (Vec<Vec<(String, bool)>>, String) { |
| 110 | + let (ctx, _dir) = context().await; |
| 111 | + let plan = ctx |
| 112 | + .sql(sql) |
| 113 | + .await |
| 114 | + .unwrap() |
| 115 | + .create_physical_plan() |
| 116 | + .await |
| 117 | + .unwrap(); |
| 118 | + let conjuncts = scan_conjuncts(&plan); |
| 119 | + let batches = collect(plan, ctx.task_ctx()).await.unwrap(); |
| 120 | + ( |
| 121 | + conjuncts, |
| 122 | + pretty_format_batches(&batches).unwrap().to_string(), |
| 123 | + ) |
| 124 | +} |
| 125 | + |
| 126 | +fn is_dynamic_filter(conjunct: &(String, bool)) -> bool { |
| 127 | + conjunct.0.starts_with("DynamicFilter") |
| 128 | +} |
| 129 | + |
| 130 | +#[tokio::test] |
| 131 | +async fn hash_join_dynamic_filter_arrives_optional() { |
| 132 | + let (scans, result) = run("SELECT p.k, p.v FROM build b JOIN probe p ON b.k = p.k \ |
| 133 | + WHERE p.v > 10 ORDER BY p.k") |
| 134 | + .await; |
| 135 | + // The build side scan has no filter. The probe side scan has the |
| 136 | + // required user filter and the optional dynamic filter of the join. |
| 137 | + let probe = scans |
| 138 | + .iter() |
| 139 | + .find(|conjuncts| conjuncts.iter().any(is_dynamic_filter)) |
| 140 | + .expect("a scan with the dynamic filter of the join"); |
| 141 | + assert!( |
| 142 | + probe |
| 143 | + .iter() |
| 144 | + .all(|conjunct| conjunct.1 == is_dynamic_filter(conjunct)), |
| 145 | + "only the dynamic filter is optional: {probe:?}" |
| 146 | + ); |
| 147 | + assert!( |
| 148 | + probe |
| 149 | + .iter() |
| 150 | + .any(|(expr, optional)| expr == "v@1 > 10" && !optional) |
| 151 | + ); |
| 152 | + assert_snapshot!(result, @r" |
| 153 | + +---+----+ |
| 154 | + | k | v | |
| 155 | + +---+----+ |
| 156 | + | 2 | 20 | |
| 157 | + | 3 | 30 | |
| 158 | + +---+----+ |
| 159 | + "); |
| 160 | +} |
| 161 | + |
| 162 | +#[tokio::test] |
| 163 | +async fn topk_dynamic_filter_arrives_optional() { |
| 164 | + let (scans, result) = run("SELECT v FROM probe ORDER BY v DESC LIMIT 2").await; |
| 165 | + assert_eq!(scans.len(), 1); |
| 166 | + let [conjunct] = scans[0].as_slice() else { |
| 167 | + panic!("expected one conjunct: {scans:?}"); |
| 168 | + }; |
| 169 | + assert!(is_dynamic_filter(conjunct) && conjunct.1, "{conjunct:?}"); |
| 170 | + assert_snapshot!(result, @r" |
| 171 | + +-----+ |
| 172 | + | v | |
| 173 | + +-----+ |
| 174 | + | 990 | |
| 175 | + | 980 | |
| 176 | + +-----+ |
| 177 | + "); |
| 178 | +} |
| 179 | + |
| 180 | +#[tokio::test] |
| 181 | +async fn aggregate_dynamic_filter_arrives_optional() { |
| 182 | + // The `WHERE` clause prevents an answer from the file statistics. |
| 183 | + let (scans, result) = run("SELECT max(v) FROM probe WHERE k > 5").await; |
| 184 | + assert_eq!(scans.len(), 1); |
| 185 | + let [required, optional] = scans[0].as_slice() else { |
| 186 | + panic!("expected two conjuncts: {scans:?}"); |
| 187 | + }; |
| 188 | + assert_eq!(required, &("k@0 > 5".to_string(), false)); |
| 189 | + assert!(is_dynamic_filter(optional) && optional.1, "{optional:?}"); |
| 190 | + assert_snapshot!(result, @r" |
| 191 | + +--------------+ |
| 192 | + | max(probe.v) | |
| 193 | + +--------------+ |
| 194 | + | 990 | |
| 195 | + +--------------+ |
| 196 | + "); |
| 197 | +} |
0 commit comments