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
  •  
  •  
  •  
132 changes: 130 additions & 2 deletions src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ struct KahanAvgState {
void Combine(const KahanAvgState &other) {
this->count += other.count;
KahanAddInternal(other.value, this->value, this->err);
KahanAddInternal(-other.err, this->value, this->err);
this->err += other.err;
}
};

Expand Down Expand Up @@ -229,6 +229,92 @@ struct TimestampAverageOperation : public DiscreteAverageOperation {
}
};

//! The average of timestamps in nanosecond resolution - mirrors TimestampAverageOperation, but
//! interprets the state value as a nanosecond timestamp so infinity is the ns infinity
template <class NS_TIMESTAMP>
struct TimestampNSAverageOperation : public DiscreteAverageOperation {
static constexpr uint64_t INFINITE_COUNT = NumericLimits<uint64_t>::Maximum();
static constexpr uint64_t POSITIVE_INFINITY = 1;
static constexpr uint64_t NEGATIVE_INFINITY = 2;
static constexpr uint64_t BOTH_INFINITIES = POSITIVE_INFINITY | NEGATIVE_INFINITY;

template <class STATE>
static void AddInfinities(STATE &state, uint64_t infinities) {
if (state.count != INFINITE_COUNT) {
state.count = INFINITE_COUNT;
state.value = hugeint_t(0);
}
state.value.lower |= infinities;
}

static uint64_t GetInfinity(int64_t input) {
return input > 0 ? POSITIVE_INFINITY : NEGATIVE_INFINITY;
}

template <class STATE, class OP>
static void Combine(const STATE &source, STATE &target, AggregateInputData &) {
if (source.count == INFINITE_COUNT) {
AddInfinities(target, source.value.lower);
} else if (source.count != 0 && target.count != INFINITE_COUNT) {
if (target.count == 0) {
// an empty target holds no sum
target.value = hugeint_t(0);
}
if (!TryAddOperator::Operation(target.count, source.count, target.count) ||
target.count == INFINITE_COUNT) {
throw OutOfRangeException("Overflow in aggregate state combine");
}
CombineSumStateValue(target.value, source.value);
}
}

template <class STATE, class OP>
static void RepeatedCombine(const STATE &source, STATE &target, AggregateInputData &input, idx_t count) {
if (source.count == INFINITE_COUNT) {
if (count > 0) {
AddInfinities(target, source.value.lower);
}
} else if (target.count != INFINITE_COUNT) {
DiscreteAverageOperation::RepeatedCombine<STATE, OP>(source, target, input, count);
if (target.count == INFINITE_COUNT) {
throw OutOfRangeException("Overflow in repeated aggregate state combine");
}
}
}

template <class INPUT_TYPE, class STATE, class OP>
static void Operation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input) {
if (DUCKDB_UNLIKELY(!NS_TIMESTAMP(input).IsFinite())) {
AddInfinities(state, GetInfinity(input));
} else if (state.count != INFINITE_COUNT) {
DiscreteAverageOperation::Operation<INPUT_TYPE, STATE, OP>(state, input, unary_input);
}
}

template <class INPUT_TYPE, class STATE, class OP>
static void ConstantOperation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input,
idx_t count) {
if (DUCKDB_UNLIKELY(!NS_TIMESTAMP(input).IsFinite())) {
AddInfinities(state, GetInfinity(input));
} else if (state.count != INFINITE_COUNT) {
DiscreteAverageOperation::ConstantOperation<INPUT_TYPE, STATE, OP>(state, input, unary_input, count);
}
}

template <class T, class STATE>
static void Finalize(STATE &state, T &target, AggregateFinalizeData &finalize_data) {
if (state.count != INFINITE_COUNT) {
DiscreteAverageOperation::Finalize<T, STATE>(state, target, finalize_data);
} else if (state.value == hugeint_t(POSITIVE_INFINITY)) {
target = NS_TIMESTAMP::infinity().value;
} else if (state.value == hugeint_t(NEGATIVE_INFINITY)) {
target = NS_TIMESTAMP::ninfinity().value;
} else {
finalize_data.ReturnNull();
}
}
};

