This is an automated email from the ASF dual-hosted git repository.
HappenLee pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/master by this push:
new eedce64f659 [fix](serde) Serialize exact HLL byte lengths in
DataTypeHLLSerDe (#70908)
eedce64f659 is described below
commit eedce64f659471441c3afdb7086c7720e8002d12
Author: linrrarity <[email protected]>
AuthorDate: Wed Nov 25 14:14:34 2026 +0800
[fix](serde) Serialize exact HLL byte lengths in DataTypeHLLSerDe (#70908)
### Background
Doris `HyperLogLog` encodes values as `EMPTY` (1 byte), `EXPLICIT` (up to
160 hashes), `SPARSE` (161 to 4,096 non-zero registers, 5 to 12,293 bytes), or
`FULL` (16,385 bytes). `max_serialized_size()` returns the 16,385-byte upper
bound for both sparse and full states, whereas `serialize()` returns the exact
byte count written and `is_valid()` rejects trailing bytes.
### What problem does this PR solve?
Issue Number: None
Related PR: #18627 (Protobuf HLL SerDe), #19091 (Arrow HLL SerDe), #20928
(MySQL binary HLL output), #24812 (ORC HLL SerDe)
PR Type: Bugfix
Problem Summary:
Four `DataTypeHLLSerDe` writers emitted `max_serialized_size()` (`16,385`
bytes) instead of the byte count returned by `HyperLogLog::serialize()`. For
sparse HLLs, MySQL binary output, ORC `INTO OUTFILE`, Arrow, and Protobuf
appended trailing padding or uninitialized heap bytes, causing
`HyperLogLog::deserialize()` (such as `hll_from_base64`) to fail. This PR emits
the exact byte length returned by `serialize()` across all four writers.
### Details
- **Change map:** Production +17/-17 in `data_type_hll_serde.cpp`; tests
+315/-6 across `data_type_serde_hll_test.cpp` (+186/-1),
`test_hll_sparse_return_binary.groovy` (+97/-0, new), and
`data_type_hll_test.cpp` (+32/-5).
- **Frequency:** Every `HLL_DATA_SPARSE` value (`161..4096` non-zero
registers) written through PB, Arrow, MySQL binary, or ORC SerDe.
- **Root cause:** Those four writers allocated or bounded buffers by
`max_serialized_size()` and discarded the actual byte count returned by
`serialize()`.
- **Why existing tests missed it:** Existing HLL SerDe and binary-output
tests used at most `100` hashes (`EXPLICIT`), where `serialize()` equals
`max_serialized_size()`.
- **Fix:** Capture `actual_size` from `serialize()` in PB, Arrow, MySQL
text, and ORC writers, and advance ORC batch length and offset by `actual_size`
without extra temporary buffering.
- **Other paths and branches:** Block shuffle (`DataTypeHLL`) and storage
(`HllColumnWriter`) already write exact sizes; `branch-3.0` through
`branch-4.2` carry the same SerDe writers.
### Testing
Sparse HLL fixture (`200` distinct registers, cardinality `201`, compact
serialized length `1 + 4 + 3 * 200 = 605` bytes):
```sql
SELECT
hll_cardinality(h) AS orig_card,
OCTET_LENGTH(FROM_BASE64(hll_to_base64(h))) AS expected_bytes
FROM (
SELECT hll_union(hll_hash(CAST(number AS VARCHAR))) AS h
FROM numbers("number" = "200")
) t;
```
```text
+-----------+----------------+
| orig_card | expected_bytes |
+-----------+----------------+
| 201 | 605 |
+-----------+----------------+
```
**1. MySQL binary output (`write_column_to_mysql_text`) and
`hll_from_base64` round-trip**
```sql
SET return_object_data_as_binary = true;
SELECT hll_union(hll_hash(CAST(number AS VARCHAR)))
FROM numbers("number" = "200");
```
Before the fix (`6a6c7529c1e`), the client received `16,385` bytes (`605`
valid sparse bytes + `15,780` uninitialized tail bytes), and passing the Base64
payload back to `hll_from_base64` failed:
```text
received_bytes=16385, hll_type=2, num_registers=200, actual_bytes=605,
tail_bytes=15780
ERROR 1105 (HY000) at line 1: errCode = 2, detailMessage =
(127.0.0.1)[RUNTIME_ERROR]hll_from_base64 decode failed: base64:
AsgAAAB0AAO8AAVVAQJ3AQSjAQTvAQINAgFCAgGLAgWOAgJWAwHWAwHuAwErBAFYBAF2BAS5BANMBQKJBQGhBQOzBQICBgELBgFDBgFWBgGZBwStBwHnBwLwBwdcCAJiCAJsCAGfCAOOCQHpCQILCgEUCgEKCwGPDAGaDAEcDQM1DQFTDQGVDQLCDQHbDQJUDgFcDgaMDgE4DwFEDwHzDwH2DwQvEANkEAHcEAEkEQF4EQGrEQEMEgE6EgJBEgGNEgGQEgPmEgVrEwHBEwLCEwFNFAGxFAIJFQIfFQFDFQFVFQR1FQIWFgcnFgGBFgEXFwFQFwF2FwHDFwHGFwHpGAEcGQFQGQK0GgFjGwaoGwUPH
[...]
```
With the fix, the client receives `605` bytes (`tail_bytes=0`) and `SELECT
hll_cardinality(hll_from_base64('$PAYLOAD_B64')) AS card` succeeds:
```text
received_bytes=605, hll_type=2, num_registers=200, actual_bytes=605,
tail_bytes=0
+------+
| card |
+------+
| 201 |
+------+
```
**2. ORC `INTO OUTFILE` (`write_column_to_orc`)**
```sql
SELECT hll_union(hll_hash(CAST(number AS VARCHAR))) AS h
FROM numbers("number" = "200")
INTO OUTFILE "file://$OUT_DIR/orc_"
FORMAT AS ORC;
```
`orc-statistics` on Column 1 (`h`) before vs. with the fix:
```text
# Before the fix (6a6c7529c1e) # With the fix
*** Column 1 *** *** Column 1 ***
Data type: Binary Data type: Binary
Values: 1 Values: 1
Has null: no Has null: no
Total length: 16385 Total length: 605
```
**3. Automated tests**
- BE UT (`./run-be-ut.sh --run
--filter="HLLSerdeTest.*:*DataTypeHLL*:*SerDePb*" -j50 --coverage`, ASAN):
48/48 passed (`84.56%` line coverage and `87.21%` region coverage on
`data_type_hll_serde.cpp`; `100.00%` on `data_type_hll_serde.h`), covering
`EMPTY`/`EXPLICIT`/`SPARSE`/`FULL` serialization across PB, Arrow, MySQL, and
ORC.
- Regression P0 (`./run-regression-test.sh`):
`datatype_p0/hll/test_hll_sparse_return_binary.groovy` (1/1 passed; `SELECT
COUNT(*)` verified 4 retained rows) and
`query_p0/sql_functions/hll_functions/test_hll_functions.groovy` (1/1 passed).
### Release note
`DataTypeHLLSerDe` now writes exact serialized byte lengths for sparse
`HLL` values across MySQL binary output, ORC export, Arrow, and Protobuf.
### Check List (For Author)
- Behavior changed: No
- Does this need documentation: No
- Pre-submission status: Ready
### AI Disclosure
- Tool: Codex (gpt-6.2-sol)
- Generated: BE fix, unit tests, regression test, and this description
- Human review: Author reviewed earlier revisions and directed reverting
`read_column_from_pb()` and simplifying buffer allocations in ORC, Arrow, and
Protobuf writers; the final commit and this description await author review.
- Prompts: Requested fixing HLL SerDe upper-bound serialization, reverting
`read_column_from_pb()`, restoring single-allocation ORC serialization without
outer loop buffers, pushing without opening a PR, and updating the PR
description with concrete examples.
---
.../core/data_type_serde/data_type_hll_serde.cpp | 34 ++--
be/test/core/data_type/data_type_hll_test.cpp | 37 +++-
.../data_type_serde/data_type_serde_hll_test.cpp | 187 ++++++++++++++++++++-
.../hll/test_hll_sparse_return_binary.groovy | 97 +++++++++++
4 files changed, 332 insertions(+), 23 deletions(-)
diff --git a/be/src/core/data_type_serde/data_type_hll_serde.cpp
b/be/src/core/data_type_serde/data_type_hll_serde.cpp
index 46f832d10ae..687bf1af561 100644
--- a/be/src/core/data_type_serde/data_type_hll_serde.cpp
+++ b/be/src/core/data_type_serde/data_type_hll_serde.cpp
@@ -87,10 +87,10 @@ Status DataTypeHLLSerDe::write_column_to_pb(const IColumn&
column, PValues& resu
auto row_count = cast_set<int>(end - start);
result.mutable_bytes_value()->Reserve(row_count);
for (size_t row_num = start; row_num < end; ++row_num) {
- auto& value = data_column.get_element(row_num);
+ const auto& value = data_column.get_element(row_num);
std::string memory_buffer(value.max_serialized_size(), '0');
- value.serialize((uint8_t*)memory_buffer.data());
- result.add_bytes_value(memory_buffer.data(), memory_buffer.size());
+ size_t actual_size =
value.serialize(reinterpret_cast<uint8_t*>(memory_buffer.data()));
+ result.add_bytes_value(memory_buffer.data(), actual_size);
}
return Status::OK();
}
@@ -133,12 +133,13 @@ Status DataTypeHLLSerDe::write_column_to_arrow(const
IColumn& column, const Null
if (null_map && (*null_map)[string_i]) {
RETURN_IF_ERROR(checkArrowStatus(builder.AppendNull(), column,
*array_builder));
} else {
- auto& hll_value = col.get_element(string_i);
+ const auto& hll_value = col.get_element(string_i);
std::string memory_buffer(hll_value.max_serialized_size(), '0');
- hll_value.serialize((uint8_t*)memory_buffer.data());
+ size_t actual_size =
+
hll_value.serialize(reinterpret_cast<uint8_t*>(memory_buffer.data()));
RETURN_IF_ERROR(checkArrowStatus(
- builder.Append(memory_buffer.data(),
static_cast<int>(memory_buffer.size())),
- column, *array_builder));
+ builder.Append(memory_buffer.data(),
static_cast<int>(actual_size)), column,
+ *array_builder));
}
}
return Status::OK();
@@ -159,8 +160,8 @@ bool DataTypeHLLSerDe::write_column_to_mysql_text(const
IColumn& column, BufferW
const HyperLogLog& hyperLogLog = data_column.get_element(row_idx);
size_t size = hyperLogLog.max_serialized_size();
std::unique_ptr<char[]> buf =
std::make_unique_for_overwrite<char[]>(size);
- hyperLogLog.serialize((uint8_t*)buf.get());
- bw.write(buf.get(), size);
+ size_t actual_size =
hyperLogLog.serialize(reinterpret_cast<uint8_t*>(buf.get()));
+ bw.write(buf.get(), actual_size);
return true;
} else {
return false;
@@ -174,26 +175,25 @@ Status DataTypeHLLSerDe::write_column_to_orc(const
std::string& timezone, const
const FormatOptions& options)
const {
auto& col_data = assert_cast<const ColumnHLL&>(column);
orc::StringVectorBatch* cur_batch =
dynamic_cast<orc::StringVectorBatch*>(orc_col_batch);
- // First pass: calculate total memory needed and collect serialized values
+ // First pass: calculate the upper bound on the serialized size.
size_t total_size = 0;
for (size_t row_id = start; row_id < end; row_id++) {
if (cur_batch->notNull[row_id] == 1) {
- auto hll_value = col_data.get_element(row_id);
+ const auto& hll_value = col_data.get_element(row_id);
size_t len = hll_value.max_serialized_size();
total_size += len;
}
}
- // Allocate continues memory based on calculated size
char* ptr = arena.alloc(total_size);
if (!ptr) {
return Status::InternalError(
"malloc memory {} error when write variant column data to orc
file.", total_size);
}
- // Second pass: copy data to allocated memory
+ // Second pass: serialize directly into the allocated memory.
size_t offset = 0;
for (size_t row_id = start; row_id < end; row_id++) {
if (cur_batch->notNull[row_id] == 1) {
- auto hll_value = col_data.get_element(row_id);
+ const auto& hll_value = col_data.get_element(row_id);
size_t len = hll_value.max_serialized_size();
if (offset + len > total_size) {
return Status::InternalError(
@@ -201,10 +201,10 @@ Status DataTypeHLLSerDe::write_column_to_orc(const
std::string& timezone, const
"{} exceed total_size {} ",
offset, len, total_size);
}
- hll_value.serialize((uint8_t*)ptr + offset);
+ size_t actual_size =
hll_value.serialize(reinterpret_cast<uint8_t*>(ptr + offset));
cur_batch->data[row_id] = ptr + offset;
- cur_batch->length[row_id] = len;
- offset += len;
+ cur_batch->length[row_id] = actual_size;
+ offset += actual_size;
}
}
cur_batch->numElements = end - start;
diff --git a/be/test/core/data_type/data_type_hll_test.cpp
b/be/test/core/data_type/data_type_hll_test.cpp
index b68a5e60d0f..42832eec5c4 100644
--- a/be/test/core/data_type/data_type_hll_test.cpp
+++ b/be/test/core/data_type/data_type_hll_test.cpp
@@ -21,7 +21,11 @@
#include <gtest/gtest-test-part.h>
#include <gtest/gtest.h>
+#include <algorithm>
+#include <cstdint>
#include <iostream>
+#include <string>
+#include <vector>
#include "agent/be_exec_version_manager.h"
#include "core/column/column.h"
@@ -32,6 +36,7 @@
#include "core/data_type/data_type_nullable.h"
#include "core/field.h"
#include "core/types.h"
+#include "util/coding.h"
// this test is gonna to be a data type test template for all DataType which
should make ut test to coverage the function defined
// for example DataTypeHLL should test this function:
@@ -112,6 +117,28 @@ void insert_data_hll(MutableColumns* hll_cols, DataTypePtr
datetype_hll, int row
std::cout << "finish insert data" << std::endl;
}
+static void expect_hll_equal(const HyperLogLog& lhs, const HyperLogLog& rhs) {
+ const auto serialize = [](const HyperLogLog& hll) {
+ std::string bytes(hll.max_serialized_size(), '\0');
+ bytes.resize(hll.serialize(reinterpret_cast<uint8_t*>(bytes.data())));
+ if (bytes.front() == HLL_DATA_EXPLICIT) {
+ // Explicit hashes are serialized in hash set iteration order.
+ std::vector<uint64_t> hashes(static_cast<uint8_t>(bytes[1]));
+ auto* payload = reinterpret_cast<uint8_t*>(bytes.data()) + 2;
+ decode_fixed64_le_array(hashes.data(), payload, hashes.size());
+ std::sort(hashes.begin(), hashes.end());
+ for (auto hash : hashes) {
+ encode_fixed64_le(payload, hash);
+ payload += sizeof(hash);
+ }
+ }
+ return bytes;
+ };
+
+ EXPECT_EQ(lhs.estimate_cardinality(), rhs.estimate_cardinality());
+ EXPECT_EQ(serialize(lhs), serialize(rhs));
+}
+
// serialize / deserialize
TEST_P(DataTypeHLLTest, SerializeDeserializeTest) {
MutableColumns hll_cols;
@@ -123,13 +150,13 @@ TEST_P(DataTypeHLLTest, SerializeDeserializeTest) {
std::unique_ptr<char[]> buf = std::make_unique<char[]>(size);
auto* result =
dt_hll->serialize(*column, buf.get(),
BeExecVersionManager::get_newest_version());
- ASSERT_EQ(result, buf.get() + size);
+ ASSERT_LE(result, buf.get() + size);
auto column2 = dt_hll->create_column();
dt_hll->deserialize(buf.get(), &column2,
BeExecVersionManager::get_newest_version());
for (size_t i = 0; i != rows_value; ++i) {
auto* column_res = assert_cast<ColumnHLL*>(column2.get());
- ASSERT_EQ(column->get_data()[i].to_string(),
column_res->get_data()[i].to_string());
+ expect_hll_equal(column->get_element(i), column_res->get_element(i));
}
helper->serialize_deserialize_assert(hll_cols, {dt_hll});
std::cout << "finish serialize deserialize test" << std::endl;
@@ -151,11 +178,11 @@ TEST_P(DataTypeHLLTest, SerializeDeserializeAsStreamTest)
{
buffer_writer.commit();
BufferReadable buffer_readable(ser_col->get_data_at(i));
doris::DataTypeHLL::deserialize_as_stream(column_res->get_element(i),
buffer_readable);
- ASSERT_EQ(column_data->get_data()[i].to_string(),
column_res->get_data()[i].to_string());
+ expect_hll_equal(column_data->get_element(i),
column_res->get_element(i));
}
std::cout << "finish serialize deserialize as stream test" << std::endl;
}
-INSTANTIATE_TEST_SUITE_P(Params, DataTypeHLLTest, ::testing::Values(0, 1, 10,
100));
+INSTANTIATE_TEST_SUITE_P(Params, DataTypeHLLTest, ::testing::Values(0, 1, 10,
100, 200));
-} // namespace doris
\ No newline at end of file
+} // namespace doris
diff --git a/be/test/core/data_type_serde/data_type_serde_hll_test.cpp
b/be/test/core/data_type_serde/data_type_serde_hll_test.cpp
index c23b8434733..a9a5bfb48d3 100644
--- a/be/test/core/data_type_serde/data_type_serde_hll_test.cpp
+++ b/be/test/core/data_type_serde/data_type_serde_hll_test.cpp
@@ -15,18 +15,79 @@
// specific language governing permissions and limitations
// under the License.
-#include <arrow/array/builder_base.h>
+#include <arrow/api.h>
+#include <cctz/time_zone.h>
+#include <gen_cpp/types.pb.h>
#include <gtest/gtest.h>
+#include <array>
+#include <cstdint>
+#include <cstring>
+#include <iostream>
+#include <memory>
+#include <orc/OrcFile.hh>
+#include <string>
+
+#include "core/arena.h"
#include "core/column/column_complex.h"
+#include "core/column/column_string.h"
#include "core/data_type/common_data_type_serder_test.h"
#include "core/data_type/data_type_hll.h"
#include "core/data_type_serde/data_type_hll_serde.h"
+#include "core/string_buffer.hpp"
#include "core/value/hll.h"
+#include "util/jsonb_writer.h"
#include "util/slice.h"
namespace doris {
+namespace {
+
+struct HllSerdeCase {
+ uint64_t hash_count;
+ HllDataType type;
+ size_t serialized_size;
+};
+
+constexpr std::array<HllSerdeCase, 5> hll_serde_cases = {{
+ {0, HLL_DATA_EMPTY, 1},
+ {1, HLL_DATA_EXPLICIT, 10},
+ {160, HLL_DATA_EXPLICIT, 1282},
+ // These sequential hashes address distinct registers.
+ {200, HLL_DATA_SPARSE, 605},
+ {5000, HLL_DATA_FULL, 16385},
+}};
+
+ColumnHLL::MutablePtr make_hll_column() {
+ auto column = ColumnHLL::create();
+ for (const auto& test_case : hll_serde_cases) {
+ auto& hll = column->get_data().emplace_back();
+ for (uint64_t hash = 0; hash < test_case.hash_count; ++hash) {
+ hll.update(hash);
+ }
+ }
+ return column;
+}
+
+std::string serialize_hll(const HyperLogLog& value) {
+ std::string bytes(value.max_serialized_size(), '\0');
+ bytes.resize(value.serialize(reinterpret_cast<uint8_t*>(bytes.data())));
+ return bytes;
+}
+
+std::string expected_hll_bytes(const HyperLogLog& value, size_t row) {
+ const auto& test_case = hll_serde_cases[row];
+ if (test_case.type == HLL_DATA_SPARSE) {
+ EXPECT_EQ(value.max_serialized_size(), 16385);
+ }
+ auto bytes = serialize_hll(value);
+ EXPECT_EQ(bytes.size(), test_case.serialized_size);
+ EXPECT_EQ(static_cast<uint8_t>(bytes.front()), test_case.type);
+ return bytes;
+}
+
+} // namespace
+
TEST(HLLSerdeTest, writeOneCellToJsonb) {
auto hll_serde = std::make_shared<DataTypeHLLSerDe>(1);
auto column_hll = ColumnHLL::create();
@@ -207,4 +268,128 @@ TEST(HLLSerdeTest, UnsupportedArrowReadReturnsError) {
hll_serde->read_column_from_arrow(*column_hll, nullptr, 0, 0,
cctz::utc_time_zone())
.ok());
}
+
+TEST(HLLSerdeTest, SparseAndFullPbRoundTrip) {
+ DataTypeHLLSerDe serde;
+ auto column = make_hll_column();
+ const int end = static_cast<int>(column->size());
+ for (const int start : {0, 2}) {
+ PValues pv;
+ auto status = serde.write_column_to_pb(*column, pv, start, end);
+ ASSERT_TRUE(status.ok()) << status.to_string();
+ ASSERT_EQ(pv.bytes_value_size(), end - start);
+
+ auto decoded = ColumnHLL::create();
+ status = serde.read_column_from_pb(*decoded, pv);
+ ASSERT_TRUE(status.ok()) << status.to_string();
+ ASSERT_EQ(decoded->size(), end - start);
+
+ for (int idx = 0; idx < pv.bytes_value_size(); ++idx) {
+ const int row = start + idx;
+ SCOPED_TRACE(row);
+ const auto& original = column->get_element(row);
+ const auto expected_bytes = expected_hll_bytes(original, row);
+ ASSERT_EQ(pv.bytes_value(idx).size(), expected_bytes.size());
+ EXPECT_EQ(pv.bytes_value(idx), expected_bytes);
+ ASSERT_TRUE(HyperLogLog::is_valid(Slice(pv.bytes_value(idx))));
+ const auto& round_tripped = decoded->get_element(idx);
+ EXPECT_EQ(round_tripped.estimate_cardinality(),
original.estimate_cardinality());
+ EXPECT_EQ(serialize_hll(round_tripped), expected_bytes);
+ }
+ }
+}
+
+TEST(HLLSerdeTest, SparseAndFullArrowSerialize) {
+ DataTypeHLLSerDe serde;
+ auto column = make_hll_column();
+ column->insert_default();
+ NullMap null_map(column->size(), 0);
+ null_map.back() = 1;
+ arrow::BinaryBuilder builder;
+ auto status = serde.write_column_to_arrow(*column, &null_map, &builder, 0,
column->size(),
+ cctz::utc_time_zone());
+ ASSERT_TRUE(status.ok()) << status.to_string();
+ std::shared_ptr<arrow::Array> result;
+ ASSERT_TRUE(builder.Finish(&result).ok());
+ const auto& array = static_cast<const arrow::BinaryArray&>(*result);
+ ASSERT_EQ(array.length(), column->size());
+
+ for (int64_t row = 0; row < array.length(); ++row) {
+ SCOPED_TRACE(row);
+ ASSERT_EQ(array.IsNull(row), null_map[row] != 0);
+ if (null_map[row]) {
+ continue;
+ }
+ const auto expected_bytes =
expected_hll_bytes(column->get_element(row), row);
+ const auto bytes = array.GetView(row);
+ ASSERT_EQ(bytes.size(), expected_bytes.size());
+ EXPECT_EQ(bytes, expected_bytes);
+ const Slice slice(bytes.data(), bytes.size());
+ ASSERT_TRUE(HyperLogLog::is_valid(slice));
+ HyperLogLog decoded;
+ EXPECT_TRUE(decoded.deserialize(slice));
+ }
+}
+
+TEST(HLLSerdeTest, SparseAndFullMysqlTextSerialize) {
+ DataTypeHLLSerDe serde;
+ auto column = make_hll_column();
+ auto output = ColumnString::create();
+ VectorBufferWriter writer(*output);
+ DataTypeSerDe::FormatOptions options;
+
+ serde.set_return_object_as_string(false);
+ for (size_t row = 0; row < column->size(); ++row) {
+ EXPECT_FALSE(serde.write_column_to_mysql_text(*column, writer, row,
options));
+ }
+ ASSERT_EQ(output->get_chars().size(), 0);
+
+ serde.set_return_object_as_string(true);
+ for (size_t row = 0; row < column->size(); ++row) {
+ SCOPED_TRACE(row);
+ ASSERT_TRUE(serde.write_column_to_mysql_text(*column, writer, row,
options));
+ writer.commit();
+ const auto expected_bytes =
expected_hll_bytes(column->get_element(row), row);
+ const auto bytes = output->get_data_at(row);
+ ASSERT_EQ(bytes.size, expected_bytes.size());
+ EXPECT_EQ(bytes.to_string(), expected_bytes);
+ }
+}
+
+TEST(HLLSerdeTest, SparseAndFullOrcSerialize) {
+ DataTypeHLLSerDe serde;
+ auto column = make_hll_column();
+ const size_t null_row = column->size();
+ column->insert_default();
+ const size_t end = column->size();
+ Arena arena;
+ orc::StringVectorBatch batch(end, *orc::getDefaultPool());
+ batch.hasNulls = true;
+ for (size_t row = 0; row < end; ++row) {
+ batch.notNull[row] = row != null_row;
+ }
+ batch.data[null_row] = nullptr;
+ batch.length[null_row] = 0;
+
+ DataTypeSerDe::FormatOptions options;
+ batch.numElements = end;
+ auto status =
+ serde.write_column_to_orc("UTC", *column, nullptr, &batch, end,
end, arena, options);
+ ASSERT_TRUE(status.ok()) << status.to_string();
+ EXPECT_EQ(batch.numElements, 0);
+
+ const size_t start = 0;
+ status = serde.write_column_to_orc("UTC", *column, nullptr, &batch, start,
end, arena, options);
+ ASSERT_TRUE(status.ok()) << status.to_string();
+ ASSERT_EQ(batch.numElements, end - start);
+ EXPECT_EQ(batch.data[null_row], nullptr);
+ EXPECT_EQ(batch.length[null_row], 0);
+ for (size_t row = start; row < null_row; ++row) {
+ SCOPED_TRACE(row);
+ const auto expected_bytes =
expected_hll_bytes(column->get_element(row), row);
+ ASSERT_EQ(batch.length[row], expected_bytes.size());
+ EXPECT_EQ(memcmp(batch.data[row], expected_bytes.data(),
expected_bytes.size()), 0);
+ EXPECT_TRUE(HyperLogLog::is_valid(Slice(batch.data[row],
batch.length[row])));
+ }
+}
} // namespace doris
diff --git
a/regression-test/suites/datatype_p0/hll/test_hll_sparse_return_binary.groovy
b/regression-test/suites/datatype_p0/hll/test_hll_sparse_return_binary.groovy
new file mode 100644
index 00000000000..ba138a62529
--- /dev/null
+++
b/regression-test/suites/datatype_p0/hll/test_hll_sparse_return_binary.groovy
@@ -0,0 +1,97 @@
+// 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.
+
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+
+suite("test_hll_sparse_return_binary") {
+ def normalizeHllBytes = { byte[] bytes ->
+ // HLL_DATA_EXPLICIT serializes hashes in flat_hash_set bucket order.
+ if (bytes.length >= 2 && bytes[0] == (byte) 1) {
+ int count = bytes[1] & 0xff
+ assertEquals(2 + count * 8, bytes.length)
+
+ long[] hashes = new long[count]
+ def buffer = ByteBuffer.wrap(bytes, 2, count *
8).order(ByteOrder.LITTLE_ENDIAN)
+ for (int i = 0; i < count; i++) {
+ hashes[i] = buffer.getLong()
+ }
+ Arrays.sort(hashes)
+
+ byte[] normalized = Arrays.copyOf(bytes, bytes.length)
+ def out = ByteBuffer.wrap(normalized, 2, count *
8).order(ByteOrder.LITTLE_ENDIAN)
+ for (long hash : hashes) {
+ out.putLong(hash)
+ }
+ return normalized
+ }
+ return bytes
+ }
+
+ sql "DROP TABLE IF EXISTS test_hll_sparse_return_binary"
+ sql """
+ CREATE TABLE test_hll_sparse_return_binary (
+ id INT,
+ h HLL HLL_UNION
+ ) AGGREGATE KEY(id)
+ DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES("replication_num" = "1")
+ """
+ sql "INSERT INTO test_hll_sparse_return_binary VALUES (0, hll_empty())"
+ sql 'INSERT INTO test_hll_sparse_return_binary SELECT 1, hll_hash(number)
FROM numbers("number" = "10")'
+ sql 'INSERT INTO test_hll_sparse_return_binary SELECT 2, hll_hash(number)
FROM numbers("number" = "200")'
+ sql 'INSERT INTO test_hll_sparse_return_binary SELECT 3, hll_hash(number)
FROM numbers("number" = "8000")'
+
+ def rows = []
+ context.getConn().createStatement().withCloseable { statement ->
+ statement.execute("SET return_object_data_as_binary = true")
+ statement.executeQuery("""
+ SELECT id, h, hll_to_base64(h), hll_cardinality(h)
+ FROM test_hll_sparse_return_binary ORDER BY id
+ """).withCloseable { rs ->
+ while (rs.next()) {
+ rows.add([id: rs.getInt(1), rawBytes: rs.getBytes(2),
+ base64Str: rs.getString(3), card: rs.getLong(4)])
+ }
+ }
+ }
+
+ assertEquals(4, rows.size())
+ rows.eachWithIndex { row, id ->
+ assertEquals(id, row.id)
+ byte[] expectedBytes = Base64.getDecoder().decode(row.base64Str)
+ assertEquals(expectedBytes.length, row.rawBytes.length, "HLL byte
length differs for id ${id}")
+ assertTrue(Arrays.equals(normalizeHllBytes(row.rawBytes),
normalizeHllBytes(expectedBytes)),
+ "HLL bytes differ for id ${id}")
+
+ if (id == 0) {
+ assertEquals(1, row.rawBytes.length)
+ } else if (id == 1) {
+ assertTrue(row.rawBytes.length < 16385)
+ } else if (id == 2) {
+ assertEquals((byte) 2, row.rawBytes[0]) // HLL_DATA_SPARSE
+ assertTrue(row.rawBytes.length > 5)
+ assertTrue(row.rawBytes.length < 16385)
+ } else {
+ assertEquals(16385, row.rawBytes.length)
+ }
+
+ def encoded = Base64.getEncoder().encodeToString(row.rawBytes)
+ def result = sql "SELECT
hll_cardinality(hll_from_base64('${encoded}'))"
+ assertEquals(row.card as long, result[0][0] as long)
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]