Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
1 change: 0 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,6 @@ set(DUCKDB_SRC_FILES
src/duckdb/ub_src_main_capi_v2.cpp
src/duckdb/ub_src_main_http.cpp
src/duckdb/ub_src_main_profiler.cpp
src/duckdb/ub_src_main_relation.cpp
src/duckdb/ub_src_main_secret.cpp
src/duckdb/ub_src_main_settings.cpp
src/duckdb/ub_src_optimizer.cpp
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ struct AverageSetOperation {
};

template <class T>
static T GetAverageDivident(uint64_t count, optional_ptr<FunctionData> bind_data) {
static T GetAverageDivident(uint64_t count, optional_ptr<const FunctionData> bind_data) {
T divident = T(count);
if (bind_data) {
auto &avg_bind_data = bind_data->Cast<AverageDecimalBindData>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,8 @@ AggregateFunction GetGenericArgMinMaxFunction(const ArgMinMaxNullHandling null_h
function.GetSignature().AddParameter("arg", LogicalType::ANY).AddParameter("val", LogicalType::ANY);
AggregateFunction::WireStructStateType<STATE>(function);
function.SetStatisticsCallback(AggregateFunction::PropagateInputValueStats);
function.GetProperties().SetProperty(BoundAggregateExpression::NON_NULL_SELECTOR_DOMAIN_PROPERTY,
Value::BOOLEAN(true));
return function;
}

Expand All @@ -426,6 +428,8 @@ AggregateFunction GetVectorArgMinMaxFunctionInternal(const LogicalType &by_type,
function.GetSignature().AddParameter("arg", type).AddParameter("val", by_type);
AggregateFunction::WireStructStateType<STATE>(function);
function.SetStatisticsCallback(AggregateFunction::PropagateInputValueStats);
function.GetProperties().SetProperty(BoundAggregateExpression::NON_NULL_SELECTOR_DOMAIN_PROPERTY,
Value::BOOLEAN(true));
return function;
#else
auto function = GetGenericArgMinMaxFunction<OP>(null_handling);
Expand Down Expand Up @@ -487,6 +491,8 @@ AggregateFunction GetArgMinMaxFunctionInternal(const LogicalType &by_type, const
function.GetSignature().GetParameter(1).SetName("val");
function.SetBindCallback(GetBindFunction<OP>(null_handling));
function.SetStatisticsCallback(AggregateFunction::PropagateInputValueStats);
function.GetProperties().SetProperty(BoundAggregateExpression::NON_NULL_SELECTOR_DOMAIN_PROPERTY,
Value::BOOLEAN(true));
#else
auto function = GetGenericArgMinMaxFunction<OP>(null_handling);
function.GetSignature().GetParameter(0).SetType(type);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ struct BitstringAggBindData : public FunctionData {
return false;
}

static void Serialize(Serializer &serializer, const optional_ptr<FunctionData> bind_data_p,
static void Serialize(Serializer &serializer, const optional_ptr<const FunctionData> bind_data_p,
const BoundAggregateFunction &) {
auto &bind_data = bind_data_p->Cast<BitstringAggBindData>();
serializer.WriteProperty(100, "min", bind_data.min);
Expand Down Expand Up @@ -227,7 +227,7 @@ idx_t BitStringAggOperation::GetRange(uhugeint_t min, uhugeint_t max) {
unique_ptr<BaseStatistics> BitstringPropagateStats(ClientContext &context, BoundAggregateExpression &expr,
AggregateStatisticsInput &input) {
if (NumericStats::HasMinMax(input.child_stats[0])) {
auto &bind_agg_data = input.bind_data->Cast<BitstringAggBindData>();
auto &bind_agg_data = input.bind_data.write().Cast<BitstringAggBindData>();
bind_agg_data.min = NumericStats::Min(input.child_stats[0]);
bind_agg_data.max = NumericStats::Max(input.child_stats[0]);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ struct StringAggFunction {
}

static inline void PerformOperation(StringAggState &state, ArenaAllocator &allocator, string_t str,
optional_ptr<FunctionData> data_p) {
optional_ptr<const FunctionData> data_p) {
auto &data = data_p->Cast<StringAggBindData>();
PerformOperation(state, allocator, str.GetData(), data.sep.c_str(), str.GetSize(), data.sep.size());
}
Expand Down Expand Up @@ -142,7 +142,7 @@ unique_ptr<FunctionData> StringAggBind(BindAggregateFunctionInput &input) {
return make_uniq<StringAggBindData>(std::move(separator_string));
}

void StringAggSerialize(Serializer &serializer, const optional_ptr<FunctionData> bind_data_p,
void StringAggSerialize(Serializer &serializer, const optional_ptr<const FunctionData> bind_data_p,
const BoundAggregateFunction &function) {
auto bind_data = bind_data_p->Cast<StringAggBindData>();
serializer.WriteProperty(100, "separator", bind_data.sep);
Expand Down
158 changes: 113 additions & 45 deletions src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,67 @@ struct IntegerSumOperation
}
};

//! Adds to an int64 accumulator, throwing instead of wrapping when the sum does not fit
struct CheckedInt64Add {
static void Add(int64_t &target, int64_t input) {
if (!TryAddOperator::Operation(target, input, target)) {
throw OutOfRangeException("Overflow in sum_no_overflow: the sum does not fit in a 64-bit accumulator");
}
}

template <class STATE, class T>
static void AddNumber(STATE &state, T input) {
Add(state.value, int64_t(input));
}

template <class STATE, class T>
static void AddConstant(STATE &state, T input, idx_t count) {
int64_t total;
if (!TryMultiplyOperator::Operation(int64_t(input), Cast::Operation<idx_t, int64_t>(count), total)) {
throw OutOfRangeException("Overflow in sum_no_overflow: the sum does not fit in a 64-bit accumulator");
}
Add(state.value, total);
}
};

struct CheckedSumSetOperation : public SumSetOperation {
template <class STATE>
static void Combine(const STATE &source, STATE &target, AggregateInputData &) {
if (!source.is_set) {
return;
}
if (!target.is_set) {
target.value = source.value;
target.is_set = true;
} else {
CheckedInt64Add::Add(target.value, source.value);
}
}
};

//! The int64 sum of sum_no_overflow without a statistics proof that it fits (e.g. bound by name)
struct CheckedIntegerSumOperation
: public ClusteredSumOperation<BaseSumOperation<CheckedSumSetOperation, CheckedInt64Add>,
ClusteredAddOp<CheckedInt64Add>> {
template <class STATE, class OP>
static void RepeatedCombine(const STATE &source, STATE &target, AggregateInputData &, idx_t count) {
if (!source.is_set) {
return;
}
target.is_set = true;
CheckedInt64Add::AddConstant(target, source.value, count);
}

template <class T, class STATE>
static void Finalize(STATE &state, T &target, AggregateFinalizeData &finalize_data) {
if (!state.is_set) {
finalize_data.ReturnNull();
} else {
target = Hugeint::Convert(state.value);
}
}
};

struct SumToHugeintOperation
: public ClusteredSumOperation<BaseSumOperation<SumSetOperation, AddToHugeint>, ClusteredAddOp<AddToHugeint>> {
template <class STATE, class OP>
Expand Down Expand Up @@ -315,13 +376,15 @@ pair<BoundAggregateFunction, unique_ptr<FunctionData>> BindLogicalSum(FunctionBi
return binder.ResolveAggregateFunction(selection.GetBinding(), arguments, keyword_args);
}

void SumNoOverflowSerialize(Serializer &serializer, const optional_ptr<FunctionData> bind_data,
void SumNoOverflowSerialize(Serializer &serializer, const optional_ptr<const FunctionData> bind_data,
const BoundAggregateFunction &function) {
// record whether the implementation was installed without a statistics proof (bound by name)
serializer.WritePropertyWithDefault<bool>(100, "fallible",
function.GetErrorMode() == FunctionErrors::CAN_THROW_RUNTIME_ERROR);
}

bool TryUseNoOverflowSum(BoundAggregateFunction &function, bool checked);

unique_ptr<FunctionData> SumNoOverflowDeserialize(Deserializer &deserializer, BoundAggregateFunction &function) {
bool fallible = false;
deserializer.ReadPropertyWithExplicitDefault<bool>(100, "fallible", fallible, false);
Expand All @@ -339,46 +402,61 @@ unique_ptr<FunctionData> SumNoOverflowDeserialize(Deserializer &deserializer, Bo
if (logical.second || (!return_type.IsAggregateState() && logical.first.GetReturnType() != return_type)) {
throw SerializationException("Cannot reconstruct the logical sum signature");
}
logical.first.ReplaceImplementation(function);
if (!TryUseNoOverflowSum(logical.first, fallible)) {
throw SerializationException("Cannot reconstruct the no-overflow sum implementation");
}
function = std::move(logical.first);
function.SetReturnType(return_type);
if (fallible) {
function.SetFallible();
}
return nullptr;
}

unique_ptr<FunctionData> SumNoOverflowBind(BindAggregateFunctionInput &input);

AggregateFunction GetSumAggregateNoOverflow(PhysicalType type) {
switch (type) {
case PhysicalType::INT32: {
auto function = AggregateFunction::UnaryAggregate<SumState<int64_t>, int32_t, hugeint_t, IntegerSumOperation>(
LogicalType::INTEGER, LogicalType::HUGEINT);
function.GetSignature().GetParameter(0).SetName("arg");
function.SetName("sum_no_overflow");
function.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT);
function.SetBindCallback(SumNoOverflowBind);
function.SetSerializeCallback(SumNoOverflowSerialize);
function.SetDeserializeCallback(SumNoOverflowDeserialize);
return function;
}
case PhysicalType::INT64: {
auto function = AggregateFunction::UnaryAggregate<SumState<int64_t>, int64_t, hugeint_t, IntegerSumOperation>(
LogicalType::BIGINT, LogicalType::HUGEINT);
function.GetSignature().GetParameter(0).SetName("arg");
function.SetName("sum_no_overflow");
function.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT);
function.SetBindCallback(SumNoOverflowBind);
function.SetSerializeCallback(SumNoOverflowSerialize);
function.SetDeserializeCallback(SumNoOverflowDeserialize);
return function;
template <class INPUT_TYPE, class OP>
AggregateFunction GetSumAggregateNoOverflow(const LogicalType &input_type) {
auto function = AggregateFunction::UnaryAggregate<SumState<int64_t>, INPUT_TYPE, hugeint_t, OP>(
input_type, LogicalType::HUGEINT);
function.GetSignature().GetParameter(0).SetName("arg");
function.SetName("sum_no_overflow");
function.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT);
function.SetBindCallback(SumNoOverflowBind);
function.SetSerializeCallback(SumNoOverflowSerialize);
function.SetDeserializeCallback(SumNoOverflowDeserialize);
if constexpr (std::is_same<OP, CheckedIntegerSumOperation>::value) {
function.SetFallible();
}
return function;
}

//! The checked variant throws when the sum overflows the int64 accumulator, it shares the state layout
AggregateFunction GetSumAggregateNoOverflow(PhysicalType type, bool checked = false) {
switch (type) {
case PhysicalType::INT32:
return checked ? GetSumAggregateNoOverflow<int32_t, CheckedIntegerSumOperation>(LogicalType::INTEGER)
: GetSumAggregateNoOverflow<int32_t, IntegerSumOperation>(LogicalType::INTEGER);
case PhysicalType::INT64:
return checked ? GetSumAggregateNoOverflow<int64_t, CheckedIntegerSumOperation>(LogicalType::BIGINT)
: GetSumAggregateNoOverflow<int64_t, IntegerSumOperation>(LogicalType::BIGINT);
default:
throw BinderException("Unsupported internal type for sum_no_overflow");
}
}

//! Swaps in the int64 accumulator but keeps the bound signature (e.g. DECIMAL(15,2) -> DECIMAL(38,2)), so that binding
//! sum_no_overflow by that signature (e.g. to finalize an exported state) yields the same state layout
bool TryUseNoOverflowSum(BoundAggregateFunction &function, bool checked) {
const auto internal_type = function.GetArguments()[0].InternalType();
if (internal_type != PhysicalType::INT32 && internal_type != PhysicalType::INT64) {
return false;
}
auto arguments = function.GetArguments();
auto return_type = function.GetReturnType();
function.ReplaceImplementation(GetSumAggregateNoOverflow(internal_type, checked));
function.GetArguments() = std::move(arguments);
function.SetReturnType(std::move(return_type));
return true;
}

AggregateFunction GetSumAggregateNoOverflowDecimal() {
AggregateFunction aggr({}, LogicalTypeId::DECIMAL, nullptr, nullptr, nullptr, nullptr, nullptr,
FunctionNullHandling::DEFAULT_NULL_HANDLING, AggregateFunction::NoClusterUpdate(),
Expand All @@ -392,17 +470,11 @@ AggregateFunction GetSumAggregateNoOverflowDecimal() {
//! Binding sum_no_overflow by name (e.g. when re-binding an exported aggregate state) delegates to the regular sum,
//! with the no-overflow implementation swapped in as statistics propagation does
unique_ptr<FunctionData> SumNoOverflowBind(BindAggregateFunctionInput &input) {
auto &function = input.GetBoundFunction();
auto &arguments = input.GetArguments();
const auto parameter_type = function.GetArguments()[0];
auto binder = input.NestedFunctionBinder();
auto logical = BindLogicalSum(binder, arguments);
if (parameter_type.id() != LogicalTypeId::DECIMAL) {
logical.first.ReplaceImplementation(GetSumAggregateNoOverflow(parameter_type.InternalType()));
// bound by name there is no statistics proof that the int64 accumulator cannot overflow
logical.first.SetFallible();
}
function = std::move(logical.first);
auto logical = BindLogicalSum(binder, input.GetArguments());
// bound by name there is no statistics proof that the int64 accumulator cannot overflow
TryUseNoOverflowSum(logical.first, true);
input.GetBoundFunction() = std::move(logical.first);
return std::move(logical.second);
}

Expand All @@ -424,13 +496,9 @@ unique_ptr<BaseStatistics> SumPropagateStats(ClientContext &context, BoundAggreg
return nullptr;
}

// Replace with fast implementation when possible: only INT32/INT64 have a narrower no-overflow implementation to
// swap in.
const bool has_no_overflow_variant = internal_type == PhysicalType::INT32 || internal_type == PhysicalType::INT64;
const bool sum_fits_in_int64 =
bounds->min > NumericLimits<int64_t>::Minimum() && bounds->max < NumericLimits<int64_t>::Maximum();
if (has_no_overflow_variant && sum_fits_in_int64) {
expr.FunctionMutable().ReplaceImplementation(GetSumAggregateNoOverflow(internal_type));
// Replace with fast implementation when possible
if (bounds->min > NumericLimits<int64_t>::Minimum() && bounds->max < NumericLimits<int64_t>::Maximum()) {
TryUseNoOverflowSum(expr.FunctionMutable(), false);
}

// Propagate stats.
Expand Down
Loading
Loading