//! A state with the maximum count holds only infinities, reject imported ones that hold other values
void ValidateTimestampAverageStates(const_data_ptr_t states, idx_t count, idx_t stride) {
for (idx_t i = 0; i < count; i++) {
Expand Down Expand Up @@ -271,6 +357,27 @@ AggregateStateLayout TimeAverageStateLayout(AggregateLayoutInput &input) {
return layout;
}

//! The average of TIME_NS values is within a day - reject imported states that average outside of it
void ValidateTimeNSAverageStates(const_data_ptr_t states, idx_t count, idx_t stride) {
for (idx_t i = 0; i < count; i++) {
const auto state = Load<AvgState<hugeint_t>>(states + i * stride);
if (state.count == 0) {
continue;
}
const auto max_value = hugeint_t(0, state.count) * hugeint_t(Interval::NANOS_PER_DAY);
if (state.value < 0 || state.value > max_value) {
throw InvalidInputException("Invalid avg state - the average of %s over %llu values is not a valid time",
state.value.ToString(), state.count);
}
}
}

AggregateStateLayout TimeNSAverageStateLayout(AggregateLayoutInput &input) {
auto layout = AggregateFunction::StructStateLayout<AvgState<hugeint_t>>(input);
layout.validate_state = ValidateTimeNSAverageStates;
return layout;
}

struct HugeintAverageOperation : public BaseSumOperation<AverageSetOperation, HugeintAdd> {
template <class STATE, class OP>
static void RepeatedCombine(const STATE &source, STATE &target, AggregateInputData &input, idx_t count) {
Expand Down Expand Up @@ -310,7 +417,7 @@ struct KahanAverageOperation : public BaseSumOperation<AverageSetOperation, Kaha
if (state.count == 0) {
finalize_data.ReturnNull();
} else {
target = (state.value / state.count) - (state.err / state.count);
target = KahanFinalize(state.value, state.err) / static_cast<double>(state.count);
}
}
};
Expand Down Expand Up @@ -484,6 +591,27 @@ AggregateFunctionSet AvgFun::GetFunctions() {
time_tz_avg.SetStructStateExport(TimeAverageStateLayout);
avg.AddFunction(time_tz_avg);

auto timestamp_ns_avg = AggregateFunction::UnaryAggregate<AvgState<hugeint_t>, int64_t, int64_t,
TimestampNSAverageOperation<timestamp_ns_t>>(
LogicalType::TIMESTAMP_NS, LogicalType::TIMESTAMP_NS);
timestamp_ns_avg.GetSignature().GetParameter(0).SetName("x");
timestamp_ns_avg.SetStructStateExport(TimestampAverageStateLayout);
avg.AddFunction(timestamp_ns_avg);

auto timestamp_tz_ns_avg = AggregateFunction::UnaryAggregate<AvgState<hugeint_t>, int64_t, int64_t,
TimestampNSAverageOperation<timestamp_tz_ns_t>>(
LogicalType::TIMESTAMP_TZ_NS, LogicalType::TIMESTAMP_TZ_NS);
timestamp_tz_ns_avg.GetSignature().GetParameter(0).SetName("x");
timestamp_tz_ns_avg.SetStructStateExport(TimestampAverageStateLayout);
avg.AddFunction(timestamp_tz_ns_avg);

auto time_ns_avg =
AggregateFunction::UnaryAggregate<AvgState<hugeint_t>, int64_t, int64_t, DiscreteAverageOperation>(
LogicalType::TIME_NS, LogicalType::TIME_NS);
time_ns_avg.GetSignature().GetParameter(0).SetName("x");
time_ns_avg.SetStructStateExport(TimeNSAverageStateLayout);
avg.AddFunction(time_ns_avg);

return avg;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ struct KahanSumOperation : public BaseSumOperation<KahanSumSetOperation, KahanAd
if (!state.is_set) {
finalize_data.ReturnNull();
} else {
target = state.value;
target = KahanFinalize(state.value, state.err);
}
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ struct ApproxTopKOperation {
return;
}
source.Verify();
auto min_source = source.values.back().get().count;
auto min_source = source.values.size() < source.capacity ? 0 : source.values.back().get().count;
idx_t min_target;
if (target.values.empty()) {
min_target = 0;
Expand All @@ -249,7 +249,7 @@ struct ApproxTopKOperation {
throw NotImplementedException("Approx Top K - cannot combine approx_top_K with different k values. "
"K values must be the same for all entries within the same group");
}
min_target = target.values.back().get().count;
min_target = target.values.size() < target.capacity ? 0 : target.values.back().get().count;
}
// for all entries in target
// check if they are tracked in source
Expand Down Expand Up @@ -559,6 +559,10 @@ void ApproxTopKImportState(AggregateImportInputData &input) {
throw InvalidInputException("Invalid approx_top_k state - the filter values cannot be NULL");
}
target.filter[filter_idx] = filter_data[filter_entry_idx];
if (target.filter[filter_idx] != 0 && target.values.size() < target.capacity) {
throw InvalidInputException(
"Invalid approx_top_k state - the filter must be empty unless the state holds 3 * k values");
}
}
target.Verify();
state.state = internal_state.release();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,9 +187,12 @@ struct ApproxQuantileOperation {
return;
}
D_ASSERT(source.h);
auto &allocator = aggr_input_data.allocator;
if (!target.h) {
auto &allocator = aggr_input_data.allocator;
target.h = allocator.Make<duckdb_tdigest::TDigest>(allocator, 100);
} else if (&target.h->getAllocator() != &allocator) {
// Copied states can share a sink arena across partitions being combined in parallel.
target.h = allocator.Make<duckdb_tdigest::TDigest>(allocator, *target.h);
}
if (!TryAddOperator::Operation(target.pos, source.pos, target.pos)) {
throw OutOfRangeException("Overflow in aggregate state combine");
Expand Down Expand Up @@ -670,9 +673,12 @@ AggregateFunctionSet ApproxQuantileFun::GetFunctions() {

approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::DATE));
approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIME));
approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIME_NS));
approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIME_TZ));
approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIMESTAMP));
approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIMESTAMP_NS));
approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIMESTAMP_TZ));
approx_quantile.AddFunction(GetApproximateQuantileAggregate(LogicalType::TIMESTAMP_TZ_NS));

