Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 143 additions & 3 deletions crates/paimon/src/arrow/format/orc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ use crate::spec::{
};
use crate::table::{ArrowRecordBatchStream, RowRange};
use crate::Error;
use arrow_array::RecordBatch;
use arrow_array::{
Array, ArrayRef, LargeStringArray, ListArray, MapArray, RecordBatch, StringArray, StructArray,
};
use arrow_schema::{DataType as ArrowDataType, SchemaRef};
use async_trait::async_trait;
use base64::Engine;
Expand Down Expand Up @@ -412,6 +414,94 @@ impl FormatFileWriter for OrcFormatWriter {
}
}

fn normalize_orc_char(array: &ArrayRef, logical_type: &DataType) -> crate::Result<ArrayRef> {
// ORC CHAR pads on disk; the Java ORC reader removes trailing ASCII spaces.
// Do not trim VARCHAR, Unicode whitespace, or leading spaces.
let invalid = || Error::DataInvalid {
message: format!(
"Unexpected ORC array {} for {logical_type:?}",
array.data_type()
),
source: None,
};
let children = match logical_type {
DataType::Char(_) => {
if let Some(strings) = array.as_any().downcast_ref::<StringArray>() {
return Ok(Arc::new(StringArray::from_iter(
strings
.iter()
.map(|value| value.map(|s| s.trim_end_matches(' '))),
)));
}
if let Some(strings) = array.as_any().downcast_ref::<LargeStringArray>() {
return Ok(Arc::new(LargeStringArray::from_iter(
strings
.iter()
.map(|value| value.map(|s| s.trim_end_matches(' '))),
)));
}
return Err(invalid());
}
DataType::Array(ty) => {
let values = array
.as_any()
.downcast_ref::<ListArray>()
.ok_or_else(invalid)?;
vec![normalize_orc_char(values.values(), ty.element_type())?.to_data()]
}
DataType::Map(ty) => {
let values = array
.as_any()
.downcast_ref::<MapArray>()
.ok_or_else(invalid)?;
let entries = values
.entries()
.to_data()
.into_builder()
.child_data(vec![
normalize_orc_char(values.keys(), ty.key_type())?.to_data(),
normalize_orc_char(values.values(), ty.value_type())?.to_data(),
])
.build()
.map_err(|e| Error::DataInvalid {
message: format!("Invalid normalized ORC CHAR map: {e}"),
source: Some(Box::new(e)),
})?;
vec![entries]
}
DataType::Row(ty) => {
let values = array
.as_any()
.downcast_ref::<StructArray>()
.ok_or_else(invalid)?;
values
.fields()
.iter()
.zip(values.columns())
.map(|(field, column)| {
match ty.fields().iter().find(|f| f.name() == field.name()) {
Some(field) => {
normalize_orc_char(column, field.data_type()).map(|a| a.to_data())
}
None => Ok(column.to_data()),
}
})
.collect::<crate::Result<Vec<_>>>()?
}
_ => return Ok(Arc::clone(array)),
};
array
.to_data()
.into_builder()
.child_data(children)
.build()
.map(arrow_array::make_array)
.map_err(|e| Error::DataInvalid {
message: format!("Invalid normalized ORC CHAR array: {e}"),
source: Some(Box::new(e)),
})
}

#[async_trait]
impl FormatFileReader for OrcFormatReader {
async fn read_batch_stream(
Expand Down Expand Up @@ -479,6 +569,7 @@ impl FormatFileReader for OrcFormatReader {
// columns; DataFileReader projects to the requested output by name afterwards.
// Own the predicate context (scan_fields + cloned FilePredicates) for the
// 'static stream.
let logical_fields = scan_fields.clone();
let residual: Option<(FilePredicates, Vec<DataField>)> = predicates.map(|fp| {
(
FilePredicates {
Expand All @@ -492,10 +583,33 @@ impl FormatFileReader for OrcFormatReader {
Ok(stream
.map(move |r| {
let batch = r.map_err(|error| orc_error(error, "ORC read error"))?;
let batch = match &map_read_plan {
let mut batch = match &map_read_plan {
Some(plan) => plan.assemble_batch(&batch)?,
None => batch,
};
let schema = batch.schema();
let columns = schema
.fields()
.iter()
.zip(batch.columns())
.map(|(field, column)| {
match logical_fields.iter().find(|f| f.name() == field.name()) {
Some(field) => normalize_orc_char(column, field.data_type()),
None => Ok(Arc::clone(column)),
}
})
.collect::<crate::Result<Vec<_>>>()?;
if columns
.iter()
.zip(batch.columns())
.any(|(a, b)| !Arc::ptr_eq(a, b))
{
batch =
RecordBatch::try_new(schema, columns).map_err(|e| Error::DataInvalid {
message: format!("Failed to rebuild ORC batch: {e}"),
source: Some(Box::new(e)),
})?;
}
match &residual {
Some((fp, scan_fields)) => {
crate::arrow::residual::filter_record_batch_by_predicates(
Expand Down Expand Up @@ -718,7 +832,9 @@ fn datum_to_orc_value(datum: &Datum, data_type: &DataType) -> Option<PredicateVa
(Datum::Long(value), DataType::BigInt(_)) => Some(PredicateValue::Int64(Some(*value))),
(Datum::Float(value), DataType::Float(_)) => Some(PredicateValue::Float32(Some(*value))),
(Datum::Double(value), DataType::Double(_)) => Some(PredicateValue::Float64(Some(*value))),
(Datum::String(value), DataType::Char(_) | DataType::VarChar(_)) => {
// CHAR values are normalized before residual evaluation; raw padded ORC
// statistics must not exclude a matching unpadded value.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Prevent manifest statistics from dropping padded CHAR matches before the ORC reader opens the file. Java's OrcSimpleStatsExtractor copies the raw string bounds into file metadata. I confirmed that a physical CHAR(4) file stores an AB value as AB in its stats. I wrote a table with the same padded values, committed its file with Java-style bounds (AB to CD ), and planned code = 'AB'. The plan contained zero splits, although the direct ORC read correctly returned AB. Make table-level file pruning fail open for these CHAR comparisons or use safe normalized bounds, and exercise the full TableScan path in a regression test.

(Datum::String(value), DataType::VarChar(_)) => {
Some(PredicateValue::Utf8(Some(value.clone())))
}
_ => None,
Expand Down Expand Up @@ -819,6 +935,30 @@ impl AsyncChunkReader for OrcFileReader {
mod tests {
use super::*;
use arrow_array::{Array, Int32Array, RecordBatch, StringArray};

#[test]
fn orc_char_normalization_preserves_nulls_slices_and_non_padding_whitespace() {
use crate::spec::{CharType, VarCharType};
let input: ArrayRef = Arc::new(StringArray::from(vec![
Some("unused"),
Some(" AB "),
None,
Some(" "),
Some("中\t "),
Some("x\u{a0} "),
]));
let input = input.slice(1, 5);
let output =
normalize_orc_char(&input, &DataType::Char(CharType::new(8).unwrap())).unwrap();
let output = output.as_any().downcast_ref::<StringArray>().unwrap();
assert_eq!(
output.iter().collect::<Vec<_>>(),
vec![Some(" AB"), None, Some(""), Some("中\t"), Some("x\u{a0}")]
);
let unchanged =
normalize_orc_char(&input, &DataType::VarChar(VarCharType::string_type())).unwrap();
assert_eq!(unchanged.as_ref(), input.as_ref());
}
use arrow_schema::{DataType as ArrowDataType, Field, Schema};
use orc_rust::row_selection::RowSelector;
use std::sync::Arc;
Expand Down
Loading