alamb commented on code in PR #27163:
URL: https://github.com/apache/datafusion/pull/27163#discussion_r4590295801
##########
datafusion/datasource-parquet/src/metadata.rs:
##########
@@ -1209,6 +1217,19 @@ pub fn ordering_from_parquet_metadata(
return Ok(None);
};
+ // In case sorting_columns differ across row_groups, we return early
Review Comment:
this looks like the right fix 👍
##########
datafusion/datasource-parquet/src/metadata.rs:
##########
@@ -1248,6 +1267,142 @@ 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 column_bounds: Vec<_> = sorting_columns
+ .iter()
+ .map(|sorting_column| {
+ row_group_sort_bounds(row_groups, parquet_schema, &resolver,
sorting_column)
+ })
+ .collect();
+
+ let mut num_ordered = sorting_columns.len();
+ // Compare each row group with the next one, column by column
+ for i in 0..row_groups.len() - 1 {
+ let columns = sorting_columns.iter().zip(&column_bounds);
+ for (column, (sorting_column, bounds)) in
columns.take(num_ordered).enumerate() {
+ let Some(bounds) = bounds else {
+ num_ordered = column;
+ break;
+ };
+ let options = [SortOptions::new(
+ sorting_column.descending,
+ sorting_column.nulls_first,
+ )];
+ let last = std::slice::from_ref(&bounds[i].1);
+ let next_first = std::slice::from_ref(&bounds[i + 1].0);
+ // An unsupported comparison does not prove the order
+ match compare_rows(last, next_first, &options) {
+ // In order, so the later columns do not matter here
+ Ok(Ordering::Less) => break,
+ // Equal, so the next column decides
+ Ok(Ordering::Equal) => {}
+ Ok(Ordering::Greater) | Err(_) => {
+ num_ordered = column;
+ break;
+ }
+ }
+ }
+ }
+ num_ordered
+}
+
+/// Returns the values that sort first and last in each row group under
+/// `sorting_column`, or `None` if the statistics do not provide them.
+fn row_group_sort_bounds(
+ row_groups: &[RowGroupMetaData],
+ parquet_schema: &SchemaDescriptor,
+ resolver: &LeafResolver,
+ sorting_column: &SortingColumn,
+) -> Option<Vec<(ScalarValue, ScalarValue)>> {
+ 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()?;
+ let null = ScalarValue::try_new_null(mins.data_type()).ok()?;
+
+ row_groups
+ .iter()
+ .enumerate()
+ .map(|(i, row_group)| {
+ if null_counts.is_null(i) {
+ return None;
+ }
+ let null_count = null_counts.value(i);
+ if null_count == row_group.num_rows() as u64 {
+ return Some((null.clone(), null.clone()));
+ }
+ if mins.is_null(i) || maxes.is_null(i) {
+ return None;
+ }
+ let min = ScalarValue::try_from_array(&mins, i).ok()?;
Review Comment:
👎 using scalar values here will be quite slow -- let's use the code in
parquet to convert statistics to arrays and then use kernels
##########
datafusion/datasource-parquet/src/metadata.rs:
##########
@@ -1183,9 +1185,15 @@ pub(crate) fn lex_ordering_to_sorting_columns(
/// Extracts ordering information from Parquet metadata.
///
-/// This function reads the sorting_columns from the first row group's metadata
+/// This function reads the sorting_columns from the row group metadata
/// and converts them into a [`LexOrdering`] that can be used by the query
engine.
///
+/// Parquet declares sorting_columns per row group, so they only describe the
+/// order of rows within one row group. The ordering is returned for the file
+/// only if all row groups declare the same sorting_columns. It is limited to
+/// the leading columns that the row group statistics show to be ordered from
+/// one row group to the next.
Review Comment:
I double checked this is the case
👍 --
https://github.com/apache/parquet-format/blob/5cc18cae643835b19f869d3cffb085cd3c04eb15/src/main/thrift/parquet.thrift#L1078
##########
datafusion/core/tests/parquet/ordering.rs:
##########
@@ -168,3 +178,257 @@ fn find_parquet_file(
Ok(None)
}
+
+const ASC_NULLS_LAST: SortOptions = SortOptions {
+ descending: false,
+ nulls_first: false,
+};
+
+/// Each row group is sorted by `a`, but the file is not.
+#[tokio::test]
+async fn test_unordered_row_groups_are_sorted() -> Result<()> {
Review Comment:
what are all these tests for?
Reading the ticket, it seems the issue is that DataFusion is assuming the
sort order of all row groups is the same which may not be the case
Why are we testing unordered row groups?
##########
datafusion/datasource-parquet/src/metadata.rs:
##########
@@ -1248,6 +1267,142 @@ 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 column_bounds: Vec<_> = sorting_columns
+ .iter()
+ .map(|sorting_column| {
+ row_group_sort_bounds(row_groups, parquet_schema, &resolver,
sorting_column)
+ })
+ .collect();
+
+ let mut num_ordered = sorting_columns.len();
+ // Compare each row group with the next one, column by column
+ for i in 0..row_groups.len() - 1 {
+ let columns = sorting_columns.iter().zip(&column_bounds);
+ for (column, (sorting_column, bounds)) in
columns.take(num_ordered).enumerate() {
+ let Some(bounds) = bounds else {
+ num_ordered = column;
+ break;
+ };
+ let options = [SortOptions::new(
+ sorting_column.descending,
+ sorting_column.nulls_first,
+ )];
+ let last = std::slice::from_ref(&bounds[i].1);
+ let next_first = std::slice::from_ref(&bounds[i + 1].0);
+ // An unsupported comparison does not prove the order
+ match compare_rows(last, next_first, &options) {
Review Comment:
This is going to be slow for parquet files with many row groups and many
sorting columns as it basically does a row by row comparison with no
vectorization
How about we use this:
https://docs.rs/parquet/latest/parquet/arrow/arrow_reader/statistics/struct.StatisticsConverter.html
to convert the values to an arrow array and then use one of the arrow kernels
I think for example, you could slice and then use `gt` to compare the bounds
##########
datafusion/core/tests/parquet/ordering.rs:
##########
@@ -168,3 +178,257 @@ fn find_parquet_file(
Ok(None)
}
+
+const ASC_NULLS_LAST: SortOptions = SortOptions {
+ descending: false,
+ nulls_first: false,
+};
+
+/// Each row group is sorted by `a`, but the file is not.
+#[tokio::test]
+async fn test_unordered_row_groups_are_sorted() -> Result<()> {
+ let row_groups = [
+ record_batch!(("a", Int64, [1, 4]))?,
+ record_batch!(("a", Int64, [2, 3]))?,
+ ];
+
+ let output = query_row_groups(
+ &row_groups,
+ ASC_NULLS_LAST,
+ "SELECT a FROM t ORDER BY a LIMIT 2",
+ )
+ .await?;
+
+ assert_snapshot!(output, @r"
+ SortExec: TopK(fetch=2), expr=[a@0 ASC NULLS LAST],
preserve_partitioning=[false]
+ DataSourceExec: file_groups={1 group: [[data.parquet]]}, projection=[a],
file_type=parquet, predicate=DynamicFilter [ empty ],
sort_order_for_reorder=[a@0 ASC NULLS LAST], dynamic_rg_pruning=eligible
+ +---+
+ | a |
+ +---+
+ | 1 |
+ | 2 |
+ +---+
+ ");
+ Ok(())
+}
+
+#[tokio::test]
+async fn test_ordered_row_groups_are_not_sorted() -> Result<()> {
+ let row_groups = [
+ record_batch!(("a", Int64, [1, 2]))?,
+ record_batch!(("a", Int64, [2, 3]))?,
+ ];
+
+ let output =
+ query_row_groups(&row_groups, ASC_NULLS_LAST, "SELECT a FROM t ORDER
BY a")
+ .await?;
+
+ assert_snapshot!(output, @r"
+ DataSourceExec: file_groups={1 group: [[data.parquet]]}, projection=[a],
output_ordering=[a@0 ASC NULLS LAST], file_type=parquet
+ +---+
+ | a |
+ +---+
+ | 1 |
+ | 2 |
+ | 2 |
+ | 3 |
+ +---+
+ ");
+ Ok(())
+}
+
+#[tokio::test]
+async fn test_unordered_descending_row_groups_are_sorted() -> Result<()> {
+ let row_groups = [
+ record_batch!(("a", Int64, [4, 1]))?,
+ record_batch!(("a", Int64, [3, 2]))?,
+ ];
+ let sort_options = SortOptions {
+ descending: true,
+ nulls_first: true,
+ };
+
+ let output =
+ query_row_groups(&row_groups, sort_options, "SELECT a FROM t ORDER BY
a DESC")
+ .await?;
+
+ assert_snapshot!(output, @r"
+ SortExec: expr=[a@0 DESC], preserve_partitioning=[false]
+ DataSourceExec: file_groups={1 group: [[data.parquet]]}, projection=[a],
file_type=parquet, sort_order_for_reorder=[a@0 DESC], reverse_row_groups=true
+ +---+
+ | a |
+ +---+
+ | 4 |
+ | 3 |
+ | 2 |
+ | 1 |
+ +---+
+ ");
+ Ok(())
+}
+
+/// The NULL at the end of the first row group comes before the values of the
+/// second row group.
+#[tokio::test]
+async fn test_row_groups_with_unordered_nulls_are_sorted() -> Result<()> {
+ let row_groups = [
+ record_batch!(("a", Int64, [Some(1), None]))?,
+ record_batch!(("a", Int64, [Some(2), Some(3)]))?,
+ ];
+
+ let output =
+ query_row_groups(&row_groups, ASC_NULLS_LAST, "SELECT a FROM t ORDER
BY a")
+ .await?;
+
+ assert_snapshot!(output, @r"
+ SortExec: expr=[a@0 ASC NULLS LAST], preserve_partitioning=[false]
+ DataSourceExec: file_groups={1 group: [[data.parquet]]}, projection=[a],
file_type=parquet, sort_order_for_reorder=[a@0 ASC NULLS LAST]
+ +---+
+ | a |
+ +---+
+ | 1 |
+ | 2 |
+ | 3 |
+ | |
+ +---+
+ ");
+ Ok(())
+}
+
+#[tokio::test]
+async fn test_row_groups_with_ordered_nulls_are_not_sorted() -> Result<()> {
+ let row_groups = [
+ record_batch!(("a", Int64, [None, None]))?,
+ record_batch!(("a", Int64, [None, Some(1)]))?,
+ record_batch!(("a", Int64, [Some(2), Some(3)]))?,
+ ];
+ let sort_options = SortOptions {
+ descending: false,
+ nulls_first: true,
+ };
+
+ let output = query_row_groups(
+ &row_groups,
+ sort_options,
+ "SELECT a FROM t ORDER BY a NULLS FIRST",
+ )
+ .await?;
+
+ assert_snapshot!(output, @r"
+ DataSourceExec: file_groups={1 group: [[data.parquet]]}, projection=[a],
output_ordering=[a@0 ASC], file_type=parquet
+ +---+
+ | a |
+ +---+
+ | |
+ | |
+ | |
+ | 1 |
+ | 2 |
+ | 3 |
+ +---+
+ ");
+ Ok(())
+}
+
+/// `b` starts again in the second row group. This is ordered because `a`
+/// increases between the row groups.
+#[tokio::test]
+async fn test_row_groups_ordered_by_two_columns_are_not_sorted() -> Result<()>
{
+ let row_groups = [
+ record_batch!(("a", Int64, [1, 1]), ("b", Int64, [8, 9]))?,
+ record_batch!(("a", Int64, [2, 2]), ("b", Int64, [0, 1]))?,
+ ];
+
+ let output = query_row_groups(
+ &row_groups,
+ ASC_NULLS_LAST,
+ "SELECT a, b FROM t ORDER BY a, b",
+ )
+ .await?;
+
+ assert_snapshot!(output, @r"
+ DataSourceExec: file_groups={1 group: [[data.parquet]]}, projection=[a,
b], output_ordering=[a@0 ASC NULLS LAST, b@1 ASC NULLS LAST], file_type=parquet
+ +---+---+
+ | a | b |
+ +---+---+
+ | 1 | 8 |
+ | 1 | 9 |
+ | 2 | 0 |
+ | 2 | 1 |
+ +---+---+
+ ");
+ Ok(())
+}
+
+/// `b` starts again in the second row group, but `a` does not increase. The
+/// file is ordered by `a` only.
+#[tokio::test]
+async fn test_row_groups_ordered_by_first_column_only_are_sorted() ->
Result<()> {
+ let row_groups = [
+ record_batch!(("a", Int64, [1, 1]), ("b", Int64, [8, 9]))?,
+ record_batch!(("a", Int64, [1, 1]), ("b", Int64, [0, 1]))?,
+ ];
+
+ let output = query_row_groups(
+ &row_groups,
+ ASC_NULLS_LAST,
+ "SELECT a, b FROM t ORDER BY a, b",
+ )
+ .await?;
+
+ assert_snapshot!(output, @r"
+ SortExec: expr=[a@0 ASC NULLS LAST, b@1 ASC NULLS LAST],
preserve_partitioning=[false]
+ DataSourceExec: file_groups={1 group: [[data.parquet]]}, projection=[a,
b], output_ordering=[a@0 ASC NULLS LAST], file_type=parquet
+ +---+---+
+ | a | b |
+ +---+---+
+ | 1 | 0 |
+ | 1 | 1 |
+ | 1 | 8 |
+ | 1 | 9 |
+ +---+---+
+ ");
+ Ok(())
+}
+
+/// Writes one Parquet file with one row group per batch. Every row group
+/// declares that it is sorted by all columns with `sort_options`. Returns the
+/// plan and the results of `sql`, which reads the file as table `t`.
+async fn query_row_groups(
+ row_groups: &[RecordBatch],
+ sort_options: SortOptions,
+ sql: &str,
+) -> Result<String> {
+ let tmp_dir = tempdir()?;
+ let path = tmp_dir.path().join("data.parquet");
+ let schema = row_groups[0].schema();
+ let sorting_columns = (0..schema.fields().len() as i32)
Review Comment:
does this file actually have different sort orders for each row group?
--
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]