Skip to content

feat: randn expression support #2010

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jul 18, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/spark_expressions_support.md
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,8 @@
- [ ] input_file_name
- [ ] monotonically_increasing_id
- [ ] raise_error
- [x] rand
- [x] randn
- [ ] spark_partition_id
- [ ] typeof
- [x] user
Expand Down
6 changes: 5 additions & 1 deletion native/core/src/execution/planner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ use datafusion_comet_proto::{
use datafusion_comet_spark_expr::{
ArrayInsert, Avg, AvgDecimal, Cast, CheckOverflow, Correlation, Covariance, CreateNamedStruct,
GetArrayStructFields, GetStructField, IfExpr, ListExtract, NormalizeNaNAndZero, RLike,
RandExpr, SparkCastOptions, Stddev, StringSpaceExpr, SubstringExpr, SumDecimal,
RandExpr, RandnExpr, SparkCastOptions, Stddev, StringSpaceExpr, SubstringExpr, SumDecimal,
TimestampTruncExpr, ToJson, UnboundColumn, Variance,
};
use itertools::Itertools;
Expand Down Expand Up @@ -794,6 +794,10 @@ impl PhysicalPlanner {
let child = self.create_expr(expr.child.as_ref().unwrap(), input_schema)?;
Ok(Arc::new(RandExpr::new(child, self.partition)))
}
ExprStruct::Randn(expr) => {
let child = self.create_expr(expr.child.as_ref().unwrap(), input_schema)?;
Ok(Arc::new(RandnExpr::new(child, self.partition)))
}
expr => Err(GeneralError(format!("Not implemented: {expr:?}"))),
}
}
Expand Down
1 change: 1 addition & 0 deletions native/proto/src/proto/expr.proto
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ message Expr {
MathExpr integral_divide = 59;
ToPrettyString to_pretty_string = 60;
UnaryExpr rand = 61;
UnaryExpr randn = 62;
}
}

Expand Down
21 changes: 21 additions & 0 deletions native/spark-expr/src/nondetermenistic_funcs/internal/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// 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.

mod rand_utils;

pub use rand_utils::evaluate_batch_for_rand;
pub use rand_utils::StatefulSeedValueGenerator;
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// 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 arrow::array::{Float64Array, Float64Builder};
use arrow::datatypes::DataType;
use datafusion::common::{DataFusionError, ScalarValue};
use datafusion::logical_expr::ColumnarValue;
use std::ops::Deref;
use std::sync::{Arc, Mutex};

fn extract_seed_from_scalar_value(seed: &ScalarValue) -> datafusion::common::Result<i64> {
if let ScalarValue::Int64(seed_opt) = seed.cast_to(&DataType::Int64)? {
Ok(seed_opt.unwrap_or(0))
} else {
Err(DataFusionError::Internal(
"unexpected execution branch".to_string(),
))
}
}

pub fn evaluate_batch_for_rand<R, S>(
state_holder: &Arc<Mutex<Option<S>>>,
seed: ScalarValue,
init_seed_shift: i64,
num_rows: usize,
) -> datafusion::common::Result<ColumnarValue>
where
R: StatefulSeedValueGenerator<S, f64>,
S: Copy,
{
let seed_state = state_holder.lock().unwrap();
let init = extract_seed_from_scalar_value(&seed)?.wrapping_add(init_seed_shift);
let mut rnd = R::from_state_ref(seed_state, init);
let mut arr_builder = Float64Builder::with_capacity(num_rows);
std::iter::repeat_with(|| rnd.next_value())
.take(num_rows)
.for_each(|v| arr_builder.append_value(v));
let array_ref = Arc::new(Float64Array::from(arr_builder.finish()));
let mut seed_state = state_holder.lock().unwrap();
seed_state.replace(rnd.get_current_state());
Ok(ColumnarValue::Array(array_ref))
}

pub trait StatefulSeedValueGenerator<State: Copy, Value>: Sized {
fn from_init_seed(init_seed: i64) -> Self;

fn from_stored_state(stored_state: State) -> Self;

fn next_value(&mut self) -> Value;

fn get_current_state(&self) -> State;

fn from_state_ref(state: impl Deref<Target = Option<State>>, init_value: i64) -> Self {
if state.is_none() {
Self::from_init_seed(init_value)
} else {
Self::from_stored_state(state.unwrap())
}
}
}
3 changes: 3 additions & 0 deletions native/spark-expr/src/nondetermenistic_funcs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
// specific language governing permissions and limitations
// under the License.

pub mod internal;
pub mod rand;
pub mod randn;

pub use rand::RandExpr;
pub use randn::RandnExpr;
79 changes: 30 additions & 49 deletions native/spark-expr/src/nondetermenistic_funcs/rand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@
// under the License.

use crate::hash_funcs::murmur3::spark_compatible_murmur3_hash;
use arrow::array::{Float64Array, Float64Builder, RecordBatch};

