hello-stephen commented on code in PR #63430:
URL: https://github.com/apache/doris/pull/63430#discussion_r4749437836
##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/agg/LinearHistogram.java:
##########
@@ -40,9 +43,10 @@ public class LinearHistogram extends
NotNullableAggregateFunction
public static final List<FunctionSignature> SIGNATURES = ImmutableList.of(
FunctionSignature.ret(VarcharType.SYSTEM_DEFAULT)
- .args(AnyDataType.INSTANCE_WITHOUT_INDEX, DoubleType.INSTANCE),
+ .args(AnyDataType.INSTANCE_WITHOUT_INDEX,
AnyDataType.INSTANCE_WITHOUT_INDEX),
Review Comment:
[P2] Preserve per-argument types through the foreach path
These `AnyDataType` signatures also feed `ForEachCombinator`, whose
inherited `computeSignature()` still runs `defaultDecimalV3PrecisionPromotion`.
With the default `enable_decimal256=false` and `decimal_overflow_scale=6`, the
reduced plan for `linear_histogram_foreach(v, w)` becomes:
```text
Aggregate(linear_histogram_foreach(v_cast, w_cast))
Project(CAST(v AS ARRAY<DECIMAL(38,6)>) AS v_cast,
CAST(w AS ARRAY<DECIMAL(38,6)>) AS w_cast)
Scan(v ARRAY<DECIMAL(38,0)> = [0],
w ARRAY<DECIMAL(9,9)> = [0.000000001])
```
The cast rounds the valid width to zero. The coerced outer types reach the
BE through `TAggregateExpr.param_types`, so `set_parameters()` then raises the
invalid-interval error. Before this change the width signature was
`ARRAY<DOUBLE>` and avoided this promotion. Please preserve the nested
histogram's per-argument type rules in foreach as well, with a regression for
differently scaled decimal arrays.
##########
be/src/exprs/aggregate/aggregate_function_linear_histogram.cpp:
##########
@@ -17,9 +17,407 @@
#include "exprs/aggregate/aggregate_function_linear_histogram.h"
+#include <fast_float/fast_float.h>
+#include <glog/logging.h>
+#include <rapidjson/stringbuffer.h>
+#include <rapidjson/writer.h>
+
+#include <algorithm>
+#include <cmath>
+#include <limits>
+#include <system_error>
+#include <utility>
+#include <vector>
+
+#include "agent/be_exec_version_manager.h"
+#include "common/exception.h"
+#include "core/call_on_type_index.h"
#include "exprs/aggregate/helpers.h"
namespace doris {
+namespace {
+constexpr int64_t MIN_KEY = std::numeric_limits<int32_t>::min();
+constexpr int64_t MAX_KEY = std::numeric_limits<int32_t>::max();
+constexpr uint32_t STATE_FORMAT = 1;
+
+template <typename F>
+void dispatch_histogram_number(PrimitiveType type, F&& f) {
+ // A nonnumeric interval/offset can reach the factory through an
aggregate-state type.
+ if (!dispatch_type_base<F, DispatchDataTypeMask::NUMBER>(type,
std::forward<F>(f))) {
+ throw Exception(ErrorCode::INVALID_ARGUMENT, "LINEAR_HISTOGRAM
requires numeric arguments");
+ }
+}
+} // namespace
+
+LinearHistogramNumber read_linear_histogram_number(const IColumn& column,
size_t row,
+ PrimitiveType type, UInt32
scale) {
+ LinearHistogramNumber result;
+ result.scale = scale;
+ dispatch_histogram_number(type, [&](auto tag) {
+ constexpr auto PT = decltype(tag)::PType;
+ using Column = typename decltype(tag)::ColumnType;
+ const auto& value =
+ assert_cast<const Column&,
TypeCheckOnRelease::DISABLE>(column).get_data()[row];
+ if constexpr (PT == TYPE_FLOAT || PT == TYPE_DOUBLE) {
+ result.is_floating = true;
+ result.floating = value;
+ } else if constexpr (PT == TYPE_DECIMALV2) {
+ result.unscaled = value.value();
+ } else if constexpr (is_decimal(PT)) {
+ result.unscaled = value.value;
+ } else {
+ result.unscaled = value;
+ }
+ return true;
+ });
+ return result;
+}
+
+void check_linear_histogram_column(const IColumn& column, PrimitiveType type) {
+ dispatch_histogram_number(type, [&](auto tag) {
+ using Column = typename decltype(tag)::ColumnType;
+ (void)assert_cast<const Column&>(column);
+ return true;
+ });
+}
+
+LinearHistogramData::Wide LinearHistogramData::power_of_ten(UInt32 scale) {
+ // Decimal scales are at most 76, so reuse the existing Int256 power table;
+ // widen before multiplying values, not while recomputing powers per input
row.
+ return Wide(decimal_scale_multiplier<wide::Int256>(scale));
+}
+
+std::string LinearHistogramData::decimal_text(Wide value, UInt32 scale) {
+ const bool negative = value < 0;
+ if (negative) {
+ value = -value;
+ }
+ // The standard decimal formatter supports at most Int256, whereas a
boundary
+ // may exceed Decimal256 after scale alignment or multiplication by its
key.
+ std::string text;
+ do {
+ text.push_back(static_cast<char>('0' + static_cast<int>(value % 10)));
+ value /= 10;
+ } while (value != 0);
+ while (text.size() <= scale) {
+ text.push_back('0');
+ }
+ std::reverse(text.begin(), text.end());
+ if (scale != 0) {
+ text.insert(text.size() - scale, 1, '.');
+ }
+ // Preserve the existing JSON number spelling for integral boundaries
(1.0),
+ // while stripping only redundant fractional zeroes, never significant
digits.
+ if (scale == 0) {
+ text += ".0";
+ } else {
+ while (text.back() == '0' && text[text.size() - 2] != '.') {
+ text.pop_back();
+ }
+ }
+ if (negative) {
+ text.insert(text.begin(), '-');
+ }
+ return text;
+}
+
+void LinearHistogramData::reset() {
+ parameters_cached = false;
+ initialized = false;
+ exact = false;
+ boundary_scale = 0;
+ exact_interval = 0;
+ exact_offset = 0;
+ interval = 0;
+ offset = 0;
+ buckets.clear();
+}
+
+bool LinearHistogramData::same_parameters(const LinearHistogramData& rhs)
const {
+ return exact == rhs.exact &&
+ (exact ? boundary_scale == rhs.boundary_scale && exact_interval ==
rhs.exact_interval &&
+ exact_offset == rhs.exact_offset
+ : interval == rhs.interval && offset == rhs.offset);
+}
+
+void LinearHistogramData::set_parameters(const LinearHistogramNumber& width,
+ const LinearHistogramNumber& origin) {
+ // Materialized literal columns repeat these values for every input row.
+ if (parameters_cached && width == cached_interval && origin ==
cached_offset) {
+ return;
+ }
+ LinearHistogramData parameters;
+ // A DECIMAL column/expression follows the same exact path as a DECIMAL
+ // literal; an explicit FLOAT/DOUBLE in either parameter selects floating
arithmetic.
+ parameters.exact = !width.is_floating && !origin.is_floating;
+ if (parameters.exact) {
+ parameters.boundary_scale = std::max(width.scale, origin.scale);
+ parameters.exact_interval =
+ Wide(width.unscaled) * power_of_ten(parameters.boundary_scale
- width.scale);
+ parameters.exact_offset =
+ Wide(origin.unscaled) * power_of_ten(parameters.boundary_scale
- origin.scale);
+ // Zero/negative widths and offsets outside [0,width) have no valid
bucket partition.
+ if (parameters.exact_interval <= 0 || parameters.exact_offset < 0 ||
+ parameters.exact_offset >= parameters.exact_interval) {
+ throw Exception(
+ ErrorCode::INVALID_ARGUMENT,
+ "Invalid LINEAR_HISTOGRAM interval or offset; interval
should be larger "
+ "than 0 and offset should be in [0, interval)");
+ }
+ } else {
+ const auto as_double = [](const LinearHistogramNumber& value) {
+ return value.is_floating
+ ? value.floating
+ : static_cast<double>(value.unscaled) /
std::pow(10.0, value.scale);
+ };
+ parameters.interval = as_double(width);
+ parameters.offset = as_double(origin);
+ // NaN bypasses ordinary range comparisons; infinity cannot delimit
finite buckets.
+ if (!std::isfinite(parameters.interval) || parameters.interval <= 0 ||
+ !std::isfinite(parameters.offset) || parameters.offset < 0 ||
+ parameters.offset >= parameters.interval) {
+ throw Exception(
+ ErrorCode::INVALID_ARGUMENT,
+ "Invalid LINEAR_HISTOGRAM interval or offset; interval
should be finite "
+ "and larger than 0 and offset should be in [0, interval)");
+ }
+ }
+ // Varying width/offset within a group would reinterpret already counted
keys.
+ if (initialized && !same_parameters(parameters)) {
+ throw Exception(ErrorCode::INVALID_ARGUMENT,
+ "LINEAR_HISTOGRAM interval and offset must be constant
within a group");
+ }
+ exact = parameters.exact;
+ boundary_scale = parameters.boundary_scale;
+ exact_interval = parameters.exact_interval;
+ exact_offset = parameters.exact_offset;
+ interval = parameters.interval;
+ offset = parameters.offset;
+ initialized = true;
+ parameters_cached = true;
+ cached_interval = width;
+ cached_offset = origin;
+}
+
+void LinearHistogramData::check_key(const Wide& key) {
+ // Both endpoint keys are excluded: result construction also needs key + 1.
+ if (key <= MIN_KEY || key >= MAX_KEY) {
+ throw Exception(ErrorCode::INVALID_ARGUMENT,
+ "LINEAR_HISTOGRAM value exceeds the bucket range
limit");
+ }
+}
+
+LinearHistogramData::Wide LinearHistogramData::exact_boundary(int64_t key)
const {
+ return exact_offset + exact_interval * key;
+}
+
+template <typename Float>
+Float LinearHistogramData::floating_boundary(int64_t key) const {
+ if (!exact) {
+ return static_cast<Float>(key * interval + offset);
+ }
+ const auto text = decimal_text(exact_boundary(key), boundary_scale);
+ Float result = 0;
+ const auto parsed = fast_float::from_chars(text.data(), text.data() +
text.size(), result);
+ // fast_float produces signed zero on underflow and infinity on overflow.
+ // For example, 1e-76 becomes FLOAT zero; 1e76 becomes FLOAT infinity.
+ DCHECK((parsed.ec == std::errc() || parsed.ec ==
std::errc::result_out_of_range) &&
+ parsed.ptr == text.data() + text.size());
+ return result;
+}
+
+template <typename Float>
+int32_t LinearHistogramData::floating_key(Float value) const {
+ // Comparisons with NaN are unordered and cannot identify a bucket.
+ if (!std::isfinite(value)) {
+ throw Exception(ErrorCode::INVALID_ARGUMENT, "LINEAR_HISTOGRAM value
should be finite");
+ }
+ double estimate;
+ if (exact) {
+ estimate = (static_cast<double>(value) -
+ static_cast<double>(exact_offset) / std::pow(10.0,
boundary_scale)) /
+ (static_cast<double>(exact_interval) / std::pow(10.0,
boundary_scale));
+ } else {
+ estimate = (static_cast<double>(value) - offset) / interval;
+ }
+ // The usual bucket needs two comparisons. Only convert a finite, in-range
+ // estimate to an integer; tiny widths can overflow the floating quotient.
+ if (std::isfinite(estimate) && estimate >= MIN_KEY + 1 && estimate <
MAX_KEY) {
+ const int64_t key = static_cast<int64_t>(std::floor(estimate));
+ if (value >= floating_boundary<Float>(key) && value <
floating_boundary<Float>(key + 1)) {
+ return static_cast<int32_t>(key);
+ }
+ }
+
+ // Adjacent decimal endpoints can collapse to the same FLOAT. For example,
+ // near key 1e9 a width of 1 has many equal FLOAT endpoints, not just two.
+ // Upper-bound search assigns equality to the last lower endpoint <= value.
+ if (value < floating_boundary<Float>(MIN_KEY + 1) ||
+ value >= floating_boundary<Float>(MAX_KEY)) {
+ throw Exception(ErrorCode::INVALID_ARGUMENT,
+ "LINEAR_HISTOGRAM value exceeds the bucket range
limit");
+ }
+ int64_t lower = MIN_KEY + 1;
+ int64_t upper = MAX_KEY;
+ while (lower + 1 < upper) {
+ const int64_t middle = lower + (upper - lower) / 2;
+ if (value >= floating_boundary<Float>(middle)) {
Review Comment:
[P2] Avoid full-range searches for ordinary adjacent bucket corrections
For a `DOUBLE` column containing `0.3` with a `DECIMAL` interval `0.1`, the
estimate is `2.9999999999999996`, so the fast check tries key 2 and fails
because its upper endpoint parses to the same `DOUBLE 0.3`. Every such row then
repeats this roughly 32-iteration search; every comparison formats an endpoint
using 1024-bit integer division and parses it back to floating point. The
parameter cache does not cache this work, and aggregate batching still calls
`add()` per row, so even repeated values in one bucket incur the full new
search cost. Please handle ordinary adjacent-key correction before the
full-range fallback and reuse rounded endpoints where possible, while retaining
the fallback for collapsed endpoints.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]