Skip to content
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

fix(function): Support Spark legacy behavior for central moments functions and change the input type #12566

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
10 changes: 10 additions & 0 deletions velox/core/QueryConfig.h
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,12 @@ class QueryConfig {
static constexpr const char* kSparkLegacyDateFormatter =
"spark.legacy_date_formatter";

/// if true, statistical aggregation function includes skewness, kurtosis,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If true, the first letter should be uppercase, so as the document

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks.

/// will return std::numeric_limits<double>::quiet_NaN() instead of NULL when
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

std::numeric_limits::quiet_NaN() -> NaN

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks.

/// DivideByZero occurs during expression evaluation.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DivideByZero occurs during expression evaluation

dividing by zero during the aggregate result calculation

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you.

static constexpr const char* kSparkLegacyStatisticalAggregate =
"spark.legacy_statistical_aggregate";

/// The number of local parallel table writer operators per task.
static constexpr const char* kTaskWriterCount = "task_writer_count";

Expand Down Expand Up @@ -831,6 +837,10 @@ class QueryConfig {
return get<bool>(kSparkLegacyDateFormatter, false);
}

bool sparkLegacyStatisticalAggregate() const {
return get<bool>(kSparkLegacyStatisticalAggregate, false);
}

bool exprTrackCpuUsage() const {
return get<bool>(kExprTrackCpuUsage, false);
}
Expand Down
5 changes: 5 additions & 0 deletions velox/docs/configs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -887,6 +887,11 @@ Spark-specific Configuration
Joda date formatter performs strict checking of its input and uses different pattern string.
For example, the 2015-07-22 10:00:00 timestamp cannot be parsed if pattern is yyyy-MM-dd because the parser does not consume whole input.
Another example is that the 'W' pattern, which means week in month, is not supported. For more differences, see :issue:`10354`.
* - spark.legacy_statistical_aggregate
- bool
- false
- if true, statistical aggregation function includes skewness, kurtosis will return std::numeric_limits<double>::quiet_NaN()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please highlight that this config is partially honored, there is still some functions should honor this config but not such as stddev

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps rename it to statistical_agg_null_on_divide_by_zero and update all related functions in this PR as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@zhli1142015 @jinchengchenghh
Other functions are not supported in Velox Spark functions yet and Gluten transforms them to Velox Presto functions now. Therefore, I think there is no need to add the doc. BTW, I will implement the Spark version of these functions in further PRs.

Copy link
Collaborator

@rui-mo rui-mo Mar 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 for improving the documentation. We'd better make it clear which functions will depend on this config when adding it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We'd better make it clear which functions will depend on this config when adding it.

@rui-mo You are right. Updated. Thanks!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps rename it to statistical_agg_null_on_divide_by_zero

@zhli1142015 I thought it would be clear to align with Spark.

- instead of NULL when DivideByZero occurs during expression evaluation.

Tracing
--------
Expand Down
251 changes: 204 additions & 47 deletions velox/functions/sparksql/aggregates/CentralMomentsAggregate.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,40 +15,51 @@
*/

#include "velox/functions/sparksql/aggregates/CentralMomentsAggregate.h"
#include <limits>
#include "velox/functions/lib/aggregates/CentralMomentsAggregatesBase.h"

namespace facebook::velox::functions::aggregate::sparksql {

namespace {
template <bool nullOnDivideByZero>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps document this variable.

struct SkewnessResultAccessor {
static bool hasResult(const CentralMomentsAccumulator& accumulator) {
return accumulator.count() >= 1 && accumulator.m2() != 0;
if constexpr (nullOnDivideByZero) {
return accumulator.count() >= 1 && accumulator.m2() != 0;
}
return accumulator.count() >= 1;
}

static double result(const CentralMomentsAccumulator& accumulator) {
if (accumulator.m2() == 0) {
return std::numeric_limits<double>::quiet_NaN();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps check nullOnDivideByZero is false.

}
return std::sqrt(accumulator.count()) * accumulator.m3() /
std::pow(accumulator.m2(), 1.5);
}
};

template <bool nullOnDivideByZero>
struct KurtosisResultAccessor {
static bool hasResult(const CentralMomentsAccumulator& accumulator) {
return accumulator.count() >= 1 && accumulator.m2() != 0;
if constexpr (nullOnDivideByZero) {
return accumulator.count() >= 1 && accumulator.m2() != 0;
}
return accumulator.count() >= 1;
}

static double result(const CentralMomentsAccumulator& accumulator) {
if (accumulator.m2() == 0) {
return std::numeric_limits<double>::quiet_NaN();
}
double count = accumulator.count();
double m2 = accumulator.m2();
double m4 = accumulator.m4();
return count * m4 / (m2 * m2) - 3.0;
}
};

template <typename TResultAccessor>
exec::AggregateRegistrationResult registerCentralMoments(
const std::string& name,
bool withCompanionFunctions,
bool overwrite) {
std::vector<std::shared_ptr<exec::AggregateFunctionSignature>> getSignatures() {
std::vector<std::shared_ptr<exec::AggregateFunctionSignature>> signatures;
std::vector<std::string> inputTypes = {
"smallint", "integer", "bigint", "real", "double"};
Expand All @@ -60,6 +71,115 @@ exec::AggregateRegistrationResult registerCentralMoments(
.argumentType(inputType)
.build());
}
return signatures;
}

exec::AggregateRegistrationResult registerSkewness(
const std::string& name,
bool withCompanionFunctions,
bool overwrite) {
std::vector<std::shared_ptr<exec::AggregateFunctionSignature>> signatures =
getSignatures();

return exec::registerAggregateFunction(
name,
std::move(signatures),
[name](
core::AggregationNode::Step step,
const std::vector<TypePtr>& argTypes,
const TypePtr& resultType,
const core::QueryConfig& config) -> std::unique_ptr<exec::Aggregate> {
VELOX_CHECK_LE(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this function should require exactly one argument, rather than allowing at most one.

argTypes.size(), 1, "{} takes at most one argument", name);
const auto& inputType = argTypes[0];
if (config.sparkLegacyStatisticalAggregate()) {
if (exec::isRawInput(step)) {
switch (inputType->kind()) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might don't need a switch clause if only one valid case.

case TypeKind::SMALLINT:
return std::make_unique<CentralMomentsAggregatesBase<
int16_t,
SkewnessResultAccessor<false>>>(resultType);
case TypeKind::INTEGER:
return std::make_unique<CentralMomentsAggregatesBase<
int32_t,
SkewnessResultAccessor<false>>>(resultType);
case TypeKind::BIGINT:
return std::make_unique<CentralMomentsAggregatesBase<
int64_t,
SkewnessResultAccessor<false>>>(resultType);
case TypeKind::DOUBLE:
return std::make_unique<CentralMomentsAggregatesBase<
double,
SkewnessResultAccessor<false>>>(resultType);
case TypeKind::REAL:
return std::make_unique<CentralMomentsAggregatesBase<
float,
SkewnessResultAccessor<false>>>(resultType);
default:
VELOX_UNSUPPORTED(
"Unsupported input type: {}. "
"Expected SMALLINT, INTEGER, BIGINT, DOUBLE or REAL.",
inputType->toString());
}
} else {
checkAccumulatorRowType(
inputType,
"Input type for final aggregation must be "
"(count:bigint, m1:double, m2:double, m3:double, m4:double) struct");
return std::make_unique<CentralMomentsAggregatesBase<
int64_t /*unused*/,
SkewnessResultAccessor<false>>>(resultType);
}
} else {
if (exec::isRawInput(step)) {
switch (inputType->kind()) {
case TypeKind::SMALLINT:
return std::make_unique<CentralMomentsAggregatesBase<
int16_t,
SkewnessResultAccessor<true>>>(resultType);
case TypeKind::INTEGER:
return std::make_unique<CentralMomentsAggregatesBase<
int32_t,
SkewnessResultAccessor<true>>>(resultType);
case TypeKind::BIGINT:
return std::make_unique<CentralMomentsAggregatesBase<
int64_t,
SkewnessResultAccessor<true>>>(resultType);
case TypeKind::DOUBLE:
Copy link
Contributor

@zhli1142015 zhli1142015 Mar 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we only need to register this function with double type raw input.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean this function should only support double type input? If so, I agree with you, as Spark only supports double type input, see https://github.com/apache/spark/blob/master/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/CentralMomentAgg.scala#L58C16-L58C24

return std::make_unique<CentralMomentsAggregatesBase<
double,
SkewnessResultAccessor<true>>>(resultType);
case TypeKind::REAL:
return std::make_unique<CentralMomentsAggregatesBase<
float,
SkewnessResultAccessor<true>>>(resultType);
default:
VELOX_UNSUPPORTED(
"Unsupported input type: {}. "
"Expected SMALLINT, INTEGER, BIGINT, DOUBLE or REAL.",
inputType->toString());
}
} else {
checkAccumulatorRowType(
inputType,
"Input type for final aggregation must be "
"(count:bigint, m1:double, m2:double, m3:double, m4:double) struct");
return std::make_unique<CentralMomentsAggregatesBase<
int64_t /*unused*/,
SkewnessResultAccessor<true>>>(resultType);
}
}
},
withCompanionFunctions,
overwrite);
}

exec::AggregateRegistrationResult registerKurtosis(
const std::string& name,
bool withCompanionFunctions,
bool overwrite) {
std::vector<std::shared_ptr<exec::AggregateFunctionSignature>> signatures =
getSignatures();

return exec::registerAggregateFunction(
name,
Expand All @@ -68,47 +188,86 @@ exec::AggregateRegistrationResult registerCentralMoments(
core::AggregationNode::Step step,
const std::vector<TypePtr>& argTypes,
const TypePtr& resultType,
const core::QueryConfig& /*config*/)
-> std::unique_ptr<exec::Aggregate> {
const core::QueryConfig& config) -> std::unique_ptr<exec::Aggregate> {
VELOX_CHECK_LE(
argTypes.size(), 1, "{} takes at most one argument", name);
const auto& inputType = argTypes[0];
if (exec::isRawInput(step)) {
switch (inputType->kind()) {
case TypeKind::SMALLINT:
return std::make_unique<
CentralMomentsAggregatesBase<int16_t, TResultAccessor>>(
resultType);
case TypeKind::INTEGER:
return std::make_unique<
CentralMomentsAggregatesBase<int32_t, TResultAccessor>>(
resultType);
case TypeKind::BIGINT:
return std::make_unique<
CentralMomentsAggregatesBase<int64_t, TResultAccessor>>(
resultType);
case TypeKind::DOUBLE:
return std::make_unique<
CentralMomentsAggregatesBase<double, TResultAccessor>>(
resultType);
case TypeKind::REAL:
return std::make_unique<
CentralMomentsAggregatesBase<float, TResultAccessor>>(
resultType);
default:
VELOX_UNSUPPORTED(
"Unsupported input type: {}. "
"Expected SMALLINT, INTEGER, BIGINT, DOUBLE or REAL.",
inputType->toString());
if (config.sparkLegacyStatisticalAggregate()) {
if (exec::isRawInput(step)) {
switch (inputType->kind()) {
case TypeKind::SMALLINT:
return std::make_unique<CentralMomentsAggregatesBase<
int16_t,
KurtosisResultAccessor<false>>>(resultType);
case TypeKind::INTEGER:
return std::make_unique<CentralMomentsAggregatesBase<
int32_t,
KurtosisResultAccessor<false>>>(resultType);
case TypeKind::BIGINT:
return std::make_unique<CentralMomentsAggregatesBase<
int64_t,
KurtosisResultAccessor<false>>>(resultType);
case TypeKind::DOUBLE:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same for this function.

return std::make_unique<CentralMomentsAggregatesBase<
double,
KurtosisResultAccessor<false>>>(resultType);
case TypeKind::REAL:
return std::make_unique<CentralMomentsAggregatesBase<
float,
KurtosisResultAccessor<false>>>(resultType);
default:
VELOX_UNSUPPORTED(
"Unsupported input type: {}. "
"Expected SMALLINT, INTEGER, BIGINT, DOUBLE or REAL.",
inputType->toString());
}
} else {
checkAccumulatorRowType(
inputType,
"Input type for final aggregation must be "
"(count:bigint, m1:double, m2:double, m3:double, m4:double) struct");
return std::make_unique<CentralMomentsAggregatesBase<
int64_t /*unused*/,
KurtosisResultAccessor<false>>>(resultType);
}
} else {
checkAccumulatorRowType(
inputType,
"Input type for final aggregation must be "
"(count:bigint, m1:double, m2:double, m3:double, m4:double) struct");
return std::make_unique<CentralMomentsAggregatesBase<
int64_t /*unused*/,
TResultAccessor>>(resultType);
if (exec::isRawInput(step)) {
switch (inputType->kind()) {
case TypeKind::SMALLINT:
return std::make_unique<CentralMomentsAggregatesBase<
int16_t,
KurtosisResultAccessor<true>>>(resultType);
case TypeKind::INTEGER:
return std::make_unique<CentralMomentsAggregatesBase<
int32_t,
KurtosisResultAccessor<true>>>(resultType);
case TypeKind::BIGINT:
return std::make_unique<CentralMomentsAggregatesBase<
int64_t,
KurtosisResultAccessor<true>>>(resultType);
case TypeKind::DOUBLE:
return std::make_unique<CentralMomentsAggregatesBase<
double,
KurtosisResultAccessor<true>>>(resultType);
case TypeKind::REAL:
return std::make_unique<CentralMomentsAggregatesBase<
float,
KurtosisResultAccessor<true>>>(resultType);
default:
VELOX_UNSUPPORTED(
"Unsupported input type: {}. "
"Expected SMALLINT, INTEGER, BIGINT, DOUBLE or REAL.",
inputType->toString());
}
} else {
checkAccumulatorRowType(
inputType,
"Input type for final aggregation must be "
"(count:bigint, m1:double, m2:double, m3:double, m4:double) struct");
return std::make_unique<CentralMomentsAggregatesBase<
int64_t /*unused*/,
KurtosisResultAccessor<true>>>(resultType);
}
}
},
withCompanionFunctions,
Expand All @@ -120,10 +279,8 @@ void registerCentralMomentsAggregate(
const std::string& prefix,
bool withCompanionFunctions,
bool overwrite) {
registerCentralMoments<SkewnessResultAccessor>(
prefix + "skewness", withCompanionFunctions, overwrite);
registerCentralMoments<KurtosisResultAccessor>(
prefix + "kurtosis", withCompanionFunctions, overwrite);
registerSkewness(prefix + "skewness", withCompanionFunctions, overwrite);
registerKurtosis(prefix + "kurtosis", withCompanionFunctions, overwrite);
}

} // namespace facebook::velox::functions::aggregate::sparksql
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,18 @@ class CentralMomentsAggregationTest : public AggregationTestBase {
builder.singleAggregation({}, {fmt::format("spark_{}(c0)", agg)});
AssertQueryBuilder(builder.planNode()).assertResults({expected});
}

void testLegacyCenteralMomentsAggResult(
const std::string& agg,
const RowVectorPtr& input,
const RowVectorPtr& expected) {
PlanBuilder builder(pool());
builder.values({input});
builder.singleAggregation({}, {fmt::format("spark_{}(c0)", agg)});
AssertQueryBuilder(builder.planNode())
.config("spark.legacy_statistical_aggregate", "true")
.assertResults({expected});
}
};

TEST_F(CentralMomentsAggregationTest, skewnessHasResult) {
Expand All @@ -54,6 +66,19 @@ TEST_F(CentralMomentsAggregationTest, skewnessHasResult) {
expected = makeRowVector({makeNullableFlatVector<double>(
std::vector<std::optional<double>>{std::nullopt})});
testCenteralMomentsAggResult(agg, input, expected);

// Output NULL when m2 equals 0.
input = makeRowVector({makeFlatVector<int32_t>({1, 1})});
expected = makeRowVector({makeNullableFlatVector<double>(
std::vector<std::optional<double>>{std::nullopt})});
testCenteralMomentsAggResult(agg, input, expected);

// Output NaN when m2 equals 0 for legacy aggregate.
input = makeRowVector({makeFlatVector<int32_t>({1, 1})});
expected = makeRowVector(
{makeNullableFlatVector<double>(std::vector<std::optional<double>>{
std::numeric_limits<double>::quiet_NaN()})});
testLegacyCenteralMomentsAggResult(agg, input, expected);
}

TEST_F(CentralMomentsAggregationTest, pearsonKurtosis) {
Expand All @@ -78,6 +103,13 @@ TEST_F(CentralMomentsAggregationTest, pearsonKurtosis) {
expected = makeRowVector({makeNullableFlatVector<double>(
std::vector<std::optional<double>>{std::nullopt})});
testCenteralMomentsAggResult(agg, input, expected);

// Output NaN when m2 equals 0 for legacy aggregate.
input = makeRowVector({makeFlatVector<int32_t>({1, 1})});
expected = makeRowVector(
{makeNullableFlatVector<double>(std::vector<std::optional<double>>{
std::numeric_limits<double>::quiet_NaN()})});
testLegacyCenteralMomentsAggResult(agg, input, expected);
}

} // namespace
Expand Down
Loading