// List variants
approx_quantile.AddFunction(GetApproxQuantileDecimalList());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ struct STDDevBaseOperation {
} else if (source.count > 0) {
uint64_t count;
if (!TryAddOperator::Operation(target.count, source.count, count)) {
throw OutOfRangeException("Overflow in aggregate state combine");
OutOfRangeException::Throw("Overflow in aggregate state combine");
}
const double target_count = static_cast<double>(target.count);
const double source_count = static_cast<double>(source.count);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ struct WindowQuantileState {
throw InternalException(idx_err.message());
}
} else {
throw InternalException("No accelerator for scalar QUANTILE");
InternalException::Throw("No accelerator for scalar QUANTILE");
}
}

Expand Down Expand Up @@ -354,7 +354,7 @@ inline Value QuantileNeg(const Value &v) {
case PhysicalType::INT128:
return Value::DECIMAL(QuantileNeg<hugeint_t>(integral), width, scale);
default:
throw InternalException("Unknown DECIMAL type");
InternalException::Throw("Unknown DECIMAL type");
}
}
default:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include "duckdb/common/exception.hpp"
#include "duckdb/common/operator/add.hpp"
#include "duckdb/common/operator/multiply.hpp"
#include "duckdb/common/types/value.hpp"
#include "duckdb/function/aggregate_state.hpp"
#include "duckdb/function/aggregate_state_layout.hpp"
#include "duckdb/common/operator/cast_operators.hpp"
Expand Down Expand Up @@ -66,13 +67,21 @@ struct RepeatedStateValue {
}
};

//! Neumaier summation: the exact rounding error of each addition (TwoSum) is accumulated in err
//! The compensated sum is summed - err
static inline void KahanAddInternal(double input, double &summed, double &err) {
double diff = input - err;
double newval = summed + diff;
err = (newval - summed) - diff;
double newval = summed + input;
double input_part = newval - summed;
double rounding = (summed - (newval - input_part)) + (input - input_part);
err -= rounding;
summed = newval;
}

static inline double KahanFinalize(double summed, double err) {
// once the sum overflows the error term is meaningless (inf - inf)
return Value::IsFinite(summed) ? summed - err : summed;
}

template <class T>
static inline void CombineSumStateValue(T &target, const T &source) {
if constexpr (std::is_same<T, hugeint_t>::value) {
Expand Down Expand Up @@ -101,7 +110,7 @@ struct KahanSumState {
void Combine(const KahanSumState &other) {
this->is_set = other.is_set || this->is_set;
KahanAddInternal(other.value, this->value, this->err);
KahanAddInternal(-other.err, this->value, this->err);
this->err += other.err;
}
};

Expand Down
Loading
Loading