hello-stephen commented on code in PR #71194:
URL: https://github.com/apache/doris/pull/71194#discussion_r4780308959


##########
regression-test/suites/insert_p0/test_group_commit_variant.groovy:
##########
@@ -40,4 +57,21 @@ suite("test_group_commit_variant") {
         logger.info(e.getMessage())
         assertTrue(False)
     }
+
+    // Non-empty VARIANT values have to survive the WAL round trip: SQL NULL,
+    // JSON null, one path holding different types in different rows, and 
sparse
+    // paths that are not materialized as subcolumns. Use JSON-typed inputs
+    // for the fields that are queried as objects.
+    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)
+        """
+    waitVisibleRows(testTable, 7)

Review Comment:
   [P3] Force WAL recovery in the Group Commit regression
   
   With the default configuration, async Group Commit queues the original block 
in memory and appends a WAL separately. A successful original commit makes all 
seven rows visible and deletes the WAL without decoding it, so this check 
passes even if WAL replay is broken. Use the abort and replay debug points from 
`test_group_commit_wal_row_count.groovy` to keep the original load invisible 
and then verify the rows after replay.



##########
be/src/core/data_type/data_type_variant_v2.cpp:
##########
@@ -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) {

Review Comment:
   [P2] Keep WAL String normalization out of live block exchange
   
   This branch is also reached from `VDataStreamRecvr::BlockItem::get_block` 
through `Block::deserialize`. During a BE-first upgrade with the 4.0.8 FE, both 
BEs can use execution version 8. If the old sender projects `CAST(s AS 
VARIANT)` for a String containing the five characters `"foo"`, it puts those 
exact bytes in the Variant String root. The new receiver parses that root as 
JSON and strips the quotes, so a subsequent cast back to String returns `foo`. 
Scope the ingestion conversion to WAL replay, or preserve the String payload 
when accepting V1 exchange blocks.



##########
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,

Review Comment:
   [P2] Convert legacy STRUCT and MAP roots before segment assembly
   
   An async V1 insert of `CAST(NAMED_STRUCT('a', 7) AS VARIANT)` writes a typed 
STRUCT root into the WAL. The old scalar-root write path converts it to a JSONB 
object and can commit the row. This handoff reaches 
`prepare_materialized_column`, which rejects STRUCT with `DORIS_CHECK`. 
String-keyed MAP roots follow the same path. These top-level types fail before 
any recursive array handling. Convert them to Variant objects before assembly 
and cover at least one typed root with a legacy WAL fixture.



##########
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);

Review Comment:
   [P2] Preserve distinct legacy paths under repeated JSON object names
   
   A pending V1 async insert can contain the deferred String 
`{"a":{"b":5},"a":{"c":6}}`. Doris 4.0.8 and 4.1.5 flatten these into the 
distinct paths `a.b` and `a.c` and retain both values. Their 
`duplicate_json_path.groovy` suites expect both descendants. Here the V2 
builder rejects the repeated `a` member after JSON syntax parsing succeeds, so 
the entire WAL block fails to replay. Apply the V1 path merge for deferred 
roots and add a fixture that checks both descendants after conversion.



-- 
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]

Reply via email to