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


##########
spark/src/test/resources/sql-tests/expressions/misc/is_variant_null.sql:
##########
@@ -0,0 +1,64 @@
+-- Licensed to the Apache Software Foundation (ASF) under one
+-- or more contributor license agreements.  See the NOTICE file
+-- distributed with this work for additional information
+-- regarding copyright ownership.  The ASF licenses this file
+-- to you under the Apache License, Version 2.0 (the
+-- "License"); you may not use this file except in compliance
+-- with the License.  You may obtain a copy of the License at
+--
+--   http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing,
+-- software distributed under the License is distributed on an
+-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+-- KIND, either express or implied.  See the License for the
+-- specific language governing permissions and limitations
+-- under the License.
+
+-- MinSparkVersion: 4.0
+-- Config: spark.sql.variant.allowReadingShredded=true
+-- Config: spark.sql.variant.pushVariantIntoScan=false
+-- Config: spark.sql.variant.writeShredding.enabled=false
+-- ConfigMatrix: parquet.enable.dictionary=false,true
+
+statement
+CREATE TABLE test_is_variant_null(id INT, v VARIANT) USING parquet
+
+statement
+INSERT INTO test_is_variant_null VALUES
+  (1, parse_json('null')),
+  (2, NULL),
+  (3, parse_json('true')),
+  (4, parse_json('false')),
+  (5, parse_json('42')),
+  (6, parse_json('-9223372036854775808')),
+  (7, parse_json('1.25')),
+  (8, parse_json('1e100')),
+  (9, parse_json('""')),
+  (10, parse_json('"null"')),
+  (11, parse_json('"中文"')),
+  (12, parse_json('[]')),
+  (13, parse_json('{}')),
+  (14, parse_json('[1,null,{"a":true}]')),
+  (15, parse_json('{"a":null,"b":[1,2]}')),
+  (16, CAST(DATE '2024-01-01' AS VARIANT)),
+  (17, CAST(TIMESTAMP '2024-01-01 12:34:56' AS VARIANT)),
+  (18, CAST(X'0001FF' AS VARIANT))
+
+query
+SELECT id, is_variant_null(v) FROM test_is_variant_null
+
+query
+SELECT id, NOT is_variant_null(v), is_variant_null(v) IS NULL FROM 
test_is_variant_null
+
+query
+SELECT id FROM test_is_variant_null WHERE is_variant_null(v)

Review Comment:
   Could we add a filter query that keeps `v` in the output? `variantFilter` 
now lets a native filter return Variant to Spark, but these filter tests 
project it away first.
   
   ```suggestion
   SELECT id FROM test_is_variant_null WHERE is_variant_null(v)
   
   query
   SELECT id, v FROM test_is_variant_null WHERE NOT is_variant_null(v) OR v IS 
NULL
   ```



