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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,14 @@ struct HugeintSumOperation
}
};

struct UhugeintSumOperation
: public ClusteredSumOperation<BaseSumOperation<SumSetOperation, UhugeintAdd>, ClusteredAddOp<UhugeintAdd>> {
template <class STATE, class OP>
static void RepeatedCombine(const STATE &source, STATE &target, AggregateInputData &input, idx_t count) {
RepeatedSumState::Combine(source, target, input, count);
}
};

//! The sum of a DECIMAL is a DECIMAL(38) - finalizing throws if the sum does not fit in it
template <class OP>
struct DecimalSumOperation : public OP {
Expand Down Expand Up @@ -556,6 +564,15 @@ AggregateFunction GetSumAggregate(PhysicalType type) {
function.SetFallible(); // adding HUGEINT values to the HUGEINT accumulator throws on overflow
return function;
}
case PhysicalType::UINT128: {
auto function =
AggregateFunction::UnaryAggregate<SumState<uhugeint_t>, uhugeint_t, uhugeint_t, UhugeintSumOperation>(
LogicalType::UHUGEINT, LogicalType::UHUGEINT);
function.GetSignature().GetParameter(0).SetName("arg");
function.SetOrderDependent(AggregateOrderDependent::NOT_ORDER_DEPENDENT);
function.SetFallible(); // adding UHUGEINT values to the UHUGEINT accumulator throws on overflow
return function;
}
default:
throw InternalException("Unimplemented sum aggregate");
}
Expand Down Expand Up @@ -843,6 +860,7 @@ AggregateFunctionSet SumFun::GetFunctions() {
sum.AddFunction(GetSumAggregate(PhysicalType::INT32));
sum.AddFunction(GetSumAggregate(PhysicalType::INT64));
sum.AddFunction(GetSumAggregate(PhysicalType::INT128));
sum.AddFunction(GetSumAggregate(PhysicalType::UINT128));
auto sum_double = AggregateFunction::UnaryAggregate<SumState<double>, double, double, NumericSumOperation>(
LogicalType::DOUBLE, LogicalType::DOUBLE);
sum_double.GetSignature().GetParameter(0).SetName("arg");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
#include "duckdb/execution/reservoir_sample.hpp"
#include "core_functions/aggregate/holistic_functions.hpp"
#include "duckdb/planner/expression.hpp"
#include "duckdb/common/queue.hpp"
#include "duckdb/common/serializer/serializer.hpp"
#include "duckdb/common/serializer/deserializer.hpp"

#include "pcg_random.hpp"

#include <algorithm>
#include <cstdint>
#include <stdlib.h>
#include <type_traits>

namespace duckdb {

Expand All @@ -22,36 +23,77 @@ namespace {
constexpr double DEFAULT_QUANTILE = 0.5;
constexpr int32_t DEFAULT_SAMPLE_SIZE = 8192;

//! The reservoir sampling of BaseReservoirSampling with all memory in the aggregate's arena
struct ReservoirQuantileSampler : public ReservoirSampler<ReservoirQuantileSampler> {
using Weight = std::pair<double, idx_t>;

explicit ReservoirQuantileSampler(Weight *weights_p) : weights(weights_p) {
random.seed(1);
}

pcg32 random;
//! The next element to sample
idx_t next_index_to_sample = 0;
//! The reservoir threshold of the current min entry
double min_weight_threshold = 0;
//! The reservoir index of the current min entry
idx_t min_weighted_entry_index = 0;
//! The number of entries seen since the last sample
idx_t num_entries_to_skip_b4_next_sample = 0;
//! Max-heap of [-random key, index] with room for the whole sample
Weight *weights;
idx_t weight_count = 0;

const Weight &TopWeight() const {
D_ASSERT(weight_count > 0);
return weights[0];
}
void PopWeight() {
std::pop_heap(weights, weights + weight_count);
weight_count--;
}
void PushWeight(double weight, idx_t index) {
new (weights + weight_count++) Weight(weight, index);
std::push_heap(weights, weights + weight_count);
}
};
static_assert(std::is_trivially_destructible<ReservoirQuantileSampler>::value, "the sampler lives in an arena");

//! All memory of the state is allocated from the aggregate's arena, so the state needs no destructor
template <typename T>
struct ReservoirQuantileState {
T *v;
idx_t len;
idx_t pos;
BaseReservoirSampling *r_samp;

void Resize(idx_t new_len) {
if (new_len <= len) {
return;
}
T *old_v = v;
v = (T *)realloc(v, new_len * sizeof(T));
if (!v) {
free(old_v);
throw InternalException("Memory allocation failure");
}
len = new_len;
}
idx_t capacity;
ReservoirQuantileSampler *r_samp;

void ReplaceElement(T &input) {
v[r_samp->min_weighted_entry_index] = input;
r_samp->ReplaceElement();
}

void FillReservoir(idx_t sample_size, T element) {
void FillReservoir(idx_t sample_size, T element, ArenaAllocator &allocator) {
if (pos < sample_size) {
if (pos == capacity) {
// grow lazily, so that small groups do not pay for the full sample size
const auto new_capacity = MinValue<idx_t>(len, MaxValue<idx_t>(1, capacity * 2));
D_ASSERT(new_capacity > pos);
const auto new_size = new_capacity * sizeof(T);
v = reinterpret_cast<T *>(
v ? allocator.ReallocateAligned(data_ptr_cast(v), AlignValue<idx_t>(capacity * sizeof(T)), new_size)
: allocator.AllocateAligned(new_size));
capacity = new_capacity;
}
v[pos++] = element;
r_samp->InitializeReservoirWeights(pos, len);
} else {
if (!r_samp) {
auto weights = allocator.AllocateAligned(len * sizeof(ReservoirQuantileSampler::Weight));
auto sampler = allocator.Make<ReservoirQuantileSampler>(
reinterpret_cast<ReservoirQuantileSampler::Weight *>(weights));
sampler->InitializeReservoirWeights(pos, len);
r_samp = sampler;
}
D_ASSERT(r_samp->next_index_to_sample >= r_samp->num_entries_to_skip_b4_next_sample);
if (r_samp->next_index_to_sample == r_samp->num_entries_to_skip_b4_next_sample) {
ReplaceElement(element);
Expand All @@ -62,6 +104,28 @@ struct ReservoirQuantileState {
}
};

struct ReservoirQuantileFinalizeState : FunctionLocalState {
static unique_ptr<FunctionLocalState> Init(const BoundAggregateFunction &, optional_ptr<const FunctionData>) {
return make_uniq<ReservoirQuantileFinalizeState>();
}

template <class STATE, class T = typename std::remove_pointer<decltype(STATE::v)>::type>
static T *CopySample(const STATE &state, AggregateFinalizeData &finalize_data) {
D_ASSERT(finalize_data.input.local_state);
auto &scratch = finalize_data.input.local_state->Cast<ReservoirQuantileFinalizeState>();
const auto size = state.pos * sizeof(T);
if (scratch.buffer.GetSize() < size) {
scratch.buffer.Reset();
scratch.buffer = finalize_data.input.allocator.GetUnderlyingAllocator().Allocate(NextPowerOfTwo(size));
}
auto result = reinterpret_cast<T *>(scratch.buffer.get());
memcpy(result, state.v, size);
return result;
}

AllocatedData buffer;
};

struct ReservoirQuantileBindData : public FunctionData {
ReservoirQuantileBindData() : decimal_type(LogicalType::INVALID) {
}
Expand Down Expand Up @@ -119,40 +183,21 @@ struct ReservoirQuantileOperation {
static void Operation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input) {
auto &bind_data = unary_input.input.bind_data->template Cast<ReservoirQuantileBindData>();
if (state.pos == 0) {
state.Resize(bind_data.sample_size);
state.len = MaxValue<idx_t>(state.len, bind_data.sample_size);
}
if (!state.r_samp) {
state.r_samp = new BaseReservoirSampling();
}
D_ASSERT(state.v);
state.FillReservoir(bind_data.sample_size, input);
state.FillReservoir(bind_data.sample_size, input, unary_input.input.allocator);
}

template <class STATE, class OP>
static void Combine(const STATE &source, STATE &target, AggregateInputData &) {
static void Combine(const STATE &source, STATE &target, AggregateInputData &aggr_input_data) {
if (source.pos == 0) {
return;
}
if (target.pos == 0) {
target.Resize(source.len);
}
if (!target.r_samp) {
target.r_samp = new BaseReservoirSampling();
target.len = MaxValue<idx_t>(target.len, source.len);
}
for (idx_t src_idx = 0; src_idx < source.pos; src_idx++) {
target.FillReservoir(target.len, source.v[src_idx]);
}
}

template <class STATE>
static void Destroy(STATE &state, AggregateInputData &aggr_input_data) {
if (state.v) {
free(state.v);
state.v = nullptr;
}
if (state.r_samp) {
delete state.r_samp;
state.r_samp = nullptr;
target.FillReservoir(target.len, source.v[src_idx], aggr_input_data.allocator);
}
}

Expand All @@ -171,15 +216,15 @@ struct ReservoirQuantileScalarOperation : public ReservoirQuantileOperation {
D_ASSERT(state.v);
D_ASSERT(finalize_data.input.bind_data);
auto &bind_data = finalize_data.input.bind_data->template Cast<ReservoirQuantileBindData>();
auto v_t = state.v;
auto v_t = ReservoirQuantileFinalizeState::CopySample(state, finalize_data);
D_ASSERT(bind_data.quantiles.size() == 1);
auto offset = (idx_t)((double)(state.pos - 1) * bind_data.quantiles[0]);
std::nth_element(v_t, v_t + offset, v_t + state.pos);
target = v_t[offset];
}
};

AggregateFunction GetReservoirQuantileAggregateFunction(PhysicalType type) {
AggregateFunction GetReservoirQuantileAggregateFunctionInternal(PhysicalType type) {
switch (type) {
case PhysicalType::INT8:
return AggregateFunction::UnaryAggregate<ReservoirQuantileState<int8_t>, int8_t, int8_t,
Expand Down Expand Up @@ -218,6 +263,12 @@ AggregateFunction GetReservoirQuantileAggregateFunction(PhysicalType type) {
}
}

AggregateFunction GetReservoirQuantileAggregateFunction(PhysicalType type) {
auto fun = GetReservoirQuantileAggregateFunctionInternal(type);
fun.SetInitLocalStateFinalizeCallback(ReservoirQuantileFinalizeState::Init);
return fun;
}

template <class CHILD_TYPE>
struct ReservoirQuantileListOperation : public ReservoirQuantileOperation {
template <class T, class STATE>
Expand All @@ -235,12 +286,14 @@ struct ReservoirQuantileListOperation : public ReservoirQuantileOperation {
ListVector::Reserve(finalize_data.result, ridx + bind_data.quantiles.size());
auto rdata = FlatVector::GetDataMutable<CHILD_TYPE>(result);

auto v_t = state.v;
D_ASSERT(v_t);

D_ASSERT(state.v);
auto &entry = target;
entry.offset = ridx;
entry.length = bind_data.quantiles.size();
if (entry.length == 0) {
return;
}
auto v_t = ReservoirQuantileFinalizeState::CopySample(state, finalize_data);
for (size_t q = 0; q < entry.length; ++q) {
const auto &quantile = bind_data.quantiles[q];
auto offset = (idx_t)((double)(state.pos - 1) * quantile);
Expand All @@ -255,11 +308,13 @@ struct ReservoirQuantileListOperation : public ReservoirQuantileOperation {
template <class STATE, class INPUT_TYPE, class RESULT_TYPE, class OP>
AggregateFunction ReservoirQuantileListAggregate(const LogicalType &input_type, const LogicalType &child_type) {
LogicalType result_type = LogicalType::LIST(child_type);
return AggregateFunction(
auto fun = AggregateFunction(
{input_type}, result_type, AggregateFunction::StateSize<STATE>, AggregateFunction::StateInitialize<STATE, OP>,
AggregateFunction::UnaryScatterUpdate<STATE, INPUT_TYPE, OP>, AggregateFunction::StateCombine<STATE, OP>,
AggregateFunction::StateFinalize<STATE, RESULT_TYPE, OP>, FunctionNullHandling::DEFAULT_NULL_HANDLING,
AggregateFunction::NoClusterUpdate(), AggregateFunction::NoBind(), AggregateFunction::StateDestroy<STATE, OP>);
AggregateFunction::NoClusterUpdate(), AggregateFunction::NoBind(), nullptr);
fun.SetInitLocalStateFinalizeCallback(ReservoirQuantileFinalizeState::Init);
return fun;
}

template <typename INPUT_TYPE, typename SAVE_TYPE>
Expand Down Expand Up @@ -377,6 +432,7 @@ static void SetDecimalImplementation(BoundAggregateFunction &function, const Log
default:
throw NotImplementedException("Invalid physical type for decimal reservoir quantile");
}
function.SetInitLocalStateFinalizeCallback(ReservoirQuantileFinalizeState::Init);
}
for (idx_t i = function.GetArguments().size(); i < declared_arguments.size(); i++) {
function.GetArguments().push_back(declared_arguments[i]);
Expand Down Expand Up @@ -463,6 +519,7 @@ void GetReservoirQuantileDecimalFunction(AggregateFunctionSet &set, const vector
const LogicalType &return_value) {
auto fun = AggregateFunction::UnaryAggregate<ReservoirQuantileState<int64_t>, int64_t, int64_t,
ReservoirQuantileScalarOperation>(arguments[0], return_value);
fun.SetInitLocalStateFinalizeCallback(ReservoirQuantileFinalizeState::Init);
fun.SetBindCallback(BindReservoirQuantileDecimal);
fun.SetSerializeCallback(ReservoirQuantileBindData::Serialize);
fun.SetDeserializeCallback(DeserializeReservoirQuantileDecimal);
Expand Down
1 change: 0 additions & 1 deletion src/duckdb/extension/core_functions/function_list.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,6 @@ static const StaticFunctionDefinition core_functions[] = {
DUCKDB_SCALAR_FUNCTION_SET(GreatestCommonDivisorFun),
DUCKDB_AGGREGATE_FUNCTION_SET_ALIAS(GroupConcatFun),
DUCKDB_SCALAR_FUNCTION(HammingFun),
DUCKDB_SCALAR_FUNCTION(HashFun),
DUCKDB_SCALAR_FUNCTION_SET(HexFun),
DUCKDB_AGGREGATE_FUNCTION_SET(HistogramFun),
DUCKDB_AGGREGATE_FUNCTION(HistogramExactFun),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include "duckdb/common/bignum.hpp"
#include "duckdb/common/types/bignum.hpp"
#include "duckdb/common/types/hugeint.hpp"
#include "duckdb/common/types/uhugeint.hpp"
#include "duckdb/common/exception.hpp"
#include "duckdb/common/operator/add.hpp"
#include "duckdb/common/operator/multiply.hpp"
Expand Down Expand Up @@ -85,6 +86,8 @@ struct RepeatedStateValue {
return input * static_cast<float>(count);
} else if constexpr (std::is_same<T, hugeint_t>()) {
return Hugeint::Multiply(input, Hugeint::Convert(count));
} else if constexpr (std::is_same<T, uhugeint_t>()) {
return Uhugeint::Multiply(input, Uhugeint::Convert(count));
} else if constexpr (std::is_same<T, interval_t>()) {
const auto count64 = Cast::Operation<idx_t, int64_t>(count);
return MultiplyOperator::Operation<interval_t, int64_t, interval_t>(input, count64);
Expand Down Expand Up @@ -140,6 +143,8 @@ template <class T>
static inline void CombineSumStateValue(T &target, const T &source) {
if constexpr (std::is_same<T, hugeint_t>::value) {
target = Hugeint::Add(target, source);
} else if constexpr (std::is_same<T, uhugeint_t>::value) {
target = Uhugeint::Add(target, source);
} else {
target += source;
}
Expand Down Expand Up @@ -192,6 +197,18 @@ struct HugeintAdd {
}
};

struct UhugeintAdd {
template <class STATE, class T>
static void AddNumber(STATE &state, T input) {
state.value = Uhugeint::Add(state.value, input);
}

template <class STATE, class T>
static void AddConstant(STATE &state, T input, idx_t count) {
RepeatedStateValue::AddRepeated(state, input, count);
}
};

struct IntervalAdd {
template <class STATE, class T>
static void AddNumber(STATE &state, T input) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,6 @@ struct CurrentSettingFun {
static ScalarFunction GetFunction();
};

struct HashFun {
static constexpr const char *Name = "hash";
static constexpr const char *Parameters = "value";
static constexpr const char *Description = "Returns a `UBIGINT` with the hash of the `value`. Note that this is not a cryptographic hash.";
static constexpr const char *Example = "hash('🦆')";
static constexpr const char *Categories = "string";

static ScalarFunction GetFunction();
};

struct LeastFun {
static constexpr const char *Name = "least";
static constexpr const char *Parameters = "arg1,...";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -611,7 +611,10 @@ ScalarFunctionSet DateTruncFun::GetFunctions() {
ScalarFunction({}, LogicalType::INTERVAL, DateTruncFunction<interval_t, interval_t>), LogicalType::INTERVAL));
date_trunc.ApplyToFunctions([](ScalarFunction &func) {
func.SetFallible();
func.SetArgProperties(1, ArgProperties().NonDecreasing());
// Truncated interval components need not preserve the normalized interval ordering.
if (func.GetSignature().GetParameter(1).GetType() != LogicalType::INTERVAL) {
func.SetArgProperties(1, ArgProperties().NonDecreasing());
}
});
return date_trunc;
}
Expand Down
Loading
Loading