rich7420 commented on code in PR #6246:
URL: https://github.com/apache/datafusion-comet/pull/6246#discussion_r4775317934
##########
native/core/src/parquet/parquet_exec.rs:
##########
@@ -506,6 +744,510 @@ mod tests {
assert!(!calls_jvm(&native));
}
+ /// How many rows of a scan hold each decoded value of `s`.
+ type DecodedCounts = BTreeMap<Option<String>, usize>;
+
+ /// Writes three 500-row row groups with `a` counting from 0, 1,000 and
2,000, and `s` holding
+ /// `values[i]` in every row of group `i` as `s_type`. A scan's values
then show which groups a
+ /// filter pruned.
+ fn write_binary_as_string_fixture(
+ s_type: DataType,
+ values: [Option<&[u8]>; 3],
+ ) -> PartitionedFile {
+ let file_schema = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::Int32, false),
+ Field::new("s", s_type.clone(), true),
+ ]));
+ let filename = get_temp_filename()
+ .as_path()
+ .as_os_str()
+ .to_str()
+ .unwrap()
+ .to_string();
+ let props = WriterProperties::builder()
+ .set_max_row_group_row_count(Some(500))
+ .build();
+ let file = File::create(&filename).unwrap();
+ let mut writer = ArrowWriter::try_new(file, Arc::clone(&file_schema),
Some(props)).unwrap();
+ for (group, value) in values.into_iter().enumerate() {
+ let start = group as i32 * 1_000;
+ let s = arrow::compute::cast(&BinaryArray::from(vec![value; 500]),
&s_type).unwrap();
+ let a = Arc::new(Int32Array::from((start..start +
500).collect::<Vec<i32>>()));
+ let batch = RecordBatch::try_new(Arc::clone(&file_schema), vec![a,
s]).unwrap();
+ writer.write(&batch).unwrap();
+ }
+ writer.close().unwrap();
+ PartitionedFile::from_path(filename).unwrap()
+ }
+
+ fn binary_as_string_required_schema() -> SchemaRef {
+ Arc::new(Schema::new(vec![
+ Field::new("a", DataType::Int32, false),
+ Field::new("s", DataType::Utf8, true),
+ ]))
+ }
+
+ /// A session whose scans evaluate pushed filters on every row when
`row_filter` is set, and
+ /// otherwise use them only to prune row groups.
+ fn binary_as_string_session(row_filter: bool) -> Arc<SessionContext> {
+ let mut config = SessionConfig::new();
+ config.options_mut().execution.parquet.pushdown_filters = row_filter;
+ Arc::new(SessionContext::new_with_config(config))
+ }
+
+ /// A scan of `file` with `binaryAsString` on, reading `s` as a string.
+ fn binary_as_string_scan(
+ file: &PartitionedFile,
+ filters: Vec<Arc<dyn PhysicalExpr>>,
+ session_ctx: &Arc<SessionContext>,
+ ) -> Arc<DataSourceExec> {
+ let required_schema = binary_as_string_required_schema();
+ init_datasource_exec(
+ Arc::clone(&required_schema),
+ Some(required_schema),
+ None,
+ ObjectStoreUrl::local_filesystem(),
+ ObjectStoreBackend::Local,
+ vec![vec![file.clone()]],
+ Some(vec![0, 1]),
+ Some(filters),
+ None,
+ "UTC",
+ true,
+ false,
+ false,
+ false,
+ true,
+ session_ctx,
+ false,
+ false,
+ false,
+ false,
+ "",
+ "",
+ )
+ .unwrap()
+ }
+
+ /// Counts the decoded values of `s` that `scan` returns. The scan has no
residual filter, so
+ /// it returns every row of each row group its filters keep, or with row
filters only the rows
+ /// they match.
+ async fn decoded_counts(
+ scan: &Arc<DataSourceExec>,
+ session_ctx: &Arc<SessionContext>,
+ ) -> DecodedCounts {
+ let batches: Vec<RecordBatch> = scan
+ .execute(0, session_ctx.task_ctx())
+ .unwrap()
+ .map(|batch| batch.unwrap())
+ .collect()
+ .await;
+ let mut counts = BTreeMap::new();
+ for batch in &batches {
+ assert_eq!(batch.schema().field(1).data_type(), &DataType::Utf8);
+ for value in batch.column(1).as_string::<i32>() {
+ *counts.entry(value.map(str::to_string)).or_insert(0) += 1;
+ }
+ }
+ counts
+ }
+
+ async fn scan_binary_as_string(
+ file: &PartitionedFile,
+ filters: Vec<Arc<dyn PhysicalExpr>>,
+ row_filter: bool,
+ ) -> DecodedCounts {
+ let session_ctx = binary_as_string_session(row_filter);
+ decoded_counts(
+ &binary_as_string_scan(file, filters, &session_ctx),
+ &session_ctx,
+ )
+ .await
+ }
+
+ fn compare_s(op: Operator, value: &str) -> Arc<dyn PhysicalExpr> {
+ let literal = Literal::new(ScalarValue::Utf8(Some(value.to_string())));
+ Arc::new(BinaryExpr::new(
+ Arc::new(Column::new("s", 1)),
+ op,
+ Arc::new(literal),
+ ))
+ }
+
+ fn s_in(values: &[&str], negated: bool) -> Arc<dyn PhysicalExpr> {
+ let values = values
+ .iter()
+ .map(|value| {
+ let literal =
Literal::new(ScalarValue::Utf8(Some(value.to_string())));
+ Arc::new(literal) as Arc<dyn PhysicalExpr>
+ })
+ .collect();
+ let schema = binary_as_string_required_schema();
+ in_list(Arc::new(Column::new("s", 1)), values, &negated,
&schema).unwrap()
+ }
+
+ fn groups(values: &[Option<&str>]) -> DecodedCounts {
+ values
+ .iter()
+ .map(|value| (value.map(str::to_string), 500))
+ .collect()
+ }
+
+ /// A `binaryAsString` scan that projects no string column has nothing to
read as Binary, so
+ /// it builds the same plan as with the setting off, with the projection
as indices.
+ #[test]
+ fn binary_as_string_leaves_scan_without_string_columns_unchanged() {
Review Comment:
Thanks, asserting `DataType::Utf8` on `table_schema` catches removing the
gate now. Looks good!
##########
docs/source/contributor-guide/spark_configs_support.md:
##########
@@ -151,3 +157,70 @@ Comet bugs were uncovered by the original audit. The
`try_to_timestamp` policy t
use the default `query` mode to enforce both result correctness and execution
within
the Comet pipeline. Tests for expressions with known fallback paths continue
to use
`query spark_answer_only`.
+
+### `spark.sql.parquet.binaryAsString`
+
+**Source.** When enabled, Spark infers unannotated Parquet `BINARY` columns as
+`StringType`. Parquet files written by Spark carry Spark schema metadata, so
this
+configuration does not change the types inferred for those files. The
inference in
+`ParquetToSparkSchemaConverter` and the `BINARY` cases of `ParquetFilters` are
the same in every
+Spark version listed above.
+
+**Comet status.** Comet honors the configuration in the native Parquet scan.
When it is
+enabled, the scan plans every top-level string column as Arrow `Binary`.
Columns that arrow-rs reads
+as `Binary` are decoded to valid UTF-8 at the scan boundary using
Spark-compatible replacement
+semantics. arrow-rs validates UTF-8 only for Parquet columns with the `UTF8`
annotation. Reading
+malformed unannotated bytes directly as Arrow `Utf8` would create an invalid
string array, which is
+undefined behavior.
+Spark's schema doesn't say which file columns carry the `UTF8` annotation, so
the expression adapter
+decides per file: where arrow-rs reads the column as `Utf8`, it reads the
column directly, without
+the cast to `Binary` and back. This includes JSON-annotated `BINARY` columns
and unannotated columns
+that an embedded `ARROW:schema` types as `Utf8`. Both are read without UTF-8
validation, as they are
+with the configuration off. The default `false` value continues to return
unannotated
+`BINARY` columns as `BinaryType`.
+
+**Filter pushdown.** While the configuration is enabled, the scan rewrites
`=`, `IN` and
+`IS [NOT] NULL` on a top-level string column to compare raw bytes, so `value =
'one'` becomes
+`value = X'6F6E65'`. A valid value decodes to itself, and a malformed one to a
string containing
+`U+FFFD`, so for a literal without `U+FFFD` the rewritten filter keeps exactly
the rows the
+original keeps. Other filters on these columns compare the decoded value,
because decoding can
+reorder values: `"a\x80"` sorts below `"aƩ"` as bytes, but `"a\uFFFD"` sorts
above it. That covers
+ranges, `LIKE`, function calls and literals containing `U+FFFD`. They filter
rows when
+`spark.comet.parquet.rowFilterPushdown.enabled` is on, but cannot use the
column's statistics for
+pruning when arrow-rs reads it as `Binary`. For example, arrow-rs maps Parquet
`ENUM` to `Binary`,
+so a range such as `value < 'two'` can skip fewer row groups with the
configuration on than with
+it off.
+
+Where arrow-rs reads the column as `Utf8`, the expression adapter replaces the
decoded
+value with the column and compares the column with a string literal directly,
so every filter
+prunes as it does with the configuration off. Spark's `Filter` above the scan
re-evaluates every
+data filter, so results don't depend on what is pushed. Join and TopK dynamic
filters accept only
+integer keys, so they never reach these columns.
Review Comment:
Just checking in on this one. On `branch-1.2`, Join and TopK dynamic filters
still prune annotated files with `binaryAsString=true`, so keeping it here
would avoid a regression.
##########
native/core/src/parquet/schema_adapter.rs:
##########
@@ -1185,6 +1219,10 @@ impl PhysicalExprAdapter for SparkPhysicalExprAdapter {
// - CometCastColumnExpr (for Struct/List/Map, uses
spark_parquet_convert)
// - Spark Cast (for simple scalar types)
rewritten
+ .transform(|e| self.unwrap_binary_round_trip(e))
Review Comment:
Could we gate these two passes on `logical_file_schema` having a `Binary`
field, and combine them into one `.transform`? That skips two extra tree walks
when `binaryAsString` is off.
##########
native/core/src/parquet/schema_adapter.rs:
##########
@@ -1409,6 +1447,100 @@ impl SparkPhysicalExprAdapter {
.data()
}
+ /// A `binaryAsString` scan reads string columns as Binary and decodes
them to strings with a
+ /// Spark cast, in its output projection and in the filters it pushes.
Where arrow-rs reads
+ /// the column as Utf8, the default adapter makes that `CAST(CAST(s AS
BINARY) AS STRING)`.
+ /// Use the column itself to skip both casts and let filters prune. This
preserves the
+ /// setting-off behavior: arrow-rs validates UTF8-annotated columns, but
JSON annotations and
+ /// Utf8 `ARROW:schema` hints can still yield unchecked string arrays.
+ fn unwrap_binary_round_trip(
+ &self,
+ expr: Arc<dyn PhysicalExpr>,
+ ) -> DataFusionResult<Transformed<Arc<dyn PhysicalExpr>>> {
+ if let Some(cast) = expr.downcast_ref::<Cast>() {
Review Comment:
Could `unwrap_binary_round_trip` also check
`cast.cast_options.is_adapting_schema`, and `column_cast_to_binary` check
`cast.has_explicit_metadata()` like `replace_with_spark_cast`? Otherwise a
`ToPrettyString` or `binaryOutputStyle` filter on a `UTF8` column read as
`BINARY` can lose its formatting.
##########
docs/source/user-guide/latest/compatibility/index.md:
##########
@@ -106,7 +106,10 @@ a result:
- **Parquet BINARY columns read as strings.** A BINARY column without the UTF8
annotation can hold
bytes that are not valid UTF-8 when it is read as `string`, through the read
schema or
`spark.sql.parquet.binaryAsString=true`. Comet decodes such a value in a
struct field, list element
- or map value. Top-level values and map keys are not checked; see
+ or map value. With the setting on, Comet also decodes top-level columns it
reads as Arrow
Review Comment:
Line 82 above still says "a nested Parquet BINARY value read as a string".
Could we update that phrase too so both paragraphs match?
--
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]