use crate::internal::{evaluate_batch_for_rand, StatefulSeedValueGenerator};
use arrow::array::RecordBatch;
use arrow::datatypes::{DataType, Schema};
use datafusion::common::Result;
use datafusion::common::ScalarValue;
use datafusion::error::DataFusionError;
use datafusion::logical_expr::ColumnarValue;
use datafusion::physical_expr::PhysicalExpr;
Expand All @@ -42,21 +43,11 @@ const DOUBLE_UNIT: f64 = 1.1102230246251565e-16;
const SPARK_MURMUR_ARRAY_SEED: u32 = 0x3c074a61;

#[derive(Debug, Clone)]
struct XorShiftRandom {
seed: i64,
pub(crate) struct XorShiftRandom {
pub(crate) seed: i64,
}

impl XorShiftRandom {
fn from_init_seed(init_seed: i64) -> Self {
XorShiftRandom {
seed: Self::init_seed(init_seed),
}
}

fn from_stored_seed(stored_seed: i64) -> Self {
XorShiftRandom { seed: stored_seed }
}

fn next(&mut self, bits: u8) -> i32 {
let mut next_seed = self.seed ^ (self.seed << 21);
next_seed ^= ((next_seed as u64) >> 35) as i64;
Expand All @@ -70,12 +61,27 @@ impl XorShiftRandom {
let b = self.next(27) as i64;
((a << 27) + b) as f64 * DOUBLE_UNIT
}
}

fn init_seed(init: i64) -> i64 {
let bytes_repr = init.to_be_bytes();
impl StatefulSeedValueGenerator<i64, f64> for XorShiftRandom {
fn from_init_seed(init_seed: i64) -> Self {
let bytes_repr = init_seed.to_be_bytes();
let low_bits = spark_compatible_murmur3_hash(bytes_repr, SPARK_MURMUR_ARRAY_SEED);
let high_bits = spark_compatible_murmur3_hash(bytes_repr, low_bits);
((high_bits as i64) << 32) | (low_bits as i64 & 0xFFFFFFFFi64)
let init_seed = ((high_bits as i64) << 32) | (low_bits as i64 & 0xFFFFFFFFi64);
XorShiftRandom { seed: init_seed }
}

fn from_stored_state(stored_state: i64) -> Self {
XorShiftRandom { seed: stored_state }
}

fn next_value(&mut self) -> f64 {
self.next_f64()
}

fn get_current_state(&self) -> i64 {
self.seed
}
}

Expand All @@ -94,36 +100,6 @@ impl RandExpr {
state_holder: Arc::new(Mutex::new(None::<i64>)),
}
}

fn extract_init_state(seed: ScalarValue) -> Result<i64> {
if let ScalarValue::Int64(seed_opt) = seed.cast_to(&DataType::Int64)? {
Ok(seed_opt.unwrap_or(0))
} else {
Err(DataFusionError::Internal(
"unexpected execution branch".to_string(),
))
}
}
fn evaluate_batch(&self, seed: ScalarValue, num_rows: usize) -> Result<ColumnarValue> {
let mut seed_state = self.state_holder.lock().unwrap();
let mut rnd = if seed_state.is_none() {
let init_seed = RandExpr::extract_init_state(seed)?;
let init_seed = init_seed.wrapping_add(self.init_seed_shift as i64);
*seed_state = Some(init_seed);
XorShiftRandom::from_init_seed(init_seed)
} else {
let stored_seed = seed_state.unwrap();
XorShiftRandom::from_stored_seed(stored_seed)
};

let mut arr_builder = Float64Builder::with_capacity(num_rows);
std::iter::repeat_with(|| rnd.next_f64())
.take(num_rows)
.for_each(|v| arr_builder.append_value(v));
let array_ref = Arc::new(Float64Array::from(arr_builder.finish()));
*seed_state = Some(rnd.seed);
Ok(ColumnarValue::Array(array_ref))
}
}

impl Display for RandExpr {
Expand Down Expand Up @@ -161,7 +137,12 @@ impl PhysicalExpr for RandExpr {

fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
match self.seed.evaluate(batch)? {
ColumnarValue::Scalar(seed) => self.evaluate_batch(seed, batch.num_rows()),
ColumnarValue::Scalar(seed) => evaluate_batch_for_rand::<XorShiftRandom, i64>(
&self.state_holder,
seed,
self.init_seed_shift as i64,
batch.num_rows(),
),
ColumnarValue::Array(_arr) => Err(DataFusionError::NotImplemented(format!(
"Only literal seeds are supported for {self}"
))),
Expand Down Expand Up @@ -194,7 +175,7 @@ pub fn rand(seed: Arc<dyn PhysicalExpr>, init_seed_shift: i32) -> Result<Arc<dyn
#[cfg(test)]
mod tests {
use super::*;
use arrow::array::{Array, BooleanArray, Int64Array};
use arrow::array::{Array, BooleanArray, Float64Array, Int64Array};
use arrow::{array::StringArray, compute::concat, datatypes::*};
use datafusion::common::cast::as_float64_array;
use datafusion::physical_expr::expressions::lit;
Expand Down
Loading
Loading