rich7420 commented on code in PR #6246:
URL: https://github.com/apache/datafusion-comet/pull/6246#discussion_r4759996389


##########
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:
   Letting the check accept that `Utf8` to `Binary` cast restored pruning of 3 
row groups for me. Worth doing here, or under #6123?



##########
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:
   This still passed for me with the no-string-column gate removed. Asserting 
`s` is `Utf8` in the `FileScanConfig` table schema caught it.



##########
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() {
+        let file = write_binary_as_string_fixture(DataType::Binary, 
[Some(b"one"), None, None]);
+        let required_schema = Arc::new(Schema::new(vec![Field::new("a", 
DataType::Int32, false)]));
+        let session_ctx = binary_as_string_session(false);
+        let plan = |binary_as_string: bool| {
+            let filter: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
+                Arc::new(Column::new("a", 0)),
+                Operator::Eq,
+                Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
+            ));
+            let scan = init_datasource_exec(
+                Arc::clone(&required_schema),
+                Some(binary_as_string_required_schema()),
+                None,
+                ObjectStoreUrl::local_filesystem(),
+                ObjectStoreBackend::Local,
+                vec![vec![file.clone()]],
+                Some(vec![0]),
+                Some(vec![filter]),
+                None,
+                "UTC",
+                true,
+                false,
+                false,
+                false,
+                binary_as_string,
+                &session_ctx,
+                false,
+                false,
+                false,
+                false,
+                "",
+                "",
+            )
+            .unwrap();
+            let plan = displayable(scan.as_ref()).indent(true).to_string();
+            plan
+        };
+        let plan_off = plan(false);
+        assert!(plan_off.contains("projection=[a]"), "{plan_off}");
+        assert_eq!(plan(true), plan_off);
+    }
+
+    /// A filter, the row groups left when it only prunes, and the groups 
whose rows match it.
+    type FilterCase = (
+        &'static str,
+        Arc<dyn PhysicalExpr>,
+        DecodedCounts,
+        DecodedCounts,
+    );
+
+    /// Runs each case with pushed filters only pruning row groups, and then 
filtering rows too.
+    async fn assert_binary_as_string_filters(file: &PartitionedFile, cases: 
Vec<FilterCase>) {
+        for (name, filter, pruned, matched) in cases {
+            for (row_filter, expected) in [(false, &pruned), (true, &matched)] 
{
+                assert_eq!(
+                    &scan_binary_as_string(file, vec![Arc::clone(&filter)], 
row_filter).await,
+                    expected,
+                    "{name}, row filter {row_filter}"
+                );
+            }
+        }
+    }
+
+    /// An unannotated BINARY column read as a string prunes on `=`, `IN` and 
`IS [NOT] NULL`
+    /// compared as raw bytes. Filters that could disagree with the decoded 
strings compare the
+    /// decoded values, which filters rows but can't prune.
+    #[tokio::test]
+    async fn binary_as_string_pushes_raw_byte_filters_on_unannotated_binary() {
+        let file = write_binary_as_string_fixture(
+            DataType::Binary,
+            [Some(b"one".as_slice()), Some(&[0xff]), None],
+        );
+        let s = || Arc::new(Column::new("s", 1)) as Arc<dyn PhysicalExpr>;
+        let a_below_1000: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
+            Arc::new(Column::new("a", 0)),
+            Operator::Lt,
+            Arc::new(Literal::new(ScalarValue::Int32(Some(1_000)))),
+        ));
+        let every_group = groups(&[Some("one"), Some("\u{fffd}"), None]);
+        let cases: Vec<FilterCase> = vec![
+            (
+                "=",
+                compare_s(Operator::Eq, "one"),
+                groups(&[Some("one")]),
+                groups(&[Some("one")]),
+            ),
+            (
+                "IN",
+                s_in(&["one", "zzz"], false),
+                groups(&[Some("one")]),
+                groups(&[Some("one")]),
+            ),
+            (
+                "IS NULL",
+                Arc::new(IsNullExpr::new(s())),
+                groups(&[None]),
+                groups(&[None]),
+            ),
+            (
+                "IS NOT NULL",
+                Arc::new(IsNotNullExpr::new(s())),
+                groups(&[Some("one"), Some("\u{fffd}")]),
+                groups(&[Some("one"), Some("\u{fffd}")]),
+            ),
+            // A range on the decoded strings can disagree with the same range 
on the bytes, so it
+            // doesn't prune on the byte statistics. `[0xff]` matches because 
it decodes to U+FFFD.
+            (
+                "range",
+                compare_s(Operator::Gt, "a"),
+                every_group.clone(),
+                groups(&[Some("one"), Some("\u{fffd}")]),
+            ),
+            (
+                "NOT IN",
+                s_in(&["one"], true),
+                every_group.clone(),
+                groups(&[Some("\u{fffd}")]),
+            ),
+            // The invalid group decodes to U+FFFD, so comparing the literal's 
bytes would prune a
+            // group that matches.
+            (
+                "U+FFFD literal",
+                compare_s(Operator::Eq, "\u{fffd}"),
+                every_group.clone(),
+                groups(&[Some("\u{fffd}")]),
+            ),
+            // Nor is an `IN` list holding one: pushing its other values would 
prune that group too.
+            (
+                "IN with a U+FFFD literal",
+                s_in(&["one", "\u{fffd}"], false),
+                every_group,
+                groups(&[Some("one"), Some("\u{fffd}")]),
+            ),
+            // A filter on another column still prunes beside one on the 
decoded strings.
+            (
+                "AND",
+                Arc::new(BinaryExpr::new(
+                    a_below_1000,
+                    Operator::And,
+                    compare_s(Operator::Gt, "a"),
+                )),
+                groups(&[Some("one")]),
+                groups(&[Some("one")]),
+            ),
+        ];
+        assert_binary_as_string_filters(&file, cases).await;
+    }
+
+    /// A join or TopK dynamic filter is pushed onto the scan's output, which 
holds the decoded
+    /// strings, so the scan maps it through its decoding projection and it 
compares decoded
+    /// values rather than bytes. `"a\x80"` sorts below `"aé"` as bytes, but 
it decodes to
+    /// `"a\u{FFFD}"`, which sorts above it.
+    #[tokio::test]
+    async fn binary_as_string_output_filter_compares_decoded_strings() {
+        let file = write_binary_as_string_fixture(
+            DataType::Binary,
+            [Some(b"a\x80".as_slice()), Some(b"a"), None],
+        );
+        let session_ctx = binary_as_string_session(true);
+        let scan = binary_as_string_scan(&file, vec![], &session_ctx);
+        let config = session_ctx.copied_config();
+        let pushed = scan
+            .data_source()
+            .try_pushdown_filters(vec![compare_s(Operator::Lt, "aé")], 
config.options())
+            .unwrap()
+            .updated_node
+            .expect("the scan should accept the filter");
+        let scan = Arc::new(scan.as_ref().clone().with_data_source(pushed));
+        assert_eq!(
+            decoded_counts(&scan, &session_ctx).await,
+            groups(&[Some("a")])
+        );
+    }
+
+    /// A column the file annotates as a string is read as Binary too, and the 
adapter's cast back
+    /// would hide it from pruning. The adapter compares the column directly 
instead, so ranges
+    /// and `LIKE` prune as they do with the setting off.
+    #[tokio::test]
+    async fn binary_as_string_prunes_annotated_strings() {
+        let file = write_binary_as_string_fixture(
+            DataType::Utf8,
+            [Some(b"one".as_slice()), Some(b"two"), None],
+        );
+        let s = || Arc::new(Column::new("s", 1)) as Arc<dyn PhysicalExpr>;
+        let prefix = 
Arc::new(Literal::new(ScalarValue::Utf8(Some("t%".to_string()))));
+        let like = LikeExpr::new(false, false, s(), prefix);
+        // Every case prunes down to the groups that match.
+        let case = |name, filter: Arc<dyn PhysicalExpr>, matched: 
&[Option<&str>]| -> FilterCase {
+            (name, filter, groups(matched), groups(matched))
+        };
+        let cases = vec![
+            case("=", compare_s(Operator::Eq, "one"), &[Some("one")]),
+            case("IN", s_in(&["two"], false), &[Some("two")]),
+            case("NOT IN", s_in(&["one"], true), &[Some("two")]),
+            case("IS NULL", Arc::new(IsNullExpr::new(s())), &[None]),
+            case(
+                "IS NOT NULL",
+                Arc::new(IsNotNullExpr::new(s())),
+                &[Some("one"), Some("two")],
+            ),
+            case("<", compare_s(Operator::Lt, "two"), &[Some("one")]),
+            case(">=", compare_s(Operator::GtEq, "p"), &[Some("two")]),
+            case("LIKE", Arc::new(like), &[Some("two")]),
+            case("U+FFFD literal", compare_s(Operator::Eq, "\u{fffd}"), &[]),
+        ];
+        assert_binary_as_string_filters(&file, cases).await;
+    }
+
+    /// For a file that annotates the column as a string, the scan outputs the 
column as arrow-rs
+    /// decoded it, without the cast to Binary and back.
+    #[tokio::test]
+    async fn binary_as_string_reads_annotated_strings_without_casts() {

Review Comment:
   The hints and JSON test below now makes this same adapter call. Maybe move 
the unannotated assert there and drop this test?



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