jayzhan211 commented on code in PR #27163:
URL: https://github.com/apache/datafusion/pull/27163#discussion_r4731352631
##########
datafusion/datasource-parquet/src/metadata.rs:
##########
@@ -1276,6 +1294,132 @@ fn sorting_columns_to_physical_exprs(
.collect()
}
+/// Returns how many leading `sorting_columns` are ordered across the whole
+/// file, given that every row group is sorted by all of them.
+///
+/// The row group statistics give the values that sort first and last in each
+/// row group. The file is ordered if the value that sorts last in each row
+/// group is not after the value that sorts first in the next row group. For
+/// `a ASC`:
+///
+/// ```text
+/// row groups [1, 2] [3, 4]: ordered, because 2 <= 3
+/// row groups [1, 4] [2, 3]: not ordered, because 4 > 2
+/// ```
+///
+/// A later column must be ordered only where all earlier columns are equal.
+/// For `a ASC, b ASC`:
+///
+/// ```text
+/// row groups [(1, 8), (1, 9)] [(2, 0), (2, 1)]: ordered by (a, b), because a
increases
+/// row groups [(1, 8), (1, 9)] [(1, 0), (1, 1)]: ordered by (a) only, because
a is equal and 9 > 0
+/// ```
+///
+/// A column whose order cannot be proved, for example because it has no
+/// usable statistics, counts as not ordered. Ordering is optional information,
+/// so this never fails the query.
+fn num_columns_ordered_across_row_groups(
+ metadata: &ParquetMetaData,
+ sorting_columns: &[SortingColumn],
+) -> usize {
+ let row_groups = metadata.row_groups();
+ if row_groups.len() < 2 {
+ return sorting_columns.len();
+ }
+ let file_metadata = metadata.file_metadata();
+ let parquet_schema = file_metadata.schema_descr();
+ let Ok(arrow_schema) =
+ parquet_to_arrow_schema(parquet_schema,
file_metadata.key_value_metadata())
+ else {
+ return 0;
+ };
+ let resolver = LeafResolver::new(parquet_schema, &arrow_schema);
+
+ let mut sort_exprs = vec![];
+ let mut fields = vec![];
+ let mut mins = vec![];
+ let mut maxes = vec![];
+ for (num_ordered, sorting_column) in sorting_columns.iter().enumerate() {
+ let Some((min, max)) =
+ row_group_min_max(row_groups, parquet_schema, &resolver,
sorting_column)
+ else {
+ return num_ordered;
+ };
+ // `MinMaxStatistics` finds a column by name, so name it by its
position
+ let name = num_ordered.to_string();
+ sort_exprs.push(PhysicalSortExpr::new(
+ Arc::new(Column::new(&name, num_ordered)),
+ SortOptions::new(sorting_column.descending,
sorting_column.nulls_first),
+ ));
+ fields.push(Field::new(name, min.data_type().clone(), true));
+ mins.push(min);
+ maxes.push(max);
+
+ let statistics = || {
+ let schema = Arc::new(Schema::new(fields.clone()));
+ let mins = RecordBatch::try_new(Arc::clone(&schema),
mins.clone()).ok()?;
+ let maxes = RecordBatch::try_new(Arc::clone(&schema),
maxes.clone()).ok()?;
+ let sort_order = LexOrdering::new(sort_exprs.iter().cloned())?;
+ MinMaxStatistics::new(&sort_order, &schema, mins, maxes).ok()
+ };
+ let Some(statistics) = statistics().filter(|statistics|
statistics.is_sorted())
+ else {
+ return num_ordered;
+ };
+ // Each row group ends before the next one starts, so the later sorting
+ // columns cannot change the order
+ if (1..row_groups.len()).all(|i| statistics.max(i - 1) <
statistics.min(i)) {
+ break;
+ }
+ }
+ sorting_columns.len()
+}
+
+/// Returns the min and the max of `sorting_column` in each row group, as two
+/// arrays with one entry per row group. Where a row group has NULLs, the entry
+/// on the side where NULLs sort is NULL. Returns `None` if the statistics do
+/// not provide the values.
+fn row_group_min_max(
+ row_groups: &[RowGroupMetaData],
+ parquet_schema: &SchemaDescriptor,
+ resolver: &LeafResolver,
+ sorting_column: &SortingColumn,
+) -> Option<(ArrayRef, ArrayRef)> {
+ let column_index = usize::try_from(sorting_column.column_idx).ok()?;
+ let name = parquet_schema.columns().get(column_index)?.name();
+ // The statistics must belong to the sorting column
+ if resolver.leaf_index(name) != Some(column_index) {
Review Comment:
Three of the new checks have no test: every PR test still passes when this
`leaf_index` check, the `null_counts.null_count() == 0` check, or the
`row_groups.len() < 2` early return is removed. This one matters most: without
it, a file sorted by `s.x` that also has a top-level `x` uses `x`'s statistics,
and `ORDER BY x` returns `3, 1, 4, 5`. Main returns the same wrong rows for
this file, so this is also a regression test. Could you add the tests below?
Each one fails when its check is removed.
<details>
<summary>Unit test cases for test_ordering_across_row_groups (change the
case arrays to vec!)</summary>
```rs
let stats_without_null_count = |min, max| {
Some(ParquetStatistics::int32(
Some(min),
Some(max),
None,
None,
false,
))
};
// ...
(
"null counts missing",
vec![
row_group(stats_without_null_count(1, 2), &sorted),
row_group(stats_without_null_count(3, 4), &sorted),
],
false,
),
(
"one row group without statistics",
vec![row_group(None, &sorted)],
true,
),
// ...
let metadata = create_parquet_metadata(Arc::clone(&descriptor), row_groups);
```
</details>
<details>
<summary>Integration test for the nested sorting column
(core/tests/parquet/ordering.rs)</summary>
```rs
/// The file declares that it is sorted by `s.x`, whose leaf name is also the
/// name of the top-level column `x`. The statistics of `x` must not be used
to
/// decide the order of `s.x`.
#[tokio::test]
async fn test_nested_sorting_column_does_not_use_top_level_statistics() ->
Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("x", DataType::Int64, true),
Field::new_struct("s", vec![Field::new("x", DataType::Int64, true)],
true),
]));
let row_group = |x: [i64; 2], s_x: [i64; 2]| {
let s = StructArray::from(vec![(
Arc::new(Field::new("x", DataType::Int64, true)),
Arc::new(Int64Array::from(s_x.to_vec())) as ArrayRef,
)]);
RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(Int64Array::from(x.to_vec())), Arc::new(s)],
)
};
let tmp_dir = tempdir()?;
let path = tmp_dir.path().join("data.parquet");
let properties = WriterProperties::builder()
.set_sorting_columns(Some(vec![SortingColumn {
column_idx: 1,
descending: false,
nulls_first: false,
}]))
.build();
let mut writer = ArrowWriter::try_new(
File::create(&path)?,
Arc::clone(&schema),
Some(properties),
)?;
// `x` is not sorted within a row group, but its row-group bounds are
ordered
for batch in [row_group([3, 1], [1, 2])?, row_group([5, 4], [3, 4])?] {
writer.write(&batch)?;
writer.flush()?;
}
writer.close()?;
let ctx = SessionContext::new();
ctx.register_parquet("t", path.to_str().unwrap(),
ParquetReadOptions::default())
.await?;
let results = ctx
.sql("SELECT x FROM t ORDER BY x")
.await?
.collect()
.await?;
assert_snapshot!(batches_to_string(&results), @r"
+---+
| x |
+---+
| 1 |
| 3 |
| 4 |
| 5 |
+---+
");
Ok(())
}
```
Imports: `std::sync::Arc`, `arrow::array::{ArrayRef, Int64Array,
StructArray}`, `arrow::datatypes::{DataType, Field, Schema}`.
</details>
##########
datafusion/datasource-parquet/src/metadata.rs:
##########
@@ -1276,6 +1294,132 @@ fn sorting_columns_to_physical_exprs(
.collect()
}
+/// Returns how many leading `sorting_columns` are ordered across the whole
+/// file, given that every row group is sorted by all of them.
+///
+/// The row group statistics give the values that sort first and last in each
+/// row group. The file is ordered if the value that sorts last in each row
+/// group is not after the value that sorts first in the next row group. For
+/// `a ASC`:
+///
+/// ```text
+/// row groups [1, 2] [3, 4]: ordered, because 2 <= 3
+/// row groups [1, 4] [2, 3]: not ordered, because 4 > 2
+/// ```
+///
+/// A later column must be ordered only where all earlier columns are equal.
+/// For `a ASC, b ASC`:
+///
+/// ```text
+/// row groups [(1, 8), (1, 9)] [(2, 0), (2, 1)]: ordered by (a, b), because a
increases
+/// row groups [(1, 8), (1, 9)] [(1, 0), (1, 1)]: ordered by (a) only, because
a is equal and 9 > 0
+/// ```
+///
+/// A column whose order cannot be proved, for example because it has no
+/// usable statistics, counts as not ordered. Ordering is optional information,
+/// so this never fails the query.
+fn num_columns_ordered_across_row_groups(
+ metadata: &ParquetMetaData,
+ sorting_columns: &[SortingColumn],
+) -> usize {
+ let row_groups = metadata.row_groups();
+ if row_groups.len() < 2 {
+ return sorting_columns.len();
+ }
+ let file_metadata = metadata.file_metadata();
+ let parquet_schema = file_metadata.schema_descr();
+ let Ok(arrow_schema) =
+ parquet_to_arrow_schema(parquet_schema,
file_metadata.key_value_metadata())
+ else {
+ return 0;
+ };
+ let resolver = LeafResolver::new(parquet_schema, &arrow_schema);
+
+ let mut sort_exprs = vec![];
+ let mut fields = vec![];
+ let mut mins = vec![];
+ let mut maxes = vec![];
+ for (num_ordered, sorting_column) in sorting_columns.iter().enumerate() {
+ let Some((min, max)) =
+ row_group_min_max(row_groups, parquet_schema, &resolver,
sorting_column)
+ else {
+ return num_ordered;
+ };
+ // `MinMaxStatistics` finds a column by name, so name it by its
position
+ let name = num_ordered.to_string();
+ sort_exprs.push(PhysicalSortExpr::new(
+ Arc::new(Column::new(&name, num_ordered)),
+ SortOptions::new(sorting_column.descending,
sorting_column.nulls_first),
+ ));
+ fields.push(Field::new(name, min.data_type().clone(), true));
+ mins.push(min);
+ maxes.push(max);
+
+ let statistics = || {
+ let schema = Arc::new(Schema::new(fields.clone()));
+ let mins = RecordBatch::try_new(Arc::clone(&schema),
mins.clone()).ok()?;
+ let maxes = RecordBatch::try_new(Arc::clone(&schema),
maxes.clone()).ok()?;
+ let sort_order = LexOrdering::new(sort_exprs.iter().cloned())?;
+ MinMaxStatistics::new(&sort_order, &schema, mins, maxes).ok()
+ };
+ let Some(statistics) = statistics().filter(|statistics|
statistics.is_sorted())
+ else {
+ return num_ordered;
+ };
+ // Each row group ends before the next one starts, so the later sorting
+ // columns cannot change the order
+ if (1..row_groups.len()).all(|i| statistics.max(i - 1) <
statistics.min(i)) {
+ break;
+ }
+ }
+ sorting_columns.len()
+}
+
+/// Returns the min and the max of `sorting_column` in each row group, as two
+/// arrays with one entry per row group. Where a row group has NULLs, the entry
+/// on the side where NULLs sort is NULL. Returns `None` if the statistics do
+/// not provide the values.
+fn row_group_min_max(
+ row_groups: &[RowGroupMetaData],
+ parquet_schema: &SchemaDescriptor,
+ resolver: &LeafResolver,
+ sorting_column: &SortingColumn,
+) -> Option<(ArrayRef, ArrayRef)> {
+ let column_index = usize::try_from(sorting_column.column_idx).ok()?;
+ let name = parquet_schema.columns().get(column_index)?.name();
+ // The statistics must belong to the sorting column
+ if resolver.leaf_index(name) != Some(column_index) {
+ return None;
+ }
+ let converter = resolver
+ .converter(name)
+ .ok()?
+ .with_missing_null_counts_as_zero(false);
+ let mins = converter.row_group_mins(row_groups).ok()?;
+ let maxes = converter.row_group_maxes(row_groups).ok()?;
+ let null_counts = converter.row_group_null_counts(row_groups).ok()?;
Review Comment:
Float columns with a NaN in any row group except the last still give wrong
rows: Parquet min/max leave NaN out, so `[1.0, NaN] [2.0, 3.0]` declared ASC
passes the check and `ORDER BY a` returns `1, NaN, 2, 3` (main does the same).
The arrow-rs writer records `nan_count`, so a narrow gate fixes files that have
it and changes nothing for files without it. I'm fine with this going into a
follow-up under #15812 to keep float changes out of this PR, as @alamb asked.
If you defer it, could the doc comment on
`num_columns_ordered_across_row_groups` mention that NaN isn't covered?
```rs
let null_counts = converter.row_group_null_counts(row_groups).ok()?;
// Statistics exclude NaN, which sorts outside the min and max
// (https://github.com/apache/datafusion/issues/15812)
let nan_counts = converter.row_group_nan_counts(row_groups).ok()?;
if nan_counts.iter().any(|count| count.is_some_and(|count| count > 0)) {
return None;
}
```
<details>
<summary>Probe (add to core/tests/parquet/ordering.rs; with the gate it
returns 1, 2, 3, NaN)</summary>
```rs
#[tokio::test]
async fn test_row_groups_with_nan_are_sorted() -> Result<()> {
let row_groups = [
record_batch!(("a", Float64, [1.0, f64::NAN]))?,
record_batch!(("a", Float64, [2.0, 3.0]))?,
];
let output =
query_row_groups(&row_groups, ASC_NULLS_LAST, "SELECT a FROM t ORDER
BY a")
.await?;
println!("{output}");
Ok(())
}
```
</details>
--
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]