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


##########
native/core/src/parquet/parquet_exec.rs:
##########
@@ -506,6 +744,521 @@ 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() {
+        let physical = Arc::new(Schema::new(vec![Field::new("s", 
DataType::Utf8, true)]));
+        let logical = binary_as_string_read_schema(&physical);
+        let options = SparkParquetOptions::new(EvalMode::Legacy, "UTC");
+        let projection = binary_as_string_projection(&logical, &physical, 
None, &options);
+        let decode = Arc::clone(&projection.as_ref()[0].expr);
+        assert!(decode.downcast_ref::<Cast>().is_some());
+
+        let adapt = |physical: &SchemaRef| {
+            SparkPhysicalExprAdapterFactory::new(options.clone(), None)
+                .create(Arc::clone(&logical), Arc::clone(physical))
+                .unwrap()
+                .rewrite(Arc::clone(&decode))
+                .unwrap()
+        };
+        assert!(adapt(&physical).downcast_ref::<Column>().is_some());
+        // An unannotated file still decodes.
+        assert!(adapt(&logical).downcast_ref::<Cast>().is_some());
+    }
+
+    #[tokio::test]
+    async fn binary_as_string_reads_schema_hints_and_json_without_casts() {
+        use arrow::array::StringArray;
+        use datafusion::datasource::physical_plan::FileScanConfig;
+        use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
+        use parquet::arrow::arrow_writer::ArrowWriterOptions;
+        use parquet::arrow::ARROW_SCHEMA_META_KEY;
+        use parquet::basic::ConvertedType;
+        use parquet::schema::parser::parse_message_type;
+        use parquet::schema::types::SchemaDescriptor;
+
+        let schema = binary_as_string_required_schema();
+        let batch = RecordBatch::try_new(
+            Arc::clone(&schema),
+            vec![
+                Arc::new(Int32Array::from(vec![1, 2])),
+                Arc::new(StringArray::from(vec![Some(r#"{"value":"one"}"#), 
None])),
+            ],
+        )
+        .unwrap();
+        for (annotation, embedded_schema, converted_type) in [
+            ("", true, ConvertedType::NONE),
+            ("(JSON)", false, ConvertedType::JSON),
+        ] {
+            let parquet_schema = SchemaDescriptor::new(Arc::new(
+                parse_message_type(&format!(
+                    "message test {{ required int32 a; optional binary s 
{annotation}; }}"
+                ))
+                .unwrap(),
+            ));
+            let file = tempfile::NamedTempFile::new().unwrap();
+            let options = ArrowWriterOptions::new()
+                .with_parquet_schema(parquet_schema)
+                .with_skip_arrow_metadata(!embedded_schema);
+            let mut writer = ArrowWriter::try_new_with_options(
+                file.reopen().unwrap(),
+                Arc::clone(&schema),
+                options,
+            )
+            .unwrap();
+            writer.write(&batch).unwrap();
+            writer.close().unwrap();
+
+            let reader = 
ParquetRecordBatchReaderBuilder::try_new(file.reopen().unwrap()).unwrap();
+            assert_eq!(
+                reader.parquet_schema().column(1).converted_type(),
+                converted_type
+            );
+            let has_schema_hint = reader
+                .metadata()
+                .file_metadata()
+                .key_value_metadata()
+                .is_some_and(|entries| {
+                    entries
+                        .iter()
+                        .any(|entry| entry.key == ARROW_SCHEMA_META_KEY)
+                });
+            assert_eq!(has_schema_hint, embedded_schema);
+            assert_eq!(reader.schema().field(1).data_type(), &DataType::Utf8);
+
+            let partitioned_file =
+                
PartitionedFile::from_path(file.path().to_str().unwrap().to_string()).unwrap();
+            let session = binary_as_string_session(false);
+            let scan = binary_as_string_scan(&partitioned_file, vec![], 
&session);
+            let config = 
scan.data_source().downcast_ref::<FileScanConfig>().unwrap();
+            let projection = config.file_source.projection().unwrap();
+            let decode = Arc::clone(&projection.as_ref()[1].expr);
+            assert!(decode.downcast_ref::<Cast>().is_some());
+            let adapted = config
+                .expr_adapter_factory
+                .as_ref()
+                .unwrap()
+                .create(
+                    
Arc::clone(config.file_source.table_schema().table_schema()),
+                    Arc::clone(reader.schema()),
+                )
+                .unwrap()
+                .rewrite(decode)
+                .unwrap();
+            assert!(adapted.downcast_ref::<Column>().is_some(), "{adapted}");
+
+            let actual = datafusion::physical_plan::collect(scan, 
session.task_ctx())
+                .await
+                .unwrap();
+            assert_eq!(actual, vec![batch.clone()]);

Review Comment:
   The values written are valid UTF-8, so a scan that still decoded through the 
cast pair would return the same batch. This `collect` and `assert_eq` therefore 
cannot tell a pass-through from a decode, and the property the test is named 
for is pinned only by the `Column` assertion on the adapted projection above. I 
would drop the `collect` and the `binary_as_string_session` setup it needs, or 
keep it only if it is meant as a smoke test that the real scan opens these two 
file shapes. I did not run the 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