hello-stephen commented on code in PR #71194: URL: https://github.com/apache/doris/pull/71194#discussion_r4779160129
########## be/src/core/value/variant/variant_v1_wire_reader.cpp: ########## @@ -0,0 +1,157 @@ +// 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) { + encoder.add_json(root.is_null_at(row) ? json_null : root.get_data_at(row)); Review Comment: [P2] Preserve the legacy normalization of empty deferred roots An old async Group Commit insert with an empty SQL String in a VARIANT column can leave an empty deferred String root in the WAL. Legacy storage ingestion explicitly treats zero-length input as an empty object (`parse_json_to_variant_impl` in the V1 `variant_util.cpp`), but this call passes it to `JsonStringToVariantEncoder` with `throw_on_invalid_json=false`, whose empty-input branch emits an empty Variant string. The V2 shredder persists that scalar, so the same accepted WAL produces `{}` before upgrade and an empty string after upgrade. Normalize non-null empty legacy root text to `{}` here, and change the new block test that currently expects an empty string to verify the legacy replay result. ########## be/src/core/value/variant/variant_v1_wire_reader.cpp: ########## @@ -0,0 +1,157 @@ +// 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) { + encoder.add_json(root.is_null_at(row) ? json_null : root.get_data_at(row)); + } + 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) Review Comment: [P2] Handle Variant-valued array elements before segment assembly V1 can serialize a typed `Array<Variant>` root, for example from `CAST(CAST([1] AS ARRAY<VARIANT>) AS VARIANT)` in an async `INSERT ... VALUES`: the old cast wraps the original array column/type and WAL serialization retains it. Recursive decoding above successfully creates V2 Variant elements, but this assembly call descends through the array into `prepare_materialized_column`, whose primitive whitelist excludes `TYPE_VARIANT` (`variant_assembler_value.cpp:75`). Consequently the pending WAL fails replay with `FATAL_ERROR` (and aborts debug builds). V2's existing array cast already supports encoded Variant leaves, so this value is representable. Convert these leaves before using the segment assembler and add a legacy typed-array root fixture. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
