anoopj commented on code in PR #3058:
URL: https://github.com/apache/iceberg-rust/pull/3058#discussion_r3845705896
##########
crates/iceberg/src/arrow/reader/pipeline.rs:
##########
@@ -1453,6 +1510,523 @@ 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() {
Review Comment:
That makes sense. Added `test_row_id_survives_positional_delete`
--
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]