github-actions[bot] commented on code in PR #63143: URL: https://github.com/apache/doris/pull/63143#discussion_r3297262923
########## be/src/exprs/aggregate/aggregate_function_datasketches_hll_union_agg.h: ########## @@ -0,0 +1,234 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once +#include <stddef.h> + +#include <DataSketches/hll.hpp> +#include <algorithm> +#include <boost/iterator/iterator_facade.hpp> +#include <memory> +#include <optional> +#include <type_traits> +#include <vector> + +#include "common/compiler_util.h" // IWYU pragma: keep +#include "core/assert_cast.h" +#include "core/column/column.h" +#include "core/column/column_varbinary.h" +#include "core/column/column_vector.h" +#include "core/custom_allocator.h" +#include "core/data_type/data_type_number.h" +#include "core/data_type/define_primitive_type.h" +#include "core/field.h" +#include "core/string_ref.h" +#include "core/types.h" +#include "core/uint128.h" +#include "exec/common/hash_table/hash.h" +#include "exec/common/hash_table/phmap_fwd_decl.h" +#include "exprs/aggregate/aggregate_function.h" +#include "util/var_int.h" +template <typename T> +struct HashCRC32; +namespace doris { +class Arena; +class BufferReadable; +class BufferWritable; +template <PrimitiveType T> +class ColumnDecimal; +/// datasketches_hll_union_agg +template <PrimitiveType T> +struct AggregateFunctionHllSketchData { + /** We set the default LgK to 12, + * as this value is used as a performance baseline in the relevant documentation. + * (https://datasketches.apache.org/docs/HLL/HllPerformance.html) + */ + static constexpr uint8_t DEFAULT_LOG_K = 12; + using Alloc = CustomStdAllocator<uint8_t>; + using Sketch = datasketches::hll_sketch_alloc<Alloc>; + using Union = datasketches::hll_union_alloc<Alloc>; + + std::optional<Union> hll_union_data; + + static String get_name() { return "datasketches_hll_union_agg"; } + + void merge(const Sketch& sketch_data) { + if (!hll_union_data.has_value()) { + /** We clamp max lg_k to [7, 21], + * considering that the code comment requires 7 to 21. + * See: datasketches-cpp/hll/include/hll.hpp:451 + */ + constexpr uint8_t MIN_UNION_LOG_K = 7; + const uint8_t union_lg_k = + std::clamp<uint8_t>(sketch_data.get_lg_config_k(), MIN_UNION_LOG_K, + datasketches::hll_constants::MAX_LOG_K); + hll_union_data.emplace(union_lg_k, Alloc()); + } + try { + hll_union_data->update(sketch_data); + } catch (const doris::Exception& e) { + throw Exception(e.code(), "Internal error happened when update HLL sketch: {}", + e.to_string()); + } catch (const std::exception& e) { + throw Exception(ErrorCode::INTERNAL_ERROR, + "Internal error happened when update HLL sketch: {}", e.what()); + } catch (...) { + throw Exception(ErrorCode::INTERNAL_ERROR, + "Internal error happened when update HLL sketch: unknown exception."); + } + } + void reset() { + if (hll_union_data.has_value()) { + hll_union_data->reset(); + } + hll_union_data.reset(); + } + + void write_sketch(BufferWritable& buf, const Sketch& sk) const { + auto serialized_bytes = sk.serialize_compact(); + StringRef d(serialized_bytes.data(), serialized_bytes.size()); + buf.write_binary(d); + } + void write(BufferWritable& buf) const { + if (!hll_union_data.has_value()) { + /** Using DEFAULT_LOG_K(12) here is surely sufficient, + * because in this case the union that actually needs to be serialized should contain no data. + */ + Union u(DEFAULT_LOG_K, Alloc()); + write_sketch(buf, u.get_result()); + return; + } + try { + auto cache = hll_union_data->get_result(); + write_sketch(buf, cache); + } catch (const doris::Exception& e) { + throw Exception(e.code(), "Internal error happened when serialize HLL sketch: {}", + e.to_string()); + } catch (const std::exception& e) { + throw Exception(ErrorCode::INTERNAL_ERROR, + "Internal error happened when serialize HLL sketch: {}", e.what()); + } catch (...) { + throw Exception( + ErrorCode::INTERNAL_ERROR, + "Internal error happened when serialize HLL sketch: unknown exception."); + } + } + void read(BufferReadable& buf) { + StringRef d; + buf.read_binary(d); + try { + auto cache = Sketch::deserialize(d.data, d.size, Alloc()); + merge(cache); + } catch (const doris::Exception& e) { Review Comment: This catch converts every `doris::Exception` from both `Sketch::deserialize()` and `merge(cache)` into `CORRUPTION`. With the new `CustomStdAllocator`, memory-tracker or allocation failures are also raised as `doris::Exception` (for example `MEM_ALLOC_FAILED` while deserializing or while `merge()` allocates/downsamples the union), so a resource-limit failure will be reported to the query as corrupt HLL input. The same pattern exists in `add_one()` below. Please preserve non-corruption Doris error codes, and only report `CORRUPTION` for actual invalid serialized sketch data. ########## regression-test/suites/query_p0/sql_functions/aggregate_functions/test_datasketches_hll_union_agg.groovy: ########## @@ -0,0 +1,175 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +suite("test_datasketches_hll_union_agg") { + def tableName = "test_datasketches_hll_union_agg_tbl" + def varcharTableName = "test_datasketches_hll_union_agg_varchar_tbl" + def emptyTableName = "test_datasketches_hll_union_agg_empty_tbl" + def badTableName = "test_datasketches_hll_union_agg_bad_tbl" + + // sk = new HllSketch(8, HLL_8); for (int i = 0; i < 7; i++) sk.update(i); + def sk1Base64 = "AgEHCAMIBwjL18IEK/L7BoYv+Q11gWYHgbxdBntl5gj8LUIK" + + // sk = new HllSketch(8, HLL_8); for (int i = 20; i < 30; i++) sk.update(i); + def sk2Base64 = "AwEHCAUIAAkKAAAAIjvrBcS1nwfGGWoEyHokBO8t9wc1qTEENkcJB7hWqQxZf9QNnuSbGA==" + + sql "DROP TABLE IF EXISTS ${tableName}" + sql """ + CREATE TABLE ${tableName} ( + id INT, + sk STRING + ) + DISTRIBUTED BY HASH(id) BUCKETS 1 + PROPERTIES ( + "replication_num" = "1" + ) + """ + + sql """ + INSERT INTO ${tableName} VALUES + (1, from_base64('${sk1Base64}')), + (2, from_base64('${sk2Base64}')), + (3, NULL) + """ + + // 1) Basic union: {0..6} U {20..29} => 17 distinct values + qt_basic_union """SELECT CAST(ROUND(datasketches_hll_union_agg(sk)) AS BIGINT) FROM ${tableName}""" + + // 2) Aliases should behave identically + qt_aliases """SELECT + CAST(ROUND(datasketches_hll_union_agg(sk)) AS BIGINT), + CAST(ROUND(ds_hll_estimate(sk)) AS BIGINT), + CAST(ROUND(datasketches_hll_estimate(sk)) AS BIGINT) + FROM ${tableName} + """ + + // 3) Group-by + qt_group_by """SELECT id, CAST(ROUND(datasketches_hll_union_agg(sk)) AS BIGINT) + FROM ${tableName} + WHERE id IN (1, 2) + GROUP BY id + ORDER BY id + """ + + // 4) DISTINCT should not change result in this data set + sql "INSERT INTO ${tableName} VALUES (5, from_base64('${sk1Base64}'))" + qt_distinct """SELECT + CAST(ROUND(datasketches_hll_union_agg(sk)) AS BIGINT), + CAST(ROUND(datasketches_hll_union_agg(DISTINCT sk)) AS BIGINT) + FROM ${tableName} + """ + + // 4.1) Input type coverage: VARCHAR + sql "DROP TABLE IF EXISTS ${varcharTableName}" + sql """ + CREATE TABLE ${varcharTableName} ( + id INT, + sk VARCHAR(256) + ) + DISTRIBUTED BY HASH(id) BUCKETS 1 + PROPERTIES ( + "replication_num" = "1" + ) + """ + + sql """ + INSERT INTO ${varcharTableName} VALUES + (1, from_base64('${sk1Base64}')), + (2, from_base64('${sk2Base64}')), + (3, NULL) + """ + + qt_basic_union_varchar """SELECT CAST(ROUND(datasketches_hll_union_agg(sk)) AS BIGINT) FROM ${varcharTableName}""" + + qt_aliases_varchar """SELECT + CAST(ROUND(datasketches_hll_union_agg(sk)) AS BIGINT), + CAST(ROUND(ds_hll_estimate(sk)) AS BIGINT), + CAST(ROUND(datasketches_hll_estimate(sk)) AS BIGINT) + FROM ${varcharTableName} + """ + + // 4.2) Input type coverage: VARBINARY (no table column; VARBINARY is not supported for table storage) + qt_basic_union_varbinary """SELECT CAST(ROUND(datasketches_hll_union_agg(sk)) AS BIGINT) FROM ( + SELECT from_base64_binary('${sk1Base64}') AS sk + UNION ALL SELECT from_base64_binary('${sk2Base64}') + UNION ALL SELECT NULL + ) t + """ + + qt_aliases_varbinary """SELECT + CAST(ROUND(datasketches_hll_union_agg(sk)) AS BIGINT), + CAST(ROUND(ds_hll_estimate(sk)) AS BIGINT), + CAST(ROUND(datasketches_hll_estimate(sk)) AS BIGINT) + FROM ( + SELECT from_base64_binary('${sk1Base64}') AS sk + UNION ALL SELECT from_base64_binary('${sk2Base64}') + UNION ALL SELECT NULL + ) t + """ + + // 5) Empty input should return 0 + sql "DROP TABLE IF EXISTS ${emptyTableName}" + sql """ + CREATE TABLE ${emptyTableName} ( + id INT, + sk STRING + ) + DISTRIBUTED BY HASH(id) BUCKETS 1 + PROPERTIES ( + "replication_num" = "1" + ) + """ + qt_empty_input """SELECT CAST(ROUND(datasketches_hll_union_agg(sk)) AS BIGINT) FROM ${emptyTableName}""" + + // 6) Illegal input should throw (base64 is valid but bytes are not a datasketches HLL sketch) + test { + sql """SELECT datasketches_hll_union_agg(from_base64('AA=='))""" + exception "CORRUPTION" + } + test { + sql """SELECT ds_hll_estimate(from_base64('AA=='))""" + exception "CORRUPTION" + } + test { + sql """SELECT datasketches_hll_estimate(from_base64('AA=='))""" + exception "CORRUPTION" + } + + // Empty string is a valid STRING value, but it is an invalid serialized DataSketches HLL sketch. + // It should not fail at INSERT time; it should fail when the aggregate function reads it. + sql "DROP TABLE IF EXISTS ${badTableName}" + sql """ + CREATE TABLE ${badTableName} ( + id INT, + sk STRING + ) + DISTRIBUTED BY HASH(id) BUCKETS 1 + PROPERTIES ( + "replication_num" = "1" + ) + """ + sql """INSERT INTO ${badTableName} VALUES (1, '')""" + test { + sql """SELECT datasketches_hll_union_agg(sk) FROM ${badTableName}""" + exception "CORRUPTION" + } + + sql "DROP TABLE IF EXISTS ${tableName}" Review Comment: Doris regression-test standards require dropping tables before use, not after the test, so the failed-test environment is preserved for debugging. These final drops remove the tables and make post-failure inspection harder; please remove the end-of-suite drops and keep only the existing `DROP TABLE IF EXISTS` setup before each table is created. -- 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]
