jayzhan211 commented on code in PR #27546:
URL: https://github.com/apache/datafusion/pull/27546#discussion_r4719555325
##########
datafusion/datasource-parquet/src/push_decoder.rs:
##########
@@ -240,6 +241,9 @@ impl RowGroupPruner {
.map(Vec::as_slice),
row_group_metadatas,
arrow_schema: self.arrow_schema.as_ref(),
+ missing_null_counts_as_zero: missing_null_counts_are_zero(
Review Comment:
Forcing this to `false` still passes every test in the PR. On a legacy file,
`ORDER BY v NULLS FIRST LIMIT 1` then prunes 0 row groups at runtime instead of
1, so the TopK path in the description isn't covered. Could you add a test like
the one below in `dynamic_row_group_pruning.rs`? It passes on this branch and
fails with this flag forced to `false`.
<details>
<summary>Test for runtime TopK pruning on a legacy footer</summary>
```rs
/// Runtime TopK pruning reads the same footer: with `NULLS FIRST` the live
/// filter keeps `v IS NULL`, so a group can be skipped only when its omitted
/// count means zero.
#[tokio::test]
async fn missing_null_count_is_zero_for_runtime_topk_pruning() {
for (created_by, expected_pruned) in [
("parquet-rs version 53.0.0", 1),
("parquet-rs version 53.1.0", 0),
] {
let file = file_without_zero_null_counts(created_by);
let mut config = SessionConfig::new()
.with_target_partitions(1)
.with_batch_size(1)
.with_parquet_page_index_pruning(false);
// Keep the live filter on the row-group path, as in
// `dynamic_rg_pruning_preserves_missing_null_count`.
config.options_mut().execution.collect_statistics = false;
config.options_mut().optimizer.enable_sort_pushdown = false;
config
.options_mut()
.optimizer
.enable_topk_dynamic_filter_pushdown = true;
config.options_mut().execution.parquet.pushdown_filters = false;
let ctx = SessionContext::new_with_config(config);
ctx.register_parquet(
"t",
file.path().to_str().unwrap(),
ParquetReadOptions::default(),
)
.await
.unwrap();
let plan = ctx
.sql("SELECT v FROM t ORDER BY v NULLS FIRST LIMIT 1")
.await
.unwrap()
.create_physical_plan()
.await
.unwrap();
let batches = collect(plan.clone(), ctx.task_ctx()).await.unwrap();
assert_eq!(
ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(),
ScalarValue::Int64(None),
"{created_by}",
);
let metrics = MetricsFinder::find_metrics(plan.as_ref()).unwrap();
let pruned = metrics
.sum_by_name("row_groups_pruned_dynamic_filter")
.unwrap()
.as_usize();
assert_eq!(pruned, expected_pruned, "{created_by}\n{metrics}");
}
}
```
</details>
##########
datafusion/core/tests/parquet/dynamic_row_group_pruning.rs:
##########
@@ -98,12 +102,132 @@ fn file_with_missing_null_count(descending: bool,
has_null: bool) -> NamedTempFi
.unwrap();
let mut output = TrackedWrite::new(file.as_file_mut());
output.write_all(&bytes).unwrap();
- ParquetMetaDataWriter::new_with_tracked(output, &metadata)
+ ParquetMetaDataWriter::new_with_tracked(output, metadata)
.finish()
.unwrap();
file
}
+fn file_without_zero_null_counts(created_by: &str) -> NamedTempFile {
+ let schema = Arc::new(Schema::new(vec![Field::new("v", DataType::Int64,
true)]));
+ let props = WriterProperties::builder()
+ .set_statistics_enabled(EnabledStatistics::Chunk)
+ .build();
+ let mut bytes = Vec::new();
+ let mut writer =
+ ArrowWriter::try_new(&mut bytes, schema.clone(), Some(props)).unwrap();
+ for values in [
+ vec![Some(0), Some(1), Some(2)],
+ vec![None, Some(100), Some(101)],
+ vec![Some(200), Some(201), Some(202)],
+ ] {
+ let values: Int64Array = values.into_iter().collect();
+ let batch = RecordBatch::try_new(schema.clone(),
vec![Arc::new(values)]).unwrap();
+ writer.write(&batch).unwrap();
+ writer.flush().unwrap();
+ }
+ let metadata = writer.close().unwrap();
+ let groups = metadata
+ .row_groups()
+ .iter()
+ .map(|group| {
+ let column = group.column(0).clone();
+ let Statistics::Int64(stats) = column.statistics().unwrap() else {
+ panic!("expected Int64 statistics");
+ };
+ let null_count = stats.null_count_opt().filter(|&count| count > 0);
+ let stats = Statistics::int64(
+ stats.min_opt().copied(),
+ stats.max_opt().copied(),
+ None,
+ null_count,
+ false,
+ );
+ let column =
column.into_builder().set_statistics(stats).build().unwrap();
+ group
+ .clone()
+ .into_builder()
+ .set_column_metadata(vec![column])
+ .build()
+ .unwrap()
+ })
+ .collect();
+ let file_metadata = metadata.file_metadata();
+ let file_metadata = FileMetaData::new(
+ file_metadata.version(),
+ file_metadata.num_rows(),
+ Some(created_by.to_owned()),
+ file_metadata.key_value_metadata().cloned(),
+ file_metadata.schema_descr_ptr(),
+ file_metadata.column_orders().cloned(),
+ );
+ replace_footer(bytes, &ParquetMetaData::new(file_metadata, groups))
+}
+
+/// A zero `null_count` omitted by parquet-rs before 53.1.0 is zero, so
+/// `IS NULL` can skip the row groups without nulls. For any other writer the
+/// same footer is unknown and no row group may be skipped. The results are
+/// the same either way.
+#[tokio::test]
+async fn missing_null_count_is_zero_for_legacy_writers() {
+ for (created_by, expected_pruned) in [
+ ("parquet-rs version 53.0.0", 2),
+ ("datafusion version 42.0.0", 2),
+ ("parquet-rs version 53.1.0", 0),
+ ("parquet-mr version 1.13.1", 0),
+ ] {
+ let file = file_without_zero_null_counts(created_by);
+ let ctx = SessionContext::new_with_config(
+ SessionConfig::new()
+ .with_target_partitions(1)
+ .with_parquet_page_index_pruning(false),
+ );
+ ctx.register_parquet(
+ "t",
+ file.path().to_str().unwrap(),
+ ParquetReadOptions::default(),
+ )
+ .await
+ .unwrap();
+
+ let plan = ctx
+ .sql("SELECT v FROM t WHERE v IS NULL")
+ .await
+ .unwrap()
+ .create_physical_plan()
+ .await
+ .unwrap();
+ let batches = collect(plan.clone(), ctx.task_ctx()).await.unwrap();
+ let rows: usize = batches.iter().map(|b| b.num_rows()).sum();
+ assert_eq!(rows, 1, "{created_by}");
+
+ let metrics = MetricsFinder::find_metrics(plan.as_ref()).unwrap();
+ let pruned = match metrics
+ .sum(|m| m.value().name() == "row_groups_pruned_statistics")
+ .unwrap()
+ {
+ MetricValue::PruningMetrics {
+ pruning_metrics, ..
+ } => pruning_metrics.pruned(),
+ other => panic!("unexpected metric {other:?}"),
+ };
+ assert_eq!(pruned, expected_pruned, "{created_by}\n{metrics}");
Review Comment:
Forcing the flag in `identify_fully_matched_row_groups`
(`row_group_filter.rs` line 436) to `false` also passes every test. A legacy
file then loses its 2 fully matched row groups for `WHERE v >= 0`. This
assertion covers that. It passes here and fails with that flag forced off:
````suggestion
assert_eq!(pruned, expected_pruned, "{created_by}\n{metrics}");
// `v >= 0` holds for every non-null value, so the groups that
// `IS NULL` pruned (proven null-free) are exactly the fully matched
ones.
let plan = ctx
.sql("SELECT v FROM t WHERE v >= 0")
.await
.unwrap()
.create_physical_plan()
.await
.unwrap();
collect(plan.clone(), ctx.task_ctx()).await.unwrap();
let metrics = MetricsFinder::find_metrics(plan.as_ref()).unwrap();
let fully_matched = match metrics
.sum(|m| m.value().name() == "row_groups_pruned_statistics")
.unwrap()
{
MetricValue::PruningMetrics {
pruning_metrics, ..
} => pruning_metrics.fully_matched(),
other => panic!("unexpected metric {other:?}"),
};
assert_eq!(fully_matched, expected_pruned,
"{created_by}\n{metrics}");
````
##########
datafusion/datasource-parquet/src/metadata.rs:
##########
@@ -651,8 +679,10 @@ impl<'a> DFParquetMetadata<'a> {
Ok(stats_converter) => {
// An omitted count must not become an exact zero
in
// file statistics used for pruning and aggregates.
Review Comment:
Optional cleanup: this comment now contradicts the line below it, because
for legacy writers an omitted count does become an exact zero.
```suggestion
// A missing count is zero only for writers that
omitted
// zero counts; otherwise it stays unknown, so
file
// statistics never report a guessed exact zero.
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]