anoopj commented on code in PR #3058: URL: https://github.com/apache/iceberg-rust/pull/3058#discussion_r3867434867
########## crates/iceberg/src/arrow/reader/row_lineage.rs: ########## @@ -0,0 +1,286 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Reader-level synthesis of the v3 `_row_id` metadata column. +//! +//! `_row_id` is `first_row_id + pos`, overridden by a physically-stored `_row_id` where the +//! file carries one. The position comes from the reader-produced `_pos` (`RowNumber`) +//! column, which is the true global file position under filter pushdown, row-group pruning, +//! and page-index pruning -- so synthesis is done here, over the record-batch stream, using +//! that position rather than recomputing it. + +use std::sync::Arc; + +use arrow_arith::boolean::is_not_null; +use arrow_arith::numeric::add; +use arrow_array::{Array, ArrayRef, Int64Array, RecordBatch}; +use arrow_schema::{DataType, Field, Schema}; +use arrow_select::zip::zip; +use parquet::arrow::PARQUET_FIELD_ID_META_KEY; + +use crate::metadata_columns::{ + RESERVED_COL_NAME_ROW_ID, RESERVED_FIELD_ID_POS, RESERVED_FIELD_ID_ROW_ID, +}; +use crate::{Error, ErrorKind, Result}; + +/// Appends the synthesized `_row_id` column to `batch`. +/// +/// - `first_row_id == None`: the file carries no row lineage, so `_row_id` is all-null +/// (matching Java `ValueReaders.rowIds`). +/// - `first_row_id == Some(base)`: `_row_id` is the physically-stored value where the file +/// carries one and it is non-null, else `base + pos` (from the `_pos`/`RowNumber` column). +/// +/// A physically-stored `_row_id` leaf already in `batch` is replaced by the synthesized +/// column (its values are folded in via the coalesce), so the result carries exactly one +/// column tagged with the reserved `_row_id` field id. +pub(crate) fn synthesize_row_id_column( + batch: RecordBatch, + first_row_id: Option<i64>, +) -> Result<RecordBatch> { + let row_id: ArrayRef = match first_row_id { + None => Arc::new(Int64Array::new_null(batch.num_rows())), + Some(base) => { + let pos = column_by_field_id(&batch, RESERVED_FIELD_ID_POS).ok_or_else(|| { + Error::new( + ErrorKind::Unexpected, + "_row_id synthesis requires the _pos position column in the record batch", + ) + })?; + if pos.data_type() != &DataType::Int64 { + return Err(Error::new( + ErrorKind::Unexpected, + format!( + "_pos position column must be Int64, got {}", + pos.data_type() + ), + )); + } + + // base + pos, the fallback for every row. + let fallback = add(pos, &Int64Array::new_scalar(base))?; Review Comment: `arrow_arith::numeric::add` is actually the checked variant. The [doc](https://arrow.apache.org/rust/arrow_arith/numeric/fn.add.html) says > Perform lhs + rhs, returning an error on overflow So i think we should be OK here. ########## crates/iceberg/src/arrow/reader/row_lineage.rs: ########## @@ -0,0 +1,286 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Reader-level synthesis of the v3 `_row_id` metadata column. +//! +//! `_row_id` is `first_row_id + pos`, overridden by a physically-stored `_row_id` where the +//! file carries one. The position comes from the reader-produced `_pos` (`RowNumber`) +//! column, which is the true global file position under filter pushdown, row-group pruning, +//! and page-index pruning -- so synthesis is done here, over the record-batch stream, using +//! that position rather than recomputing it. + +use std::sync::Arc; + +use arrow_arith::boolean::is_not_null; +use arrow_arith::numeric::add; +use arrow_array::{Array, ArrayRef, Int64Array, RecordBatch}; +use arrow_schema::{DataType, Field, Schema}; +use arrow_select::zip::zip; +use parquet::arrow::PARQUET_FIELD_ID_META_KEY; + +use crate::metadata_columns::{ + RESERVED_COL_NAME_ROW_ID, RESERVED_FIELD_ID_POS, RESERVED_FIELD_ID_ROW_ID, +}; +use crate::{Error, ErrorKind, Result}; + +/// Appends the synthesized `_row_id` column to `batch`. +/// +/// - `first_row_id == None`: the file carries no row lineage, so `_row_id` is all-null +/// (matching Java `ValueReaders.rowIds`). +/// - `first_row_id == Some(base)`: `_row_id` is the physically-stored value where the file +/// carries one and it is non-null, else `base + pos` (from the `_pos`/`RowNumber` column). +/// +/// A physically-stored `_row_id` leaf already in `batch` is replaced by the synthesized +/// column (its values are folded in via the coalesce), so the result carries exactly one +/// column tagged with the reserved `_row_id` field id. +pub(crate) fn synthesize_row_id_column( + batch: RecordBatch, + first_row_id: Option<i64>, +) -> Result<RecordBatch> { + let row_id: ArrayRef = match first_row_id { + None => Arc::new(Int64Array::new_null(batch.num_rows())), + Some(base) => { + let pos = column_by_field_id(&batch, RESERVED_FIELD_ID_POS).ok_or_else(|| { + Error::new( + ErrorKind::Unexpected, + "_row_id synthesis requires the _pos position column in the record batch", + ) + })?; + if pos.data_type() != &DataType::Int64 { + return Err(Error::new( + ErrorKind::Unexpected, + format!( + "_pos position column must be Int64, got {}", + pos.data_type() + ), + )); + } + + // base + pos, the fallback for every row. + let fallback = add(pos, &Int64Array::new_scalar(base))?; + match column_by_field_id(&batch, RESERVED_FIELD_ID_ROW_ID) { + Some(id) => { + if id.data_type() != &DataType::Int64 { + return Err(Error::new( + ErrorKind::DataInvalid, + format!("_row_id source must be Int64, got {}", id.data_type()), + )); + } + + zip(&is_not_null(id)?, id, &fallback)? + } + None => fallback, + } + } + }; + + append_row_id(batch, row_id) +} + +/// Returns the batch column tagged with `field_id` (via `PARQUET_FIELD_ID_META_KEY`), if any. +fn column_by_field_id(batch: &RecordBatch, field_id: i32) -> Option<&ArrayRef> { + batch + .schema() + .fields() + .iter() + .position(|f| field_id_of(f) == Some(field_id)) + .map(|idx| batch.column(idx)) +} + +fn field_id_of(field: &Field) -> Option<i32> { + field + .metadata() + .get(PARQUET_FIELD_ID_META_KEY) + .and_then(|id| id.parse::<i32>().ok()) +} + +/// Rebuilds `batch` with `row_id` as its `_row_id` column: any existing `_row_id`-tagged +/// column is dropped (already folded into `row_id`) and the synthesized column is appended. +fn append_row_id(batch: RecordBatch, row_id: ArrayRef) -> Result<RecordBatch> { + let schema = batch.schema(); + let mut fields: Vec<Arc<Field>> = Vec::with_capacity(schema.fields().len() + 1); + let mut columns: Vec<ArrayRef> = Vec::with_capacity(schema.fields().len() + 1); + + for (idx, field) in schema.fields().iter().enumerate() { + if field_id_of(field) != Some(RESERVED_FIELD_ID_ROW_ID) { + fields.push(field.clone()); + columns.push(batch.column(idx).clone()); + } + } + + fields.push(Arc::new( + Field::new(RESERVED_COL_NAME_ROW_ID, DataType::Int64, true).with_metadata( + [( + PARQUET_FIELD_ID_META_KEY.to_string(), + RESERVED_FIELD_ID_ROW_ID.to_string(), + )] + .into(), + ), + )); + columns.push(row_id); + + Ok(RecordBatch::try_new( + Arc::new(Schema::new(fields)), Review Comment: Done. ########## crates/iceberg/src/arrow/reader/pipeline.rs: ########## @@ -1453,6 +1520,680 @@ mod tests { ); } + /// A scan task projecting `id` + `_row_id`, with the given `first_row_id`. + fn row_id_task(file_path: String, first_row_id: Option<i64>) -> FileScanTask { + let schema = Arc::new( + Schema::builder() + .with_schema_id(1) + .with_fields(vec![ + NestedField::required(1, "id", Type::Primitive(PrimitiveType::Int)).into(), + ]) + .build() + .unwrap(), + ); + + FileScanTask::builder() + .with_file_size_in_bytes(std::fs::metadata(&file_path).unwrap().len()) + .with_start(0) + .with_length(0) + .with_data_file_path(file_path) + .with_data_file_format(DataFileFormat::Parquet) + .with_schema(schema) + .with_project_field_ids(vec![1, RESERVED_FIELD_ID_ROW_ID]) + .with_first_row_id(first_row_id) + .with_case_sensitive(false) + .build() + } + + /// Asserts the logical per-row values of the `_row_id` column across all batches, + /// independent of the physical (run-end) encoding. + fn assert_row_id_column(batches: &[RecordBatch], expected: &[Option<i64>]) { + use arrow_array::cast::AsArray; + use arrow_cast::cast; + use arrow_schema::DataType; + + let mut actual = Vec::new(); + for batch in batches { + let col = batch + .column_by_name(RESERVED_COL_NAME_ROW_ID) + .expect("_row_id column should be present"); + let logical = cast(col, &DataType::Int64).unwrap(); + let values = logical.as_primitive::<arrow_array::types::Int64Type>(); + for i in 0..values.len() { + actual.push((!values.is_null(i)).then(|| values.value(i))); + } + } + assert_eq!(actual, expected); + } + + /// A parquet field carrying the embedded `_row_id` field id. + fn physical_row_id_field() -> Field { + Field::new(RESERVED_COL_NAME_ROW_ID, DataType::Int64, true).with_metadata(HashMap::from([ + ( + PARQUET_FIELD_ID_META_KEY.to_string(), + RESERVED_FIELD_ID_ROW_ID.to_string(), + ), + ])) + } + + #[tokio::test] + async fn test_row_id_synthesized_from_first_row_id_and_pos() { + let tmp_dir = TempDir::new().unwrap(); + let dir = tmp_dir.path().to_str().unwrap(); + let file_path = write_plain_parquet(dir, "row_id_synth.parquet", vec![], vec![]); + + // No physical column: every row is first_row_id + pos. + let task = row_id_task(file_path, Some(100)); + + let reader = ArrowReaderBuilder::new(FileIO::new_with_fs(), Runtime::current()).build(); + let tasks = Box::pin(futures::stream::iter(vec![Ok(task)])) as FileScanTaskStream; + let batches: Vec<RecordBatch> = reader + .read(tasks) + .unwrap() + .stream() + .try_collect() + .await + .unwrap(); + + assert_row_id_column(&batches, &[Some(100), Some(101), Some(102)]); + } + + #[tokio::test] + async fn test_row_id_physical_column_coalesced() { + let tmp_dir = TempDir::new().unwrap(); + let dir = tmp_dir.path().to_str().unwrap(); + // A file that physically carries `_row_id`, as written when carrying rows forward + // across a rewrite: some rows have a stored value, some are null. + let id_col = Arc::new(Int64Array::from(vec![Some(5), None, Some(8)])) as ArrayRef; + let file_path = write_plain_parquet( + dir, + "row_id_phys.parquet", + vec![physical_row_id_field()], + vec![id_col], + ); + + let task = row_id_task(file_path, Some(100)); + + let reader = ArrowReaderBuilder::new(FileIO::new_with_fs(), Runtime::current()).build(); + let tasks = Box::pin(futures::stream::iter(vec![Ok(task)])) as FileScanTaskStream; + let batches: Vec<RecordBatch> = reader + .read(tasks) + .unwrap() + .stream() + .try_collect() + .await + .unwrap(); + + // Per-row value where non-null; first_row_id + pos (101) where null. + assert_row_id_column(&batches, &[Some(5), Some(101), Some(8)]); + } + + #[tokio::test] + async fn test_row_id_only_synthesis_reads_no_data_columns() { + // The common v3 case: a new-row file with `first_row_id` set and NO physically + // stored `_row_id`, projecting only `_row_id`. `_row_id` synthesis installs the + // RowNumber virtual column (via `need_row_number`), so the row count comes from it + // -- the scan must read no data columns, not fall back to reading everything. + let tmp_dir = TempDir::new().unwrap(); + let dir = tmp_dir.path().to_str().unwrap(); + + let mut meta_only = metadata_projection_task( + write_parquet_with_wide_column(dir, "row_id_only.parquet", vec![], vec![]), + id_and_wide_schema(), + vec![RESERVED_FIELD_ID_ROW_ID], + ); + meta_only.first_row_id = Some(100); + let (batches, meta_only_bytes) = scan_task(meta_only).await; + + assert_eq!(batches[0].num_columns(), 1); + assert_row_id_column(&batches, &[Some(100), Some(101), Some(102)]); + + // A scan that also projects the wide data column must read materially more. + let mut with_data = metadata_projection_task( + write_parquet_with_wide_column(dir, "row_id_only_ref.parquet", vec![], vec![]), + id_and_wide_schema(), + vec![2, RESERVED_FIELD_ID_ROW_ID], + ); + with_data.first_row_id = Some(100); + let (_, with_data_bytes) = scan_task(with_data).await; + + assert!( + meta_only_bytes < with_data_bytes, + "_row_id-only synthesis should read fewer bytes than a scan of the wide column: \ + {meta_only_bytes} vs {with_data_bytes}" + ); + } + + #[tokio::test] + async fn test_row_id_resolves_alongside_id_less_leaf() { + // A file with an id-less leaf (mimicking a Variant column's internal metadata/value + // leaves, which the spec requires to have no field id) plus a physical `_row_id` + // that carries its embedded id. The reserved id must still resolve -- an + // all-or-nothing field map would bail on the id-less leaf and wrongly reject the file. + let tmp_dir = TempDir::new().unwrap(); + let dir = tmp_dir.path().to_str().unwrap(); + let idless_field = Field::new("variant_internal", DataType::Utf8, true); + let idless_col = Arc::new(StringArray::from(vec!["a", "b", "c"])) as ArrayRef; + let row_id_col = Arc::new(Int64Array::from(vec![Some(5), None, Some(8)])) as ArrayRef; + let file_path = write_plain_parquet( + dir, + "row_id_with_idless_leaf.parquet", + vec![idless_field, physical_row_id_field()], + vec![idless_col, row_id_col], + ); + + let task = row_id_task(file_path, Some(100)); + + let reader = ArrowReaderBuilder::new(FileIO::new_with_fs(), Runtime::current()).build(); + let tasks = Box::pin(futures::stream::iter(vec![Ok(task)])) as FileScanTaskStream; + let batches: Vec<RecordBatch> = reader + .read(tasks) + .unwrap() + .stream() + .try_collect() + .await + .unwrap(); + + // Physical value where non-null; first_row_id + pos (101) where null. + assert_row_id_column(&batches, &[Some(5), Some(101), Some(8)]); + } + + #[tokio::test] + async fn test_row_id_and_last_updated_seq_co_projected() { + use crate::metadata_columns::RESERVED_FIELD_ID_LAST_UPDATED_SEQUENCE_NUMBER; + + // Both lineage columns projected together over a file carrying both physical + // leaves. Each must materialize independently -- neither leaf's mask clobbers the + // other, and the two synthesized columns keep their own values. + let tmp_dir = TempDir::new().unwrap(); + let dir = tmp_dir.path().to_str().unwrap(); + let row_id_col = Arc::new(Int64Array::from(vec![Some(5), None, Some(8)])) as ArrayRef; + let seq_col = Arc::new(Int64Array::from(vec![Some(50), None, Some(70)])) as ArrayRef; + let file_path = write_plain_parquet( + dir, + "row_id_and_seq.parquet", + vec![physical_row_id_field(), physical_last_updated_seq_field()], + vec![row_id_col, seq_col], + ); + + let schema = Arc::new( + Schema::builder() + .with_schema_id(1) + .with_fields(vec![ + NestedField::required(1, "id", Type::Primitive(PrimitiveType::Int)).into(), + ]) + .build() + .unwrap(), + ); + let task = FileScanTask::builder() + .with_file_size_in_bytes(std::fs::metadata(&file_path).unwrap().len()) + .with_start(0) + .with_length(0) + .with_data_file_path(file_path) + .with_data_file_format(DataFileFormat::Parquet) + .with_schema(schema) + .with_project_field_ids(vec![ + 1, + RESERVED_FIELD_ID_ROW_ID, + RESERVED_FIELD_ID_LAST_UPDATED_SEQUENCE_NUMBER, + ]) + .with_first_row_id(Some(100)) + .with_data_sequence_number(Some(9)) + .with_case_sensitive(false) + .build(); + + let reader = ArrowReaderBuilder::new(FileIO::new_with_fs(), Runtime::current()).build(); + let tasks = Box::pin(futures::stream::iter(vec![Ok(task)])) as FileScanTaskStream; + let batches: Vec<RecordBatch> = reader + .read(tasks) + .unwrap() + .stream() + .try_collect() + .await + .unwrap(); + + // _row_id: physical value where non-null, else first_row_id + pos (101). + assert_row_id_column(&batches, &[Some(5), Some(101), Some(8)]); + // _last_updated_sequence_number: physical value where non-null, else data seq (9). + assert_last_updated_seq_column(&batches, &[Some(50), Some(9), Some(70)]); + } + + #[tokio::test] + async fn test_row_id_null_when_no_first_row_id() { + let tmp_dir = TempDir::new().unwrap(); + let dir = tmp_dir.path().to_str().unwrap(); + // Physically carries `_row_id`, but the file has a null first_row_id. + let id_col = Arc::new(Int64Array::from(vec![Some(5), Some(6), Some(7)])) as ArrayRef; + let file_path = write_plain_parquet( + dir, + "row_id_no_first.parquet", + vec![physical_row_id_field()], + vec![id_col], + ); + + // Null first_row_id: the whole column is null; the physical values are not read. + let task = row_id_task(file_path, None); + + let reader = ArrowReaderBuilder::new(FileIO::new_with_fs(), Runtime::current()).build(); + let tasks = Box::pin(futures::stream::iter(vec![Ok(task)])) as FileScanTaskStream; + let batches: Vec<RecordBatch> = reader + .read(tasks) + .unwrap() + .stream() + .try_collect() + .await + .unwrap(); + + assert_row_id_column(&batches, &[None, None, None]); + } + + #[tokio::test] + async fn test_row_id_with_pos_column() { + use crate::metadata_columns::RESERVED_COL_NAME_POS; + + let tmp_dir = TempDir::new().unwrap(); + let dir = tmp_dir.path().to_str().unwrap(); + let id_col = Arc::new(Int64Array::from(vec![Some(5), None, Some(8)])) as ArrayRef; + let file_path = write_plain_parquet( + dir, + "row_id_and_pos.parquet", + vec![physical_row_id_field()], + vec![id_col], + ); + + // Co-project `_pos` and `_row_id`. `_row_id` synthesis consumes the position, and + // `_pos` is also emitted -- the RowNumber column must be added once and the two + // must not interfere. + let schema = Arc::new( + Schema::builder() + .with_schema_id(1) + .with_fields(vec![ + NestedField::required(1, "id", Type::Primitive(PrimitiveType::Int)).into(), + ]) + .build() + .unwrap(), + ); + let task = FileScanTask::builder() + .with_file_size_in_bytes(std::fs::metadata(&file_path).unwrap().len()) + .with_start(0) + .with_length(0) + .with_data_file_path(file_path) + .with_data_file_format(DataFileFormat::Parquet) + .with_schema(schema) + .with_project_field_ids(vec![1, RESERVED_FIELD_ID_POS, RESERVED_FIELD_ID_ROW_ID]) + .with_first_row_id(Some(100)) + .with_case_sensitive(false) + .build(); + + let reader = ArrowReaderBuilder::new(FileIO::new_with_fs(), Runtime::current()).build(); + let tasks = Box::pin(futures::stream::iter(vec![Ok(task)])) as FileScanTaskStream; + let batches: Vec<RecordBatch> = reader + .read(tasks) + .unwrap() + .stream() + .try_collect() + .await + .unwrap(); + + // `_row_id` coalesces correctly... + assert_row_id_column(&batches, &[Some(5), Some(101), Some(8)]); + // ...and `_pos` is the row position, not double-counted. + let pos_col = batches[0] + .column_by_name(RESERVED_COL_NAME_POS) + .expect("_pos column should be present") + .as_primitive::<arrow_array::types::Int64Type>(); + assert_eq!(pos_col.values(), &[0, 1, 2]); + } + + #[tokio::test] + async fn test_row_id_mixed_files_share_schema() { + use arrow_select::concat::concat_batches; + + let tmp_dir = TempDir::new().unwrap(); + let dir = tmp_dir.path().to_str().unwrap(); + + // Three files in one scan exercising all three column paths, which must all + // produce the SAME Arrow type (plain Int64) or concatenation fails: + // - synthesis: first_row_id set, no physical column -> first_row_id + pos + // - null gate: no first_row_id -> null column + // - coalesce: first_row_id set, physical column present -> per-row + fallback + let synth = row_id_task( + write_plain_parquet(dir, "row_id_synth2.parquet", vec![], vec![]), + Some(42), + ); + let nulled = row_id_task( + write_plain_parquet(dir, "row_id_null2.parquet", vec![], vec![]), + None, + ); + let coalesced = row_id_task( + write_plain_parquet( + dir, + "row_id_coalesced2.parquet", + vec![physical_row_id_field()], + vec![Arc::new(Int64Array::from(vec![Some(5), None, Some(8)])) as ArrayRef], + ), + Some(50), + ); + + let reader = ArrowReaderBuilder::new(FileIO::new_with_fs(), Runtime::current()).build(); + let tasks = Box::pin(futures::stream::iter(vec![ + Ok(synth), + Ok(nulled), + Ok(coalesced), + ])) as FileScanTaskStream; + let batches: Vec<RecordBatch> = reader + .read(tasks) + .unwrap() + .stream() + .try_collect() + .await + .unwrap(); + + assert_eq!(batches.len(), 3); + let schema = batches[0].schema(); + concat_batches(&schema, &batches) + .expect("synthesis, null and coalesce files must share one column type"); + } + + #[tokio::test] + async fn test_row_id_present_by_name_without_id_unsupported() { + let tmp_dir = TempDir::new().unwrap(); + let dir = tmp_dir.path().to_str().unwrap(); + // Column present by name but WITHOUT the embedded field id. The transformer keys + // the source column by field id, so this shape can't be threaded and is rejected. + let id_field = Field::new(RESERVED_COL_NAME_ROW_ID, DataType::Int64, true); + let id_col = Arc::new(Int64Array::from(vec![Some(5), None, Some(8)])) as ArrayRef; + let file_path = + write_plain_parquet(dir, "row_id_by_name.parquet", vec![id_field], vec![id_col]); + + let task = row_id_task(file_path, Some(100)); + + let reader = ArrowReaderBuilder::new(FileIO::new_with_fs(), Runtime::current()).build(); + let tasks = Box::pin(futures::stream::iter(vec![Ok(task)])) as FileScanTaskStream; + let result: Result<Vec<RecordBatch>, _> = + reader.read(tasks).unwrap().stream().try_collect().await; + + let err = result.unwrap_err(); + assert_eq!(err.kind(), crate::ErrorKind::FeatureUnsupported); + assert!( + format!("{err}").contains("without an embedded field id"), + "unexpected error: {err}" + ); + } + + /// Builds a `row_id_task` (see above) that additionally carries a bound predicate, + /// so a `RowSelection` is applied when the reader has row selection enabled. + fn row_id_task_with_predicate( + file_path: String, + first_row_id: Option<i64>, + extra_project_field_ids: Vec<i32>, + predicate: crate::expr::Predicate, + ) -> FileScanTask { + use crate::expr::Bind; + + let schema = Arc::new( + Schema::builder() + .with_schema_id(1) + .with_fields(vec![ + NestedField::required(1, "id", Type::Primitive(PrimitiveType::Int)).into(), + ]) + .build() + .unwrap(), + ); + let bound = predicate.bind(Arc::clone(&schema), false).unwrap(); + + let mut project_field_ids = vec![1]; + project_field_ids.extend(extra_project_field_ids); + project_field_ids.push(RESERVED_FIELD_ID_ROW_ID); + + FileScanTask::builder() + .with_file_size_in_bytes(std::fs::metadata(&file_path).unwrap().len()) + .with_start(0) + .with_length(0) + .with_data_file_path(file_path) + .with_data_file_format(DataFileFormat::Parquet) + .with_schema(schema) + .with_project_field_ids(project_field_ids) + .with_predicate(Some(bound)) + .with_first_row_id(first_row_id) + .with_case_sensitive(false) + .build() + } + + #[tokio::test] + async fn test_row_id_stable_under_row_selection() { + use crate::expr::Reference; + use crate::spec::Datum; + + let tmp_dir = TempDir::new().unwrap(); + let dir = tmp_dir.path().to_str().unwrap(); + // id = [1, 2, 3]; drop the middle physical row via a predicate + row selection. + let file_path = write_plain_parquet(dir, "row_id_selection.parquet", vec![], vec![]); + + let task = row_id_task_with_predicate( + file_path, + Some(100), + vec![], + Reference::new("id").not_equal_to(Datum::int(2)), + ); + + // Row selection must be enabled for the predicate to produce a RowSelection. + let reader = ArrowReaderBuilder::new(FileIO::new_with_fs(), Runtime::current()) + .with_row_selection_enabled(true) + .build(); + let tasks = Box::pin(futures::stream::iter(vec![Ok(task)])) as FileScanTaskStream; + let batches: Vec<RecordBatch> = reader + .read(tasks) + .unwrap() + .stream() + .try_collect() + .await + .unwrap(); + + // The survivors are physical rows 0 and 2, so their _row_id is first_row_id + the + // PHYSICAL position: [100, 102]. A dense output index would wrongly give [100, 101]. + assert_row_id_column(&batches, &[Some(100), Some(102)]); + } + + #[tokio::test] + async fn test_row_id_coalesce_stable_under_row_selection() { + use crate::expr::Reference; + use crate::spec::Datum; + + let tmp_dir = TempDir::new().unwrap(); + let dir = tmp_dir.path().to_str().unwrap(); + // Physical _row_id = [Some(5), None, Some(8)] over id = [1, 2, 3]. Dropping the + // middle row must keep the physical column and the RowNumber fallback row-aligned. + let id_col = Arc::new(Int64Array::from(vec![Some(5), None, Some(8)])) as ArrayRef; + let file_path = write_plain_parquet( + dir, + "row_id_coalesce_selection.parquet", + vec![physical_row_id_field()], + vec![id_col], + ); + + let task = row_id_task_with_predicate( + file_path, + Some(100), + vec![], + Reference::new("id").not_equal_to(Datum::int(2)), + ); + + let reader = ArrowReaderBuilder::new(FileIO::new_with_fs(), Runtime::current()) + .with_row_selection_enabled(true) + .build(); + let tasks = Box::pin(futures::stream::iter(vec![Ok(task)])) as FileScanTaskStream; + let batches: Vec<RecordBatch> = reader + .read(tasks) + .unwrap() + .stream() + .try_collect() + .await + .unwrap(); + + // Rows 0 and 2 survive: their stored values (5, 8) pass through. The dropped + // row's null (which would have fallen back to 100 + 1) is gone -- proving the + // physical column and the positional fallback are filtered by the same selection. + assert_row_id_column(&batches, &[Some(5), Some(8)]); + } + + #[tokio::test] + async fn test_row_id_global_across_row_groups() { Review Comment: Added `test_row_id_global_when_first_row_group_pruned` -- 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]
