This is an automated email from the ASF dual-hosted git repository.
eldenmoon 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 8f07a817461 [fix](be) Replay legacy Variant WALs after an upgrade
(#71194)
8f07a817461 is described below
commit 8f07a81746134b7edacfe237d20bba4723a4b31f
Author: lihangyu <[email protected]>
AuthorDate: Fri Dec 4 15:21:44 2026 +0800
[fix](be) Replay legacy Variant WALs after an upgrade (#71194)
---
be/benchmark/benchmark_variant_assembler.hpp | 2 +-
be/src/core/data_type/data_type_factory.cpp | 18 +-
be/src/core/data_type/data_type_variant_v2.cpp | 16 +-
be/src/core/data_type/data_type_variant_v2.h | 6 +-
.../value/variant}/variant_assembler.cpp | 40 +-
.../v2 => core/value/variant}/variant_assembler.h | 2 +
.../value/variant}/variant_assembler_internal.h | 2 +-
.../value/variant}/variant_assembler_value.cpp | 12 +-
.../value/variant}/variant_storage_cell.cpp | 2 +-
.../value/variant}/variant_storage_cell.h | 0
.../core/value/variant/variant_v1_wire_reader.cpp | 159 +++++++
.../core/value/variant/variant_v1_wire_reader.h | 32 +-
.../variant/binary_column_extract_iterator.cpp | 2 +-
.../segment/variant/binary_column_reader.cpp | 2 +-
.../segment/variant/hierarchical_data_iterator.cpp | 2 +-
.../segment/variant/v2/variant_column_writer.cpp | 2 +-
.../variant_doc_snpashot_compact_iterator.h | 2 +-
.../core/block/block_variant_wire_format_test.cpp | 524 ++++++++++++++++++---
be/test/format/wal/test_data/wal_variant_v1_31.wal | Bin 0 -> 1272 bytes
be/test/format/wal/test_data/wal_variant_v1_40.wal | Bin 0 -> 1184 bytes
.../wal/test_data/wal_variant_v1_40_rich.wal | Bin 0 -> 468 bytes
be/test/format/wal/test_data/wal_variant_v1_42.wal | Bin 0 -> 1524 bytes
.../wal/test_data/wal_variant_v1_doc_order.wal | Bin 0 -> 414 bytes
.../wal/test_data/wal_variant_v1_doc_value.wal | Bin 0 -> 1538 bytes
.../format/wal/test_data/wal_variant_v1_legacy.wal | Bin 0 -> 1198 bytes
.../wal/test_data/wal_variant_v2_current.wal | Bin 0 -> 972 bytes
be/test/format/wal/wal_reader_writer_test.cpp | 27 ++
.../format/wal/wal_variant_wire_compat_test.cpp | 281 +++++++++++
be/test/format_v2/wal/wal_reader_test.cpp | 480 ++++++++++++++++++-
.../binary_column_extract_iterator_test.cpp | 2 +-
.../segment/variant_assembler_legacy_test.cpp | 19 +-
.../storage/variant/test_data/variant_doris40.dat | Bin 0 -> 4944 bytes
.../variant/variant_column_writer_reader_test.cpp | 2 +-
.../variant/variant_legacy_segment_test.cpp | 95 ++++
be/test/testutil/variant_v1_wire_test_util.h | 170 +++++++
.../data/insert_p0/test_group_commit_variant.out | 9 +
regression-test/script/variant_wal_upgrade.py | 386 +++++++++++++++
.../insert_p0/test_group_commit_variant.groovy | 56 ++-
38 files changed, 2222 insertions(+), 130 deletions(-)
diff --git a/be/benchmark/benchmark_variant_assembler.hpp
b/be/benchmark/benchmark_variant_assembler.hpp
index 4dfe6e20162..3a963a4d83e 100644
--- a/be/benchmark/benchmark_variant_assembler.hpp
+++ b/be/benchmark/benchmark_variant_assembler.hpp
@@ -31,7 +31,7 @@
#include "core/custom_allocator.h"
#include "core/data_type/data_type_nullable.h"
#include "core/data_type/data_type_number.h"
-#include "storage/segment/variant/v2/variant_assembler.h"
+#include "core/value/variant/variant_assembler.h"
namespace doris::variant_assembler_benchmark {
diff --git a/be/src/core/data_type/data_type_factory.cpp
b/be/src/core/data_type/data_type_factory.cpp
index ed3a684bbed..ea5336a8de5 100644
--- a/be/src/core/data_type/data_type_factory.cpp
+++ b/be/src/core/data_type/data_type_factory.cpp
@@ -260,11 +260,21 @@ DataTypePtr DataTypeFactory::create_data_type(const
PColumnMeta& pcolumn) {
case PGenericType::STRING:
nested = std::make_shared<DataTypeString>();
break;
- case PGenericType::VARIANT:
- nested =
std::make_shared<DataTypeVariantV2>(pcolumn.variant_max_subcolumns_count(),
-
pcolumn.variant_enable_doc_mode(),
- pcolumn.variant_is_v2());
+ case PGenericType::VARIANT: {
+ using WireFormat = DataTypeVariantV2::WireFormat;
+ // Older V1 writers omit the doc-mode field and end at the sparse map.
+ // The later V1 layout includes a doc-value map even for
doc_mode=false.
+ auto wire_format = WireFormat::V1;
+ if (pcolumn.variant_is_v2()) {
+ wire_format = WireFormat::V2;
+ } else if (pcolumn.has_variant_enable_doc_mode()) {
+ wire_format = WireFormat::V1_WITH_DOC_VALUE;
+ }
+ nested =
+
std::make_shared<DataTypeVariantV2>(pcolumn.variant_max_subcolumns_count(),
+
pcolumn.variant_enable_doc_mode(), wire_format);
break;
+ }
case PGenericType::JSONB:
nested = std::make_shared<DataTypeJsonb>();
break;
diff --git a/be/src/core/data_type/data_type_variant_v2.cpp
b/be/src/core/data_type/data_type_variant_v2.cpp
index 89970a4b90a..566ab09d547 100644
--- a/be/src/core/data_type/data_type_variant_v2.cpp
+++ b/be/src/core/data_type/data_type_variant_v2.cpp
@@ -27,6 +27,7 @@
#include "core/data_type_serde/data_type_variant_v2_serde.h"
#include "core/field.h"
#include "core/typeid_cast.h"
+#include "core/value/variant/variant_v1_wire_reader.h"
namespace doris {
@@ -34,10 +35,10 @@ DataTypeVariantV2::DataTypeVariantV2(int32_t
max_subcolumns_count)
: DataTypeVariantV2(max_subcolumns_count, false) {}
DataTypeVariantV2::DataTypeVariantV2(int32_t max_subcolumns_count, bool
enable_doc_mode,
- bool serialized_as_v2)
+ WireFormat wire_format)
: _max_subcolumns_count(max_subcolumns_count),
_enable_doc_mode(enable_doc_mode),
- _serialized_as_v2(serialized_as_v2) {
+ _wire_format(wire_format) {
_name = fmt::format("Variant(max subcolumns count = {}, enable doc mode =
{})",
max_subcolumns_count, enable_doc_mode);
}
@@ -68,12 +69,11 @@ char* DataTypeVariantV2::serialize(const IColumn& column,
char* buf, int be_exec
const char* DataTypeVariantV2::deserialize(const char* buf, MutableColumnPtr*
column,
int be_exec_version) const {
- // V1 starts with a subcolumn count, not the V2 const/row header. Reject
the legacy
- // marker before reading these bytes as V2 lengths during a mixed-version
transfer.
- if (!_serialized_as_v2) {
- throw Exception(Status::NotSupported(
- "Unsupported VARIANT block format: Variant V1 cannot be
decoded as Variant V2; "
- "use compatible backend versions for Variant block transfer"));
+ // A V1 WAL starts with a subcolumn count where the V2 decoder expects its
+ // const/row header. Dispatch before consuming any bytes.
+ if (_wire_format != WireFormat::V2) {
+ return deserialize_variant_v1(buf, column, be_exec_version,
+ _wire_format ==
WireFormat::V1_WITH_DOC_VALUE);
}
return DataTypeVariantV2SerDe::deserialize(buf, column, be_exec_version);
}
diff --git a/be/src/core/data_type/data_type_variant_v2.h
b/be/src/core/data_type/data_type_variant_v2.h
index dd5a9232f74..c6deb86360a 100644
--- a/be/src/core/data_type/data_type_variant_v2.h
+++ b/be/src/core/data_type/data_type_variant_v2.h
@@ -27,10 +27,12 @@ namespace doris {
class DataTypeVariantV2 final : public IDataType {
public:
+ enum class WireFormat : uint8_t { V2, V1, V1_WITH_DOC_VALUE };
+
DataTypeVariantV2() = default;
explicit DataTypeVariantV2(int32_t max_subcolumns_count);
DataTypeVariantV2(int32_t max_subcolumns_count, bool enable_doc_mode,
- bool serialized_as_v2 = true);
+ WireFormat wire_format = WireFormat::V2);
static constexpr PrimitiveType PType = TYPE_VARIANT;
PrimitiveType get_primitive_type() const override { return TYPE_VARIANT; }
@@ -58,7 +60,7 @@ protected:
private:
int32_t _max_subcolumns_count = 0;
bool _enable_doc_mode = false;
- bool _serialized_as_v2 = true;
+ WireFormat _wire_format = WireFormat::V2;
std::string _name = "Variant";
};
diff --git a/be/src/storage/segment/variant/v2/variant_assembler.cpp
b/be/src/core/value/variant/variant_assembler.cpp
similarity index 95%
rename from be/src/storage/segment/variant/v2/variant_assembler.cpp
rename to be/src/core/value/variant/variant_assembler.cpp
index 64522ff9f6e..672a938b205 100644
--- a/be/src/storage/segment/variant/v2/variant_assembler.cpp
+++ b/be/src/core/value/variant/variant_assembler.cpp
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-#include "storage/segment/variant/v2/variant_assembler.h"
+#include "core/value/variant/variant_assembler.h"
#include <algorithm>
#include <cstring>
@@ -33,11 +33,11 @@
#include "core/column/column_vector.h"
#include "core/column/variant_column_utils.h"
#include "core/column/variant_v2/column_variant_v2.h"
+#include "core/value/variant/variant_assembler_internal.h"
#include "core/value/variant/variant_batch_builder.h"
#include "core/value/variant/variant_parquet_encoding.h"
+#include "core/value/variant/variant_storage_cell.h"
#include "exprs/function/parse/variant_jsonb_parse.h"
-#include "storage/segment/variant/v2/variant_assembler_internal.h"
-#include "storage/segment/variant/v2/variant_storage_cell.h"
#include "util/simd/bits.h"
namespace doris::segment_v2::variant_v2 {
@@ -563,14 +563,13 @@ Status assemble_hierarchical_row(StorageMapKind
storage_map_kind, bool has_root,
std::span<const MaterializedSlot>
materialized_slots,
const PreparedHierarchicalBatch& batch,
size_t row_index,
VariantBatchBuilder::Row* row,
StorageMapRowCursor* map_cursor,
- DorisVector<MergeValue>* pending,
ObjectEmitter* emitter,
- bool* is_outer_null) {
+ StorageMapRowCursor* doc_cursor,
DorisVector<MergeValue>* pending,
+ ObjectEmitter* emitter, bool* is_outer_null) {
const bool has_sparse = storage_map_kind == StorageMapKind::SPARSE;
- const bool has_doc = storage_map_kind == StorageMapKind::DOC;
const bool has_root_sidecar_value =
has_root && (batch.root_nulls == nullptr ||
batch.root_nulls[row_index] == 0) &&
batch.root_values->get_data_at(row_index).size != 0;
- const bool has_doc_row = has_doc && !map_cursor->row_empty(row_index);
+ const bool has_doc_row = doc_cursor != nullptr &&
!doc_cursor->row_empty(row_index);
const bool reads_whole_variant = requested.empty();
const auto candidate_slots = batch.candidate_materialized_slots(row_index);
@@ -597,7 +596,7 @@ Status assemble_hierarchical_row(StorageMapKind
storage_map_kind, bool has_root,
const StringRef requested_raw {requested_path.data(),
requested_path.size()};
emitter->start_row(row);
if (has_doc_row) {
- RETURN_IF_ERROR(emit_doc_row(row_index, requested_raw,
reads_whole_variant, map_cursor,
+ RETURN_IF_ERROR(emit_doc_row(row_index, requested_raw,
reads_whole_variant, doc_cursor,
pending, emitter));
} else {
RETURN_IF_ERROR(emit_merged_row(batch.materialized, has_sparse,
materialized_slots,
@@ -635,6 +634,14 @@ Status assemble_hierarchical(uint32_t path_encoding,
StorageMapKind storage_map_
StorageMapRowCursor map_cursor;
PreparedHierarchicalBatch prepared = prepare_hierarchical_batch(
storage_map_kind, has_root, materialized_slots, batch,
&map_cursor);
+ StorageMapRowCursor legacy_doc_cursor;
+ auto* doc_cursor = storage_map_kind == StorageMapKind::DOC ? &map_cursor :
nullptr;
+ // V1 blocks can have sparse paths on one row and a complete doc value on
+ // another. Use the doc map when that row has one, with sparse as fallback.
+ if (batch.legacy_doc_map != nullptr) {
+ legacy_doc_cursor.bind(batch.legacy_doc_map, batch.num_rows);
+ doc_cursor = &legacy_doc_cursor;
+ }
VariantBatchBuilder builder(
{.rows = batch.num_rows, .metadata_keys =
materialized_slots.size() + 8});
auto outer = ColumnUInt8::create();
@@ -651,9 +658,9 @@ Status assemble_hierarchical(uint32_t path_encoding,
StorageMapKind storage_map_
continue;
}
bool is_outer_null = false;
- RETURN_IF_ERROR(assemble_hierarchical_row(storage_map_kind, has_root,
requested,
- materialized_slots,
prepared, row_index, &row,
- &map_cursor, &pending,
&emitter, &is_outer_null));
+ RETURN_IF_ERROR(assemble_hierarchical_row(
+ storage_map_kind, has_root, requested, materialized_slots,
prepared, row_index,
+ &row, &map_cursor, doc_cursor, &pending, &emitter,
&is_outer_null));
outer->insert_value(is_outer_null ? 1 : 0);
row.finish();
}
@@ -711,9 +718,6 @@ DorisVector<MaterializedSlot>
build_materialized_slots(const VariantAssemblerOpt
return left.relative_path.empty() && !right.relative_path.empty();
});
- for (const MaterializedSlot& slot : slots) {
- DORIS_CHECK_LE(slot.relative_path.get_parts().size(),
VARIANT_MAX_NESTING_DEPTH);
- }
return slots;
}
@@ -762,6 +766,14 @@ Result<std::unique_ptr<VariantAssembler>>
VariantAssembler::create(
VariantAssemblerOptions options) {
RETURN_IF_ERROR_RESULT(check_options(options));
DorisVector<MaterializedSlot> materialized =
build_materialized_slots(options);
+ for (const MaterializedSlot& slot : materialized) {
+ // Older writers could materialize paths deeper than the V2 builder
can encode.
+ if (slot.relative_path.get_parts().size() > VARIANT_MAX_NESTING_DEPTH)
{
+ return ResultError(
+ Status::NotSupported("Variant materialized path exceeds
maximum depth {}",
+ VARIANT_MAX_NESTING_DEPTH));
+ }
+ }
return std::unique_ptr<VariantAssembler>(
new VariantAssembler(options.path_encoding,
options.storage_map_kind, options.has_root,
options.requested_path,
std::move(materialized)));
diff --git a/be/src/storage/segment/variant/v2/variant_assembler.h
b/be/src/core/value/variant/variant_assembler.h
similarity index 97%
rename from be/src/storage/segment/variant/v2/variant_assembler.h
rename to be/src/core/value/variant/variant_assembler.h
index 9f66126bc53..fd344c71787 100644
--- a/be/src/storage/segment/variant/v2/variant_assembler.h
+++ b/be/src/core/value/variant/variant_assembler.h
@@ -82,6 +82,8 @@ struct VariantAssemblerBatchView {
const IColumn* root_jsonb = nullptr;
std::span<const IColumn* const> materialized_columns;
const ColumnMap* storage_map = nullptr;
+ // A V1 block can carry both maps, whereas a segment supplies one kind.
+ const ColumnMap* legacy_doc_map = nullptr;
};
// Owns normalized PathInData/DataType metadata from create(), then prepares
and assembles each
diff --git a/be/src/storage/segment/variant/v2/variant_assembler_internal.h
b/be/src/core/value/variant/variant_assembler_internal.h
similarity index 97%
rename from be/src/storage/segment/variant/v2/variant_assembler_internal.h
rename to be/src/core/value/variant/variant_assembler_internal.h
index 3a1cd0b95a1..20fd78843d0 100644
--- a/be/src/storage/segment/variant/v2/variant_assembler_internal.h
+++ b/be/src/core/value/variant/variant_assembler_internal.h
@@ -23,8 +23,8 @@
#include "core/column/column_array.h"
#include "core/column/column_vector.h"
+#include "core/value/variant/variant_assembler.h"
#include "core/value/variant/variant_batch_builder.h"
-#include "storage/segment/variant/v2/variant_assembler.h"
namespace doris::segment_v2::variant_v2::variant_assembler_detail {
diff --git a/be/src/storage/segment/variant/v2/variant_assembler_value.cpp
b/be/src/core/value/variant/variant_assembler_value.cpp
similarity index 91%
rename from be/src/storage/segment/variant/v2/variant_assembler_value.cpp
rename to be/src/core/value/variant/variant_assembler_value.cpp
index bb0202340c0..20ab30d9f18 100644
--- a/be/src/storage/segment/variant/v2/variant_assembler_value.cpp
+++ b/be/src/core/value/variant/variant_assembler_value.cpp
@@ -19,6 +19,7 @@
#include <utility>
#include "common/check.h"
+#include "common/exception.h"
#include "core/assert_cast.h"
#include "core/column/column_nullable.h"
#include "core/column/column_string.h"
@@ -27,8 +28,8 @@
#include "core/data_type/data_type_array.h"
#include "core/data_type/data_type_nullable.h"
#include "core/typeid_cast.h"
+#include "core/value/variant/variant_assembler_internal.h"
#include "exprs/function/parse/variant_jsonb_parse.h"
-#include "storage/segment/variant/v2/variant_assembler_internal.h"
namespace doris::segment_v2::variant_v2 {
namespace {
@@ -72,8 +73,13 @@ PreparedMaterializedColumn prepare_materialized_column(const
DataTypePtr& type,
const DataTypePtr base = remove_nullable(type);
const PrimitiveType primitive = base->get_primitive_type();
- DORIS_CHECK(primitive == TYPE_ARRAY || primitive == TYPE_JSONB ||
- primitive == TYPE_DECIMAL256 ||
is_supported_variant_typed_identity(primitive));
+ // A legacy WAL can legitimately contain a type the assembler cannot
convert,
+ // such as the Variant element of an Array<Variant> root.
+ if (primitive != TYPE_ARRAY && primitive != TYPE_JSONB && primitive !=
TYPE_DECIMAL256 &&
+ !is_supported_variant_typed_identity(primitive)) {
+ throw Exception(Status::NotSupported("Cannot assemble Variant
materialized type {}",
+ base->get_name()));
+ }
DORIS_CHECK(base->check_column(*data).ok());
PreparedMaterializedColumn output;
diff --git a/be/src/storage/segment/variant/v2/variant_storage_cell.cpp
b/be/src/core/value/variant/variant_storage_cell.cpp
similarity index 99%
rename from be/src/storage/segment/variant/v2/variant_storage_cell.cpp
rename to be/src/core/value/variant/variant_storage_cell.cpp
index a451dfc4c92..6bd3ecb8bf9 100644
--- a/be/src/storage/segment/variant/v2/variant_storage_cell.cpp
+++ b/be/src/core/value/variant/variant_storage_cell.cpp
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-#include "storage/segment/variant/v2/variant_storage_cell.h"
+#include "core/value/variant/variant_storage_cell.h"
#include <array>
#include <cstring>
diff --git a/be/src/storage/segment/variant/v2/variant_storage_cell.h
b/be/src/core/value/variant/variant_storage_cell.h
similarity index 100%
rename from be/src/storage/segment/variant/v2/variant_storage_cell.h
rename to be/src/core/value/variant/variant_storage_cell.h
diff --git a/be/src/core/value/variant/variant_v1_wire_reader.cpp
b/be/src/core/value/variant/variant_v1_wire_reader.cpp
new file mode 100644
index 00000000000..c945eee4d23
--- /dev/null
+++ b/be/src/core/value/variant/variant_v1_wire_reader.cpp
@@ -0,0 +1,159 @@
+// 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.
+
+#include "core/value/variant/variant_v1_wire_reader.h"
+
+#include <gen_cpp/data.pb.h>
+
+#include <algorithm>
+#include <limits>
+#include <string_view>
+#include <utility>
+
+#include "common/exception.h"
+#include "core/assert_cast.h"
+#include "core/column/column_map.h"
+#include "core/column/column_nullable.h"
+#include "core/column/variant_v2/column_variant_v2.h"
+#include "core/custom_allocator.h"
+#include "core/data_type/data_type_factory.hpp"
+#include "core/data_type/data_type_map.h"
+#include "core/data_type/data_type_nullable.h"
+#include "core/data_type/data_type_string.h"
+#include "core/value/variant/variant_assembler.h"
+#include "exprs/function/parse/variant_string_parse.h"
+#include "util/json/path_in_data.h"
+#include "util/unaligned.h"
+
+namespace doris {
+
+const char* deserialize_variant_v1(const char* buf, MutableColumnPtr* column,
int be_exec_version,
+ bool with_doc_value) {
+ using segment_v2::variant_v2::StorageMapKind;
+ using segment_v2::variant_v2::VariantAssembler;
+ using segment_v2::variant_v2::VariantAssemblerOptions;
+ VariantAssemblerOptions options;
+ options.storage_map_kind = StorageMapKind::SPARSE;
+ DorisVector<MutableColumnPtr> materialized;
+ DorisVector<const IColumn*> materialized_views;
+
+ // V1 stores each materialized path as its protobuf metadata followed by
the
+ // ordinary serialization of that path's column.
+ const auto num_subcolumns = unaligned_load<uint32_t>(buf);
+ buf += sizeof(uint32_t);
+ for (uint32_t i = 0; i < num_subcolumns; ++i) {
+ const auto meta_size = unaligned_load<uint32_t>(buf);
+ buf += sizeof(uint32_t);
+ PColumnMeta meta;
+ if (meta_size > std::numeric_limits<int>::max() ||
+ !meta.ParseFromArray(buf, static_cast<int>(meta_size)) ||
!meta.has_type()) {
+ throw Exception(Status::Corruption("Invalid VARIANT V1 subcolumn
metadata"));
+ }
+ buf += meta_size;
+ auto type = DataTypeFactory::instance().create_data_type(meta);
+ auto values = type->create_column();
+ buf = type->deserialize(buf, &values, be_exec_version);
+ PathInData path;
+ if (meta.has_column_path()) {
+ path.from_protobuf(meta.column_path());
+ const auto& parts = path.get_parts();
+ if (std::ranges::any_of(parts,
+ [](const PathInData::Part& part) {
+ return part.key.find('.') !=
std::string_view::npos;
+ }) &&
+ std::ranges::all_of(parts, [](const PathInData::Part& part) {
+ return part.get_array_depth() == 0;
+ })) {
+ // V1 splits the raw dotted name when rendering materialized
paths.
+ // Match that behavior even when the wire kept a dot within
one part.
+ path = PathInData(path.get_path(), path.get_is_typed());
+ }
+ } else if (!meta.name().empty()) {
+ // Older blocks can record the path in the name only.
+ path = PathInData(meta.name());
+ }
+ options.materialized_paths.push_back({path, std::move(type)});
+ materialized_views.push_back(values.get());
+ materialized.push_back(std::move(values));
+ }
+
+ const auto rows = unaligned_load<uint32_t>(buf);
+ buf += sizeof(uint32_t);
+ for (const auto* values : materialized_views) {
+ if (values->size() != rows) {
+ throw Exception(Status::Corruption("VARIANT V1 subcolumn has {}
rows, expected {}",
+ values->size(), rows));
+ }
+ }
+
+ static const auto string_type = std::make_shared<DataTypeString>();
+ static const DataTypeMap binary_map_type(string_type, string_type);
+ auto sparse = binary_map_type.create_column();
+ buf = binary_map_type.deserialize(buf, &sparse, be_exec_version);
+ MutableColumnPtr doc;
+ // The pre-doc layout ends right after the sparse map. In a block with
+ // multiple columns, the next bytes then belong to the following column.
+ if (with_doc_value) {
+ doc = binary_map_type.create_column();
+ buf = binary_map_type.deserialize(buf, &doc, be_exec_version);
+ }
+ if (sparse->size() != rows || (doc && doc->size() != rows)) {
+ throw Exception(Status::Corruption("VARIANT V1 map row count does not
match {}", rows));
+ }
+
+ const auto* sparse_map = assert_cast<const ColumnMap*>(sparse.get());
+ const auto* doc_map = doc ? assert_cast<const ColumnMap*>(doc.get()) :
nullptr;
+ // V1 can defer JSON parsing in a single String root. Decide from the
+ // original wire type and the entire column, before assembling typed
values.
+ if (num_subcolumns == 1 && options.materialized_paths.front().path.empty()
&&
+
remove_nullable(options.materialized_paths.front().type)->get_primitive_type()
==
+ TYPE_STRING &&
+ sparse_map->get_keys().empty() && (doc_map == nullptr ||
doc_map->get_keys().empty())) {
+ auto json_options = JsonToVariantOptions::current_config();
+ json_options.throw_on_invalid_json = false;
+ JsonStringToVariantEncoder encoder(json_options);
+ const auto& root = *materialized_views.front();
+ const StringRef json_null("null", 4);
+ for (size_t row = 0; row < rows; ++row) {
+ const auto json = root.is_null_at(row) ? json_null :
root.get_data_at(row);
+ // The V1 parser treated zero-length input as an empty object.
+ encoder.add_json(json.size == 0 ? StringRef("{}", 2) : json);
+ }
+ auto result = ColumnVariantV2::create();
+ result->insert_encoded_batch(encoder.finish_batch());
+ *column = std::move(result);
+ return buf;
+ }
+
+ // V1 blocks and segments use the same binary cells.
+ auto assembler = VariantAssembler::create(std::move(options));
+ if (!assembler) {
+ throw Exception(assembler.error());
+ }
+ ColumnNullable::MutablePtr assembled;
+ THROW_IF_ERROR((*assembler)
+ ->assemble({.num_rows = rows,
+ .materialized_columns =
materialized_views,
+ .storage_map = sparse_map,
+ .legacy_doc_map = doc_map},
+ &assembled));
+ // DataTypeNullable reads the original outer null map independently.
+ *column = assembled->get_nested_column_ptr();
+ return buf;
+}
+
+} // namespace doris
diff --git a/regression-test/suites/insert_p0/test_group_commit_variant.groovy
b/be/src/core/value/variant/variant_v1_wire_reader.h
similarity index 52%
copy from regression-test/suites/insert_p0/test_group_commit_variant.groovy
copy to be/src/core/value/variant/variant_v1_wire_reader.h
index 15d8304bd4f..2fe043023ee 100644
--- a/regression-test/suites/insert_p0/test_group_commit_variant.groovy
+++ b/be/src/core/value/variant/variant_v1_wire_reader.h
@@ -15,29 +15,15 @@
// specific language governing permissions and limitations
// under the License.
-suite("test_group_commit_variant") {
+#pragma once
- sql "set group_commit=async_mode"
+#include "core/column/column.h"
- def testTable = "test_group_commit_variant"
+namespace doris {
- sql """
- CREATE TABLE IF NOT EXISTS ${testTable} (
- k bigint,
- var variant
- )
- UNIQUE KEY(`k`)
- DISTRIBUTED BY HASH (`k`) BUCKETS 5
- properties("replication_num" = "1",
- "disable_auto_compaction" = "false");
- """
-
- try {
- sql "insert into ${testTable} (k) values (1),(2);"
- sql "insert into ${testTable} (k) values (3),(4);"
- } catch (Exception e) {
- // should not throw exception
- logger.info(e.getMessage())
- assertTrue(False)
- }
-}
+// Reads the V1 block layout and returns the cursor just past this column.
+// The caller reads the surrounding column's nullable/const framing.
+const char* deserialize_variant_v1(const char* buf, MutableColumnPtr* column,
int be_exec_version,
+ bool with_doc_value);
+
+} // namespace doris
diff --git a/be/src/storage/segment/variant/binary_column_extract_iterator.cpp
b/be/src/storage/segment/variant/binary_column_extract_iterator.cpp
index d9764f0e315..b677b57d768 100644
--- a/be/src/storage/segment/variant/binary_column_extract_iterator.cpp
+++ b/be/src/storage/segment/variant/binary_column_extract_iterator.cpp
@@ -21,8 +21,8 @@
#include "core/column/column_string.h"
#include "core/column/variant_column_utils.h"
#include "core/custom_allocator.h"
+#include "core/value/variant/variant_storage_cell.h"
#include "storage/segment/variant/v2/variant_column_reader.h"
-#include "storage/segment/variant/v2/variant_storage_cell.h"
namespace doris::segment_v2 {
diff --git a/be/src/storage/segment/variant/binary_column_reader.cpp
b/be/src/storage/segment/variant/binary_column_reader.cpp
index ee31bef634f..8bf4da8d97a 100644
--- a/be/src/storage/segment/variant/binary_column_reader.cpp
+++ b/be/src/storage/segment/variant/binary_column_reader.cpp
@@ -20,9 +20,9 @@
#include "core/assert_cast.h"
#include "core/column/column_map.h"
#include "core/string_ref.h"
+#include "core/value/variant/variant_assembler.h"
#include "exec/common/variant_util.h"
#include "storage/segment/segment.h"
-#include "storage/segment/variant/v2/variant_assembler.h"
namespace doris::segment_v2 {
diff --git a/be/src/storage/segment/variant/hierarchical_data_iterator.cpp
b/be/src/storage/segment/variant/hierarchical_data_iterator.cpp
index a3188b18feb..d8d78f09a57 100644
--- a/be/src/storage/segment/variant/hierarchical_data_iterator.cpp
+++ b/be/src/storage/segment/variant/hierarchical_data_iterator.cpp
@@ -29,11 +29,11 @@
#include "core/data_type/data_type_factory.hpp"
#include "core/data_type/data_type_nullable.h"
#include "core/data_type/define_primitive_type.h"
+#include "core/value/variant/variant_assembler.h"
#include "io/io_common.h"
#include "storage/segment/column_reader.h"
#include "storage/segment/column_reader_cache.h"
#include "storage/segment/variant/nested_group_path.h"
-#include "storage/segment/variant/v2/variant_assembler.h"
#include "storage/segment/variant/v2/variant_column_reader.h"
#include "util/json/path_in_data.h"
diff --git a/be/src/storage/segment/variant/v2/variant_column_writer.cpp
b/be/src/storage/segment/variant/v2/variant_column_writer.cpp
index fbfc9dff76c..6704ba1ed60 100644
--- a/be/src/storage/segment/variant/v2/variant_column_writer.cpp
+++ b/be/src/storage/segment/variant/v2/variant_column_writer.cpp
@@ -30,12 +30,12 @@
#include "core/column/column_string.h"
#include "core/column/column_vector.h"
#include "core/column/variant_v2/column_variant_v2.h"
+#include "core/value/variant/variant_assembler.h"
#include "exec/common/variant_util.h"
#include "exprs/function/parse/variant_jsonb_parse.h"
#include "io/fs/file_writer.h"
#include "storage/index/index_file_writer.h"
#include "storage/rowset/rowset_writer_context.h"
-#include "storage/segment/variant/v2/variant_assembler.h"
#include "storage/segment/variant/v2/variant_shredder.h"
#include "storage/segment/variant/v2/variant_values_index_writer.h"
#include "storage/segment/variant/variant_column_writer_impl.h"
diff --git
a/be/src/storage/segment/variant/variant_doc_snpashot_compact_iterator.h
b/be/src/storage/segment/variant/variant_doc_snpashot_compact_iterator.h
index c21a1c1e530..0f31a611edd 100644
--- a/be/src/storage/segment/variant/variant_doc_snpashot_compact_iterator.h
+++ b/be/src/storage/segment/variant/variant_doc_snpashot_compact_iterator.h
@@ -17,9 +17,9 @@
#include "core/column/column_map.h"
#include "core/column/column_nullable.h"
+#include "core/value/variant/variant_assembler.h"
#include "exec/common/variant_util.h"
#include "storage/segment/column_reader.h"
-#include "storage/segment/variant/v2/variant_assembler.h"
#include "storage/segment/variant/v2/variant_column_reader.h"
namespace doris::segment_v2 {
diff --git a/be/test/core/block/block_variant_wire_format_test.cpp
b/be/test/core/block/block_variant_wire_format_test.cpp
index 88251c768d9..9c09176da17 100644
--- a/be/test/core/block/block_variant_wire_format_test.cpp
+++ b/be/test/core/block/block_variant_wire_format_test.cpp
@@ -18,21 +18,30 @@
#include <gen_cpp/data.pb.h>
#include <gtest/gtest.h>
+#include <array>
#include <memory>
#include <string>
+#include <utility>
#include "agent/be_exec_version_manager.h"
#include "core/block/block.h"
#include "core/column/column_nullable.h"
+#include "core/column/column_string.h"
+#include "core/column/column_struct.h"
#include "core/column/column_vector.h"
#include "core/column/variant_v2/column_variant_v2.h"
#include "core/data_type/data_type_array.h"
+#include "core/data_type/data_type_jsonb.h"
#include "core/data_type/data_type_map.h"
#include "core/data_type/data_type_nullable.h"
#include "core/data_type/data_type_number.h"
#include "core/data_type/data_type_string.h"
#include "core/data_type/data_type_struct.h"
#include "core/data_type/data_type_variant_v2.h"
+#include "core/value/variant/variant_parquet_encoding.h"
+#include "testutil/variant_v1_wire_test_util.h"
+#include "util/jsonb_writer.h"
+#include "util/unaligned.h"
namespace doris {
namespace {
@@ -69,74 +78,164 @@ Status deserialize_block(const PBlock& wire, Block& block)
{
return block.deserialize(wire, &uncompressed_bytes, &decompression_time);
}
-void expect_unsupported_variant(const PBlock& wire, size_t preceding_columns =
0) {
- Block decoded;
- const Status status = deserialize_block(wire, decoded);
- EXPECT_TRUE(status.is<ErrorCode::NOT_IMPLEMENTED_ERROR>()) << status;
- EXPECT_NE(status.to_string().find("Unsupported VARIANT block format"),
std::string::npos)
- << status;
- EXPECT_EQ(decoded.columns(), preceding_columns);
+Status decode_as_variant_v2(const PBlock& wire, Block& block) {
+ size_t bytes = 0;
+ int64_t time = 0;
+ return block.deserialize(wire, &bytes, &time);
}
-} // namespace
+ColumnPtr strings(std::initializer_list<std::string_view> values) {
+ auto column = ColumnString::create();
+ for (const auto value : values) {
+ column->insert_data(value.data(), value.size());
+ }
+ return column->get_ptr();
+}
-TEST(BlockVariantWireFormatTest, RejectsLegacyVariantMetadata) {
- for (bool nullable : {false, true}) {
- const Block source = variant_block(nullable);
- const PBlock serialized = serialize_block(source,
segment_v2::NO_COMPRESSION);
- // Keep a valid payload so the unfixed decoder demonstrates that it
ignores the format
- // marker, without relying on an out-of-bounds read to reproduce the
missing rejection.
- for (int legacy_format = 0; legacy_format < 3; ++legacy_format) {
- PBlock wire = serialized;
- auto* meta = wire.mutable_column_metas(0);
- meta->clear_variant_is_v2();
- if (legacy_format == 0) {
- meta->clear_variant_enable_doc_mode();
- } else {
- meta->set_variant_is_v2(false);
- meta->set_variant_enable_doc_mode(legacy_format == 2);
- }
- expect_unsupported_variant(wire);
- }
+const ColumnVariantV2& variant_at(const Block& block) {
+ const auto& column = *block.get_by_position(1).column;
+ const auto* nullable = check_and_get_column<ColumnNullable>(column);
+ return assert_cast<const ColumnVariantV2&>(nullable ?
nullable->get_nested_column() : column);
+}
+
+void expect_legacy_doc_map(bool with_tail) {
+ constexpr int version = 8;
+ constexpr uint32_t rows = 1;
+ const auto sparse = test::legacy_variant_wire_map(rows);
+ const auto doc = test::legacy_variant_wire_map(rows, "doc", 20);
+ const auto body = test::legacy_variant_wire_body(version, rows, *sparse,
doc.get());
+
+ PBlock wire;
+ const int variant_position = with_tail ? 1 : 0;
+ if (with_tail) {
+ wire = test::legacy_variant_wire_with_sentinels(body, rows, true, {},
version);
+ } else {
+ wire.set_be_exec_version(version);
+ wire.add_column_metas()->set_type(PGenericType::VARIANT);
+ wire.set_column_values(body);
}
+
wire.mutable_column_metas(variant_position)->set_variant_enable_doc_mode(false);
+
+ const auto check_decoded = [&](const Block& block) {
+ ASSERT_EQ(block.columns(), wire.column_metas_size());
+ ASSERT_EQ(block.rows(), rows);
+ const auto& variant = block.get_by_position(variant_position);
+ EXPECT_EQ(variant.type->to_string(*variant.column, 0),
R"({"doc":20})");
+ if (with_tail) {
+ EXPECT_EQ(block.get_by_position(0).column->get_int(0), 100);
+ const auto& tail = block.get_by_position(2).column;
+ ASSERT_EQ(tail->size(), rows);
+ EXPECT_EQ(tail->get_int(0), 200);
+ }
+ };
+
+ Block block;
+ size_t bytes = 0;
+ int64_t time = 0;
+ const auto status = block.deserialize(wire, &bytes, &time);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_NO_FATAL_FAILURE(check_decoded(block));
}
-TEST(BlockVariantWireFormatTest, RejectsLegacyVariantAfterPrecedingColumn) {
- auto numbers = ColumnInt32::create();
- numbers->insert_value(1);
- numbers->insert_value(2);
- Block source = variant_block(false);
- source.insert(0, {std::move(numbers), std::make_shared<DataTypeInt32>(),
"n"});
- for (auto compression : {segment_v2::NO_COMPRESSION, segment_v2::SNAPPY}) {
- PBlock wire = serialize_block(source, compression);
- wire.mutable_column_metas(1)->clear_variant_is_v2();
- expect_unsupported_variant(wire, 1);
+void expect_dotted_payload(const Block& block, std::string_view expected) {
+ ASSERT_EQ(block.columns(), 3);
+ ASSERT_EQ(block.rows(), 1);
+ EXPECT_EQ(block.get_by_position(0).column->get_int(0), 100);
+ EXPECT_EQ(block.get_by_position(2).column->get_int(0), 200);
+ const auto& payload = block.get_by_position(1);
+ EXPECT_EQ(payload.type->to_string(*payload.column, 0), expected);
+}
+
+void expect_legacy_dotted_wire(bool shared_prefix, std::string_view expected) {
+ for (bool with_doc : {false, true}) {
+ SCOPED_TRACE(with_doc);
+ const auto wire = test::legacy_variant_dotted_path_block(with_doc,
shared_prefix);
+
+ Block decoded;
+ const auto status = decode_as_variant_v2(wire, decoded);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_NO_FATAL_FAILURE(expect_dotted_payload(decoded, expected));
+
+ const auto v2_wire = serialize_block(decoded,
segment_v2::NO_COMPRESSION);
+ ASSERT_TRUE(v2_wire.column_metas(1).variant_is_v2());
+ Block round_trip;
+ size_t bytes = 0;
+ int64_t time = 0;
+ const auto round_trip_status = round_trip.deserialize(v2_wire, &bytes,
&time);
+ ASSERT_TRUE(round_trip_status.ok()) << round_trip_status;
+ ASSERT_NO_FATAL_FAILURE(expect_dotted_payload(round_trip, expected));
}
}
-TEST(BlockVariantWireFormatTest, RejectsLegacyVariantInsideComplexTypes) {
- const DataTypePtr variant = std::make_shared<DataTypeVariantV2>();
- const DataTypePtr array =
std::make_shared<DataTypeArray>(make_nullable(variant));
- const DataTypes types = {
- std::make_shared<DataTypeArray>(array),
- std::make_shared<DataTypeMap>(std::make_shared<DataTypeString>(),
array),
- std::make_shared<DataTypeStruct>(DataTypes {array}, Strings
{"v"})};
- for (const auto& type : types) {
- auto column = type->create_column();
- column->insert_default();
- Block source({{std::move(column), type, "nested_variant"}});
- for (auto compression : {segment_v2::NO_COMPRESSION,
segment_v2::SNAPPY}) {
- PBlock wire = serialize_block(source, compression);
- auto* meta = wire.mutable_column_metas(0);
- if (meta->type() == PGenericType::MAP) {
- meta = meta->mutable_children(1);
- } else {
- meta = meta->mutable_children(0);
- }
- meta->mutable_children(0)->clear_variant_is_v2();
- expect_unsupported_variant(wire);
+using LegacyIntEntry = std::pair<std::string_view, int32_t>;
+
+ColumnMap::MutablePtr legacy_int_map(
+ std::initializer_list<std::initializer_list<LegacyIntEntry>> rows) {
+ auto keys = ColumnString::create();
+ auto values = ColumnString::create();
+ auto offsets = ColumnArray::ColumnOffsets::create();
+ for (const auto& row : rows) {
+ for (const auto& [key, value] : row) {
+ keys->insert_data(key.data(), key.size());
+ char cell[1 + sizeof(value)]
{static_cast<char>(FieldType::OLAP_FIELD_TYPE_INT)};
+ unaligned_store<int32_t>(cell + 1, value);
+ values->insert_data(cell, sizeof(cell));
}
+ offsets->insert_value(keys->size());
}
+ return ColumnMap::create(std::move(keys), std::move(values),
std::move(offsets));
+}
+
+} // namespace
+
+TEST(BlockVariantWireFormatTest, ReadsPreDocValueVariantInsideStruct) {
+ constexpr int version = 8;
+ auto variant = std::make_shared<DataTypeVariantV2>();
+ auto number = std::make_shared<DataTypeInt64>();
+ const DataTypeStruct type(DataTypes {variant, number}, Strings {"v",
"tail"});
+ auto frame = type.create_column();
+ frame->insert_many_defaults(2);
+ auto keys = std::make_shared<DataTypeString>();
+ const DataTypeMap map_type(keys, keys);
+ auto sparse = map_type.create_column();
+ sparse->insert_many_defaults(2);
+ auto tail = ColumnInt64::create();
+ tail->insert_value(42);
+ tail->insert_value(7);
+
+ // A 4.0 Variant with no subcolumns carries the row count and sparse map.
+ // The next byte starts the struct's BIGINT field.
+ std::string bytes(sizeof(bool) + 2 * sizeof(size_t) + 2 * sizeof(uint32_t)
+
+
map_type.get_uncompressed_serialized_bytes(*sparse, version) +
+ number->get_uncompressed_serialized_bytes(*tail,
version),
+ '\0');
+ const IColumn* struct_rows = frame.get();
+ size_t saved_rows = 0;
+ char* cursor = serialize_const_flag_and_row_num(&struct_rows,
bytes.data(), &saved_rows);
+ unaligned_store<uint32_t>(cursor, 0);
+ cursor += sizeof(uint32_t);
+ unaligned_store<uint32_t>(cursor, 2);
+ cursor += sizeof(uint32_t);
+ cursor = map_type.serialize(*sparse, cursor, version);
+ cursor = number->serialize(*tail, cursor, version);
+
+ PBlock wire;
+ wire.set_be_exec_version(version);
+ type.to_pb_column_meta(wire.add_column_metas());
+ auto* legacy_meta = wire.mutable_column_metas(0)->mutable_children(0);
+ legacy_meta->clear_variant_enable_doc_mode();
+ legacy_meta->clear_variant_is_v2();
+ wire.set_column_values(bytes.data(), cursor - bytes.data());
+
+ Block result;
+ const auto status = deserialize_block(wire, result);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_EQ(result.rows(), 2);
+ const auto& decoded = assert_cast<const
ColumnStruct&>(*result.get_by_position(0).column);
+ EXPECT_EQ(variant->to_string(decoded.get_column(0), 0), "{}");
+ EXPECT_EQ(variant->to_string(decoded.get_column(0), 1), "{}");
+ EXPECT_EQ(number->to_string(decoded.get_column(1), 0), "42");
+ EXPECT_EQ(number->to_string(decoded.get_column(1), 1), "7");
}
TEST(BlockVariantWireFormatTest, RoundTripsVariantV2) {
@@ -179,4 +278,315 @@ TEST(BlockVariantWireFormatTest,
RoundTripsVariantV2InsideComplexTypes) {
}
}
+TEST(BlockVariantWireFormatTest,
ParsesOnlyLegacyStringRootAndPreservesFraming) {
+ const auto string_type = std::make_shared<DataTypeString>();
+ auto values = strings({R"({"a":1})", "[2,3]", "123", "true", R"("123")",
"null", "",
+ "invalid JSON", R"({"hidden":true})", "false",
R"("")"});
+ auto root_nulls = ColumnUInt8::create();
+ root_nulls->insert_many_defaults(values->size());
+ root_nulls->get_data()[8] = 1;
+ const ColumnPtr root = ColumnNullable::create(values,
std::move(root_nulls));
+ const auto map = test::legacy_variant_wire_map(root->size());
+ std::string outer_nulls(root->size(), '\0');
+ outer_nulls[9] = 1;
+ for (bool with_doc : {false, true}) {
+ SCOPED_TRACE(with_doc);
+ constexpr int version = 13;
+ const auto body = test::legacy_variant_wire_body(
+ version, root->size(), *map, with_doc ? map.get() : nullptr,
+ {{PathInData(), make_nullable(string_type), root}});
+ const auto wire =
+ test::legacy_variant_wire_with_sentinels(body, root->size(),
with_doc, outer_nulls);
+ Block block;
+ const auto status = decode_as_variant_v2(wire, block);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_EQ(block.rows(), root->size());
+ const auto& column = *block.get_by_position(1).column;
+ const auto view = variant_at(block).read_view();
+ for (size_t row = 0; row < block.rows(); ++row) {
+ EXPECT_EQ(block.get_by_position(0).column->get_int(row), 100 +
row);
+ EXPECT_EQ(block.get_by_position(2).column->get_int(row), 200 +
row);
+ EXPECT_EQ(column.is_null_at(row), row == 9);
+ }
+ VariantRef field;
+ ASSERT_TRUE(view.value_at(0).object_find(StringRef("a", 1), &field));
+ EXPECT_EQ(field.get_int(), 1);
+ ASSERT_EQ(view.value_at(1).basic_type(), VariantBasicType::ARRAY);
+ EXPECT_EQ(view.value_at(1).array_at(1).get_int(), 3);
+ EXPECT_EQ(view.value_at(2).get_int(), 123);
+ EXPECT_EQ(view.value_at(3).primitive_id(),
VariantPrimitiveId::TRUE_VALUE);
+ EXPECT_EQ(view.value_at(4).get_string().to_string_view(), "123");
+ EXPECT_TRUE(view.value_at(5).is_null());
+ ASSERT_EQ(view.value_at(6).basic_type(), VariantBasicType::OBJECT);
+ EXPECT_EQ(view.value_at(6).num_elements(), 0);
+ EXPECT_TRUE(view.value_at(10).get_string().empty());
+ EXPECT_EQ(view.value_at(7).get_string().to_string_view(), "invalid
JSON");
+ EXPECT_TRUE(view.value_at(8).is_null());
+
+ for (int round = 0; round < 2; ++round) {
+ auto v2_wire = serialize_block(block, segment_v2::NO_COMPRESSION);
+ EXPECT_TRUE(v2_wire.column_metas(1).variant_is_v2());
+ Block decoded;
+ ASSERT_TRUE(decode_as_variant_v2(v2_wire, decoded).ok());
+
EXPECT_EQ(variant_at(decoded).read_view().value_at(4).get_string().to_string_view(),
+ "123");
+ block.swap(decoded);
+ }
+ }
+}
+
+TEST(BlockVariantWireFormatTest, RejectsRepeatedLegacyObjectKeys) {
+ constexpr int version = 13;
+ const auto values = strings({R"({"ok":1})",
R"({"a":{"b":5},"a":{"c":6}})"});
+ const auto sparse = test::legacy_variant_wire_map(values->size());
+ const auto body = test::legacy_variant_wire_body(
+ version, values->size(), *sparse, nullptr,
+ {{PathInData(), std::make_shared<DataTypeString>(), values}});
+ Block decoded;
+ const auto status = decode_as_variant_v2(
+ test::legacy_variant_wire_with_sentinels(body, values->size(),
false), decoded);
+ ASSERT_TRUE(status.is<ErrorCode::INVALID_ARGUMENT>()) << status;
+ EXPECT_NE(status.to_string().find("Duplicate Variant object key"),
std::string::npos);
+}
+
+TEST(BlockVariantWireFormatTest, RejectsUnsupportedLegacyTypedRoots) {
+ constexpr int version = 13;
+ const auto int_type = std::make_shared<DataTypeInt32>();
+ const std::array<DataTypePtr, 3> root_types {
+
std::make_shared<DataTypeArray>(std::make_shared<DataTypeVariantV2>()),
+ std::make_shared<DataTypeMap>(std::make_shared<DataTypeString>(),
int_type),
+ std::make_shared<DataTypeStruct>(DataTypes {int_type}, Strings
{"a"})};
+ const auto sparse = test::legacy_variant_wire_map(1);
+ for (const auto& type : root_types) {
+ SCOPED_TRACE(type->get_name());
+ auto values = type->create_column();
+ values->insert_default();
+ const auto body = test::legacy_variant_wire_body(version, 1, *sparse,
nullptr,
+ {{PathInData(), type,
std::move(values)}});
+ Block decoded;
+ const auto status = decode_as_variant_v2(
+ test::legacy_variant_wire_with_sentinels(body, 1, false),
decoded);
+ EXPECT_TRUE(status.is<ErrorCode::NOT_IMPLEMENTED_ERROR>()) << status;
+ }
+}
+
+TEST(BlockVariantWireFormatTest, LegacyMaterializedPathDepthBoundary) {
+ constexpr int version = 13;
+ const auto sparse = test::legacy_variant_wire_map(1);
+ const ColumnPtr values = ColumnInt32::create(1, 7);
+ const auto type = std::make_shared<DataTypeInt32>();
+ std::string path = "a";
+ for (uint32_t depth = 1; depth < VARIANT_MAX_NESTING_DEPTH; ++depth) {
+ path += ".a";
+ }
+ for (bool too_deep : {false, true}) {
+ SCOPED_TRACE(too_deep);
+ const auto body = test::legacy_variant_wire_body(
+ version, 1, *sparse, nullptr,
+ {{PathInData(too_deep ? path + ".a" : path), type, values}});
+ Block decoded;
+ const auto status = decode_as_variant_v2(
+ test::legacy_variant_wire_with_sentinels(body, 1, false),
decoded);
+ if (too_deep) {
+ EXPECT_TRUE(status.is<ErrorCode::NOT_IMPLEMENTED_ERROR>()) <<
status;
+ } else {
+ ASSERT_TRUE(status.ok()) << status;
+ EXPECT_EQ(decoded.get_by_position(0).column->get_int(0), 100);
+ EXPECT_EQ(decoded.get_by_position(2).column->get_int(0), 200);
+ auto value = variant_at(decoded).read_view().value_at(0);
+ for (uint32_t depth = 0; depth < VARIANT_MAX_NESTING_DEPTH;
++depth) {
+ VariantRef child;
+ ASSERT_TRUE(value.object_find(StringRef("a", 1), &child));
+ value = child;
+ }
+ EXPECT_EQ(value.get_int(), 7);
+ }
+ }
+}
+
+TEST(BlockVariantWireFormatTest, KeepsTypedJsonbAndNamedLegacyStrings) {
+ constexpr int version = 13;
+ const auto map = test::legacy_variant_wire_map(1);
+ const auto check = [&](std::initializer_list<test::LegacyVariantWirePath>
paths,
+ const char* key) {
+ const auto body = test::legacy_variant_wire_body(version, 1, *map,
nullptr, paths);
+ Block decoded;
+
ASSERT_TRUE(decode_as_variant_v2(test::legacy_variant_wire_with_sentinels(body,
1, false),
+ decoded)
+ .ok());
+ const auto view = variant_at(decoded).read_view();
+ auto value = view.value_at(0);
+ if (key != nullptr) {
+ VariantRef field;
+ ASSERT_TRUE(value.object_find(StringRef(key, std::strlen(key)),
&field));
+ value = field;
+ }
+ EXPECT_EQ(value.get_string().to_string_view(), "123");
+ };
+
+ const auto string_type = std::make_shared<DataTypeString>();
+ const auto text = strings({"123"});
+ check({{PathInData("key"), string_type, text}}, "key");
+ check({{PathInData(PathInData::Parts {{"", false, 0}}), string_type,
text}}, "");
+ check({{PathInData(), string_type, text}, {PathInData("key"), string_type,
text}}, "key");
+
+ JsonbWriter writer;
+ ASSERT_TRUE(writer.writeStartString());
+ ASSERT_TRUE(writer.writeString("123", 3));
+ ASSERT_TRUE(writer.writeEndString());
+ const std::string_view jsonb(writer.getOutput()->getBuffer(),
writer.getOutput()->getSize());
+ check({{PathInData(), std::make_shared<DataTypeJsonb>(),
strings({jsonb})}}, nullptr);
+}
+
+TEST(BlockVariantWireFormatTest,
SparseAndDocEntriesDisableRootParsingForWholeColumn) {
+ constexpr int version = 13;
+ const auto string_type = std::make_shared<DataTypeString>();
+ const auto text = strings({"123", "true"});
+ const auto empty = test::legacy_variant_wire_map(2);
+ const auto sparse = test::legacy_variant_wire_map(2, "s", 7);
+ const auto doc = test::legacy_variant_wire_map(2, "d", 9);
+ for (const ColumnMap* doc_map : std::array<const ColumnMap*, 2> {nullptr,
doc.get()}) {
+ const auto body =
+ test::legacy_variant_wire_body(version, 2, doc_map != nullptr
? *empty : *sparse,
+ doc_map, {{PathInData(),
string_type, text}});
+ Block decoded;
+ ASSERT_TRUE(decode_as_variant_v2(
+ test::legacy_variant_wire_with_sentinels(body, 2,
doc_map != nullptr),
+ decoded)
+ .ok());
+ const auto view = variant_at(decoded).read_view();
+ VariantRef field;
+ const auto key = doc_map != nullptr ? StringRef("d", 1) :
StringRef("s", 1);
+ ASSERT_TRUE(view.value_at(0).object_find(key, &field));
+ EXPECT_EQ(field.get_int(), doc_map != nullptr ? 9 : 7);
+ EXPECT_EQ(view.value_at(1).get_string().to_string_view(), "true");
+ }
+}
+
+TEST(BlockVariantWireFormatTest, ReadsMarkedLegacyDocMap) {
+ for (bool with_tail : {false, true}) {
+ SCOPED_TRACE(with_tail);
+ ASSERT_NO_FATAL_FAILURE(expect_legacy_doc_map(with_tail));
+ }
+}
+
+TEST(BlockVariantWireFormatTest, ReadsLegacyLiteralDottedPath) {
+ expect_legacy_dotted_wire(false, R"({"a":{"b":7}})");
+}
+
+TEST(BlockVariantWireFormatTest, ReadsLegacyDottedPathsWithSharedPrefix) {
+ expect_legacy_dotted_wire(true, R"({"a":{"b":1,"c":2}})");
+}
+
+TEST(BlockVariantWireFormatTest, ReadsSortedLegacyDocRow) {
+ const auto doc = legacy_int_map({{{"a.b", 1}, {"a.c", 2}, {"z", 3}}});
+ const auto sparse = test::legacy_variant_wire_map(1);
+ const auto body = test::legacy_variant_wire_body(8, 1, *sparse, doc.get());
+ Block decoded;
+ const auto status = decode_as_variant_v2(
+ test::legacy_variant_wire_with_sentinels(body, 1, true, {}, 8),
decoded);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_NO_FATAL_FAILURE(expect_dotted_payload(decoded,
R"({"a":{"b":1,"c":2},"z":3})"));
+}
+
+TEST(BlockVariantWireFormatTest,
ReadsLegacyMaterializedPathsWithSameRawNameInSeparateRows) {
+ const auto type = make_nullable(std::make_shared<DataTypeInt32>());
+ const auto path_values = [](int value, bool first_row) {
+ auto nulls = ColumnUInt8::create();
+ nulls->insert_value(!first_row);
+ nulls->insert_value(first_row);
+ return ColumnNullable::create(ColumnInt32::create(2, value),
std::move(nulls));
+ };
+ const auto empty = test::legacy_variant_wire_map(2);
+ const auto body = test::legacy_variant_wire_body(
+ 8, 2, *empty, empty.get(),
+ {{PathInData(PathInData::Parts {{"a.b", false, 0}}), type,
path_values(1, true)},
+ {PathInData("a.b"), type, path_values(2, false)}});
+ Block decoded;
+ const auto status = decode_as_variant_v2(
+ test::legacy_variant_wire_with_sentinels(body, 2, true, {}, 8),
decoded);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_EQ(decoded.rows(), 2);
+ const auto& value = decoded.get_by_position(1);
+ EXPECT_EQ(value.type->to_string(*value.column, 0), R"({"a":{"b":1}})");
+ EXPECT_EQ(value.type->to_string(*value.column, 1), R"({"a":{"b":2}})");
+}
+
+TEST(BlockVariantWireFormatTest,
ReadsDottedPathsWithDocAndSparseRowsInOneBlock) {
+ constexpr int version = 8;
+ constexpr uint32_t rows = 2;
+ const auto sparse = legacy_int_map({{{"a.c", 10}, {"s", 11}}, {{"a.c",
20}, {"s", 21}}});
+ const auto doc = legacy_int_map({{{"a.b", 40}, {"a.c", 50}}, {}});
+ auto materialized = ColumnInt32::create();
+ materialized->insert_value(1);
+ materialized->insert_value(2);
+ // The V2 decoder supports this mixed layout. V1 ColumnVariant rejects doc
entries
+ // alongside materialized non-root subcolumns, so construct the wire body
directly.
+ const auto body = test::legacy_variant_wire_body(
+ version, rows, *sparse, doc.get(),
+ {{PathInData(PathInData::Parts {{"a.b", false, 0}}),
std::make_shared<DataTypeInt32>(),
+ std::move(materialized)}});
+ const auto wire = test::legacy_variant_wire_with_sentinels(body, rows,
true, {}, version);
+ const auto check = [&](const Block& block) {
+ ASSERT_EQ(block.columns(), 3);
+ ASSERT_EQ(block.rows(), rows);
+ const auto& value = block.get_by_position(1);
+ EXPECT_EQ(value.type->to_string(*value.column, 0),
R"({"a":{"b":40,"c":50}})");
+ EXPECT_EQ(value.type->to_string(*value.column, 1),
R"({"a":{"b":2,"c":20},"s":21})");
+ for (uint32_t row = 0; row < rows; ++row) {
+ EXPECT_EQ(block.get_by_position(0).column->get_int(row), 100 +
row);
+ EXPECT_EQ(block.get_by_position(2).column->get_int(row), 200 +
row);
+ }
+ };
+
+ Block decoded;
+ const auto status = decode_as_variant_v2(wire, decoded);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_NO_FATAL_FAILURE(check(decoded));
+
+ const auto v2_wire = serialize_block(decoded, segment_v2::NO_COMPRESSION);
+ ASSERT_TRUE(v2_wire.column_metas(1).variant_is_v2());
+ Block round_trip;
+ const auto round_trip_status = deserialize_block(v2_wire, round_trip);
+ ASSERT_TRUE(round_trip_status.ok()) << round_trip_status;
+ ASSERT_NO_FATAL_FAILURE(check(round_trip));
+}
+
+TEST(BlockVariantWireFormatTest, RejectsMismatchedLegacyRowCounts) {
+ constexpr int version = 13;
+ constexpr uint32_t rows = 2;
+ for (int bad_column = 0; bad_column < 3; ++bad_column) {
+ SCOPED_TRACE(bad_column);
+ const ColumnPtr values = ColumnInt32::create(bad_column == 0 ? 1 :
rows, 7);
+ const auto sparse = test::legacy_variant_wire_map(bad_column == 1 ? 1
: rows);
+ const auto doc = test::legacy_variant_wire_map(bad_column == 2 ? 1 :
rows);
+ const auto body = test::legacy_variant_wire_body(
+ version, rows, *sparse, doc.get(),
+ {{PathInData("a"), std::make_shared<DataTypeInt32>(),
values}});
+ Block decoded;
+ const auto status = decode_as_variant_v2(
+ test::legacy_variant_wire_with_sentinels(body, rows, true, {},
version), decoded);
+ EXPECT_TRUE(status.is<ErrorCode::CORRUPTION>()) << status;
+ }
+}
+
+TEST(BlockVariantWireFormatTest, DoesNotParseNativeVariantV2Strings) {
+ const auto text = strings({"123", "true", "null", R"({"a":1})"});
+ auto values =
+ ColumnVariantV2::create_typed(make_nullable(text),
std::make_shared<DataTypeString>());
+ Block source({{std::move(values), std::make_shared<DataTypeVariantV2>(),
"v"}});
+ const auto wire = serialize_block(source, segment_v2::NO_COMPRESSION);
+ ASSERT_TRUE(wire.column_metas(0).variant_is_v2());
+ Block decoded;
+ size_t bytes = 0;
+ int64_t time = 0;
+ ASSERT_TRUE(decoded.deserialize(wire, &bytes, &time).ok());
+ const auto& variant = assert_cast<const
ColumnVariantV2&>(*decoded.get_by_position(0).column);
+ for (size_t row = 0; row < text->size(); ++row) {
+ const auto value = variant[row];
+
EXPECT_EQ(value.get<TYPE_VARIANT>().ref().get_string().to_string_view(),
+ text->get_data_at(row).to_string_view());
+ }
+}
+
} // namespace doris
diff --git a/be/test/format/wal/test_data/wal_variant_v1_31.wal
b/be/test/format/wal/test_data/wal_variant_v1_31.wal
new file mode 100644
index 00000000000..5421ed861d5
Binary files /dev/null and b/be/test/format/wal/test_data/wal_variant_v1_31.wal
differ
diff --git a/be/test/format/wal/test_data/wal_variant_v1_40.wal
b/be/test/format/wal/test_data/wal_variant_v1_40.wal
new file mode 100644
index 00000000000..b5065c74933
Binary files /dev/null and b/be/test/format/wal/test_data/wal_variant_v1_40.wal
differ
diff --git a/be/test/format/wal/test_data/wal_variant_v1_40_rich.wal
b/be/test/format/wal/test_data/wal_variant_v1_40_rich.wal
new file mode 100644
index 00000000000..f2e9407a219
Binary files /dev/null and
b/be/test/format/wal/test_data/wal_variant_v1_40_rich.wal differ
diff --git a/be/test/format/wal/test_data/wal_variant_v1_42.wal
b/be/test/format/wal/test_data/wal_variant_v1_42.wal
new file mode 100644
index 00000000000..e12ae242704
Binary files /dev/null and b/be/test/format/wal/test_data/wal_variant_v1_42.wal
differ
diff --git a/be/test/format/wal/test_data/wal_variant_v1_doc_order.wal
b/be/test/format/wal/test_data/wal_variant_v1_doc_order.wal
new file mode 100644
index 00000000000..8e49d147812
Binary files /dev/null and
b/be/test/format/wal/test_data/wal_variant_v1_doc_order.wal differ
diff --git a/be/test/format/wal/test_data/wal_variant_v1_doc_value.wal
b/be/test/format/wal/test_data/wal_variant_v1_doc_value.wal
new file mode 100644
index 00000000000..a96c1b0da85
Binary files /dev/null and
b/be/test/format/wal/test_data/wal_variant_v1_doc_value.wal differ
diff --git a/be/test/format/wal/test_data/wal_variant_v1_legacy.wal
b/be/test/format/wal/test_data/wal_variant_v1_legacy.wal
new file mode 100644
index 00000000000..1409d25d792
Binary files /dev/null and
b/be/test/format/wal/test_data/wal_variant_v1_legacy.wal differ
diff --git a/be/test/format/wal/test_data/wal_variant_v2_current.wal
b/be/test/format/wal/test_data/wal_variant_v2_current.wal
new file mode 100644
index 00000000000..d86473676e4
Binary files /dev/null and
b/be/test/format/wal/test_data/wal_variant_v2_current.wal differ
diff --git a/be/test/format/wal/wal_reader_writer_test.cpp
b/be/test/format/wal/wal_reader_writer_test.cpp
index 1b5ebffe10e..c2da6bc638e 100644
--- a/be/test/format/wal/wal_reader_writer_test.cpp
+++ b/be/test/format/wal/wal_reader_writer_test.cpp
@@ -19,6 +19,7 @@
#include <array>
#include <filesystem>
+#include <fstream>
#include <memory>
#include "agent/be_exec_version_manager.h"
@@ -191,6 +192,32 @@ TEST_F(WalReaderWriterTest, TestReadIncompleteLastRecord) {
}
}
+TEST_F(WalReaderWriterTest, TestRejectsWrongChecksum) {
+ const std::string path = _s_test_data_path + "/wrong_checksum";
+ PBlock written;
+ generate_block(written, 0);
+ WalWriter writer(path);
+ ASSERT_TRUE(writer.init(io::global_local_filesystem()).ok());
+ ASSERT_TRUE(writer.append_blocks({&written}).ok());
+ ASSERT_TRUE(writer.finalize().ok());
+
+ std::fstream file(path, std::ios::binary | std::ios::in | std::ios::out);
+ ASSERT_TRUE(file.is_open());
+ file.seekg(-1, std::ios::end);
+ char byte = 0;
+ ASSERT_TRUE(file.get(byte));
+ file.seekp(-1, std::ios::end);
+ ASSERT_TRUE(file.put(static_cast<char>(byte ^ 1)));
+ file.close();
+
+ WalFileReader reader(path);
+ ASSERT_TRUE(reader.init().ok());
+ PBlock block;
+ const auto status = reader.read_block(block);
+ EXPECT_TRUE(status.is<ErrorCode::INTERNAL_ERROR>()) << status;
+ EXPECT_NE(status.to_string().find("checksum failed"), std::string::npos)
<< status;
+}
+
TEST_F(WalReaderWriterTest, TestReadIncompleteHeader) {
const std::string column_ids = "1,2";
const size_t version_header_size = k_wal_magic_length +
WalWriter::VERSION_SIZE;
diff --git a/be/test/format/wal/wal_variant_wire_compat_test.cpp
b/be/test/format/wal/wal_variant_wire_compat_test.cpp
new file mode 100644
index 00000000000..bc8544b237b
--- /dev/null
+++ b/be/test/format/wal/wal_variant_wire_compat_test.cpp
@@ -0,0 +1,281 @@
+// 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.
+
+#include <gen_cpp/data.pb.h>
+#include <gtest/gtest.h>
+
+#include <cstdint>
+#include <filesystem>
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "common/status.h"
+#include "core/block/block.h"
+#include "core/column/column_map.h"
+#include "core/column/column_nullable.h"
+#include "core/column/column_string.h"
+#include "core/column/variant_v2/column_variant_v2.h"
+#include "core/data_type/data_type.h"
+#include "core/data_type/data_type_map.h"
+#include "core/data_type/data_type_number.h"
+#include "core/data_type/data_type_string.h"
+#include "load/group_commit/wal/wal_file_reader.h"
+#include "storage/field_type.h"
+#include "testutil/scoped_temp_dir.h"
+#include "util/unaligned.h"
+
+namespace doris {
+namespace {
+
+void expect_wal_values(const char* fixture, int exec_version, int first_key,
int first_id,
+ const char* note, bool has_doc_value, bool is_v2 =
false,
+ const char* first_path = "k", int first_path_value = 0)
{
+ SCOPED_TRACE(fixture);
+ // A VARCHAR after the first Variant and a BIGINT after the last check the
+ // cursor at both boundaries.
+ const test::ScopedTempDirectory temp_dir("variant_legacy_wal");
+ const auto path = temp_dir.path() / "1" / "2" / fixture;
+ std::filesystem::create_directories(path.parent_path());
+
std::filesystem::copy_file(std::filesystem::path("be/test/format/wal/test_data")
/ fixture,
+ path);
+ WalFileReader reader(path.string());
+ ASSERT_TRUE(reader.init().ok());
+ uint32_t wal_version = 0;
+ std::string column_ids;
+ ASSERT_TRUE(reader.read_header(wal_version, column_ids).ok());
+
+ PBlock wire;
+ const auto read_status = reader.read_block(wire);
+ ASSERT_TRUE(read_status.ok()) << read_status;
+ ASSERT_EQ(wire.be_exec_version(), exec_version);
+ ASSERT_GE(wire.column_metas_size(), 8);
+ ASSERT_EQ(wire.column_metas(2).type(), PGenericType::VARIANT);
+ ASSERT_EQ(wire.column_metas(2).has_variant_enable_doc_mode(),
has_doc_value);
+ ASSERT_EQ(wire.column_metas(2).variant_is_v2(), is_v2);
+
+ Block block;
+ size_t uncompressed_bytes = 0;
+ int64_t decompress_time = 0;
+ const auto status = block.deserialize(wire, &uncompressed_bytes,
&decompress_time);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_EQ(block.rows(), 2);
+ ASSERT_GE(block.columns(), 8);
+ const auto value = [&](size_t column, size_t row) {
+ const auto& entry = block.get_by_position(column);
+ return entry.type->to_string(*entry.column, row);
+ };
+ PColumnMeta decoded_meta;
+ block.get_by_position(2).type->to_pb_column_meta(&decoded_meta);
+ EXPECT_TRUE(decoded_meta.variant_is_v2());
+ for (size_t row = 0; row < block.rows(); ++row) {
+ const auto key = std::to_string(first_key + row);
+ EXPECT_EQ(value(0, row), key);
+ EXPECT_EQ(value(1, row), std::to_string(first_id + row));
+ const auto first_value =
+ first_path_value == 0 ? key : std::to_string(first_path_value
+ row);
+ EXPECT_EQ(value(2, row), std::string("{\"") + first_path + "\":" +
first_value + "}");
+ EXPECT_EQ(value(3, row), note);
+ EXPECT_EQ(value(4, row), "{\"p\":" + key + "}");
+ EXPECT_EQ(value(5, row), "{\"q\":" + key + "}");
+ EXPECT_EQ(value(6, row), "{\"r\":" + key + "}");
+ EXPECT_EQ(value(7, row), key);
+ }
+ EXPECT_TRUE(reader.read_block(wire).is<ErrorCode::END_OF_FILE>());
+}
+
+TEST(WalVariantWireCompatTest, ReadsDoris31VariantWal) {
+ expect_wal_values("wal_variant_v1_31.wal", 9, 101, 1001, "wal31", false);
+}
+
+TEST(WalVariantWireCompatTest, ReadsDoris40VariantWal) {
+ expect_wal_values("wal_variant_v1_40.wal", 8, 91, 901, "wal40", false);
+}
+
+TEST(WalVariantWireCompatTest, ReadsDoris42VariantWal) {
+ expect_wal_values("wal_variant_v1_42.wal", 14, 81, 801, "wal42", true);
+}
+
+TEST(WalVariantWireCompatTest, ReadsDoris41RcBeforeDocValueMap) {
+ expect_wal_values("wal_variant_v1_legacy.wal", 8, 51, 501, "kill_window4",
false);
+}
+
+TEST(WalVariantWireCompatTest, ReadsDoris41WithDocValueMap) {
+ expect_wal_values("wal_variant_v1_doc_value.wal", 13, 71, 701,
"current_wal", true, false,
+ "cur", 1);
+}
+
+TEST(WalVariantWireCompatTest, ReadsCurrentVariantV2Wal) {
+ expect_wal_values("wal_variant_v2_current.wal", 19, 71, 701,
"current_wal", true, true);
+}
+
+TEST(WalVariantWireCompatTest, ReadsNonemptyV1DocValueMap) {
+ constexpr int version = 13;
+ auto string_type = std::make_shared<DataTypeString>();
+ const DataTypeMap map_type(string_type, string_type);
+ auto sparse = map_type.create_column();
+ sparse->insert_many_defaults(2);
+ auto keys = ColumnString::create();
+ auto values = ColumnString::create();
+ auto offsets = ColumnArray::ColumnOffsets::create();
+ for (int32_t value : {20, 30}) {
+ keys->insert_data("d", 1);
+ // A V1 integer cell stores a FieldType byte followed by its value.
+ char cell[1 + sizeof(value)]
{static_cast<char>(FieldType::OLAP_FIELD_TYPE_INT)};
+ unaligned_store<int32_t>(cell + 1, value);
+ values->insert_data(cell, sizeof(cell));
+ offsets->insert_value(keys->size());
+ }
+ const auto doc = ColumnMap::create(std::move(keys), std::move(values),
std::move(offsets));
+ const DataTypeInt64 tail_type;
+ auto tail = ColumnInt64::create();
+ tail->insert_value(101);
+ tail->insert_value(102);
+ std::string bytes(2 * sizeof(uint32_t) +
+
map_type.get_uncompressed_serialized_bytes(*sparse, version) +
+ map_type.get_uncompressed_serialized_bytes(*doc,
version) +
+
tail_type.get_uncompressed_serialized_bytes(*tail, version),
+ '\0');
+ // The original 4.1 fixtures have an empty doc-value map. Encode the
+ // historical layout here so one row must consume an actual doc cell.
+ char* cursor = bytes.data();
+ unaligned_store<uint32_t>(cursor, 0);
+ unaligned_store<uint32_t>(cursor + sizeof(uint32_t), 2);
+ cursor += 2 * sizeof(uint32_t);
+ cursor = map_type.serialize(*sparse, cursor, version);
+ cursor = map_type.serialize(*doc, cursor, version);
+ cursor = tail_type.serialize(*tail, cursor, version);
+
+ PBlock wire;
+ wire.set_be_exec_version(version);
+ auto* meta = wire.add_column_metas();
+ meta->set_name("payload");
+ meta->set_type(PGenericType::VARIANT);
+ meta->set_variant_enable_doc_mode(true);
+ auto* tail_meta = wire.add_column_metas();
+ tail_meta->set_name("tail");
+ tail_type.to_pb_column_meta(tail_meta);
+ wire.set_column_values(bytes.data(), cursor - bytes.data());
+
+ Block block;
+ size_t uncompressed_bytes = 0;
+ int64_t decompress_time = 0;
+ const auto status = block.deserialize(wire, &uncompressed_bytes,
&decompress_time);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_EQ(block.rows(), 2);
+ ASSERT_EQ(block.columns(), 2);
+ const auto& variant = block.get_by_position(0);
+ const auto& trailing = block.get_by_position(1);
+ EXPECT_EQ(variant.type->to_string(*variant.column, 0), R"({"d":20})");
+ EXPECT_EQ(variant.type->to_string(*variant.column, 1), R"({"d":30})");
+ EXPECT_EQ(trailing.type->to_string(*trailing.column, 0), "101");
+ EXPECT_EQ(trailing.type->to_string(*trailing.column, 1), "102");
+}
+
+// Captured from async Group Commit on a 4.1.5 V1 backend. The table enabled
doc mode.
+TEST(WalVariantWireCompatTest, ReadsDocModeTableWalWithDottedInputKeys) {
+ const test::ScopedTempDirectory dir("variant_doc_order_wal");
+ const auto path = dir.path() / "1" / "2" / "pending.wal";
+ std::filesystem::create_directories(path.parent_path());
+
std::filesystem::copy_file("be/test/format/wal/test_data/wal_variant_v1_doc_order.wal",
path);
+ WalFileReader reader(path.string());
+ ASSERT_TRUE(reader.init().ok());
+ uint32_t version = 0;
+ std::string ids;
+ ASSERT_TRUE(reader.read_header(version, ids).ok());
+ ASSERT_EQ(ids, "0,1,2");
+ PBlock wire;
+ ASSERT_TRUE(reader.read_block(wire).ok());
+ ASSERT_EQ(wire.column_metas_size(), 3);
+ ASSERT_EQ(wire.column_metas(1).type(), PGenericType::VARIANT);
+ ASSERT_FALSE(wire.column_metas(1).variant_is_v2());
+ EXPECT_EQ(wire.be_exec_version(), 13);
+ EXPECT_TRUE(wire.column_metas(1).variant_enable_doc_mode());
+ size_t bytes = 0;
+ int64_t time = 0;
+
+ Block decoded;
+ const auto status = decoded.deserialize(wire, &bytes, &time);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_EQ(decoded.rows(), 1);
+ ASSERT_EQ(decoded.columns(), 3);
+ const auto as_text = [&](size_t i) {
+ const auto& col = decoded.get_by_position(i);
+ return col.type->to_string(*col.column, 0);
+ };
+ EXPECT_EQ(as_text(0), "11");
+ EXPECT_EQ(as_text(2), "211");
+ const auto nested = remove_nullable(decoded.get_by_position(1).column);
+ const auto& variant = assert_cast<const ColumnVariantV2&>(*nested);
+ const auto view = variant.read_view();
+ const auto root = view.value_at(0);
+ ASSERT_EQ(root.basic_type(), VariantBasicType::OBJECT);
+ ASSERT_EQ(root.num_elements(), 3);
+ VariantRef field;
+ for (const auto& [key, value] : {std::pair {"a.b", 1}, {"z", 3}, {"a.c",
2}}) {
+ ASSERT_TRUE(root.object_find(StringRef(key), &field)) << key;
+ EXPECT_EQ(field.get_int(), value) << key;
+ }
+ EXPECT_TRUE(reader.read_block(wire).is<ErrorCode::END_OF_FILE>());
+}
+
+// Captured from an async Group Commit on 4.0.8-rc02 with replay paused.
+TEST(WalVariantWireCompatTest, ReadsDoris40PendingGroupCommitWal) {
+ const test::ScopedTempDirectory temp_dir("variant_legacy_group_commit");
+ const auto path = temp_dir.path() / "1" / "2" / "pending.wal";
+ std::filesystem::create_directories(path.parent_path());
+
std::filesystem::copy_file("be/test/format/wal/test_data/wal_variant_v1_40_rich.wal",
path);
+ WalFileReader reader(path.string());
+ ASSERT_TRUE(reader.init().ok());
+ uint32_t version = 0;
+ std::string ids;
+ ASSERT_TRUE(reader.read_header(version, ids).ok());
+ ASSERT_EQ(ids, "0,1,2");
+
+ PBlock wire;
+ ASSERT_TRUE(reader.read_block(wire).ok());
+ ASSERT_EQ(wire.column_metas_size(), 3);
+ EXPECT_EQ(wire.column_metas(1).type(), PGenericType::VARIANT);
+ EXPECT_FALSE(wire.column_metas(1).has_variant_enable_doc_mode());
+ Block block;
+ size_t uncompressed_bytes = 0;
+ int64_t decompress_time = 0;
+ const auto status = block.deserialize(wire, &uncompressed_bytes,
&decompress_time);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_EQ(block.rows(), 4);
+ ASSERT_EQ(block.columns(), 3);
+ const auto value = [&](size_t column, size_t row) {
+ const auto& entry = block.get_by_position(column);
+ return entry.type->to_string(*entry.column, row);
+ };
+ // The decoder parses the root input text stored by Group Commit.
+ const char* const payloads[] = {
+ R"({"arr":[4,5],"deep":{"rare":"w11"},"hot":11})",
+ R"({"hot":12,"other":true})",
+ "null",
+ "{}",
+ };
+ for (size_t row = 0; row < block.rows(); ++row) {
+ EXPECT_EQ(value(0, row), std::to_string(11 + row));
+ EXPECT_EQ(value(1, row), payloads[row]);
+ EXPECT_EQ(value(2, row), std::to_string(2011 + row));
+ }
+ EXPECT_TRUE(reader.read_block(wire).is<ErrorCode::END_OF_FILE>());
+}
+
+} // namespace
+} // namespace doris
diff --git a/be/test/format_v2/wal/wal_reader_test.cpp
b/be/test/format_v2/wal/wal_reader_test.cpp
index 709d5840961..f7b74836526 100644
--- a/be/test/format_v2/wal/wal_reader_test.cpp
+++ b/be/test/format_v2/wal/wal_reader_test.cpp
@@ -19,27 +19,38 @@
#include <gtest/gtest.h>
+#include <array>
#include <chrono>
+#include <cstring>
#include <filesystem>
#include <memory>
+#include <span>
+#include <string>
+#include <string_view>
#include <tuple>
#include <vector>
#include "agent/be_exec_version_manager.h"
#include "core/block/block.h"
+#include "core/column/column_map.h"
+#include "core/column/column_nullable.h"
#include "core/column/column_string.h"
+#include "core/column/column_vector.h"
+#include "core/column/variant_v2/column_variant_v2.h"
#include "core/data_type/data_type_array.h"
#include "core/data_type/data_type_map.h"
#include "core/data_type/data_type_nullable.h"
#include "core/data_type/data_type_number.h"
#include "core/data_type/data_type_string.h"
#include "core/data_type/data_type_struct.h"
+#include "core/data_type/data_type_variant_v2.h"
#include "format_v2/column_mapper.h"
#include "format_v2/table_reader.h"
#include "io/fs/local_file_system.h"
#include "load/group_commit/wal/wal_file_reader.h"
#include "load/group_commit/wal/wal_writer.h"
#include "testutil/scoped_temp_dir.h"
+#include "testutil/variant_v1_wire_test_util.h"
namespace doris::format::wal {
namespace {
@@ -50,18 +61,137 @@ std::string temporary_wal_path(const
std::filesystem::path& root) {
return path.string();
}
-PBlock serialize_block(const Block& block) {
+PBlock serialize_block(const Block& block,
+ segment_v2::CompressionTypePB compression =
segment_v2::SNAPPY) {
PBlock pblock;
size_t uncompressed_bytes = 0;
size_t compressed_bytes = 0;
int64_t compress_time = 0;
EXPECT_TRUE(block.serialize(BeExecVersionManager::get_newest_version(),
&pblock,
- &uncompressed_bytes, &compressed_bytes,
&compress_time,
- segment_v2::CompressionTypePB::SNAPPY)
+ &uncompressed_bytes, &compressed_bytes,
&compress_time, compression)
.ok());
return pblock;
}
+void expect_current_wire_round_trip(const Block& legacy, size_t
variant_position,
+ std::string_view first_row_key = {}) {
+ Block source = legacy;
+ // Force the compressed path without changing the columns read from the
old WAL.
+ auto padding = ColumnString::create();
+ const std::string repeated(512, 'x');
+ for (size_t row = 0; row < source.rows(); ++row) {
+ padding->insert_data(repeated.data(), repeated.size());
+ }
+ source.insert({std::move(padding), std::make_shared<DataTypeString>(),
"compression_padding"});
+
+ for (bool compressed : {false, true}) {
+ SCOPED_TRACE(compressed);
+ auto wire = serialize_block(source,
+ compressed ? segment_v2::SNAPPY :
segment_v2::NO_COMPRESSION);
+ ASSERT_EQ(wire.compressed(), compressed);
+ ASSERT_EQ(wire.be_exec_version(),
BeExecVersionManager::get_newest_version());
+ ASSERT_EQ(wire.column_metas_size(), source.columns());
+ const auto& marker = wire.column_metas(variant_position);
+ EXPECT_TRUE(marker.has_variant_enable_doc_mode());
+ EXPECT_TRUE(marker.variant_is_v2());
+ EXPECT_EQ(marker.is_nullable(),
+
source.get_by_position(variant_position).type->is_nullable());
+
+ Block result;
+ size_t bytes = 0;
+ int64_t time = 0;
+ const auto status = result.deserialize(wire, &bytes, &time);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_EQ(result.rows(), source.rows());
+ ASSERT_EQ(result.columns(), source.columns());
+ for (size_t column = 0; column < source.columns(); ++column) {
+ const auto& expected = source.get_by_position(column);
+ const auto& actual = result.get_by_position(column);
+ ASSERT_TRUE(expected.type->equals(*actual.type)) << expected.name;
+ for (size_t row = 0; row < source.rows(); ++row) {
+ const bool is_null = expected.column->is_null_at(row);
+ ASSERT_EQ(actual.column->is_null_at(row), is_null) <<
expected.name;
+ if (!is_null) {
+ EXPECT_EQ(actual.type->to_string(*actual.column, row),
+ expected.type->to_string(*expected.column, row))
+ << expected.name << " row " << row;
+ if (column == variant_position) {
+ const auto expected_value = (*expected.column)[row];
+ const auto actual_value = (*actual.column)[row];
+ const auto expected_ref =
expected_value.get<TYPE_VARIANT>().ref();
+ const auto actual_ref =
actual_value.get<TYPE_VARIANT>().ref();
+ ASSERT_EQ(actual_ref.basic_type(),
expected_ref.basic_type());
+ if (row == 0 && !first_row_key.empty()) {
+ const StringRef key(first_row_key.data(),
first_row_key.size());
+ VariantRef expected_leaf;
+ VariantRef actual_leaf;
+ ASSERT_TRUE(expected_ref.object_find(key,
&expected_leaf));
+ ASSERT_TRUE(actual_ref.object_find(key,
&actual_leaf));
+ ASSERT_EQ(actual_leaf.basic_type(),
expected_leaf.basic_type());
+ EXPECT_EQ(actual_leaf.primitive_id(),
expected_leaf.primitive_id());
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+ColumnDefinition wal_projection(int32_t uid, const char* name, const
DataTypePtr& type) {
+ ColumnDefinition column;
+ column.identifier = Field::create_field<TYPE_INT>(uid);
+ column.name = name;
+ column.type = type;
+ return column;
+}
+
+// Build the old Variant payload using the ordinary serializers for its maps
and
+// neighboring columns. The old block has zero materialized subcolumns.
+PBlock legacy_variant_boundary_block(bool with_doc) {
+ const int version = with_doc ? 13 : 8;
+ const uint32_t rows = with_doc ? 3 : 1;
+ const DataTypeInt64 int_type;
+ auto before = ColumnInt64::create();
+ auto after = ColumnInt64::create();
+ for (uint32_t row = 0; row < rows; ++row) {
+ before->insert_value(11 + row);
+ after->insert_value(101 + row);
+ }
+ const auto doc =
+ with_doc ? test::legacy_variant_wire_map(rows, "d", 20) :
ColumnMap::MutablePtr {};
+ const auto sparse = test::legacy_variant_wire_map(rows);
+ const auto body = test::legacy_variant_wire_body(version, rows, *sparse,
doc.get());
+
+ constexpr std::array<uint8_t, 3> nulls {0, 1, 0};
+ const size_t nullable_header = sizeof(bool) + 2 * sizeof(size_t) + rows;
+ const size_t size = int_type.get_uncompressed_serialized_bytes(*before,
version) +
+ nullable_header + body.size() +
+ int_type.get_uncompressed_serialized_bytes(*after,
version);
+ std::string bytes(size, '\0');
+ char* cursor = int_type.serialize(*before, bytes.data(), version);
+ const IColumn* row_shape = before.get();
+ size_t saved_rows = 0;
+ cursor = serialize_const_flag_and_row_num(&row_shape, cursor, &saved_rows);
+ std::memcpy(cursor, nulls.data(), saved_rows);
+ cursor += saved_rows;
+ std::memcpy(cursor, body.data(), body.size());
+ cursor += body.size();
+ cursor = int_type.serialize(*after, cursor, version);
+
+ PBlock wire;
+ wire.set_be_exec_version(version);
+ int_type.to_pb_column_meta(wire.add_column_metas());
+ auto* variant = wire.add_column_metas();
+ variant->set_type(PGenericType::VARIANT);
+ variant->set_is_nullable(true);
+ if (with_doc) {
+ variant->set_variant_enable_doc_mode(true);
+ }
+ int_type.to_pb_column_meta(wire.add_column_metas());
+ wire.set_column_values(bytes.data(), cursor - bytes.data());
+ return wire;
+}
+
void expect_wal_column(const IColumn& column, const std::string& name, size_t
expected_rows,
size_t offset) {
ASSERT_EQ(column.size(), expected_rows);
@@ -337,6 +467,350 @@ TEST(WalReaderV2Test,
WriterBackedReaderPreservesNestedSchemaAndMovesFirstPayloa
std::filesystem::path(wal_path).parent_path().parent_path().parent_path());
}
+namespace {
+
+struct LegacyVariantWalFixture {
+ const char* file;
+ int first_key;
+ const char* note;
+ int max_subcolumns;
+};
+
+constexpr LegacyVariantWalFixture doris31_wal {"wal_variant_v1_31.wal", 101,
"wal31", 0};
+
+void expect_legacy_variant_projection(const std::string& wal_path,
+ std::span<const LegacyVariantWalFixture>
fixtures) {
+ std::shared_ptr<io::FileSystemProperties> properties;
+ std::unique_ptr<io::FileDescription> description;
+ WalReader reader(properties, description, nullptr, nullptr, {});
+ ASSERT_NO_FATAL_FAILURE(initialize_wal_reader(&reader, wal_path, false));
+ std::vector<ColumnDefinition> schema;
+ ASSERT_TRUE(reader.get_schema(&schema).ok());
+ ASSERT_EQ(schema.size(), 10);
+ const auto type = remove_nullable(schema[2].type);
+ EXPECT_EQ(assert_cast<const
DataTypeVariantV2&>(*type).variant_max_subcolumns_count(),
+ fixtures.front().max_subcolumns);
+ std::vector<ColumnDefinition> projected {schema[7], schema[2], schema[3]};
+ projected[0].name = "tail";
+ projected[1].name = "payload";
+ projected[2].name = "note";
+ auto mapper = reader.create_column_mapper({});
+ ASSERT_TRUE(mapper->create_mapping(projected, {}, schema).ok());
+ ASSERT_EQ(mapper->mappings().size(), 3);
+ EXPECT_EQ(mapper->mappings()[0].file_local_id, 7);
+ EXPECT_EQ(mapper->mappings()[1].file_local_id, 2);
+ EXPECT_EQ(mapper->mappings()[2].file_local_id, 3);
+ auto request = std::make_shared<FileScanRequest>();
+ ASSERT_TRUE(mapper->create_scan_request({}, projected,
request.get()).ok());
+ const auto tail = request->local_positions.at(LocalColumnId(7)).value();
+ const auto payload = request->local_positions.at(LocalColumnId(2)).value();
+ const auto note = request->local_positions.at(LocalColumnId(3)).value();
+ ASSERT_TRUE(reader.open(std::move(request)).ok());
+
+ Block output;
+ for (const auto& column : projected) {
+ output.insert({column.type->create_column(), column.type,
column.name});
+ }
+ const auto value = [&](size_t index, size_t row) {
+ const auto& entry = output.get_by_position(index);
+ return entry.type->to_string(*entry.column, row);
+ };
+ for (const auto& fixture : fixtures) {
+ SCOPED_TRACE(fixture.file);
+ output.clear_column_data();
+ size_t rows = 0;
+ bool eof = true;
+ const auto status = reader.get_block(&output, &rows, &eof);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_EQ(rows, 2);
+ EXPECT_FALSE(eof);
+ for (size_t row = 0; row < rows; ++row) {
+ const auto key = std::to_string(fixture.first_key + row);
+ EXPECT_EQ(value(tail, row), key);
+ EXPECT_EQ(value(payload, row), "{\"k\":" + key + "}");
+ EXPECT_EQ(value(note, row), fixture.note);
+ }
+ ASSERT_NO_FATAL_FAILURE(expect_current_wire_round_trip(output,
payload));
+ }
+ ASSERT_NO_FATAL_FAILURE(expect_wal_eof(&reader, &output));
+ ASSERT_TRUE(reader.close().ok());
+}
+
+} // namespace
+
+TEST(WalReaderV2Test, ReplaysLegacyVariantAcrossProjectedBlocks) {
+ const test::ScopedTempDirectory temp_dir("wal_legacy_variant_projection");
+ const auto wal_path = temporary_wal_path(temp_dir.path());
+ const std::array fixtures {
+ LegacyVariantWalFixture {"wal_variant_v1_40.wal", 91, "wal40",
2048},
+ LegacyVariantWalFixture {"wal_variant_v1_legacy.wal", 51,
"kill_window4", 2048},
+ doris31_wal,
+ };
+ constexpr auto ids = "0,1,2,3,4,5,6,7,8,9";
+ WalWriter writer(wal_path);
+ ASSERT_TRUE(writer.init(io::global_local_filesystem()).ok());
+ ASSERT_TRUE(writer.append_header(ids).ok());
+
+ // Keep original PBlocks from #71029, including their execution versions.
+ for (const auto& sample : fixtures) {
+ const auto* file = sample.file;
+ SCOPED_TRACE(file);
+ const auto fixture =
std::filesystem::path("be/test/format/wal/test_data") / file;
+ const auto staged = std::filesystem::path(wal_path).parent_path() /
file;
+ std::filesystem::copy_file(fixture, staged);
+ WalFileReader legacy(staged.string());
+ ASSERT_TRUE(legacy.init().ok());
+ uint32_t version = 0;
+ std::string column_ids;
+ ASSERT_TRUE(legacy.read_header(version, column_ids).ok());
+ ASSERT_EQ(column_ids, ids);
+ PBlock block;
+ ASSERT_TRUE(legacy.read_block(block).ok());
+ ASSERT_TRUE(writer.append_blocks({&block}).ok());
+ ASSERT_TRUE(legacy.finalize().ok());
+ }
+ ASSERT_TRUE(writer.finalize().ok());
+
+ ASSERT_NO_FATAL_FAILURE(expect_legacy_variant_projection(wal_path,
fixtures));
+}
+
+TEST(WalReaderV2Test, ReadsDoris31WalWithItsOwnSchema) {
+ const test::ScopedTempDirectory temp_dir("wal_doris31_schema");
+ const auto wal_path = temporary_wal_path(temp_dir.path());
+ const auto fixture = std::filesystem::path("be/test/format/wal/test_data")
/ doris31_wal.file;
+ // Keep the real WAL header as well as the PBlock used for schema
discovery.
+ std::filesystem::copy_file(fixture, wal_path);
+ const std::array fixtures {doris31_wal};
+ ASSERT_NO_FATAL_FAILURE(expect_legacy_variant_projection(wal_path,
fixtures));
+}
+
+TEST(WalReaderV2Test, ReplaysNullableLegacyVariantBoundaryBlocks) {
+ const auto v2_type = make_nullable(std::make_shared<DataTypeVariantV2>());
+ const auto int_type = make_nullable(std::make_shared<DataTypeInt64>());
+ const std::vector<ColumnDefinition> projected {
+ wal_projection(9, "tail", int_type),
+ wal_projection(7, "payload", v2_type),
+ wal_projection(2, "head", int_type),
+ };
+
+ for (bool with_doc : {false, true}) {
+ SCOPED_TRACE(with_doc);
+ const test::ScopedTempDirectory temp_dir("wal_variant_boundary");
+ const auto path = temporary_wal_path(temp_dir.path());
+ auto wire = legacy_variant_boundary_block(with_doc);
+ {
+ WalWriter writer(path);
+ ASSERT_TRUE(writer.init(io::global_local_filesystem()).ok());
+ ASSERT_TRUE(writer.append_header("2,7,9").ok());
+ ASSERT_TRUE(writer.append_blocks({&wire}).ok());
+ ASSERT_TRUE(writer.finalize().ok());
+ }
+
+ std::shared_ptr<io::FileSystemProperties> properties;
+ std::unique_ptr<io::FileDescription> description;
+ WalReader reader(properties, description, nullptr, nullptr, projected);
+ ASSERT_NO_FATAL_FAILURE(initialize_wal_reader(&reader, path, false));
+ std::vector<ColumnDefinition> schema;
+ ASSERT_TRUE(reader.get_schema(&schema).ok());
+ auto mapper = reader.create_column_mapper({});
+ ASSERT_TRUE(mapper->create_mapping(projected, {}, schema).ok());
+ auto request = std::make_shared<FileScanRequest>();
+ ASSERT_TRUE(mapper->create_scan_request({}, projected,
request.get()).ok());
+ const auto head =
request->local_positions.at(LocalColumnId(0)).value();
+ const auto payload =
request->local_positions.at(LocalColumnId(1)).value();
+ const auto tail =
request->local_positions.at(LocalColumnId(2)).value();
+ ASSERT_TRUE(reader.open(std::move(request)).ok());
+
+ Block output;
+ for (const auto& column : projected) {
+ output.insert({column.type->create_column(), column.type,
column.name});
+ }
+ size_t rows = 0;
+ bool eof = true;
+ const auto read = reader.get_block(&output, &rows, &eof);
+ ASSERT_TRUE(read.ok()) << read;
+ ASSERT_EQ(rows, with_doc ? 3 : 1);
+ EXPECT_FALSE(eof);
+ const auto* nullable =
+
check_and_get_column<ColumnNullable>(*output.get_by_position(payload).column);
+ ASSERT_NE(nullable, nullptr);
+ const auto* variant =
check_and_get_column<ColumnVariantV2>(nullable->get_nested_column());
+ ASSERT_NE(variant, nullptr);
+ const auto values = variant->read_view();
+ for (size_t row = 0; row < rows; ++row) {
+
EXPECT_EQ(int_type->to_string(*output.get_by_position(head).column, row),
+ std::to_string(11 + row));
+
EXPECT_EQ(int_type->to_string(*output.get_by_position(tail).column, row),
+ std::to_string(101 + row));
+ EXPECT_EQ(nullable->is_null_at(row), with_doc && row == 1);
+ }
+ if (with_doc) {
+ VariantRef value;
+ ASSERT_TRUE(values.value_at(0).object_find(StringRef("d", 1),
&value));
+ EXPECT_EQ(value.get_int(), 20);
+ ASSERT_EQ(values.value_at(2).basic_type(),
VariantBasicType::OBJECT);
+ EXPECT_EQ(values.value_at(2).num_elements(), 0);
+ } else {
+ ASSERT_EQ(values.value_at(0).basic_type(),
VariantBasicType::OBJECT);
+ EXPECT_EQ(values.value_at(0).num_elements(), 0);
+ }
+ ASSERT_NO_FATAL_FAILURE(
+ expect_current_wire_round_trip(output, payload, with_doc ? "d"
: ""));
+ ASSERT_NO_FATAL_FAILURE(expect_wal_eof(&reader, &output));
+ ASSERT_TRUE(reader.close().ok());
+ }
+}
+
+TEST(WalReaderV2Test, ReplaysLegacyDottedPathsWithDifferentProjections) {
+ const auto int_type = make_nullable(std::make_shared<DataTypeInt64>());
+ const auto variant_type =
make_nullable(std::make_shared<DataTypeVariantV2>());
+ const auto tail = wal_projection(9, "tail", int_type);
+ const std::array<std::vector<ColumnDefinition>, 3> projections {
+ {{tail, wal_projection(7, "payload", variant_type),
+ wal_projection(2, "head", int_type)},
+ {tail},
+ {}}};
+
+ for (bool with_doc : {false, true}) {
+ SCOPED_TRACE(with_doc);
+ const test::ScopedTempDirectory temp_dir("wal_legacy_dotted_paths");
+ const auto path = temporary_wal_path(temp_dir.path());
+ auto single = test::legacy_variant_dotted_path_block(with_doc, false);
+ auto shared = test::legacy_variant_dotted_path_block(with_doc, true);
+ {
+ WalWriter writer(path);
+ ASSERT_TRUE(writer.init(io::global_local_filesystem()).ok());
+ ASSERT_TRUE(writer.append_header("2,7,9").ok());
+ ASSERT_TRUE(writer.append_blocks({&single, &shared}).ok());
+ ASSERT_TRUE(writer.finalize().ok());
+ }
+
+ for (const auto& projected : projections) {
+ SCOPED_TRACE(projected.size());
+ std::shared_ptr<io::FileSystemProperties> properties;
+ std::unique_ptr<io::FileDescription> description;
+ WalReader reader(properties, description, nullptr, nullptr,
projected);
+ ASSERT_NO_FATAL_FAILURE(initialize_wal_reader(&reader, path,
false));
+ std::vector<ColumnDefinition> schema;
+ ASSERT_TRUE(reader.get_schema(&schema).ok());
+ auto mapper = reader.create_column_mapper({});
+ ASSERT_TRUE(mapper->create_mapping(projected, {}, schema).ok());
+ auto request = std::make_shared<FileScanRequest>();
+ ASSERT_TRUE(mapper->create_scan_request({}, projected,
request.get()).ok());
+ const auto positions = request->local_positions;
+ ASSERT_EQ(positions.size(), projected.size());
+ if (!projected.empty()) {
+ EXPECT_EQ(positions.at(LocalColumnId(2)).value(), 0);
+ }
+ ASSERT_TRUE(reader.open(std::move(request)).ok());
+
+ Block output;
+ for (const auto& definition : projected) {
+ output.insert({definition.type->create_column(),
definition.type, definition.name});
+ }
+ for (const char* payload : {R"({"a":{"b":7}})",
R"({"a":{"b":1,"c":2}})"}) {
+ output.clear_column_data();
+ size_t rows = 0;
+ bool eof = true;
+ const auto status = reader.get_block(&output, &rows, &eof);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_EQ(rows, 1);
+ EXPECT_FALSE(eof);
+ ASSERT_EQ(output.columns(), projected.size());
+ const std::array<const char*, 3> expected {"100", payload,
"200"};
+ for (const auto& [local_id, position] : positions) {
+ const auto& column =
output.get_by_position(position.value());
+ EXPECT_EQ(column.type->to_string(*column.column, 0),
+ expected.at(local_id.value()));
+ }
+ }
+ ASSERT_NO_FATAL_FAILURE(expect_wal_eof(&reader, &output));
+ ASSERT_TRUE(reader.close().ok());
+ }
+ }
+}
+
+TEST(WalReaderV2Test, ReadsHeaderOnlyVariantWal) {
+ const test::ScopedTempDirectory temp_dir("wal_variant_header_only");
+ const auto path = temporary_wal_path(temp_dir.path());
+ {
+ WalWriter writer(path);
+ ASSERT_TRUE(writer.init(io::global_local_filesystem()).ok());
+ ASSERT_TRUE(writer.append_header("2,7").ok());
+ ASSERT_TRUE(writer.finalize().ok());
+ }
+
+ const auto v2_type = make_nullable(std::make_shared<DataTypeVariantV2>());
+ const std::vector<ColumnDefinition> projected {wal_projection(7,
"payload", v2_type)};
+ std::shared_ptr<io::FileSystemProperties> properties;
+ std::unique_ptr<io::FileDescription> description;
+ WalReader reader(properties, description, nullptr, nullptr, projected);
+ ASSERT_NO_FATAL_FAILURE(initialize_wal_reader(&reader, path, false));
+ std::vector<ColumnDefinition> schema;
+ ASSERT_TRUE(reader.get_schema(&schema).ok());
+ ASSERT_EQ(schema.size(), 1);
+ EXPECT_EQ(schema[0].local_id, 1);
+ EXPECT_EQ(schema[0].get_identifier_field_id(), 7);
+ EXPECT_TRUE(schema[0].type->equals(*v2_type));
+ auto mapper = reader.create_column_mapper({});
+ ASSERT_TRUE(mapper->create_mapping(projected, {}, schema).ok());
+ auto request = std::make_shared<FileScanRequest>();
+ ASSERT_TRUE(mapper->create_scan_request({}, projected,
request.get()).ok());
+ ASSERT_TRUE(reader.open(std::move(request)).ok());
+
+ Block output({{v2_type->create_column(), v2_type, "payload"}});
+ ASSERT_NO_FATAL_FAILURE(expect_wal_eof(&reader, &output));
+ EXPECT_TRUE(output.get_by_position(0).type->equals(*v2_type));
+ ASSERT_TRUE(reader.close().ok());
+}
+
+TEST(WalReaderV2Test, ReplaysLegacyGroupCommitJsonAsStructuredVariant) {
+ const doris::test::ScopedTempDirectory
temp_dir("wal_legacy_group_commit_json");
+ const auto path = temporary_wal_path(temp_dir.path());
+
std::filesystem::copy_file("be/test/format/wal/test_data/wal_variant_v1_40_rich.wal",
path);
+
+ std::shared_ptr<io::FileSystemProperties> properties;
+ std::unique_ptr<io::FileDescription> description;
+ WalReader reader(properties, description, nullptr, nullptr, {});
+ ASSERT_NO_FATAL_FAILURE(initialize_wal_reader(&reader, path, false));
+ std::vector<ColumnDefinition> schema;
+ ASSERT_TRUE(reader.get_schema(&schema).ok());
+ ASSERT_EQ(schema.size(), 3);
+ auto request = std::make_shared<FileScanRequest>();
+ request->local_positions.emplace(LocalColumnId(1), LocalIndex(0));
+ ASSERT_TRUE(reader.open(std::move(request)).ok());
+
+ const auto& type = schema[1].type;
+ Block output({{type->create_column(), type, "payload"}});
+ size_t rows = 0;
+ bool eof = false;
+ const auto status = reader.get_block(&output, &rows, &eof);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_EQ(rows, 4);
+ const auto& column = *output.get_by_position(0).column;
+ const auto& variant = assert_cast<const ColumnVariantV2&>(
+ assert_cast<const ColumnNullable&>(column).get_nested_column());
+ const auto view = variant.read_view();
+ const auto first = view.value_at(0);
+ ASSERT_EQ(first.basic_type(), VariantBasicType::OBJECT);
+ VariantRef value;
+ ASSERT_TRUE(first.object_find(StringRef("deep", 4), &value));
+ ASSERT_TRUE(value.object_find(StringRef("rare", 4), &value));
+ EXPECT_EQ(value.get_string().to_string_view(), "w11");
+ ASSERT_TRUE(first.object_find(StringRef("arr", 3), &value));
+ ASSERT_EQ(value.num_elements(), 2);
+ EXPECT_EQ(value.array_at(1).get_int(), 5);
+ ASSERT_TRUE(view.value_at(1).object_find(StringRef("other", 5), &value));
+ EXPECT_EQ(value.primitive_id(), VariantPrimitiveId::TRUE_VALUE);
+ EXPECT_FALSE(column.is_null_at(2));
+ EXPECT_TRUE(view.value_at(2).is_null());
+ EXPECT_EQ(view.value_at(3).basic_type(), VariantBasicType::OBJECT);
+ EXPECT_EQ(type->to_string(column, 3), "{}");
+ ASSERT_NO_FATAL_FAILURE(expect_current_wire_round_trip(output, 0));
+ ASSERT_NO_FATAL_FAILURE(expect_wal_eof(&reader, &output));
+ ASSERT_TRUE(reader.close().ok());
+}
+
TEST(WalReaderV2Test, MaterializationTransfersColumnOwnership) {
std::shared_ptr<io::FileSystemProperties> properties;
std::unique_ptr<io::FileDescription> description;
diff --git a/be/test/storage/segment/binary_column_extract_iterator_test.cpp
b/be/test/storage/segment/binary_column_extract_iterator_test.cpp
index c1419198536..70a8787f355 100644
--- a/be/test/storage/segment/binary_column_extract_iterator_test.cpp
+++ b/be/test/storage/segment/binary_column_extract_iterator_test.cpp
@@ -39,10 +39,10 @@
#include "core/data_type_serde/data_type_variant_v2_serde.h"
#include "core/string_buffer.hpp"
#include "core/value/jsonb_value.h"
+#include "core/value/variant/variant_assembler.h"
#include "exec/common/variant_util.h"
#include "storage/iterators.h"
#include "storage/segment/variant/sparse_column_merge_iterator.h"
-#include "storage/segment/variant/v2/variant_assembler.h"
namespace doris::segment_v2 {
namespace {
diff --git a/be/test/storage/segment/variant_assembler_legacy_test.cpp
b/be/test/storage/segment/variant_assembler_legacy_test.cpp
index 032410f8e9c..9049704ec53 100644
--- a/be/test/storage/segment/variant_assembler_legacy_test.cpp
+++ b/be/test/storage/segment/variant_assembler_legacy_test.cpp
@@ -44,10 +44,10 @@
#include "core/value/timestamp_ns_value.h"
#include "core/value/timestamptz_value.h"
#include "core/value/uuid_value.h"
+#include "core/value/variant/variant_assembler.h"
+#include "core/value/variant/variant_storage_cell.h"
#include "exprs/function/parse/variant_string_parse.h"
-#include "storage/segment/variant/v2/variant_assembler.h"
#include "storage/segment/variant/v2/variant_column_reader.h"
-#include "storage/segment/variant/v2/variant_storage_cell.h"
#include "util/variant/variant_test_utils.h"
namespace doris::segment_v2::variant_v2 {
@@ -1053,6 +1053,21 @@ TEST(VariantAssemblerLegacyTest,
MixedDocRowsPreserveMaterializedAndRootPreceden
}
}
+TEST(VariantAssemblerLegacyTest, LegacyBlockReadsDocAndSparseRows) {
+ const auto cell =
fixed_storage_cell<int32_t>(FieldType::OLAP_FIELD_TYPE_INT, 20);
+ auto sparse = map_column_rows({{{"s", cell}}, {{"s", cell}}, {}});
+ auto doc = map_column_rows({{}, {{"d", cell}}, {}});
+ VariantAssemblerOptions options;
+ options.storage_map_kind = StorageMapKind::SPARSE;
+ auto assembler = create_assembler(std::move(options));
+ expect_assembled_rows(*assembler,
+ {.num_rows = 3,
+ .materialized_columns = {},
+ .storage_map = sparse.get(),
+ .legacy_doc_map = doc.get()},
+ {R"({"s":20})", R"({"d":20})", "{}"});
+}
+
TEST(VariantAssemblerLegacyTest, VisibleSlotsResetAcrossBatchBoundaries) {
auto type = make_nullable(std::make_shared<DataTypeInt32>());
VariantAssemblerOptions options;
diff --git a/be/test/storage/variant/test_data/variant_doris40.dat
b/be/test/storage/variant/test_data/variant_doris40.dat
new file mode 100644
index 00000000000..54fce20e28f
Binary files /dev/null and
b/be/test/storage/variant/test_data/variant_doris40.dat differ
diff --git a/be/test/storage/variant/variant_column_writer_reader_test.cpp
b/be/test/storage/variant/variant_column_writer_reader_test.cpp
index 8f5e18df5bc..465a6812afe 100644
--- a/be/test/storage/variant/variant_column_writer_reader_test.cpp
+++ b/be/test/storage/variant/variant_column_writer_reader_test.cpp
@@ -48,6 +48,7 @@
#include "core/string_buffer.hpp"
#include "core/value/jsonb_value.h"
#include "core/value/uuid_value.h"
+#include "core/value/variant/variant_assembler.h"
#include "core/value/variant/variant_batch_builder.h"
#include "core/value/variant/variant_parquet_encoding.h"
#include "exec/common/variant_util.h"
@@ -90,7 +91,6 @@
#include "storage/segment/variant/nested_group_provider.h"
#include "storage/segment/variant/nested_group_streaming_write_plan.h"
#include "storage/segment/variant/sparse_column_merge_iterator.h"
-#include "storage/segment/variant/v2/variant_assembler.h"
#include "storage/segment/variant/v2/variant_column_writer.h"
#include "storage/segment/variant/v2/variant_path_builder.h"
#include "storage/segment/variant/v2/variant_shredder.h"
diff --git a/be/test/storage/variant/variant_legacy_segment_test.cpp
b/be/test/storage/variant/variant_legacy_segment_test.cpp
new file mode 100644
index 00000000000..d515f6c0083
--- /dev/null
+++ b/be/test/storage/variant/variant_legacy_segment_test.cpp
@@ -0,0 +1,95 @@
+// 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.
+
+#include <gen_cpp/olap_file.pb.h>
+#include <gtest/gtest.h>
+
+#include <array>
+#include <memory>
+#include <string>
+
+#include "core/data_type/data_type_factory.hpp"
+#include "io/fs/local_file_system.h"
+#include "storage/iterators.h"
+#include "storage/segment/column_reader.h"
+#include "storage/segment/segment.h"
+#include "storage/tablet/tablet_schema.h"
+
+namespace doris {
+namespace {
+
+TEST(VariantLegacySegmentTest, ReadsDoris40CommittedRows) {
+ // This is the segment that Doris 4.0 wrote when it committed the rows
+ // in wal_variant_v1_40.wal from PR #71029. Column UIDs match that table.
+ constexpr auto path =
"be/test/storage/variant/test_data/variant_doris40.dat";
+ constexpr std::array names {"k", "id", "v1", "note", "v2", "v3", "v4",
"tail"};
+ constexpr std::array types {"BIGINT", "INT", "VARIANT", "VARCHAR",
+ "VARIANT", "VARIANT", "VARIANT", "BIGINT"};
+ auto schema = std::make_shared<TabletSchema>();
+ for (size_t uid = 0; uid < names.size(); ++uid) {
+ ColumnPB pb;
+ pb.set_unique_id(static_cast<int32_t>(uid));
+ pb.set_name(names[uid]);
+ pb.set_type(types[uid]);
+ pb.set_is_key(uid == 0);
+ pb.set_is_nullable(true);
+ schema->append_column(TabletColumn(pb));
+ }
+
+ std::shared_ptr<segment_v2::Segment> segment;
+ auto status = segment_v2::Segment::open(io::global_local_filesystem(),
path, 100, 0,
+ RowsetId {.version = 1}, schema,
+ io::FileReaderOptions {},
&segment);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_EQ(segment->num_rows(), 2);
+
+ OlapReaderStatistics stats;
+ StorageReadOptions read_options(stats);
+ read_options.io_ctx.reader_type = ReaderType::READER_QUERY;
+ segment_v2::ColumnIteratorOptions iterator_options;
+ iterator_options.stats = &stats;
+ iterator_options.file_reader = segment->file_reader().get();
+ constexpr std::array variant_uids {2, 4, 5, 6};
+ constexpr std::array keys {"k", "p", "q", "r"};
+ for (size_t i = 0; i < variant_uids.size(); ++i) {
+ const auto& column = schema->column(variant_uids[i]);
+ SCOPED_TRACE(column.name());
+ std::unique_ptr<segment_v2::ColumnIterator> iterator;
+ status = segment->new_column_iterator(column, &iterator,
&read_options);
+ ASSERT_TRUE(status.ok()) << status;
+ status = iterator->init(iterator_options);
+ ASSERT_TRUE(status.ok()) << status;
+ status = iterator->seek_to_ordinal(0);
+ ASSERT_TRUE(status.ok()) << status;
+
+ auto type = DataTypeFactory::instance().create_data_type(column);
+ auto decoded = type->create_column();
+ size_t rows = segment->num_rows();
+ status = iterator->next_batch(&rows, decoded);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_EQ(rows, 2);
+ ASSERT_EQ(decoded->size(), rows);
+ for (size_t row = 0; row < rows; ++row) {
+ const std::string expected =
+ std::string("{\"") + keys[i] + "\":" + std::to_string(91 +
row) + "}";
+ EXPECT_EQ(type->to_string(*decoded, row), expected);
+ }
+ }
+}
+
+} // namespace
+} // namespace doris
diff --git a/be/test/testutil/variant_v1_wire_test_util.h
b/be/test/testutil/variant_v1_wire_test_util.h
new file mode 100644
index 00000000000..f39641a0049
--- /dev/null
+++ b/be/test/testutil/variant_v1_wire_test_util.h
@@ -0,0 +1,170 @@
+// 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 <gen_cpp/data.pb.h>
+
+#include <cstring>
+#include <initializer_list>
+#include <string>
+#include <string_view>
+#include <vector>
+
+#include "core/column/column_map.h"
+#include "core/column/column_string.h"
+#include "core/column/column_vector.h"
+#include "core/data_type/data_type_map.h"
+#include "core/data_type/data_type_number.h"
+#include "core/data_type/data_type_string.h"
+#include "storage/field_type.h"
+#include "util/json/path_in_data.h"
+#include "util/unaligned.h"
+
+namespace doris::test {
+
+struct LegacyVariantWirePath {
+ PathInData path;
+ DataTypePtr type;
+ ColumnPtr values;
+};
+
+// Writes only the V1 Variant body. The caller owns the surrounding PBlock and
Nullable framing.
+inline std::string legacy_variant_wire_body(
+ int version, uint32_t rows, const ColumnMap& sparse, const ColumnMap*
doc = nullptr,
+ std::initializer_list<LegacyVariantWirePath> paths = {}) {
+ const auto string_type = std::make_shared<DataTypeString>();
+ const DataTypeMap map_type(string_type, string_type);
+ size_t size =
+ 2 * sizeof(uint32_t) +
map_type.get_uncompressed_serialized_bytes(sparse, version);
+ if (doc != nullptr) {
+ size += map_type.get_uncompressed_serialized_bytes(*doc, version);
+ }
+ std::vector<std::string> metadata;
+ for (const auto& [path, type, values] : paths) {
+ PColumnMeta meta;
+ type->to_pb_column_meta(&meta);
+ path.to_protobuf(meta.mutable_column_path(), 0);
+ metadata.push_back(meta.SerializeAsString());
+ size += sizeof(uint32_t) + metadata.back().size() +
+ type->get_uncompressed_serialized_bytes(*values, version);
+ }
+
+ std::string bytes(size, '\0');
+ char* cursor = bytes.data();
+ unaligned_store<uint32_t>(cursor, paths.size());
+ cursor += sizeof(uint32_t);
+ size_t index = 0;
+ for (const auto& entry : paths) {
+ const auto& meta = metadata[index++];
+ unaligned_store<uint32_t>(cursor, meta.size());
+ cursor += sizeof(uint32_t);
+ std::memcpy(cursor, meta.data(), meta.size());
+ cursor += meta.size();
+ cursor = entry.type->serialize(*entry.values, cursor, version);
+ }
+ unaligned_store<uint32_t>(cursor, rows);
+ cursor += sizeof(uint32_t);
+ cursor = map_type.serialize(sparse, cursor, version);
+ if (doc != nullptr) {
+ cursor = map_type.serialize(*doc, cursor, version);
+ }
+ bytes.resize(cursor - bytes.data());
+ return bytes;
+}
+
+// The optional integer cell lives in the first row only.
+inline ColumnMap::MutablePtr legacy_variant_wire_map(size_t rows, const char*
key = nullptr,
+ int32_t value = 0) {
+ auto keys = ColumnString::create();
+ auto values = ColumnString::create();
+ auto offsets = ColumnArray::ColumnOffsets::create();
+ if (key != nullptr) {
+ keys->insert_data(key, std::strlen(key));
+ char cell[1 + sizeof(value)]
{static_cast<char>(FieldType::OLAP_FIELD_TYPE_INT)};
+ unaligned_store<int32_t>(cell + 1, value);
+ values->insert_data(cell, sizeof(cell));
+ }
+ for (size_t row = 0; row < rows; ++row) {
+ offsets->insert_value(keys->size());
+ }
+ return ColumnMap::create(std::move(keys), std::move(values),
std::move(offsets));
+}
+
+inline PBlock legacy_variant_wire_with_sentinels(std::string_view body,
uint32_t rows,
+ bool with_doc,
std::string_view outer_nulls = {},
+ int version = 13) {
+ const DataTypeInt64 bigint;
+ auto head = ColumnInt64::create();
+ auto tail = ColumnInt64::create();
+ for (uint32_t row = 0; row < rows; ++row) {
+ head->insert_value(100 + row);
+ tail->insert_value(200 + row);
+ }
+ const auto nullable_size = outer_nulls.empty() ? 0 : sizeof(bool) + 2 *
sizeof(size_t) + rows;
+ std::string bytes(bigint.get_uncompressed_serialized_bytes(*head, version)
+ nullable_size +
+ body.size() +
+ bigint.get_uncompressed_serialized_bytes(*tail,
version),
+ '\0');
+ char* cursor = bigint.serialize(*head, bytes.data(), version);
+ if (!outer_nulls.empty()) {
+ const IColumn* row_shape = head.get();
+ size_t saved_rows = 0;
+ cursor = serialize_const_flag_and_row_num(&row_shape, cursor,
&saved_rows);
+ std::memcpy(cursor, outer_nulls.data(), saved_rows);
+ cursor += saved_rows;
+ }
+ std::memcpy(cursor, body.data(), body.size());
+ cursor += body.size();
+ cursor = bigint.serialize(*tail, cursor, version);
+
+ PBlock wire;
+ wire.set_be_exec_version(version);
+ bigint.to_pb_column_meta(wire.add_column_metas());
+ auto* variant = wire.add_column_metas();
+ variant->set_type(PGenericType::VARIANT);
+ variant->set_is_nullable(!outer_nulls.empty());
+ if (with_doc) {
+ variant->set_variant_enable_doc_mode(false);
+ }
+ bigint.to_pb_column_meta(wire.add_column_metas());
+ wire.set_column_values(bytes.data(), cursor - bytes.data());
+ return wire;
+}
+
+// Keep each dotted key in one protobuf path component, as a V1 writer can.
+inline PBlock legacy_variant_dotted_path_block(bool with_doc, bool
shared_prefix) {
+ const int version = with_doc ? 13 : 8;
+ constexpr uint32_t rows = 1;
+ const auto sparse = legacy_variant_wire_map(rows);
+ const auto doc = with_doc ? legacy_variant_wire_map(rows) :
ColumnMap::MutablePtr {};
+ const auto int_type = std::make_shared<DataTypeInt32>();
+ const auto make_path = [&](std::string_view key, int32_t value) {
+ auto values = ColumnInt32::create();
+ values->insert_value(value);
+ return LegacyVariantWirePath {PathInData(PathInData::Parts {{key,
false, 0}}), int_type,
+ std::move(values)};
+ };
+ const auto ab = make_path("a.b", shared_prefix ? 1 : 7);
+ const auto body = shared_prefix
+ ? legacy_variant_wire_body(version, rows,
*sparse, doc.get(),
+ {ab, make_path("a.c",
2)})
+ : legacy_variant_wire_body(version, rows,
*sparse, doc.get(), {ab});
+ return legacy_variant_wire_with_sentinels(body, rows, with_doc, {},
version);
+}
+
+} // namespace doris::test
diff --git a/regression-test/data/insert_p0/test_group_commit_variant.out
b/regression-test/data/insert_p0/test_group_commit_variant.out
new file mode 100644
index 00000000000..923a79b2486
--- /dev/null
+++ b/regression-test/data/insert_p0/test_group_commit_variant.out
@@ -0,0 +1,9 @@
+-- This file is automatically generated. You should know what you did if you
want to edit this
+-- !replayed --
+1 \N \N \N \N \N \N \N \N \N
+11 101 \N sql_null null {"p": 1} {"n":{"x":1}}
11 \N 1
+12 102 {"p": 1} mixed_type {"p":"s"} {"p": [1, 2]}
{"n": {"x": null}} 12 string \N
+13 103 {"a.b": 1} sparse {"c": {"d": true}} {"e": [1, {"f":
2}]} {"g": 3.5} 13 \N \N
+2 \N \N \N \N \N \N \N \N \N
+3 \N \N \N \N \N \N \N \N \N
+4 \N \N \N \N \N \N \N \N \N
diff --git a/regression-test/script/variant_wal_upgrade.py
b/regression-test/script/variant_wal_upgrade.py
new file mode 100644
index 00000000000..ade4c0e38c1
--- /dev/null
+++ b/regression-test/script/variant_wal_upgrade.py
@@ -0,0 +1,386 @@
+# 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.
+
+"""Run a VARIANT WAL upgrade test with local Doris packages and an isolated
runtime."""
+
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import re
+import subprocess
+import time
+from urllib import request
+
+
+DB = "variant_wal_upgrade"
+TABLE = "values_after_upgrade"
+LOAD_ERROR = "LoadBlockQueue._finish_group_commit_load.load_error"
+REPLAY_STOP = "WalTable.replay_wals.stop"
+BE_STATE = ("storage", "wal")
+HTTP = request.build_opener(request.ProxyHandler({}))
+OLD_ROWS = """(1, '{"hot":1,"deep":{"old":"c1"},"arr":[1,null,2]}', 1001),
+ (2, '{"hot":2,"deep":{"old":"c2"},"arr":[]}', 1002),
+ (3, NULL, 1003)"""
+PENDING_ROWS = """(11, '{"hot":11,"deep":{"rare":"w11"},"arr":[4,5]}', 2011),
+ (12, '{"hot":12,"other":true}', 2012),
+ (13, 'null', 2013),
+ (14, '{}', 2014)"""
+# Use a typed JSON value so the original FE can plan writes on both Variant
implementations.
+NEW_ROWS = """(21, CAST('{"hot":21,"deep":{"rare":"n21"},"arr":[6,7]}' AS
JSON), 3021),
+ (22, CAST('{"hot":22,"other":0}' AS JSON), 3022)"""
+
+
+# The committed rows come from the old cluster. Specify the replay and new
writes
+# separately because the V2 decoder can give deferred JSON different types.
+PENDING_V2_ROWS = [
+ [11, 0, '{"arr":[4,5],"deep":{"rare":"w11"},"hot":11}', "11", "NULL",
"w11", 2011],
+ [12, 0, '{"hot":12,"other":true}', "12", "NULL", "NULL", 2012],
+ # V2 Block JSON null is stored as an empty root object by the segment
writer.
+ [13, 0, '{}', "NULL", "NULL", "NULL", 2013],
+ [14, 0, '{}', "NULL", "NULL", "NULL", 2014],
+]
+EMPTY_STRING_ROW = "(15, '', 2015)"
+EMPTY_STRING_V2_ROW = [15, 0, '{}', "NULL", "NULL", "NULL", 2015]
+NEW_V2_ROWS = [
+ [21, 0, '{"arr":[6,7],"deep":{"rare":"n21"},"hot":21}', "21", "NULL",
"n21", 3021],
+ [22, 0, '{"hot":22,"other":0}', "22", "NULL", "NULL", 3022],
+]
+
+def run(*args, capture=False, timeout=None):
+ result = subprocess.run(args, text=True, capture_output=capture,
timeout=timeout)
+ if result.returncode:
+ if capture:
+ print(result.stderr, flush=True)
+ result.check_returncode()
+ return result.stdout if capture else None
+
+
+def wait_for(description, probe, timeout=90):
+ deadline = time.monotonic() + timeout
+ last = None
+ while time.monotonic() < deadline:
+ try:
+ result = probe()
+ if result:
+ return result
+ except (OSError, subprocess.SubprocessError, ValueError) as error:
+ last = error
+ time.sleep(1)
+ raise AssertionError(f"Timed out waiting for {description}. Last error:
{last}")
+
+
+def copy_tree(source, dest, skip=()):
+ dest.mkdir(parents=True, exist_ok=True)
+ for entry in source.iterdir():
+ if entry.name not in skip:
+ run("cp", "-a", "--reflink=auto", entry, dest)
+
+
+def copy_package(source, dest, kind):
+ # Each case gets private configuration, logs, PID files and storage.
+ copy_tree(source, dest, ("doris-meta", "storage", "wal", "log",
"minidump"))
+ (dest / "bin" / f"{kind}.pid").unlink(missing_ok=True)
+ (dest / "log").mkdir()
+
+
+def set_config(path, settings):
+ managed = re.compile(r"^\s*(" + "|".join(settings) + r")\s*=")
+ lines = [line for line in path.read_text().splitlines() if not
managed.match(line)]
+ lines.extend(f"{key} = {value}" for key, value in settings.items())
+ path.write_text("\n".join(lines) + "\n")
+
+
+def get_config(path, key):
+ for line in path.read_text().splitlines():
+ if re.match(rf"^\s*{key}\s*=", line):
+ return line.split("=", 1)[1].strip()
+ raise ValueError(f"Missing {key} in {path}")
+
+
+def digest(path):
+ with path.open("rb") as data:
+ return hashlib.file_digest(data, "sha256").hexdigest()
+
+
+def snapshot_files(root, paths):
+ return {str(path.relative_to(root)): digest(path) for path in paths}
+
+
+class Cluster:
+ def __init__(self, args, root):
+ self.args = args
+ self.root = root
+ self.fe_conf = root / "fe/conf/fe.conf"
+ self.be_conf = root / "be/conf/be.conf"
+
+ def helper(self, command, *args):
+ run(self.args.helper, command, "--repo", self.args.old_repo,
"--output-root", self.root,
+ *args, timeout=200)
+
+ def configure_paths(self):
+ set_config(self.fe_conf, {"meta_dir": self.root / "fe/doris-meta"})
+ set_config(self.be_conf, {
+ "storage_root_path": self.root / "be/storage",
+ "group_commit_wal_path": self.root / "be/wal",
+ "enable_debug_points": "true",
+ })
+ for path in (self.root / "fe/doris-meta", self.root / "be/storage",
self.root / "be/wal"):
+ path.mkdir(exist_ok=True)
+
+ def start(self):
+ self.helper("start", "--backend-host", self.args.host, "--timeout",
"100")
+
+ def stop(self):
+ self.helper("stop")
+
+ def sql(self, statement, headers=False):
+ port = get_config(self.fe_conf, "query_port")
+ command = ["mysql", "--protocol=TCP", "-h127.0.0.1", "-P", port,
"-uroot",
+ "--connect-timeout=5", "--batch", "--raw"]
+ if not headers:
+ command.append("--skip-column-names")
+ return run(*command, "-e", statement, capture=True, timeout=45).strip()
+
+ def be_http(self, endpoint, method="GET"):
+ port = get_config(self.be_conf, "webserver_port")
+ req = request.Request(f"http://127.0.0.1:{port}{endpoint}",
method=method)
+ with HTTP.open(req, timeout=15) as response:
+ return response.read().decode()
+
+ def debug(self, point):
+ self.be_http(f"/api/debug_point/add/{point}", "POST")
+
+ def rows(self):
+ data = self.sql(f"""SELECT k, v IS NULL, CAST(v AS STRING),
CAST(v['hot'] AS INT),
+ CAST(v['deep']['old'] AS STRING),
CAST(v['deep']['rare'] AS STRING),
+ tail FROM {DB}.{TABLE} ORDER BY k""")
+ result = []
+ for line in data.splitlines():
+ key, is_null, raw, hot, old, rare, tail = line.split("\t")
+ if raw == "":
+ # CAST returns the contents of a Variant string without JSON
quotes.
+ raw = '""'
+ elif raw != "NULL":
+ raw = json.dumps(json.loads(raw), sort_keys=True,
separators=(",", ":"))
+ result.append([int(key), int(is_null), raw, hot, old, rare,
int(tail)])
+ return result
+
+ def pending_wals(self):
+ return sorted(path for path in (self.root / "be/wal").glob("*/*/*")
+ if path.is_file() and path.stat().st_size > 0)
+
+ def matching_log_lines(self, pattern):
+ lines = []
+ for path in (self.root / "be/log").glob("be.WARNING*"):
+ if not path.is_symlink():
+ lines.extend(line for line in
path.read_text(errors="replace").splitlines()
+ if pattern in line)
+ return lines
+
+ def running_be_digest(self):
+ pid = int((self.root / "be/bin/be.pid").read_text())
+ return digest(Path(f"/proc/{pid}/exe"))
+
+ def tablet(self):
+ result = self.sql(f"SHOW TABLETS FROM {DB}.{TABLE}",
headers=True).splitlines()
+ assert len(result) == 2, result
+ return dict(zip(result[0].split("\t"),
result[1].split("\t")))["TabletId"]
+
+
+def create_table(cluster):
+ cluster.sql(f"""CREATE TABLE {DB}.{TABLE} (
+ k INT NOT NULL, v
VARIANT<PROPERTIES("variant_max_subcolumns_count"="1")>,
+ tail BIGINT NOT NULL
+ ) DUPLICATE KEY(k) DISTRIBUTED BY HASH(k) BUCKETS 1
+ PROPERTIES("replication_num"="1", "disable_auto_compaction"="true",
+ "group_commit_interval_ms"="1000")""")
+
+
+def seed(args):
+ root = args.state / "seed"
+ root.mkdir(parents=True)
+ old_output = args.old_repo / "output"
+ for kind in ("fe", "be"):
+ copy_package(old_output / kind, root / kind, kind)
+ cluster = Cluster(args, root)
+ cluster.helper("configure-ports", "--priority-networks", f"{args.host}/32",
+ "--no-regression-conf")
+ cluster.configure_paths()
+ expected = {}
+ try:
+ cluster.start()
+ print(cluster.sql("SHOW BACKENDS", headers=True), flush=True)
+ cluster.sql(f"CREATE DATABASE {DB}")
+ create_table(cluster)
+ cluster.sql(f"SET group_commit=off_mode; INSERT INTO {DB}.{TABLE}
VALUES {OLD_ROWS}")
+ expected["committed"] = cluster.rows()
+ assert [row[0] for row in expected["committed"]] == [1, 2, 3], expected
+ expected["tablet"] = cluster.tablet()
+ assert cluster.running_be_digest() == digest(old_output /
"be/lib/doris_be")
+ cluster.debug(LOAD_ERROR)
+ cluster.debug(REPLAY_STOP)
+ pending_rows = PENDING_ROWS
+ if args.empty_string_root:
+ pending_rows += ", " + EMPTY_STRING_ROW
+ expected["empty_string_root"] = True
+ print(cluster.sql(f"""SET group_commit=async_mode;
+ INSERT INTO {DB}.{TABLE} VALUES
{pending_rows}"""), flush=True)
+ wait_for("4.0 WAL file", cluster.pending_wals)
+ wait_for("4.0 replay parked by the debug point",
+ lambda: cluster.matching_log_lines(REPLAY_STOP))
+ assert cluster.rows() == expected["committed"], "Pending WAL became
visible on 4.0"
+ finally:
+ cluster.stop()
+ expected["wals"] = snapshot_files(root, cluster.pending_wals())
+ segments = (root /
"be/storage/data").glob(f"*/{expected['tablet']}/*/*.dat")
+ expected["segments"] = snapshot_files(root, sorted(segments))
+ assert expected["wals"] and expected["segments"], expected
+ expected["old_be_sha256"] = digest(root / "be/lib/doris_be")
+ (args.state / "seed.json").write_text(json.dumps(expected, indent=2) +
"\n")
+ print(f"SEED_OK WAL={len(expected['wals'])}
committed_segments={len(expected['segments'])} "
+ f"tablet={expected['tablet']}
old_be_sha256={expected['old_be_sha256']}", flush=True)
+
+
+def prepare_upgrade(args, expected):
+ source = args.state / "seed"
+ root = args.state / args.case
+ root.mkdir()
+ copy_package(args.fe_package or source / "fe", root / "fe", "fe")
+ copy_package(args.be_package, root / "be", "be")
+ for kind in ("fe", "be"):
+ config = Path(kind) / "conf" / f"{kind}.conf"
+ run("cp", source / config, root / config)
+ run("cp", "-a", "--reflink=auto", source / "fe/doris-meta", root / "fe")
+ for name in BE_STATE:
+ run("cp", "-a", "--reflink=auto", source / "be" / name, root / "be")
+ for key in ("wals", "segments"):
+ assert snapshot_files(root, (root / path for path in expected[key]))
== expected[key], key
+ cluster = Cluster(args, root)
+ cluster.configure_paths()
+ if args.enable_variant_v2:
+ set_config(cluster.fe_conf, {"enable_variant_v2": "true"})
+ return cluster
+
+
+def expect_rows(cluster, expected):
+ actual = cluster.rows()
+ assert actual == expected, f"Expected {expected}; got {actual}"
+ return actual
+
+
+def compact(cluster, tablet):
+ def versions():
+ status =
json.loads(cluster.be_http(f"/api/compaction/show?tablet_id={tablet}"))
+ assert not status["missing_rowsets"], status
+ return [tuple(map(int, re.match(r"\[(\d+)-(\d+)\]", rowset).groups()))
+ for rowset in status["rowsets"]]
+
+ before = versions()
+ assert len(before) >= 3, f"No independent old, replayed and new rowsets:
{before}"
+ status = json.loads(cluster.be_http(
+ f"/api/compaction/run?tablet_id={tablet}&compact_type=full", "POST"))
+ assert status["status"].lower() == "success", status
+ expected = [(min(start for start, _ in before), max(end for _, end in
before))]
+
+ def merged():
+ return versions() == expected
+
+ wait_for(f"full compaction to replace {before} with {expected}", merged)
+ print(f"COMPACTION_OK tablet={tablet} before={before} after={versions()}",
flush=True)
+
+
+def check(args):
+ expected = json.loads((args.state / "seed.json").read_text())
+ cluster = prepare_upgrade(args, expected)
+ try:
+ cluster.start()
+ print(cluster.sql("SHOW BACKENDS", headers=True), flush=True)
+ upgraded_digest = cluster.running_be_digest()
+ assert upgraded_digest == digest(args.be_package / "lib/doris_be")
+ assert upgraded_digest != expected["old_be_sha256"]
+ assert cluster.tablet() == expected["tablet"]
+ print(f"UPGRADED_BE case={args.case} sha256={upgraded_digest}",
flush=True)
+ if args.action == "red":
+ failures = wait_for("legacy WAL rejected by Block::deserialize",
+ lambda:
cluster.matching_log_lines(args.red_error))
+ assert snapshot_files(cluster.root, cluster.pending_wals()) ==
expected["wals"]
+ committed = expect_rows(cluster, expected["committed"])
+ print(f"RED_REPLAY_REJECTED case={args.case}
committed_rows={len(committed)} "
+ f"pending_wal_retained=true: {failures[0]}", flush=True)
+ return
+
+ expected_replayed = expected["committed"] + PENDING_V2_ROWS
+ if expected.get("empty_string_root"):
+ expected_replayed.append(EMPTY_STRING_V2_ROW)
+ wait_for("pending WAL rows to become visible",
+ lambda: len(cluster.rows()) >= len(expected_replayed))
+ replayed = expect_rows(cluster, expected_replayed)
+ wal_names = {Path(path).name for path in expected["wals"]}
+ wait_for("successfully replayed WAL to be removed",
+ lambda: not any(path.name in wal_names
+ for path in (cluster.root /
"be/wal").rglob("*")))
+ old_segments = (cluster.root / path for path in expected["segments"])
+ assert snapshot_files(cluster.root, old_segments) ==
expected["segments"]
+ replayed_keys = [row[0] for row in
replayed[len(expected["committed"]):]]
+ print(f"REPLAY_OK case={args.case} rows={len(replayed)} "
+ f"replayed_keys={replayed_keys} pending_wal_removed=true",
flush=True)
+ cluster.sql(f"SET group_commit=off_mode; INSERT INTO {DB}.{TABLE}
VALUES {NEW_ROWS}")
+ before = expect_rows(cluster, expected_replayed + NEW_V2_ROWS)
+ compact(cluster, expected["tablet"])
+ after = expect_rows(cluster, before)
+ rows_digest = hashlib.sha256(json.dumps(after, separators=(",",
":")).encode()).hexdigest()
+ print(f"GREEN_OK case={args.case} rows_before={len(before)}
rows_after={len(after)} "
+ f"rows_sha256={rows_digest}", flush=True)
+ finally:
+ cluster.stop()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--old-repo", type=Path, required=True, help="Checkout
with 4.0 FE/BE output")
+ parser.add_argument("--state", type=Path, required=True, help="Private
directory for snapshots")
+ parser.add_argument("--helper", type=Path, required=True)
+ parser.add_argument("--host", required=True, help="Local address used for
BE registration")
+ parser.add_argument("action", choices=("seed", "red", "green"))
+ parser.add_argument("--case", help="Unique name for the isolated upgrade
run")
+ parser.add_argument("--be-package", type=Path, help="BE package replacing
the 4.0 BE")
+ parser.add_argument("--fe-package", type=Path, help="FE package for a full
upgrade")
+ parser.add_argument("--enable-variant-v2", action="store_true",
+ help="Enable V2 execution when upgrading to a release
branch")
+ parser.add_argument("--empty-string-root", action="store_true",
+ help="Seed a pending empty SQL string and verify it
replays as an object")
+ parser.add_argument("--red-error", default="Unsupported VARIANT block
format",
+ help="Expected replay error from the unmodified BE")
+ args = parser.parse_args()
+ args.state = args.state.resolve()
+ args.old_repo = args.old_repo.resolve()
+ if args.action == "seed":
+ seed(args)
+ else:
+ if args.empty_string_root:
+ parser.error("--empty-string-root applies to seed")
+ if not args.case or not re.fullmatch(r"[a-z0-9][a-z0-9-]*", args.case)
or not args.be_package:
+ parser.error("red and green require a simple --case name and
--be-package")
+ args.be_package = args.be_package.resolve()
+ if args.fe_package:
+ args.fe_package = args.fe_package.resolve()
+ check(args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/regression-test/suites/insert_p0/test_group_commit_variant.groovy
b/regression-test/suites/insert_p0/test_group_commit_variant.groovy
index 15d8304bd4f..56dcb54c63a 100644
--- a/regression-test/suites/insert_p0/test_group_commit_variant.groovy
+++ b/regression-test/suites/insert_p0/test_group_commit_variant.groovy
@@ -15,23 +15,40 @@
// specific language governing permissions and limitations
// under the License.
-suite("test_group_commit_variant") {
+import org.awaitility.Awaitility
+import static java.util.concurrent.TimeUnit.SECONDS
+
+suite("test_group_commit_variant", "nonConcurrent") {
sql "set group_commit=async_mode"
def testTable = "test_group_commit_variant"
+ def waitVisibleRows = { String table, int expected ->
+ Awaitility.await().atMost(60, SECONDS).pollInterval(1, SECONDS).until({
+ def result = sql "select count(*) from ${table}"
+ return result[0][0] == expected
+ })
+ }
+
+ sql "DROP TABLE IF EXISTS ${testTable}"
sql """
CREATE TABLE IF NOT EXISTS ${testTable} (
k bigint,
- var variant
+ id int,
+ v1 variant,
+ note varchar(32),
+ v2 variant,
+ v3 variant,
+ v4 variant,
+ tail bigint
)
UNIQUE KEY(`k`)
- DISTRIBUTED BY HASH (`k`) BUCKETS 5
+ DISTRIBUTED BY HASH (`k`) BUCKETS 1
properties("replication_num" = "1",
"disable_auto_compaction" = "false");
"""
-
+
try {
sql "insert into ${testTable} (k) values (1),(2);"
sql "insert into ${testTable} (k) values (3),(4);"
@@ -40,4 +57,35 @@ suite("test_group_commit_variant") {
logger.info(e.getMessage())
assertTrue(False)
}
+
+ waitVisibleRows(testTable, 4)
+ String loadError = "LoadBlockQueue._finish_group_commit_load.load_error"
+ String replayStop = "WalTable.replay_wals.stop"
+ try {
+ GetDebugPoint().enableDebugPointForAllBEs(loadError)
+ GetDebugPoint().enableDebugPointForAllBEs(replayStop)
+
+ // SQL NULL, JSON null, mixed types and sparse paths must survive WAL
replay.
+ sql """
+ insert into ${testTable} values
+ (11, 101, null, 'sql_null', 'null', '{"p": 1}', CAST('{"n":
{"x": 1}}' AS JSON), 11),
+ (12, 102, '{"p": 1}', 'mixed_type', CAST('{"p": "s"}' AS
JSON), '{"p": [1, 2]}', '{"n": {"x": null}}', 12),
+ (13, 103, '{"a.b": 1}', 'sparse', '{"c": {"d": true}}', '{"e":
[1, {"f": 2}]}', '{"g": 3.5}', 13)
+ """
+ assertEquals(4L, (sql("select count(*) from ${testTable}")[0][0] as
Number).longValue())
+ // Keep failing the original load so only replay can make the new rows
visible.
+ GetDebugPoint().disableDebugPointForAllBEs(replayStop)
+ waitVisibleRows(testTable, 7)
+ order_qt_replayed """
+ select k, id, v1, note, v2, v3, v4, tail,
+ variant_type(v2['p']), cast(v4['n']['x'] as int)
+ from ${testTable} order by k
+ """
+ } finally {
+ try {
+ GetDebugPoint().disableDebugPointForAllBEs(replayStop)
+ } finally {
+ GetDebugPoint().disableDebugPointForAllBEs(loadError)
+ }
+ }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]