3559: feat: Cast numeric (non int) to timestamp#44
3559: feat: Cast numeric (non int) to timestamp#44martin-augment wants to merge 10 commits intomainfrom
Conversation
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly expands Comet's data type casting capabilities by introducing native support for converting floating-point numbers (Float32, Float64), decimal values, and boolean types into timestamps. This feature ensures closer alignment with Spark's casting semantics, particularly for non-integer numeric types, and improves the overall compatibility and robustness of Comet's expression evaluation engine. Highlights
Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 2 potential issues.
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
| builder.append_null(); | ||
| } else { | ||
| let micros = if bool_array.value(i) { 1 } else { 0 }; | ||
| builder.append_value(micros); |
There was a problem hiding this comment.
Boolean-to-timestamp maps true to 1µs instead of 1s
High Severity
cast_boolean_to_timestamp maps true to 1 (1 microsecond) instead of MICROS_PER_SECOND (1,000,000 = 1 second). In Spark, boolean-to-timestamp works by converting true → 1 (second) → 1_000_000 microseconds. The existing cast_int_to_timestamp_impl macro confirms integers are treated as seconds and multiplied by MICROS_PER_SECOND. The result is that true produces 1970-01-01 00:00:00.000001 instead of the correct 1970-01-01 00:00:01. The unit test also encodes this wrong expectation.
Additional Locations (1)
| val df2 = spark.sql(s"select a, try_cast(a as ${toType.sql}) from t order by a") | ||
| if (useDataFrameDiff) { | ||
| assertDataFrameEqualsWithExceptions(df2, assertCometNative = !hasIncompatibleType) | ||
| } else { |
There was a problem hiding this comment.
ANSI try_cast test runs outside required config scope
Medium Severity
The if (testTry) block for try_cast in the ANSI section was moved outside the withSQLConf block that sets ANSI_ENABLED -> "true" and getExprAllowIncompatConfigKey -> "true". Without the incompat config key, the Comet native path may not be exercised, reducing test coverage for the ANSI try_cast path.
|
PR Review: Cast numeric (non-int) to Timestamp Good work implementing these casting conversions! The feature is well-structured and the benchmarks are a nice addition. Here are my findings: BUGS / CORRECTNESS
POTENTIAL ISSUES
CODE QUALITY / STYLE
|
There was a problem hiding this comment.
Code Review
This pull request adds support for casting non-integer numeric types (Float32, Float64, Decimal, Boolean) to Timestamp, along with corresponding benchmarks and tests. The implementation correctly handles special float values (NaN, Infinity) and potential overflows, aligning with Spark's behavior. The test suite has been enhanced to accommodate tests that cannot use collect() due to extreme values. I've provided a few suggestions to improve code clarity and fix a minor issue in an error message.
| pub(crate) fn cast_boolean_to_timestamp( | ||
| array_ref: &ArrayRef, | ||
| target_tz: &Option<Arc<str>>, | ||
| ) -> SparkResult<ArrayRef> { | ||
| let bool_array = array_ref.as_boolean(); | ||
| let mut builder = TimestampMicrosecondBuilder::with_capacity(bool_array.len()); | ||
|
|
||
| for i in 0..bool_array.len() { | ||
| if bool_array.is_null(i) { | ||
| builder.append_null(); | ||
| } else { | ||
| let micros = if bool_array.value(i) { 1 } else { 0 }; | ||
| builder.append_value(micros); | ||
| } | ||
| } | ||
|
|
||
| Ok(Arc::new(builder.finish().with_timezone_opt(target_tz.clone())) as ArrayRef) | ||
| } |
There was a problem hiding this comment.
The implementation of cast_boolean_to_timestamp can be simplified by using iterators and collect instead of a manual loop with a builder. This makes the code more concise and idiomatic.
pub(crate) fn cast_boolean_to_timestamp(
array_ref: &ArrayRef,
target_tz: &Option<Arc<str>>,
) -> SparkResult<ArrayRef> {
let bool_array = array_ref.as_boolean();
let result: arrow::array::TimestampMicrosecondArray = bool_array
.iter()
.map(|v| v.map(|b| if b { 1 } else { 0 }))
.collect();
Ok(Arc::new(result.with_timezone_opt(target_tz.clone())) as ArrayRef)
}| macro_rules! cast_float_to_timestamp_impl { | ||
| ($array:expr, $builder:expr, $primitive_type:ty, $eval_mode:expr) => {{ | ||
| let arr = $array.as_primitive::<$primitive_type>(); | ||
| for i in 0..arr.len() { | ||
| if arr.is_null(i) { | ||
| $builder.append_null(); | ||
| } else { | ||
| let val = arr.value(i) as f64; | ||
| // Path 1: NaN/Infinity check - error says TIMESTAMP | ||
| if val.is_nan() || val.is_infinite() { | ||
| if $eval_mode == EvalMode::Ansi { | ||
| return Err(SparkError::CastInvalidValue { | ||
| value: val.to_string(), | ||
| from_type: "DOUBLE".to_string(), | ||
| to_type: "TIMESTAMP".to_string(), | ||
| }); | ||
| } | ||
| $builder.append_null(); | ||
| } else { | ||
| // Path 2: Multiply then check overflow - error says BIGINT | ||
| let micros = val * MICROS_PER_SECOND as f64; | ||
| if micros.floor() <= i64::MAX as f64 && micros.ceil() >= i64::MIN as f64 { | ||
| $builder.append_value(micros as i64); | ||
| } else { | ||
| if $eval_mode == EvalMode::Ansi { | ||
| let value_str = if micros.is_infinite() { | ||
| if micros.is_sign_positive() { | ||
| "Infinity".to_string() | ||
| } else { | ||
| "-Infinity".to_string() | ||
| } | ||
| } else if micros.is_nan() { | ||
| "NaN".to_string() | ||
| } else { | ||
| format!("{:e}", micros).to_uppercase() + "D" | ||
| }; | ||
| return Err(SparkError::CastOverFlow { | ||
| value: value_str, | ||
| from_type: "DOUBLE".to_string(), | ||
| to_type: "BIGINT".to_string(), | ||
| }); | ||
| } | ||
| $builder.append_null(); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| }}; | ||
| } |
There was a problem hiding this comment.
The from_type in the CastInvalidValue error is hardcoded to "DOUBLE". This is incorrect when casting from Float32, as Spark would report "FLOAT".
To fix this, the macro should accept the from_type as a parameter. Additionally, using the original float value (f32 or f64) in the error message is more accurate than the value after casting to f64.
macro_rules! cast_float_to_timestamp_impl {
($array:expr, $builder:expr, $primitive_type:ty, $eval_mode:expr, $from_type_str:expr) => {{
let arr = $array.as_primitive::<$primitive_type>();
for i in 0..arr.len() {
if arr.is_null(i) {
$builder.append_null();
} else {
let val_native = arr.value(i);
let val = val_native as f64;
// Path 1: NaN/Infinity check - error says TIMESTAMP
if val.is_nan() || val.is_infinite() {
if $eval_mode == EvalMode::Ansi {
return Err(SparkError::CastInvalidValue {
value: val_native.to_string(),
from_type: $from_type_str.to_string(),
to_type: "TIMESTAMP".to_string(),
});
}
$builder.append_null();
} else {
// Path 2: Multiply then check overflow - error says BIGINT
let micros = val * MICROS_PER_SECOND as f64;
if micros.floor() <= i64::MAX as f64 && micros.ceil() >= i64::MIN as f64 {
$builder.append_value(micros as i64);
} else {
if $eval_mode == EvalMode::Ansi {
let value_str = if micros.is_infinite() {
if micros.is_sign_positive() {
"Infinity".to_string()
} else {
"-Infinity".to_string()
}
} else if micros.is_nan() {
"NaN".to_string()
} else {
format!("{:e}", micros).to_uppercase() + "D"
};
return Err(SparkError::CastOverFlow {
value: value_str,
from_type: "DOUBLE".to_string(),
to_type: "BIGINT".to_string(),
});
}
$builder.append_null();
}
}
}
}
}};
}| pub(crate) fn cast_float_to_timestamp( | ||
| array_ref: &ArrayRef, | ||
| target_tz: &Option<Arc<str>>, | ||
| eval_mode: EvalMode, | ||
| ) -> SparkResult<ArrayRef> { | ||
| let mut builder = TimestampMicrosecondBuilder::with_capacity(array_ref.len()); | ||
|
|
||
| match array_ref.data_type() { | ||
| DataType::Float32 => { | ||
| cast_float_to_timestamp_impl!(array_ref, builder, Float32Type, eval_mode) | ||
| } | ||
| DataType::Float64 => { | ||
| cast_float_to_timestamp_impl!(array_ref, builder, Float64Type, eval_mode) | ||
| } | ||
| dt => { | ||
| return Err(SparkError::Internal(format!( | ||
| "Unsupported type for cast_float_to_timestamp: {:?}", | ||
| dt | ||
| ))) | ||
| } | ||
| } | ||
|
|
||
| Ok(Arc::new(builder.finish().with_timezone_opt(target_tz.clone())) as ArrayRef) | ||
| } |
There was a problem hiding this comment.
Following the change to cast_float_to_timestamp_impl!, please update the calls to pass the correct from_type string ("FLOAT" or "DOUBLE") based on the input data type.
pub(crate) fn cast_float_to_timestamp(
array_ref: &ArrayRef,
target_tz: &Option<Arc<str>>,
eval_mode: EvalMode,
) -> SparkResult<ArrayRef> {
let mut builder = TimestampMicrosecondBuilder::with_capacity(array_ref.len());
match array_ref.data_type() {
DataType::Float32 => {
cast_float_to_timestamp_impl!(array_ref, builder, Float32Type, eval_mode, "FLOAT")
}
DataType::Float64 => {
cast_float_to_timestamp_impl!(array_ref, builder, Float64Type, eval_mode, "DOUBLE")
}
dt => {
return Err(SparkError::Internal(format!(
"Unsupported type for cast_float_to_timestamp: {:?}",
dt
)))
}
}
Ok(Arc::new(builder.finish().with_timezone_opt(target_tz.clone())) as ArrayRef)
}
🤖 Augment PR SummarySummary: This PR extends Comet’s Spark-compatible CAST implementation to support casting non-integer numeric inputs to Changes:
Technical Notes: Float/double casting handles NaN/Infinity and ANSI-mode overflow behavior, and all timestamp outputs are produced in microseconds with optional timezone metadata preserved. 🤖 Was this summary useful? React with 👍 or 👎 |
| scale: i8, | ||
| ) -> SparkResult<ArrayRef> { | ||
| let arr = array_ref.as_primitive::<Decimal128Type>(); | ||
| let scale_factor = 10_i128.pow(scale as u32); |
There was a problem hiding this comment.
scale can be negative for Spark decimals (e.g. DECIMAL(10,-4)); 10_i128.pow(scale as u32) will behave incorrectly (huge exponent) and can panic/overflow. This cast should explicitly handle negative scales to avoid crashing on valid Spark inputs.
Severity: high
🤖 Was this useful? React with 👍 or 👎, or 🚀 if it prevented an incident/outage.
| to_type: "BIGINT".to_string(), | ||
| }); | ||
| } | ||
| $builder.append_null(); |
There was a problem hiding this comment.
In LEGACY/TRY modes this path appends NULL when micros is out of the i64 range, but Spark’s legacy doubleToTimestamp uses (d * MICROS_PER_SECOND).toLong (i.e., clamps to Long.{MIN,MAX} rather than returning NULL). If the goal is strict Spark compatibility, this overflow behavior likely diverges for extreme numeric inputs.
Severity: medium
🤖 Was this useful? React with 👍 or 👎, or 🚀 if it prevented an incident/outage.
| if (hasIncompatibleType) { | ||
| checkSparkAnswer(df) | ||
| if (useDataFrameDiff) { | ||
| assertDataFrameEqualsWithExceptions(df, assertCometNative = !hasIncompatibleType) |
There was a problem hiding this comment.
When useDataFrameDiff=true, the (sparkErr, cometErr) result from assertDataFrameEqualsWithExceptions is ignored in the non-ANSI / try_cast paths, so the test can silently pass even if Spark and/or Comet throws. It seems safer to assert both sides succeeded (e.g., (None, None)) for these branches where exceptions are not expected.
Severity: medium
Other Locations
spark/src/test/scala/org/apache/comet/CometCastSuite.scala:1508spark/src/test/scala/org/apache/comet/CometCastSuite.scala:1580
🤖 Was this useful? React with 👍 or 👎, or 🚀 if it prevented an incident/outage.


3559: To review by AI