##########
native/spark-expr/src/variant_funcs.rs:
##########
@@ -0,0 +1,377 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::sync::Arc;
+
+use arrow::array::{Array, BinaryArray, BooleanArray, StructArray};
+use datafusion::common::{exec_err, Result, ScalarValue};
+use datafusion::physical_plan::ColumnarValue;
+
+use crate::SparkError;
+
+pub fn spark_is_variant_null(args: &[ColumnarValue]) -> Result<ColumnarValue> {
+    variant_predicate(args, false)
+}
+
+pub fn spark_is_valid_variant(args: &[ColumnarValue]) -> Result<ColumnarValue> 
{
+    variant_predicate(args, true)
+}
+
+fn variant_predicate(args: &[ColumnarValue], validate: bool) -> 
Result<ColumnarValue> {
+    let [arg] = args else {
+        return exec_err!("Variant predicate requires one argument");
+    };
+    let array = arg.to_array(1)?;
+    let Some(variant) = array.as_any().downcast_ref::<StructArray>() else {
+        return exec_err!("Variant predicate requires 
struct<value:binary,metadata:binary>");
+    };
+    let binary = |name| {
+        variant
+            .column_by_name(name)
+            .and_then(|a| a.as_any().downcast_ref::<BinaryArray>())
+    };
+    let (Some(values), Some(metadata)) = (binary("value"), binary("metadata")) 
else {
+        return exec_err!("Variant predicate requires Binary value and metadata 
children");
+    };
+    let result = (0..variant.len())
+        .map(|row| {
+            if variant.is_null(row) {
+                return Ok(if validate { None } else { Some(false) });
+            }
+            if validate {
+                Ok(Some(
+                    !values.is_null(row)
+                        && !metadata.is_null(row)
+                        && valid_variant(values.value(row), 
metadata.value(row)).is_some(),
+                ))
+            } else {
+                // Spark checks only the first value byte. In particular, 
neither invalid
+                // metadata nor a truncated non-null primitive changes this 
predicate.
+                if values.is_null(row) {
+                    return Err(SparkError::MalformedVariant.into());
+                }
+                values
+                    .value(row)
+                    .first()
+                    .map(|header| Some(*header == 0))
+                    .ok_or_else(|| SparkError::MalformedVariant.into())
+            }
+        })
+        .collect::<Result<BooleanArray>>()?;
+    match arg {
+        ColumnarValue::Scalar(_) => 
Ok(ColumnarValue::Scalar(ScalarValue::try_from_array(
+            &result, 0,
+        )?)),
+        ColumnarValue::Array(_) => Ok(ColumnarValue::Array(Arc::new(result))),
+    }
+}
+
+// Mirrors Spark 4.2 VariantUtil.isValidVariant, whose contract differs from 
Arrow's
+// canonical validator: it reads reachable values and dictionary keys, 
tolerates trailing
+// bytes and invalid UTF-8, and does not check key order or unused 
offsets/metadata.
+fn valid_variant(value: &[u8], metadata: &[u8]) -> Option<()> {
+    if metadata.first()? & 0x0f != 1 {
+        return None;
+    }
+    // Use an explicit stack so a deeply nested input cannot overflow the 
native call stack.
+    let mut pending = vec![0];
+    while let Some(pos) = pending.pop() {
+        let header = *value.get(pos)?;
+        let info = usize::from(header >> 2);
+        match header & 3 {
+            0 => match info {
+                0..=2 => (), // null, true, false
+                3 => {
+                    value.get(pos + 1)?;
+                }
+                4 => {
+                    value.get(pos + 2)?;
+                }
+                5 | 11 | 14 => {
+                    value.get(pos + 4)?;
+                } // int32, date, float
+                6 | 7 | 12 | 13 => {
+                    value.get(pos + 8)?;
+                }
+                8..=10 => {
+                    let (width, precision) = [(4, 9), (8, 18), (16, 38)][info 
- 8];
+                    if u32::from(*value.get(pos + 1)?) > precision {
+                        return None;
+                    }
+                    let bytes = value.get(pos + 2..pos + 2 + width)?;
+                    let mut signed = [if bytes[width - 1] & 0x80 != 0 {
+                        0xff
+                    } else {
+                        0
+                    }; 16];
+                    signed[..width].copy_from_slice(bytes);
+                    if i128::from_le_bytes(signed).unsigned_abs() >= 
10_u128.pow(precision) {
+                        return None;
+                    }
+                }
+                15 | 16 => {
+                    let len = unsigned(value, pos + 1, 4)?;
+                    value.get(pos + 5..pos + 5 + len)?;
+                }
+                20 => {
+                    value.get(pos + 16)?;
+                } // UUID
+                _ => return None,
+            },
+            1 => {
+                value.get(pos + 1..pos + 1 + info)?;
+            }
+            basic => {
+                let object = basic == 2;
+                let size_width = if info & (if object { 16 } else { 4 }) != 0 {
+                    4
+                } else {
+                    1
+                };
+                let size = unsigned(value, pos + 1, size_width)?;
+                let ids = pos + 1 + size_width;
+                let id_width = if object { ((info >> 2) & 3) + 1 } else { 0 };
+                let offset_width = (info & 3) + 1;
+                let offsets = ids + size * id_width;
+                let data = offsets + (size + 1) * offset_width;
+                // Spark does not touch the offset table of an empty 
object/array.
+                for index in (0..size).rev() {
+                    if object {
+                        let id = unsigned(value, ids + index * id_width, 
id_width)?;
+                        valid_key(metadata, id)?;
+                    }
+                    let offset = unsigned(value, offsets + index * 
offset_width, offset_width)?;
+                    let child = data.checked_add(offset)?;
+                    value.get(child)?;
+                    pending.push(child);
+                }
+            }
+        }
+    }
+    Some(())
+}
+
+fn unsigned(bytes: &[u8], pos: usize, width: usize) -> Option<usize> {
+    let mut buffer = [0; 4];
+    buffer[..width].copy_from_slice(bytes.get(pos..pos.checked_add(width)?)?);
+    let result = u32::from_le_bytes(buffer);
+    // Spark's readUnsigned rejects a 32-bit quantity whose sign bit is set.
+    (result <= i32::MAX as u32).then_some(result as usize)
+}
+
+fn valid_key(metadata: &[u8], id: usize) -> Option<()> {
+    let width = usize::from(metadata[0] >> 6) + 1;
+    let size = unsigned(metadata, 1, width)?;
+    if id >= size {
+        return None;
+    }
+    // Spark computes dictionary addresses with Java int arithmetic. A large 
declared
+    // dictionary can wrap to an in-bounds empty key even in a small metadata 
buffer.
+    let address = |index: i32| 1_i32.wrapping_add(index.wrapping_mul(width as 
i32));
+    let data = address((size as i32).wrapping_add(2));
+    let offset = unsigned(
+        metadata,
+        usize::try_from(address((id as i32).wrapping_add(1))).ok()?,
+        width,
+    )?;
+    let next = unsigned(
+        metadata,
+        usize::try_from(address((id as i32).wrapping_add(2))).ok()?,
+        width,
+    )?;
+    if offset > next {
+        return None;
+    }
+    let last = data.wrapping_add(next as i32).wrapping_sub(1);
+    metadata.get(usize::try_from(last).ok()?)?;
+    let start = usize::try_from(data.wrapping_add(offset as i32)).ok()?;

Review Comment:
   When the wrapped `start` is negative, Spark seems to throw 
`StringIndexOutOfBoundsException` instead of returning false, e.g. metadata 
`c1fdffff3f0000000004000000` with value `020100000100`. Could we match that 
here, maybe with a scan regression 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