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


##########
be/src/format_v2/wal/wal_reader.cpp:
##########
@@ -38,6 +43,57 @@
 namespace doris::format::wal {
 namespace {
 
+Status materialize_legacy_variant_wal_text(ColumnPtr& column) {
+    const auto* nullable = check_and_get_column<ColumnNullable>(*column);
+    const auto& values = nullable ? nullable->get_nested_column() : *column;
+    const auto outer_nulls =
+            nullable ? std::span<const 
NullMap::value_type>(nullable->get_null_map_data().data(),
+                                                            nullable->size())
+                     : std::span<const NullMap::value_type> {};
+    const size_t rows = values.size();
+    RETURN_IF_CATCH_EXCEPTION({
+        bool has_text = false;
+        bool has_other = false;
+        // The old writer deferred parsing only for a scalar root. Parsed
+        // objects and arrays may contain string values that must remain 
strings.
+        visit_variant_v2_values(
+                values, 0, rows, outer_nulls, [](size_t) {},
+                [&](size_t, VariantRef value) {
+                    if (value.is_null()) {
+                        return;
+                    }
+                    const auto kind = value.basic_type();
+                    const bool text = kind == VariantBasicType::SHORT_STRING ||
+                                      (kind == VariantBasicType::PRIMITIVE &&
+                                       value.primitive_id() == 
VariantPrimitiveId::STRING);
+                    has_text |= text;
+                    has_other |= !text;
+                });
+        if (!has_text || has_other) {
+            return Status::OK();
+        }
+
+        auto options = JsonToVariantOptions::current_config();
+        options.throw_on_invalid_json = false;
+        options.legacy_v1_wal = true;
+        JsonStringToVariantEncoder encoder(options);
+        visit_variant_v2_values(
+                values, 0, rows, outer_nulls, [&](size_t) { 
encoder.add_json({}); },
+                [&](size_t, VariantRef value) {
+                    encoder.add_json(value.is_null() ? StringRef {} : 
value.get_string());

Review Comment:
   [P1] Preserve the original root type before reparsing WAL strings
   
   An all-string decoded column can originate from a typed JSONB root as well 
as deferred input text. For example, a V1 async insert of `CAST('"123"' AS 
JSON)` into a Variant column writes a JSONB string root to the WAL. 
`append_materialized_scalar()` already converts that JSONB into the Variant 
string `123`; this call then parses its contents again and stores integer 123. 
The old JSONB-root load path preserved the quotes and parsed once. Retain the 
V1 root-type information and normalize only deferred text, with a reader test 
for JSONB scalar strings.



##########
regression-test/suites/insert_p0/test_group_commit_variant.groovy:
##########
@@ -40,4 +57,28 @@ 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.
+    sql """
+            insert into ${testTable} values
+                (11, 101, null, 'sql_null', 'null', '{"p": 1}', '{"n": {"x": 
1}}', 11),
+                (12, 102, '{"p": 1}', 'mixed_type', '{"p": "s"}', '{"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)
+    order_qt_replayed """
+            select k, id, v1, note, v2, v3, v4, tail
+            from ${testTable} order by k
+        """
+
+    // These rows are already committed. Check their persisted values and
+    // row count after the backend restarts.
+    cluster.restartBackends()

Review Comment:
   [P2] Initialize the Docker cluster before restarting its backends
   
   `cluster` here is the `SuiteCluster` constructed with this suite's name; 
`nonConcurrent` changes scheduling but never initializes it. 
`restartBackends()` invokes `doris-compose restart test_group_commit_variant 
--be-id`, which fails to load the nonexistent compose cluster during a normal 
clean regression run. Run this phase inside a `docker(options)` suite with the 
`docker` group, or use a supported restart mechanism for the actual cluster 
under test.



##########
be/src/exprs/function/parse/variant_string_parse.cpp:
##########
@@ -143,7 +143,11 @@ class JsonTreeCollector {
         if (element.isNull()) {
             _builder.add_null();
         } else if (element.isBool()) {
-            _builder.add_bool(element.getBool());
+            if (_options.legacy_v1_wal) {

Review Comment:
   [P1] Keep booleans inside the legacy JSONB array boundary
   
   The old parser did not turn every boolean into an integer. With the default 
flatten-nested setting disabled, arrays containing objects were serialized as 
JSONB, whose `writeValueAsJsonb()` retained boolean values. A pending V1 
raw-text row `{"arr":[{"flag":true}]}` therefore loaded with `true`, but this 
recursive legacy branch replays it with `1`, silently changing the durable row. 
Reproduce the old representation boundary for these arrays and cover it in the 
WAL replay tests; the current fixture only checks a scalar boolean and an array 
of integers.



##########
be/src/core/data_type/data_type_factory.cpp:
##########
@@ -259,11 +259,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()) {

Review Comment:
   [P1] Handle doc-map writers that predate the doc-mode metadata field
   
   `variant_enable_doc_mode` was added to `PColumnMeta` in `2f60973b98`, but 
the V1 serializer introduced in `075c7daf2e` already appended the doc-value map 
unconditionally. Records from that interval therefore select `V1` here and 
leave an entire map unread. A last Variant can lose its doc values; a following 
column starts in map bytes (a one-row nonnullable BIGINT tail of 42 can decode 
as 0), while ordinary nullable Group Commit columns can fail replay. Account 
for that intermediate layout and add a compatibility fixture with the doc map 
present and the flag absent.



##########
be/src/core/value/variant/variant_v1_wire_reader.cpp:
##########
@@ -0,0 +1,121 @@
+// 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 <limits>
+#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/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_string.h"
+#include "core/value/variant/variant_assembler.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());
+        } 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)});

Review Comment:
   [P1] Preserve literal dots in materialized V1 path components
   
   V1 `column_path` metadata can describe one component named `a.b`, which is 
distinct from two components `a` and `b` (this distinction was explicitly 
preserved by `40ddeabf42`). Passing that path unchanged to the segment 
assembler loses it: `MergeValue` sets depth to one, but 
`ObjectEmitter::open_suffix()` splits the raw path at the dot and emits only 
key `a`. A valid legacy block containing `{"a.b":7}` thus decodes as `{"a":7}`. 
Preserve the component boundaries during assembly and add a V1 wire test that 
distinguishes literal-dot keys from nested paths.



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