jpfeuffer opened a new issue, #27745:
URL: https://github.com/apache/datafusion/issues/27745

   ### Describe the bug
   
   Parquet `sorting_columns` metadata is written with top-level Arrow field 
indices, but Parquet defines `SortingColumn.column_idx` as the ordinal of a 
leaf column in the row group. When the written schema contains a struct, that 
struct expands to multiple Parquet leaf columns. As a result, a sort key after 
the struct can be recorded against one of the struct's children instead of the 
actual sort key.
   
   For example, with `payload: Struct<a, b>, id: Int64`, sorting by `id` is 
recorded as `column_idx = 1`, because `id` is top-level field 1. In the Parquet 
schema the leaves are `payload.a = 0`, `payload.b = 1`, and `id = 2`, so the 
metadata declares that the file is sorted by `payload.b`.
   
   
   ### To Reproduce
   
   Reproduced with `datafusion==55.0.0` and `pyarrow==26.0.1`. This writes a 
table ordered by `id`; the values of `payload.b` deliberately run in the 
opposite direction:
   
   ```python
   import tempfile
   from pathlib import Path
   
   import pyarrow as pa
   import pyarrow.parquet as pq
   from datafusion import SessionConfig, SessionContext
   
   ctx = SessionContext(SessionConfig().with_target_partitions(1))
   
   with tempfile.TemporaryDirectory() as directory:
       output = Path(directory) / "output"
       output.mkdir()
   
       ctx.sql(f"""
           CREATE EXTERNAL TABLE sorted_data (
             payload STRUCT<a BIGINT, b BIGINT>,
             id BIGINT
           ) STORED AS PARQUET
           LOCATION '{output}'
           WITH ORDER (id ASC NULLS FIRST)
       """).collect()
   
       batch = pa.record_batch(
           [
               pa.array(
                   [{"a": 3, "b": 1}, {"a": 1, "b": 3}, {"a": 2, "b": 2}],
                   type=pa.struct([("a", pa.int64()), ("b", pa.int64())]),
               ),
               pa.array([3, 1, 2], type=pa.int64()),
           ],
           names=["payload", "id"],
       )
       ctx.register_record_batches("input_data", [[batch]])
       ctx.sql("INSERT INTO sorted_data SELECT payload, id FROM 
input_data").collect()
   
       files = list(output.rglob("*.parquet"))
       assert len(files) == 1, files
       pf = pq.ParquetFile(files[0])
       print("leaf columns:", [pf.schema.column(i).path for i in 
range(len(pf.schema))])
       print("sorting metadata:", pf.metadata.row_group(0).sorting_columns)
       print("rows:", pf.read().to_pylist())
   ```
   
   Actual output:
   
   ```text
   leaf columns: ['payload.a', 'payload.b', 'id']
   sorting metadata: (SortingColumn(column_index=1, descending=False, 
nulls_first=True),)
   rows: [{'payload': {'a': 1, 'b': 3}, 'id': 1}, {'payload': {'a': 2, 'b': 2}, 
'id': 2}, {'payload': {'a': 3, 'b': 1}, 'id': 3}]
   ```
   
   The declared column `payload.b` is descending, not ascending. The correct 
index for the `id` ordering is 2. The released version was run; current `main` 
was inspected at commit 
[`ee92b7418fc47969dcee06a5762a43976e825420`](https://github.com/apache/datafusion/commit/ee92b7418fc47969dcee06a5762a43976e825420)
 but was not run.
   
   
   ### Expected behavior
   
   `sorting_columns` should use the index of the actual Parquet leaf column 
corresponding to the sort key. A struct before a scalar sort key must not shift 
the metadata index incorrectly. A struct sort may permit a conservative 
leaf-ordering prefix, but writing later sort keys requires care: leaf values 
alone can make a null struct indistinguishable from a non-null struct whose 
children are all null. If the full ordering cannot be represented faithfully, 
retain only a prefix that can be justified.
   
   
   ### Additional context
   
   ## Code pointers
   
   - 
[`sort_expr_to_sorting_column`](https://github.com/apache/datafusion/blob/ee92b7418fc47969dcee06a5762a43976e825420/datafusion/datasource-parquet/src/metadata.rs#L1148-L1190)
 resolves the sort expression to a top-level field and assigns that field's 
`writer_index` directly to `SortingColumn.column_idx`.
   - 
[`lex_ordering_to_sorting_columns`](https://github.com/apache/datafusion/blob/ee92b7418fc47969dcee06a5762a43976e825420/datafusion/datasource-parquet/src/metadata.rs#L1193-L1210)
 applies that conversion to each ordering expression.
   - 
[`ParquetFormat::create_writer_physical_plan`](https://github.com/apache/datafusion/blob/ee92b7418fc47969dcee06a5762a43976e825420/datafusion/datasource-parquet/src/file_format.rs#L725-L749)
 derives the metadata from the output and writer schemas and passes it to the 
sink.
   - [`ArrowWriter` leaf 
mapping](https://github.com/apache/arrow-rs/blob/main/parquet/src/arrow/arrow_writer/mod.rs#L1300-L1319)
 expands each Arrow field into a range of Parquet leaves.
   - The [Parquet 
format](https://github.com/apache/parquet-format/blob/master/src/main/thrift/parquet.thrift#L888-L901)
 defines `SortingColumn` as the sort order of a leaf column.
   
   
   ### Willingness to contribute
   
   I would like to contribute a fix for this bug, but request guidance from the 
DataFusion community


-- 
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]

Reply via email to