Coverage Report

Created: 2026-08-10 07:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/partial_update_info.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "storage/partial_update_info.h"
19
20
#include <gen_cpp/olap_file.pb.h>
21
22
#include <cstdint>
23
#include <optional>
24
25
#include "common/consts.h"
26
#include "common/logging.h"
27
#include "core/assert_cast.h"
28
#include "core/block/block.h"
29
#include "core/data_type/data_type_number.h" // IWYU pragma: keep
30
#include "core/value/bitmap_value.h"
31
#include "storage/iterator/olap_data_convertor.h"
32
#include "storage/key/row_key_encoder.h"
33
#include "storage/olap_common.h"
34
#include "storage/rowset/rowset.h"
35
#include "storage/rowset/rowset_writer_context.h"
36
#include "storage/segment/historical_row_retriever.h"
37
#include "storage/segment/vertical_segment_writer.h"
38
#include "storage/tablet/base_tablet.h"
39
#include "storage/tablet/tablet_meta.h"
40
#include "storage/tablet/tablet_schema.h"
41
#include "storage/utils.h"
42
43
namespace doris {
44
namespace {
45
46
302
ColumnBitmap* get_mutable_skip_bitmap_column(Block* block, size_t skip_bitmap_col_idx) {
47
302
    auto skip_bitmap_column =
48
302
            IColumn::mutate(std::move(block->get_by_position(skip_bitmap_col_idx).column));
49
302
    auto* skip_bitmap_column_ptr = assert_cast<ColumnBitmap*>(skip_bitmap_column.get());
50
302
    block->replace_by_position(skip_bitmap_col_idx, std::move(skip_bitmap_column));
51
302
    return skip_bitmap_column_ptr;
52
302
}
53
54
} // namespace
55
56
Status PartialUpdateInfo::init(int64_t tablet_id, int64_t txn_id, const TabletSchema& tablet_schema,
57
                               UniqueKeyUpdateModePB unique_key_update_mode,
58
                               PartialUpdateNewRowPolicyPB policy,
59
                               const std::set<std::string>& partial_update_cols,
60
                               bool is_strict_mode_, int64_t timestamp_ms_, int32_t nano_seconds_,
61
                               const std::string& timezone_,
62
                               const std::string& auto_increment_column,
63
174k
                               int32_t sequence_map_col_uid, int64_t cur_max_version) {
64
174k
    partial_update_mode = unique_key_update_mode;
65
174k
    partial_update_new_key_policy = policy;
66
174k
    partial_update_input_columns = partial_update_cols;
67
174k
    max_version_in_flush_phase = cur_max_version;
68
174k
    sequence_map_col_unqiue_id = sequence_map_col_uid;
69
174k
    timestamp_ms = timestamp_ms_;
70
174k
    nano_seconds = nano_seconds_;
71
174k
    timezone = timezone_;
72
174k
    missing_cids.clear();
73
174k
    update_cids.clear();
74
75
174k
    if (partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
76
        // partial_update_cols should include all key columns
77
10.4k
        for (std::size_t i {0}; i < tablet_schema.num_key_columns(); i++) {
78
7.15k
            const auto key_col = tablet_schema.column(i);
79
7.15k
            if (!partial_update_cols.contains(key_col.name())) {
80
0
                auto msg = fmt::format(
81
0
                        "Unable to do partial update on shadow index's tablet, tablet_id={}, "
82
0
                        "txn_id={}. Missing key column {}.",
83
0
                        tablet_id, txn_id, key_col.name());
84
0
                LOG_WARNING(msg);
85
0
                return Status::Aborted<false>(msg);
86
0
            }
87
7.15k
        }
88
3.32k
    }
89
174k
    if (is_partial_update()) {
90
35.0k
        for (auto i = 0; i < tablet_schema.num_columns(); ++i) {
91
31.4k
            if (partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
92
27.5k
                auto tablet_column = tablet_schema.column(i);
93
27.5k
                if (!partial_update_input_columns.contains(tablet_column.name())) {
94
16.0k
                    missing_cids.emplace_back(i);
95
16.0k
                    if (!tablet_column.has_default_value() && !tablet_column.is_nullable() &&
96
16.0k
                        tablet_schema.auto_increment_column() != tablet_column.name()) {
97
1.20k
                        can_insert_new_rows_in_partial_update = false;
98
1.20k
                    }
99
16.0k
                } else {
100
11.4k
                    update_cids.emplace_back(i);
101
11.4k
                }
102
27.5k
                if (auto_increment_column == tablet_column.name()) {
103
241
                    is_schema_contains_auto_inc_column = true;
104
241
                }
105
27.5k
            } else {
106
                // in flexible partial update, missing cids is all non sort keys' cid
107
3.90k
                if (i >= tablet_schema.num_key_columns()) {
108
3.62k
                    missing_cids.emplace_back(i);
109
3.62k
                }
110
3.90k
            }
111
31.4k
        }
112
3.59k
        _generate_default_values_for_missing_cids(tablet_schema);
113
3.59k
    }
114
174k
    is_strict_mode = is_strict_mode_;
115
174k
    is_input_columns_contains_auto_inc_column =
116
174k
            is_fixed_partial_update() &&
117
174k
            partial_update_input_columns.contains(auto_increment_column);
118
174k
    return Status::OK();
119
174k
}
120
121
70
void PartialUpdateInfo::to_pb(PartialUpdateInfoPB* partial_update_info_pb) const {
122
70
    partial_update_info_pb->set_partial_update_mode(partial_update_mode);
123
70
    partial_update_info_pb->set_partial_update_new_key_policy(partial_update_new_key_policy);
124
70
    partial_update_info_pb->set_max_version_in_flush_phase(max_version_in_flush_phase);
125
560
    for (const auto& col : partial_update_input_columns) {
126
560
        partial_update_info_pb->add_partial_update_input_columns(col);
127
560
    }
128
616
    for (auto cid : missing_cids) {
129
616
        partial_update_info_pb->add_missing_cids(cid);
130
616
    }
131
560
    for (auto cid : update_cids) {
132
560
        partial_update_info_pb->add_update_cids(cid);
133
560
    }
134
70
    partial_update_info_pb->set_can_insert_new_rows_in_partial_update(
135
70
            can_insert_new_rows_in_partial_update);
136
70
    partial_update_info_pb->set_is_strict_mode(is_strict_mode);
137
70
    partial_update_info_pb->set_timestamp_ms(timestamp_ms);
138
70
    partial_update_info_pb->set_nano_seconds(nano_seconds);
139
70
    partial_update_info_pb->set_timezone(timezone);
140
70
    partial_update_info_pb->set_is_input_columns_contains_auto_inc_column(
141
70
            is_input_columns_contains_auto_inc_column);
142
70
    partial_update_info_pb->set_is_schema_contains_auto_inc_column(
143
70
            is_schema_contains_auto_inc_column);
144
616
    for (const auto& value : default_values) {
145
616
        partial_update_info_pb->add_default_values(value);
146
616
    }
147
70
}
148
149
0
void PartialUpdateInfo::from_pb(PartialUpdateInfoPB* partial_update_info_pb) {
150
0
    if (!partial_update_info_pb->has_partial_update_mode()) {
151
        // for backward compatibility
152
0
        if (partial_update_info_pb->is_partial_update()) {
153
0
            partial_update_mode = UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS;
154
0
        } else {
155
0
            partial_update_mode = UniqueKeyUpdateModePB::UPSERT;
156
0
        }
157
0
    } else {
158
0
        partial_update_mode = partial_update_info_pb->partial_update_mode();
159
0
    }
160
0
    if (partial_update_info_pb->has_partial_update_new_key_policy()) {
161
0
        partial_update_new_key_policy = partial_update_info_pb->partial_update_new_key_policy();
162
0
    }
163
0
    max_version_in_flush_phase = partial_update_info_pb->has_max_version_in_flush_phase()
164
0
                                         ? partial_update_info_pb->max_version_in_flush_phase()
165
0
                                         : -1;
166
0
    partial_update_input_columns.clear();
167
0
    for (const auto& col : partial_update_info_pb->partial_update_input_columns()) {
168
0
        partial_update_input_columns.insert(col);
169
0
    }
170
0
    missing_cids.clear();
171
0
    for (auto cid : partial_update_info_pb->missing_cids()) {
172
0
        missing_cids.push_back(cid);
173
0
    }
174
0
    update_cids.clear();
175
0
    for (auto cid : partial_update_info_pb->update_cids()) {
176
0
        update_cids.push_back(cid);
177
0
    }
178
0
    can_insert_new_rows_in_partial_update =
179
0
            partial_update_info_pb->can_insert_new_rows_in_partial_update();
180
0
    is_strict_mode = partial_update_info_pb->is_strict_mode();
181
0
    timestamp_ms = partial_update_info_pb->timestamp_ms();
182
0
    timezone = partial_update_info_pb->timezone();
183
0
    is_input_columns_contains_auto_inc_column =
184
0
            partial_update_info_pb->is_input_columns_contains_auto_inc_column();
185
0
    is_schema_contains_auto_inc_column =
186
0
            partial_update_info_pb->is_schema_contains_auto_inc_column();
187
0
    if (partial_update_info_pb->has_nano_seconds()) {
188
0
        nano_seconds = partial_update_info_pb->nano_seconds();
189
0
    }
190
0
    default_values.clear();
191
0
    for (const auto& value : partial_update_info_pb->default_values()) {
192
0
        default_values.push_back(value);
193
0
    }
194
0
}
195
196
0
std::string PartialUpdateInfo::summary() const {
197
0
    std::string mode;
198
0
    switch (partial_update_mode) {
199
0
    case UniqueKeyUpdateModePB::UPSERT:
200
0
        mode = "upsert";
201
0
        break;
202
0
    case UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS:
203
0
        mode = "fixed partial update";
204
0
        break;
205
0
    case UniqueKeyUpdateModePB::UPDATE_FLEXIBLE_COLUMNS:
206
0
        mode = "flexible partial update";
207
0
        break;
208
0
    }
209
0
    return fmt::format(
210
0
            "mode={}, update_cids={}, missing_cids={}, is_strict_mode={}, "
211
0
            "max_version_in_flush_phase={}",
212
0
            mode, update_cids.size(), missing_cids.size(), is_strict_mode,
213
0
            max_version_in_flush_phase);
214
0
}
215
216
Status PartialUpdateInfo::handle_new_key(const TabletSchema& tablet_schema,
217
                                         const std::function<std::string()>& line,
218
588
                                         BitmapValue* skip_bitmap) {
219
588
    switch (partial_update_new_key_policy) {
220
554
    case doris::PartialUpdateNewRowPolicyPB::APPEND: {
221
554
        if (partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
222
261
            if (!can_insert_new_rows_in_partial_update) {
223
10
                std::string error_column;
224
18
                for (auto cid : missing_cids) {
225
18
                    const TabletColumn& col = tablet_schema.column(cid);
226
18
                    if (!col.has_default_value() && !col.is_nullable() &&
227
18
                        !(tablet_schema.auto_increment_column() == col.name())) {
228
10
                        error_column = col.name();
229
10
                        break;
230
10
                    }
231
18
                }
232
10
                return Status::Error<ErrorCode::INVALID_SCHEMA, false>(
233
10
                        "the unmentioned column `{}` should have default value or be nullable "
234
10
                        "for newly inserted rows in non-strict mode partial update",
235
10
                        error_column);
236
10
            }
237
293
        } else if (partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FLEXIBLE_COLUMNS) {
238
293
            DCHECK(skip_bitmap != nullptr);
239
293
            bool can_insert_new_row {true};
240
293
            std::string error_column;
241
4.17k
            for (auto cid : missing_cids) {
242
4.17k
                const TabletColumn& col = tablet_schema.column(cid);
243
4.17k
                if (skip_bitmap->contains(col.unique_id()) && !col.has_default_value() &&
244
4.17k
                    !col.is_nullable() && !col.is_auto_increment()) {
245
0
                    error_column = col.name();
246
0
                    can_insert_new_row = false;
247
0
                    break;
248
0
                }
249
4.17k
            }
250
293
            if (!can_insert_new_row) {
251
0
                return Status::Error<ErrorCode::INVALID_SCHEMA, false>(
252
0
                        "the unmentioned column `{}` should have default value or be "
253
0
                        "nullable for newly inserted rows in non-strict mode flexible partial "
254
0
                        "update",
255
0
                        error_column);
256
0
            }
257
293
        }
258
554
    } break;
259
544
    case doris::PartialUpdateNewRowPolicyPB::ERROR: {
260
34
        return Status::Error<ErrorCode::NEW_ROWS_IN_PARTIAL_UPDATE, false>(
261
34
                "Can't append new rows in partial update when partial_update_new_key_behavior is "
262
34
                "ERROR. Row with key=[{}] is not in table.",
263
34
                line());
264
554
    } break;
265
588
    }
266
544
    return Status::OK();
267
588
}
268
269
void PartialUpdateInfo::_generate_default_values_for_missing_cids(
270
3.59k
        const TabletSchema& tablet_schema) {
271
19.6k
    for (unsigned int cur_cid : missing_cids) {
272
19.6k
        const auto& column = tablet_schema.column(cur_cid);
273
19.6k
        if (column.has_default_value()) {
274
7.29k
            std::string default_value;
275
7.29k
            if (UNLIKELY((column.type() == FieldType::OLAP_FIELD_TYPE_DATETIMEV2 ||
276
7.29k
                          column.type() == FieldType::OLAP_FIELD_TYPE_TIMESTAMP_NS ||
277
7.29k
                          column.type() == FieldType::OLAP_FIELD_TYPE_TIMESTAMPTZ) &&
278
7.29k
                         to_lower(column.default_value()).find(to_lower("CURRENT_TIMESTAMP")) !=
279
7.29k
                                 std::string::npos)) {
280
133
                auto pos = to_lower(column.default_value()).find('(');
281
133
                if (pos == std::string::npos) {
282
64
                    DateV2Value<DateTimeV2ValueType> dtv;
283
64
                    dtv.from_unixtime(timestamp_ms / 1000, timezone);
284
64
                    default_value = dtv.to_string();
285
64
                    if (column.type() == FieldType::OLAP_FIELD_TYPE_TIMESTAMPTZ) {
286
0
                        default_value += timezone;
287
0
                    }
288
69
                } else {
289
69
                    int precision = std::stoi(column.default_value().substr(pos + 1));
290
69
                    DateV2Value<DateTimeV2ValueType> dtv;
291
69
                    dtv.from_unixtime(timestamp_ms / 1000, nano_seconds, timezone, precision);
292
69
                    if (column.type() == FieldType::OLAP_FIELD_TYPE_TIMESTAMP_NS) {
293
0
                        const int32_t scale_factor = static_cast<int32_t>(int_exp10(9 - precision));
294
0
                        const int32_t truncated_nano_seconds =
295
0
                                nano_seconds / scale_factor * scale_factor;
296
0
                        TimeStampNsValue value;
297
0
                        DORIS_CHECK(value.from_datetime(
298
0
                                dtv, static_cast<uint16_t>(
299
0
                                             truncated_nano_seconds %
300
0
                                             (TimeStampNsValue::NANOS_PER_SECOND / 1000000))));
301
0
                        default_value = value.to_string(precision);
302
69
                    } else {
303
69
                        default_value = dtv.to_string();
304
69
                    }
305
69
                    if (column.type() == FieldType::OLAP_FIELD_TYPE_TIMESTAMPTZ) {
306
0
                        default_value += timezone;
307
0
                    }
308
69
                }
309
7.15k
            } else if (UNLIKELY(column.type() == FieldType::OLAP_FIELD_TYPE_DATEV2 &&
310
7.15k
                                to_lower(column.default_value()).find(to_lower("CURRENT_DATE")) !=
311
7.15k
                                        std::string::npos)) {
312
81
                DateV2Value<DateV2ValueType> dv;
313
81
                dv.from_unixtime(timestamp_ms / 1000, timezone);
314
81
                default_value = dv.to_string();
315
7.07k
            } else if (UNLIKELY(column.type() == FieldType::OLAP_FIELD_TYPE_BITMAP &&
316
7.07k
                                to_lower(column.default_value()).find(to_lower("BITMAP_EMPTY")) !=
317
7.07k
                                        std::string::npos)) {
318
0
                BitmapValue v = BitmapValue {};
319
0
                default_value = v.to_string();
320
7.07k
            } else {
321
7.07k
                default_value = column.default_value();
322
7.07k
            }
323
7.29k
            default_values.emplace_back(default_value);
324
12.3k
        } else {
325
            // place an empty string here
326
12.3k
            default_values.emplace_back();
327
12.3k
        }
328
19.6k
    }
329
3.59k
    CHECK_EQ(missing_cids.size(), default_values.size());
330
3.59k
}
331
332
31
bool FixedReadPlan::empty() const {
333
31
    return plan.empty();
334
31
}
335
336
22.8k
void FixedReadPlan::prepare_to_read(const RowLocation& row_location, size_t pos) {
337
22.8k
    plan[row_location.rowset_id][row_location.segment_id].emplace_back(row_location.row_id, pos);
338
22.8k
}
339
340
// read columns by read plan
341
// read_index: ori_pos-> block_idx
342
Status FixedReadPlan::read_columns_by_plan(
343
        const TabletSchema& tablet_schema, std::vector<uint32_t> cids_to_read,
344
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset, Block& block,
345
        std::map<uint32_t, uint32_t>* read_index, bool force_read_old_delete_signs,
346
1.34k
        const signed char* __restrict cur_delete_signs) const {
347
1.34k
    if (force_read_old_delete_signs) {
348
        // always read delete sign column from historical data
349
1.31k
        if (block.get_position_by_name(DELETE_SIGN) == -1) {
350
747
            auto del_col_cid = tablet_schema.field_index(DELETE_SIGN);
351
747
            cids_to_read.emplace_back(del_col_cid);
352
747
            block.swap(tablet_schema.create_block_by_cids(cids_to_read));
353
747
        }
354
1.31k
    }
355
1.34k
    bool has_row_column = tablet_schema.has_row_store_for_all_columns();
356
1.34k
    std::optional<Block::ScopedMutableColumns> mutable_columns_guard;
357
1.34k
    MutableColumns* mutable_columns = nullptr;
358
1.34k
    if (!has_row_column) {
359
1.08k
        mutable_columns_guard.emplace(block);
360
1.08k
        mutable_columns = &mutable_columns_guard->mutable_columns();
361
1.08k
    }
362
1.34k
    uint32_t read_idx = 0;
363
1.34k
    for (const auto& [rowset_id, segment_row_mappings] : plan) {
364
666
        for (const auto& [segment_id, mappings] : segment_row_mappings) {
365
666
            auto rowset_iter = rsid_to_rowset.find(rowset_id);
366
666
            CHECK(rowset_iter != rsid_to_rowset.end());
367
666
            std::vector<uint32_t> rids;
368
22.7k
            for (auto [rid, pos] : mappings) {
369
22.7k
                if (cur_delete_signs && cur_delete_signs[pos]) {
370
1
                    continue;
371
1
                }
372
22.7k
                rids.emplace_back(rid);
373
22.7k
                (*read_index)[static_cast<uint32_t>(pos)] = read_idx++;
374
22.7k
            }
375
666
            if (has_row_column) {
376
190
                auto st = BaseTablet::fetch_value_through_row_column(
377
190
                        rowset_iter->second, tablet_schema, segment_id, rids, cids_to_read, block);
378
190
                if (!st.ok()) {
379
0
                    LOG(WARNING) << "failed to fetch value through row column";
380
0
                    return st;
381
0
                }
382
190
                continue;
383
190
            }
384
2.68k
            for (size_t cid = 0; cid < mutable_columns->size(); ++cid) {
385
2.20k
                TabletColumn tablet_column = tablet_schema.column(cids_to_read[cid]);
386
2.20k
                auto st = doris::BaseTablet::fetch_value_by_rowids(rowset_iter->second, segment_id,
387
2.20k
                                                                   rids, tablet_column,
388
2.20k
                                                                   (*mutable_columns)[cid]);
389
                // set read value to output block
390
2.20k
                if (!st.ok()) {
391
0
                    LOG(WARNING) << "failed to fetch value";
392
0
                    return st;
393
0
                }
394
2.20k
            }
395
476
        }
396
665
    }
397
1.34k
    return Status::OK();
398
1.34k
}
399
400
Status FixedReadPlan::fill_old_delete_signs(const Block& old_value_block,
401
                                            const std::map<uint32_t, uint32_t>& read_index,
402
                                            size_t num_rows,
403
1.29k
                                            std::vector<signed char>* old_delete_signs) const {
404
1.29k
    if (old_delete_signs == nullptr) {
405
1.27k
        return Status::OK();
406
1.27k
    }
407
21
    const auto* old_delete_sign_column_data =
408
21
            BaseTablet::get_delete_sign_column_data(old_value_block);
409
21
    if (old_delete_sign_column_data == nullptr) {
410
0
        return Status::InternalError("old delete signs column not found, block: {}",
411
0
                                     old_value_block.dump_structure());
412
0
    }
413
21
    old_delete_signs->assign(num_rows, 0);
414
71
    for (size_t idx = 0; idx < num_rows; ++idx) {
415
50
        auto it = read_index.find(cast_set<uint32_t>(idx));
416
50
        if (it != read_index.end()) {
417
32
            (*old_delete_signs)[idx] = old_delete_sign_column_data[it->second];
418
32
        }
419
50
    }
420
21
    return Status::OK();
421
21
}
422
423
Status FixedReadPlan::fill_missing_columns(
424
        const segment_v2::HistoricalRowRetrieverContext& historical_context,
425
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset,
426
        const TabletSchema& tablet_schema, Block& full_block,
427
        const std::vector<bool>& use_default_or_null_flag, bool has_default_or_nullable,
428
        uint32_t segment_start_pos, const Block* block,
429
1.28k
        std::vector<signed char>* old_delete_signs) const {
430
1.28k
    auto mutable_full_columns_guard = full_block.mutate_columns_scoped();
431
1.28k
    auto& mutable_full_columns = mutable_full_columns_guard.mutable_columns();
432
    // create old value columns
433
1.28k
    DCHECK(historical_context.partial_update_info != nullptr);
434
1.28k
    DCHECK(historical_context.tablet_schema != nullptr);
435
1.28k
    const auto& partial_update_info = *historical_context.partial_update_info;
436
1.28k
    const auto& missing_cids = partial_update_info.missing_cids;
437
1.28k
    bool have_input_seq_column = false;
438
1.28k
    if (tablet_schema.has_sequence_col()) {
439
244
        const std::vector<uint32_t>& including_cids = partial_update_info.update_cids;
440
244
        have_input_seq_column =
441
244
                (std::find(including_cids.cbegin(), including_cids.cend(),
442
244
                           tablet_schema.sequence_col_idx()) != including_cids.cend());
443
244
    }
444
445
1.28k
    auto old_value_block = tablet_schema.create_block_by_cids(missing_cids);
446
1.28k
    CHECK_EQ(missing_cids.size(), old_value_block.columns());
447
448
    // segment pos to write -> rowid to read in old_value_block
449
1.28k
    std::map<uint32_t, uint32_t> read_index;
450
1.28k
    RETURN_IF_ERROR(read_columns_by_plan(tablet_schema, missing_cids, rsid_to_rowset,
451
1.28k
                                         old_value_block, &read_index, true, nullptr));
452
453
1.28k
    const auto* old_delete_sign_column_data =
454
1.28k
            BaseTablet::get_delete_sign_column_data(old_value_block);
455
1.28k
    if (old_delete_sign_column_data == nullptr) {
456
0
        return Status::InternalError("old delete signs column not found, block: {}",
457
0
                                     old_value_block.dump_structure());
458
0
    }
459
1.28k
    RETURN_IF_ERROR(fill_old_delete_signs(old_value_block, read_index,
460
1.28k
                                          use_default_or_null_flag.size(), old_delete_signs));
461
    // build default value columns
462
1.28k
    auto default_value_block = old_value_block.clone_empty();
463
1.28k
    RETURN_IF_ERROR(BaseTablet::generate_default_value_block(tablet_schema, missing_cids,
464
1.28k
                                                             partial_update_info.default_values,
465
1.28k
                                                             old_value_block, default_value_block));
466
1.28k
    auto mutable_default_value_columns_guard = default_value_block.mutate_columns_scoped();
467
1.28k
    auto& mutable_default_value_columns = mutable_default_value_columns_guard.mutable_columns();
468
469
    // fill all missing value from mutable_old_columns, need to consider default value and null value
470
25.4k
    for (auto idx = 0; idx < use_default_or_null_flag.size(); idx++) {
471
24.1k
        auto segment_pos = idx + segment_start_pos;
472
24.1k
        auto pos_in_old_block = read_index[segment_pos];
473
474
113k
        for (auto i = 0; i < missing_cids.size(); ++i) {
475
            // if the column has default value, fill it with default value
476
            // otherwise, if the column is nullable, fill it with null value
477
89.7k
            const auto& tablet_column = tablet_schema.column(missing_cids[i]);
478
89.7k
            auto& missing_col = mutable_full_columns[missing_cids[i]];
479
480
89.7k
            bool should_use_default = use_default_or_null_flag[idx];
481
89.7k
            if (!should_use_default) {
482
79.2k
                bool old_row_delete_sign = old_delete_sign_column_data[pos_in_old_block] != 0;
483
79.2k
                if (old_row_delete_sign) {
484
153
                    if (!tablet_schema.has_sequence_col()) {
485
72
                        should_use_default = true;
486
81
                    } else if (have_input_seq_column || (!tablet_column.is_seqeunce_col())) {
487
                        // to keep the sequence column value not decreasing, we should read values of seq column
488
                        // from old rows even if the old row is deleted when the input don't specify the sequence column, otherwise
489
                        // it may cause the merge-on-read based compaction to produce incorrect results
490
77
                        should_use_default = true;
491
77
                    }
492
153
                }
493
79.2k
            }
494
495
89.7k
            if (should_use_default) {
496
10.6k
                if (tablet_column.has_default_value()) {
497
2.66k
                    missing_col->insert_from(*mutable_default_value_columns[i], 0);
498
7.96k
                } else if (tablet_column.is_nullable()) {
499
6.63k
                    auto* nullable_column = assert_cast<ColumnNullable*>(missing_col.get());
500
6.63k
                    nullable_column->insert_many_defaults(1);
501
6.63k
                } else if (tablet_schema.auto_increment_column() == tablet_column.name()) {
502
41
                    const auto& column = *DORIS_TRY(
503
41
                            historical_context.tablet_schema->column(tablet_column.name()));
504
41
                    DCHECK(column.type() == FieldType::OLAP_FIELD_TYPE_BIGINT);
505
41
                    auto* auto_inc_column = assert_cast<ColumnInt64*>(missing_col.get());
506
41
                    int pos = block->get_position_by_name(BeConsts::PARTIAL_UPDATE_AUTO_INC_COL);
507
41
                    if (pos == -1) {
508
0
                        return Status::InternalError("auto increment column not found in block {}",
509
0
                                                     block->dump_structure());
510
0
                    }
511
41
                    auto_inc_column->insert_from(*block->get_by_position(pos).column.get(), idx);
512
1.29k
                } else {
513
                    // If the control flow reaches this branch, the column neither has default value
514
                    // nor is nullable. It means that the row's delete sign is marked, and the value
515
                    // columns are useless and won't be read. So we can just put arbitary values in the cells
516
1.29k
                    missing_col->insert_default();
517
1.29k
                }
518
79.0k
            } else {
519
79.0k
                missing_col->insert_from(*old_value_block.get_by_position(i).column,
520
79.0k
                                         pos_in_old_block);
521
79.0k
            }
522
89.7k
        }
523
24.1k
    }
524
1.28k
    return Status::OK();
525
1.28k
}
526
527
void FlexibleReadPlan::prepare_to_read(const RowLocation& row_location, size_t pos,
528
1.79k
                                       const BitmapValue& skip_bitmap) {
529
1.79k
    if (!use_row_store) {
530
3.90k
        for (uint64_t col_uid : skip_bitmap) {
531
3.90k
            plan[row_location.rowset_id][row_location.segment_id][static_cast<uint32_t>(col_uid)]
532
3.90k
                    .emplace_back(row_location.row_id, pos);
533
3.90k
        }
534
935
    } else {
535
856
        row_store_plan[row_location.rowset_id][row_location.segment_id].emplace_back(
536
856
                row_location.row_id, pos);
537
856
    }
538
1.79k
}
539
540
Status FlexibleReadPlan::read_columns_by_plan(
541
        const TabletSchema& tablet_schema,
542
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset, Block& old_value_block,
543
149
        std::map<uint32_t, std::map<uint32_t, uint32_t>>* read_index) const {
544
149
    auto mutable_columns_guard = old_value_block.mutate_columns_scoped();
545
149
    auto& mutable_columns = mutable_columns_guard.mutable_columns();
546
547
    // cid -> next rid to fill in block
548
149
    std::map<uint32_t, uint32_t> next_read_idx;
549
2.26k
    for (uint32_t cid {0}; cid < tablet_schema.num_columns(); cid++) {
550
2.12k
        next_read_idx[cid] = 0;
551
2.12k
    }
552
553
182
    for (const auto& [rowset_id, segment_mappings] : plan) {
554
182
        for (const auto& [segment_id, uid_mappings] : segment_mappings) {
555
1.48k
            for (const auto& [col_uid, mappings] : uid_mappings) {
556
1.48k
                auto rowset_iter = rsid_to_rowset.find(rowset_id);
557
1.48k
                CHECK(rowset_iter != rsid_to_rowset.end());
558
1.48k
                auto cid = tablet_schema.field_index(col_uid);
559
1.48k
                DCHECK_NE(cid, -1);
560
1.48k
                DCHECK_GE(cid, tablet_schema.num_key_columns());
561
1.48k
                std::vector<uint32_t> rids;
562
3.92k
                for (auto [rid, pos] : mappings) {
563
3.92k
                    rids.emplace_back(rid);
564
3.92k
                    (*read_index)[cid][static_cast<uint32_t>(pos)] = next_read_idx[cid]++;
565
3.92k
                }
566
567
1.48k
                TabletColumn tablet_column = tablet_schema.column(cid);
568
1.48k
                auto idx = cid - tablet_schema.num_key_columns();
569
1.48k
                RETURN_IF_ERROR(doris::BaseTablet::fetch_value_by_rowids(
570
1.48k
                        rowset_iter->second, segment_id, rids, tablet_column,
571
1.48k
                        mutable_columns[idx]));
572
1.48k
            }
573
182
        }
574
182
    }
575
    // !!!ATTENTION!!!: columns in block may have different size because every row has different columns to update
576
149
    return Status::OK();
577
149
}
578
579
Status FlexibleReadPlan::read_columns_by_plan(
580
        const TabletSchema& tablet_schema, const std::vector<uint32_t>& cids_to_read,
581
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset, Block& old_value_block,
582
123
        std::map<uint32_t, uint32_t>* read_index) const {
583
123
    DCHECK(use_row_store);
584
123
    uint32_t read_idx = 0;
585
161
    for (const auto& [rowset_id, segment_row_mappings] : row_store_plan) {
586
161
        for (const auto& [segment_id, mappings] : segment_row_mappings) {
587
161
            auto rowset_iter = rsid_to_rowset.find(rowset_id);
588
161
            CHECK(rowset_iter != rsid_to_rowset.end());
589
161
            std::vector<uint32_t> rids;
590
863
            for (auto [rid, pos] : mappings) {
591
863
                rids.emplace_back(rid);
592
863
                (*read_index)[static_cast<uint32_t>(pos)] = read_idx++;
593
863
            }
594
161
            auto st = BaseTablet::fetch_value_through_row_column(rowset_iter->second, tablet_schema,
595
161
                                                                 segment_id, rids, cids_to_read,
596
161
                                                                 old_value_block);
597
161
            if (!st.ok()) {
598
0
                LOG(WARNING) << "failed to fetch value through row column";
599
0
                return st;
600
0
            }
601
161
        }
602
161
    }
603
123
    return Status::OK();
604
123
}
605
606
Status FlexibleReadPlan::fill_non_primary_key_columns(
607
        const segment_v2::HistoricalRowRetrieverContext& historical_context,
608
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset,
609
        const TabletSchema& tablet_schema, Block& full_block,
610
        const std::vector<bool>& use_default_or_null_flag, bool has_default_or_nullable,
611
        uint32_t segment_start_pos, uint32_t block_start_pos, const Block* block,
612
272
        std::vector<BitmapValue>* skip_bitmaps) const {
613
272
    auto mutable_full_columns_guard = full_block.mutate_columns_scoped();
614
272
    auto& mutable_full_columns = mutable_full_columns_guard.mutable_columns();
615
272
    DCHECK(historical_context.partial_update_info != nullptr);
616
617
    // missing_cids are all non sort key columns' cids
618
272
    const auto& non_sort_key_cids = historical_context.partial_update_info->missing_cids;
619
272
    auto old_value_block = tablet_schema.create_block_by_cids(non_sort_key_cids);
620
272
    CHECK_EQ(non_sort_key_cids.size(), old_value_block.columns());
621
622
272
    if (!use_row_store) {
623
149
        RETURN_IF_ERROR(fill_non_primary_key_columns_for_column_store(
624
149
                historical_context, rsid_to_rowset, tablet_schema, non_sort_key_cids,
625
149
                old_value_block, mutable_full_columns, use_default_or_null_flag,
626
149
                has_default_or_nullable, segment_start_pos, block_start_pos, block, skip_bitmaps));
627
149
    } else {
628
123
        RETURN_IF_ERROR(fill_non_primary_key_columns_for_row_store(
629
123
                historical_context, rsid_to_rowset, tablet_schema, non_sort_key_cids,
630
123
                old_value_block, mutable_full_columns, use_default_or_null_flag,
631
123
                has_default_or_nullable, segment_start_pos, block_start_pos, block, skip_bitmaps));
632
123
    }
633
272
    return Status::OK();
634
272
}
635
636
static void fill_non_primary_key_cell_for_column_store(
637
        const TabletColumn& tablet_column, uint32_t cid, MutableColumnPtr& new_col,
638
        const IColumn& default_value_col, const IColumn& old_value_col, const IColumn& cur_col,
639
        std::size_t block_pos, uint32_t segment_pos, bool skipped, bool row_has_sequence_col,
640
        bool use_default, const signed char* delete_sign_column_data,
641
        const TabletSchema& tablet_schema,
642
        std::map<uint32_t, std::map<uint32_t, uint32_t>>& read_index,
643
17.0k
        const PartialUpdateInfo* info) {
644
17.0k
    if (skipped) {
645
4.80k
        DCHECK(cid != tablet_schema.skip_bitmap_col_idx());
646
4.80k
        DCHECK(cid != tablet_schema.version_col_idx());
647
4.80k
        DCHECK(!tablet_column.is_row_store_column());
648
649
4.80k
        if (!use_default) {
650
3.92k
            if (delete_sign_column_data != nullptr) {
651
3.92k
                bool old_row_delete_sign = false;
652
3.92k
                if (auto it = read_index[tablet_schema.delete_sign_idx()].find(segment_pos);
653
3.92k
                    it != read_index[tablet_schema.delete_sign_idx()].end()) {
654
3.80k
                    old_row_delete_sign = (delete_sign_column_data[it->second] != 0);
655
3.80k
                }
656
657
3.92k
                if (old_row_delete_sign) {
658
7
                    if (!tablet_schema.has_sequence_col()) {
659
2
                        use_default = true;
660
5
                    } else if (row_has_sequence_col ||
661
5
                               (!tablet_column.is_seqeunce_col() &&
662
5
                                (tablet_column.unique_id() != info->sequence_map_col_uid()))) {
663
                        // to keep the sequence column value not decreasing, we should read values of seq column(and seq map column)
664
                        // from old rows even if the old row is deleted when the input don't specify the sequence column, otherwise
665
                        // it may cause the merge-on-read based compaction to produce incorrect results
666
3
                        use_default = true;
667
3
                    }
668
7
                }
669
3.92k
            }
670
3.92k
        }
671
4.80k
        if (!use_default && tablet_column.is_on_update_current_timestamp()) {
672
6
            use_default = true;
673
6
        }
674
4.80k
        if (use_default) {
675
885
            if (tablet_column.has_default_value()) {
676
436
                new_col->insert_from(default_value_col, 0);
677
449
            } else if (tablet_column.is_nullable()) {
678
426
                assert_cast<ColumnNullable*, TypeCheckOnRelease::DISABLE>(new_col.get())
679
426
                        ->insert_many_defaults(1);
680
426
            } else if (tablet_column.is_auto_increment()) {
681
                // In flexible partial update, the skip bitmap indicates whether a cell
682
                // is specified in the original load, so the generated auto-increment value is filled
683
                // in current block in place if needed rather than using a seperate column to
684
                // store the generated auto-increment value in fixed partial update
685
2
                new_col->insert_from(cur_col, block_pos);
686
21
            } else {
687
21
                new_col->insert_default();
688
21
            }
689
3.91k
        } else {
690
3.91k
            auto pos_in_old_block = read_index.at(cid).at(segment_pos);
691
3.91k
            new_col->insert_from(old_value_col, pos_in_old_block);
692
3.91k
        }
693
12.2k
    } else {
694
12.2k
        new_col->insert_from(cur_col, block_pos);
695
12.2k
    }
696
17.0k
}
697
698
Status FlexibleReadPlan::fill_non_primary_key_columns_for_column_store(
699
        const segment_v2::HistoricalRowRetrieverContext& historical_context,
700
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset,
701
        const TabletSchema& tablet_schema, const std::vector<uint32_t>& non_sort_key_cids,
702
        Block& old_value_block, MutableColumns& mutable_full_columns,
703
        const std::vector<bool>& use_default_or_null_flag, bool has_default_or_nullable,
704
        uint32_t segment_start_pos, uint32_t block_start_pos, const Block* block,
705
149
        std::vector<BitmapValue>* skip_bitmaps) const {
706
149
    auto* info = historical_context.partial_update_info.get();
707
149
    int32_t seq_col_unique_id = -1;
708
149
    if (tablet_schema.has_sequence_col()) {
709
22
        seq_col_unique_id = tablet_schema.column(tablet_schema.sequence_col_idx()).unique_id();
710
22
    }
711
    // cid -> segment pos to write -> rowid to read in old_value_block
712
149
    std::map<uint32_t, std::map<uint32_t, uint32_t>> read_index;
713
149
    RETURN_IF_ERROR(
714
149
            read_columns_by_plan(tablet_schema, rsid_to_rowset, old_value_block, &read_index));
715
    // !!!ATTENTION!!!: columns in old_value_block may have different size because every row has different columns to update
716
717
149
    const auto* delete_sign_column_data = BaseTablet::get_delete_sign_column_data(old_value_block);
718
    // build default value columns
719
149
    auto default_value_block = old_value_block.clone_empty();
720
149
    if (has_default_or_nullable || delete_sign_column_data != nullptr) {
721
149
        RETURN_IF_ERROR(BaseTablet::generate_default_value_block(
722
149
                tablet_schema, non_sort_key_cids, info->default_values, old_value_block,
723
149
                default_value_block));
724
149
    }
725
726
    // fill all non sort key columns from mutable_old_columns, need to consider default value and null value
727
2.02k
    for (std::size_t i {0}; i < non_sort_key_cids.size(); i++) {
728
1.88k
        auto cid = non_sort_key_cids[i];
729
1.88k
        const auto& tablet_column = tablet_schema.column(cid);
730
1.88k
        auto col_uid = tablet_column.unique_id();
731
18.8k
        for (auto idx = 0; idx < use_default_or_null_flag.size(); idx++) {
732
17.0k
            auto segment_pos = segment_start_pos + idx;
733
17.0k
            auto block_pos = block_start_pos + idx;
734
735
17.0k
            fill_non_primary_key_cell_for_column_store(
736
17.0k
                    tablet_column, cid, mutable_full_columns[cid],
737
17.0k
                    *default_value_block.get_by_position(i).column,
738
17.0k
                    *old_value_block.get_by_position(i).column, *block->get_by_position(cid).column,
739
17.0k
                    block_pos, segment_pos, skip_bitmaps->at(block_pos).contains(col_uid),
740
17.0k
                    tablet_schema.has_sequence_col()
741
17.0k
                            ? !skip_bitmaps->at(block_pos).contains(seq_col_unique_id)
742
17.0k
                            : false,
743
17.0k
                    use_default_or_null_flag[idx], delete_sign_column_data, tablet_schema,
744
17.0k
                    read_index, info);
745
17.0k
        }
746
1.88k
    }
747
149
    return Status::OK();
748
149
}
749
750
static void fill_non_primary_key_cell_for_row_store(
751
        const TabletColumn& tablet_column, uint32_t cid, MutableColumnPtr& new_col,
752
        const IColumn& default_value_col, const IColumn& old_value_col, const IColumn& cur_col,
753
        std::size_t block_pos, bool skipped, bool row_has_sequence_col, bool use_default,
754
        const signed char* delete_sign_column_data, uint32_t pos_in_old_block,
755
16.6k
        const TabletSchema& tablet_schema, const PartialUpdateInfo* info) {
756
16.6k
    if (skipped) {
757
4.18k
        DCHECK(cid != tablet_schema.skip_bitmap_col_idx());
758
4.18k
        DCHECK(cid != tablet_schema.version_col_idx());
759
4.18k
        DCHECK(!tablet_column.is_row_store_column());
760
4.18k
        if (!use_default) {
761
3.65k
            if (delete_sign_column_data != nullptr) {
762
3.65k
                bool old_row_delete_sign = (delete_sign_column_data[pos_in_old_block] != 0);
763
3.65k
                if (old_row_delete_sign) {
764
7
                    if (!tablet_schema.has_sequence_col()) {
765
2
                        use_default = true;
766
5
                    } else if (row_has_sequence_col ||
767
5
                               (!tablet_column.is_seqeunce_col() &&
768
5
                                (tablet_column.unique_id() != info->sequence_map_col_uid()))) {
769
                        // to keep the sequence column value not decreasing, we should read values of seq column(and seq map column)
770
                        // from old rows even if the old row is deleted when the input don't specify the sequence column, otherwise
771
                        // it may cause the merge-on-read based compaction to produce incorrect results
772
3
                        use_default = true;
773
3
                    }
774
7
                }
775
3.65k
            }
776
3.65k
        }
777
778
4.18k
        if (!use_default && tablet_column.is_on_update_current_timestamp()) {
779
6
            use_default = true;
780
6
        }
781
4.18k
        if (use_default) {
782
545
            if (tablet_column.has_default_value()) {
783
187
                new_col->insert_from(default_value_col, 0);
784
358
            } else if (tablet_column.is_nullable()) {
785
354
                assert_cast<ColumnNullable*, TypeCheckOnRelease::DISABLE>(new_col.get())
786
354
                        ->insert_many_defaults(1);
787
354
            } else if (tablet_column.is_auto_increment()) {
788
                // In flexible partial update, the skip bitmap indicates whether a cell
789
                // is specified in the original load, so the generated auto-increment value is filled
790
                // in current block in place if needed rather than using a seperate column to
791
                // store the generated auto-increment value in fixed partial update
792
2
                new_col->insert_from(cur_col, block_pos);
793
2
            } else {
794
2
                new_col->insert_default();
795
2
            }
796
3.64k
        } else {
797
3.64k
            new_col->insert_from(old_value_col, pos_in_old_block);
798
3.64k
        }
799
12.4k
    } else {
800
12.4k
        new_col->insert_from(cur_col, block_pos);
801
12.4k
    }
802
16.6k
}
803
804
Status FlexibleReadPlan::fill_non_primary_key_columns_for_row_store(
805
        const segment_v2::HistoricalRowRetrieverContext& historical_context,
806
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset,
807
        const TabletSchema& tablet_schema, const std::vector<uint32_t>& non_sort_key_cids,
808
        Block& old_value_block, MutableColumns& mutable_full_columns,
809
        const std::vector<bool>& use_default_or_null_flag, bool has_default_or_nullable,
810
        uint32_t segment_start_pos, uint32_t block_start_pos, const Block* block,
811
123
        std::vector<BitmapValue>* skip_bitmaps) const {
812
123
    auto* info = historical_context.partial_update_info.get();
813
123
    int32_t seq_col_unique_id = -1;
814
123
    if (tablet_schema.has_sequence_col()) {
815
7
        seq_col_unique_id = tablet_schema.column(tablet_schema.sequence_col_idx()).unique_id();
816
7
    }
817
    // segment pos to write -> rowid to read in old_value_block
818
123
    std::map<uint32_t, uint32_t> read_index;
819
123
    RETURN_IF_ERROR(read_columns_by_plan(tablet_schema, non_sort_key_cids, rsid_to_rowset,
820
123
                                         old_value_block, &read_index));
821
822
123
    const auto* delete_sign_column_data = BaseTablet::get_delete_sign_column_data(old_value_block);
823
    // build default value columns
824
123
    auto default_value_block = old_value_block.clone_empty();
825
123
    if (has_default_or_nullable || delete_sign_column_data != nullptr) {
826
123
        RETURN_IF_ERROR(BaseTablet::generate_default_value_block(
827
123
                tablet_schema, non_sort_key_cids, info->default_values, old_value_block,
828
123
                default_value_block));
829
123
    }
830
831
    // fill all non sort key columns from mutable_old_columns, need to consider default value and null value
832
1.90k
    for (std::size_t i {0}; i < non_sort_key_cids.size(); i++) {
833
1.78k
        auto cid = non_sort_key_cids[i];
834
1.78k
        const auto& tablet_column = tablet_schema.column(cid);
835
1.78k
        auto col_uid = tablet_column.unique_id();
836
18.3k
        for (auto idx = 0; idx < use_default_or_null_flag.size(); idx++) {
837
16.6k
            auto segment_pos = segment_start_pos + idx;
838
16.6k
            auto block_pos = block_start_pos + idx;
839
16.6k
            auto pos_in_old_block = read_index[segment_pos];
840
841
16.6k
            fill_non_primary_key_cell_for_row_store(
842
16.6k
                    tablet_column, cid, mutable_full_columns[cid],
843
16.6k
                    *default_value_block.get_by_position(i).column,
844
16.6k
                    *old_value_block.get_by_position(i).column, *block->get_by_position(cid).column,
845
16.6k
                    block_pos, skip_bitmaps->at(block_pos).contains(col_uid),
846
16.6k
                    tablet_schema.has_sequence_col()
847
16.6k
                            ? !skip_bitmaps->at(block_pos).contains(seq_col_unique_id)
848
16.6k
                            : false,
849
16.6k
                    use_default_or_null_flag[idx], delete_sign_column_data, pos_in_old_block,
850
16.6k
                    tablet_schema, info);
851
16.6k
        }
852
1.78k
    }
853
123
    return Status::OK();
854
123
}
855
856
BlockAggregator::BlockAggregator(segment_v2::VerticalSegmentWriter& vertical_segment_writer)
857
54.3k
        : _writer(vertical_segment_writer), _tablet_schema(*_writer._tablet_schema) {}
858
859
void BlockAggregator::merge_one_row(MutableBlock& dst_block, Block* src_block, int rid,
860
153
                                    BitmapValue& skip_bitmap) {
861
1.57k
    for (size_t cid {_tablet_schema.num_key_columns()}; cid < _tablet_schema.num_columns(); cid++) {
862
1.42k
        if (cid == _tablet_schema.skip_bitmap_col_idx()) {
863
153
            auto& cur_skip_bitmap =
864
153
                    assert_cast<ColumnBitmap*>(dst_block.mutable_columns()[cid].get())
865
153
                            ->get_data()
866
153
                            .back();
867
153
            const auto& new_row_skip_bitmap =
868
153
                    assert_cast<const ColumnBitmap*>(src_block->get_by_position(cid).column.get())
869
153
                            ->get_data()[rid];
870
153
            cur_skip_bitmap &= new_row_skip_bitmap;
871
153
            continue;
872
153
        }
873
1.27k
        if (!skip_bitmap.contains(_tablet_schema.column(cid).unique_id())) {
874
460
            dst_block.mutable_columns()[cid]->pop_back(1);
875
460
            dst_block.mutable_columns()[cid]->insert_from(*src_block->get_by_position(cid).column,
876
460
                                                          rid);
877
460
        }
878
1.27k
    }
879
153
    VLOG_DEBUG << fmt::format("merge a row, after merge, output_block.rows()={}, state: {}",
880
0
                              dst_block.rows(), _state.to_string());
881
153
}
882
883
260
void BlockAggregator::append_one_row(MutableBlock& dst_block, Block* src_block, int rid) {
884
260
    dst_block.add_row(src_block, rid);
885
260
    _state.rows++;
886
260
    VLOG_DEBUG << fmt::format("append a new row, after append, output_block.rows()={}, state: {}",
887
0
                              dst_block.rows(), _state.to_string());
888
260
}
889
890
127
void BlockAggregator::remove_last_n_rows(MutableBlock& dst_block, int n) {
891
127
    if (n > 0) {
892
968
        for (size_t cid {0}; cid < _tablet_schema.num_columns(); cid++) {
893
880
            DCHECK_GE(dst_block.mutable_columns()[cid]->size(), n);
894
880
            dst_block.mutable_columns()[cid]->pop_back(n);
895
880
        }
896
88
    }
897
127
}
898
899
void BlockAggregator::append_or_merge_row(MutableBlock& dst_block, Block* src_block, int rid,
900
413
                                          BitmapValue& skip_bitmap, bool have_delete_sign) {
901
413
    if (have_delete_sign) {
902
        // remove all the previous batched rows
903
127
        remove_last_n_rows(dst_block, _state.rows);
904
127
        _state.rows = 0;
905
127
        _state.has_row_with_delete_sign = true;
906
907
127
        append_one_row(dst_block, src_block, rid);
908
286
    } else {
909
286
        if (_state.should_merge()) {
910
153
            merge_one_row(dst_block, src_block, rid, skip_bitmap);
911
153
        } else {
912
133
            append_one_row(dst_block, src_block, rid);
913
133
        }
914
286
    }
915
413
};
916
917
Status BlockAggregator::aggregate_rows(
918
        MutableBlock& output_block, Block* block, int start, int end, std::string key,
919
        std::vector<BitmapValue>* skip_bitmaps, const signed char* delete_signs,
920
        IOlapColumnDataAccessor* seq_column, const std::vector<RowsetSharedPtr>& specified_rowsets,
921
145
        std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches) {
922
145
    VLOG_DEBUG << fmt::format("merge rows in range=[{}-{})", start, end);
923
145
    if (end - start == 1) {
924
42
        output_block.add_row(block, start);
925
42
        VLOG_DEBUG << fmt::format("append a row directly, rid={}", start);
926
42
        return Status::OK();
927
42
    }
928
929
103
    auto seq_col_unique_id = _tablet_schema.column(_tablet_schema.sequence_col_idx()).unique_id();
930
103
    auto delete_sign_col_unique_id =
931
103
            _tablet_schema.column(_tablet_schema.delete_sign_idx()).unique_id();
932
933
103
    _state.reset();
934
935
103
    RowLocation loc;
936
103
    RowsetSharedPtr rowset;
937
103
    std::string previous_encoded_seq_value {};
938
103
    Status st = _writer._tablet->lookup_row_key(
939
103
            key, &_tablet_schema, false, specified_rowsets, &loc, _writer._mow_context->max_version,
940
103
            segment_caches, &rowset, true, &previous_encoded_seq_value);
941
103
    int pos = start;
942
103
    bool is_expected_st = (st.is<ErrorCode::KEY_NOT_FOUND>() || st.ok());
943
103
    DCHECK(is_expected_st || st.is<ErrorCode::MEM_LIMIT_EXCEEDED>())
944
0
            << "[BlockAggregator::aggregate_rows] unexpected error status while lookup_row_key:"
945
0
            << st;
946
103
    if (!is_expected_st) {
947
0
        return st;
948
0
    }
949
950
103
    std::string cur_seq_val;
951
103
    if (st.ok()) {
952
101
        for (pos = start; pos < end; pos++) {
953
101
            auto& skip_bitmap = skip_bitmaps->at(pos);
954
101
            bool row_has_sequence_col = (!skip_bitmap.contains(seq_col_unique_id));
955
            // Discard all the rows whose seq value is smaller than previous_encoded_seq_value.
956
101
            if (row_has_sequence_col) {
957
60
                std::string seq_val {};
958
60
                _writer._key_encoder.append_seq_suffix(&seq_val, seq_column, pos);
959
60
                if (Slice {seq_val}.compare(Slice {previous_encoded_seq_value}) < 0) {
960
19
                    continue;
961
19
                }
962
41
                cur_seq_val = std::move(seq_val);
963
41
                break;
964
60
            }
965
41
            cur_seq_val = std::move(previous_encoded_seq_value);
966
41
            break;
967
101
        }
968
82
    } else {
969
21
        pos = start;
970
21
        auto& skip_bitmap = skip_bitmaps->at(pos);
971
21
        bool row_has_sequence_col = (!skip_bitmap.contains(seq_col_unique_id));
972
21
        if (row_has_sequence_col) {
973
15
            std::string seq_val {};
974
            // for rows that don't specify seqeunce col, seq_val will be encoded to minial value
975
15
            _writer._key_encoder.append_seq_suffix(&seq_val, seq_column, pos);
976
15
            cur_seq_val = std::move(seq_val);
977
15
        } else {
978
6
            cur_seq_val.clear();
979
6
            RETURN_IF_ERROR(_writer._generate_encoded_default_seq_value(
980
6
                    _tablet_schema, *_writer._opts.rowset_ctx->partial_update_info, &cur_seq_val));
981
6
        }
982
21
    }
983
984
574
    for (int rid {pos}; rid < end; rid++) {
985
471
        auto& skip_bitmap = skip_bitmaps->at(rid);
986
471
        bool row_has_sequence_col = (!skip_bitmap.contains(seq_col_unique_id));
987
471
        bool have_delete_sign =
988
471
                (!skip_bitmap.contains(delete_sign_col_unique_id) && delete_signs[rid] != 0);
989
471
        if (!row_has_sequence_col) {
990
197
            append_or_merge_row(output_block, block, rid, skip_bitmap, have_delete_sign);
991
274
        } else {
992
274
            std::string seq_val {};
993
274
            _writer._key_encoder.append_seq_suffix(&seq_val, seq_column, rid);
994
274
            if (Slice {seq_val}.compare(Slice {cur_seq_val}) >= 0) {
995
216
                append_or_merge_row(output_block, block, rid, skip_bitmap, have_delete_sign);
996
216
                cur_seq_val = std::move(seq_val);
997
216
            } else {
998
58
                VLOG_DEBUG << fmt::format(
999
0
                        "skip rid={} becasue its seq value is lower than the previous", rid);
1000
58
            }
1001
274
        }
1002
471
    }
1003
103
    return Status::OK();
1004
103
};
1005
1006
Status BlockAggregator::aggregate_for_sequence_column(
1007
        Block* block, int num_rows, const std::vector<IOlapColumnDataAccessor*>& key_columns,
1008
        IOlapColumnDataAccessor* seq_column, const std::vector<RowsetSharedPtr>& specified_rowsets,
1009
29
        std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches) {
1010
29
    DCHECK_EQ(block->columns(), _tablet_schema.num_columns());
1011
    // the process logic here is the same as MemTable::_aggregate_for_flexible_partial_update_without_seq_col()
1012
    // after this function, there will be at most 2 rows for a specified key
1013
29
    std::vector<BitmapValue>* skip_bitmaps =
1014
29
            &get_mutable_skip_bitmap_column(block, _tablet_schema.skip_bitmap_col_idx())
1015
29
                     ->get_data();
1016
29
    const auto* delete_signs = BaseTablet::get_delete_sign_column_data(*block, num_rows);
1017
1018
29
    auto filtered_block = _tablet_schema.create_block();
1019
29
    MutableBlock output_block = MutableBlock::build_mutable_block(std::move(filtered_block));
1020
1021
29
    int same_key_rows {0};
1022
29
    std::string previous_key {};
1023
561
    for (int block_pos {0}; block_pos < num_rows; block_pos++) {
1024
532
        std::string key = _writer._key_encoder.full_encode(key_columns, block_pos);
1025
532
        if (block_pos > 0 && previous_key == key) {
1026
387
            same_key_rows++;
1027
387
        } else {
1028
145
            if (same_key_rows > 0) {
1029
116
                RETURN_IF_ERROR(aggregate_rows(output_block, block, block_pos - same_key_rows,
1030
116
                                               block_pos, std::move(previous_key), skip_bitmaps,
1031
116
                                               delete_signs, seq_column, specified_rowsets,
1032
116
                                               segment_caches));
1033
116
            }
1034
145
            same_key_rows = 1;
1035
145
        }
1036
532
        previous_key = std::move(key);
1037
532
    }
1038
29
    if (same_key_rows > 0) {
1039
29
        RETURN_IF_ERROR(aggregate_rows(output_block, block, num_rows - same_key_rows, num_rows,
1040
29
                                       std::move(previous_key), skip_bitmaps, delete_signs,
1041
29
                                       seq_column, specified_rowsets, segment_caches));
1042
29
    }
1043
1044
29
    block->swap(output_block.to_block());
1045
29
    return Status::OK();
1046
29
}
1047
1048
Status BlockAggregator::fill_sequence_column(Block* block, size_t num_rows,
1049
                                             const FixedReadPlan& read_plan,
1050
8
                                             std::vector<BitmapValue>& skip_bitmaps) {
1051
8
    DCHECK(_tablet_schema.has_sequence_col());
1052
8
    std::vector<uint32_t> cids {static_cast<uint32_t>(_tablet_schema.sequence_col_idx())};
1053
8
    auto seq_col_unique_id = _tablet_schema.column(_tablet_schema.sequence_col_idx()).unique_id();
1054
1055
8
    auto seq_col_block = _tablet_schema.create_block_by_cids(cids);
1056
8
    auto tmp_block = _tablet_schema.create_block_by_cids(cids);
1057
8
    std::map<uint32_t, uint32_t> read_index;
1058
8
    RETURN_IF_ERROR(read_plan.read_columns_by_plan(_tablet_schema, cids, _writer._rsid_to_rowset,
1059
8
                                                   seq_col_block, &read_index, false));
1060
1061
8
    auto new_seq_col_ptr = tmp_block.get_by_position(0).column->assert_mutable();
1062
8
    const auto& old_seq_col_ptr = *seq_col_block.get_by_position(0).column;
1063
8
    const auto& cur_seq_col_ptr = *block->get_by_position(_tablet_schema.sequence_col_idx()).column;
1064
100
    for (uint32_t block_pos {0}; block_pos < num_rows; block_pos++) {
1065
92
        if (read_index.contains(block_pos)) {
1066
18
            new_seq_col_ptr->insert_from(old_seq_col_ptr, read_index[block_pos]);
1067
18
            skip_bitmaps[block_pos].remove(seq_col_unique_id);
1068
74
        } else {
1069
74
            new_seq_col_ptr->insert_from(cur_seq_col_ptr, block_pos);
1070
74
        }
1071
92
    }
1072
8
    block->replace_by_position(_tablet_schema.sequence_col_idx(), std::move(new_seq_col_ptr));
1073
8
    return Status::OK();
1074
8
}
1075
1076
Status BlockAggregator::aggregate_for_insert_after_delete(
1077
        Block* block, size_t num_rows, const std::vector<IOlapColumnDataAccessor*>& key_columns,
1078
        const std::vector<RowsetSharedPtr>& specified_rowsets,
1079
273
        std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches) {
1080
273
    DCHECK_EQ(block->columns(), _tablet_schema.num_columns());
1081
    // there will be at most 2 rows for a specified key in block when control flow reaches here
1082
    // after this function, there will not be duplicate rows in block
1083
1084
273
    std::vector<BitmapValue>* skip_bitmaps =
1085
273
            &get_mutable_skip_bitmap_column(block, _tablet_schema.skip_bitmap_col_idx())
1086
273
                     ->get_data();
1087
273
    const auto* delete_signs = BaseTablet::get_delete_sign_column_data(*block, num_rows);
1088
1089
273
    auto filter_column = ColumnUInt8::create(num_rows, 1);
1090
273
    auto* __restrict filter_map = filter_column->get_data().data();
1091
273
    std::string previous_key {};
1092
273
    bool previous_has_delete_sign {false};
1093
273
    int duplicate_rows {0};
1094
273
    int32_t delete_sign_col_unique_id =
1095
273
            _tablet_schema.column(_tablet_schema.delete_sign_idx()).unique_id();
1096
273
    auto seq_col_unique_id =
1097
273
            (_tablet_schema.sequence_col_idx() != -1)
1098
273
                    ? _tablet_schema.column(_tablet_schema.sequence_col_idx()).unique_id()
1099
273
                    : -1;
1100
273
    FixedReadPlan read_plan;
1101
2.49k
    for (size_t block_pos {0}; block_pos < num_rows; block_pos++) {
1102
2.22k
        size_t delta_pos = block_pos;
1103
2.22k
        auto& skip_bitmap = skip_bitmaps->at(block_pos);
1104
2.22k
        std::string key = _writer._key_encoder.full_encode(key_columns, delta_pos);
1105
2.22k
        bool have_delete_sign =
1106
2.22k
                (!skip_bitmap.contains(delete_sign_col_unique_id) && delete_signs[block_pos] != 0);
1107
2.22k
        if (delta_pos > 0 && previous_key == key) {
1108
            // !!ATTENTION!!: We can only remove the row with delete sign if there is a insert with the same key after this row.
1109
            // If there is only a row with delete sign, we should keep it and can't remove it from block, because
1110
            // compaction will not use the delete bitmap when reading data. So there may still be rows with delete sign
1111
            // in later process
1112
51
            DCHECK(previous_has_delete_sign);
1113
51
            DCHECK(!have_delete_sign);
1114
51
            ++duplicate_rows;
1115
51
            RowLocation loc;
1116
51
            RowsetSharedPtr rowset;
1117
51
            Status st = _writer._tablet->lookup_row_key(
1118
51
                    key, &_tablet_schema, false, specified_rowsets, &loc,
1119
51
                    _writer._mow_context->max_version, segment_caches, &rowset, true);
1120
51
            bool is_expected_st = (st.is<ErrorCode::KEY_NOT_FOUND>() || st.ok());
1121
51
            DCHECK(is_expected_st || st.is<ErrorCode::MEM_LIMIT_EXCEEDED>())
1122
0
                    << "[BlockAggregator::aggregate_for_insert_after_delete] unexpected error "
1123
0
                       "status while lookup_row_key:"
1124
0
                    << st;
1125
51
            if (!is_expected_st) {
1126
0
                return st;
1127
0
            }
1128
1129
51
            Slice previous_seq_slice {};
1130
51
            if (st.ok()) {
1131
46
                if (_tablet_schema.has_sequence_col()) {
1132
                    // if the insert row doesn't specify the sequence column, we need to
1133
                    // read the historical's sequence column value so that we don't need
1134
                    // to handle seqeunce column in append_block_with_flexible_content()
1135
                    // for this row
1136
38
                    bool row_has_sequence_col = (!skip_bitmap.contains(seq_col_unique_id));
1137
38
                    if (!row_has_sequence_col) {
1138
18
                        read_plan.prepare_to_read(loc, block_pos);
1139
18
                        _writer._rsid_to_rowset.emplace(rowset->rowset_id(), rowset);
1140
18
                    }
1141
38
                }
1142
                // delete the existing row
1143
46
                _writer._mow_context->delete_bitmap->add(
1144
46
                        {loc.rowset_id, loc.segment_id, DeleteBitmap::TEMP_VERSION_COMMON},
1145
46
                        loc.row_id);
1146
46
            }
1147
            // and remove the row with delete sign from the current block
1148
51
            filter_map[block_pos - 1] = 0;
1149
51
        }
1150
2.22k
        previous_has_delete_sign = have_delete_sign;
1151
2.22k
        previous_key = std::move(key);
1152
2.22k
    }
1153
273
    if (duplicate_rows > 0) {
1154
17
        if (!read_plan.empty()) {
1155
            // fill sequence column value for some rows
1156
8
            RETURN_IF_ERROR(fill_sequence_column(block, num_rows, read_plan, *skip_bitmaps));
1157
8
        }
1158
17
        RETURN_IF_ERROR(filter_block(block, num_rows, std::move(filter_column), duplicate_rows,
1159
17
                                     "__filter_insert_after_delete_col__"));
1160
17
    }
1161
273
    return Status::OK();
1162
273
}
1163
1164
Status BlockAggregator::filter_block(Block* block, size_t num_rows, MutableColumnPtr filter_column,
1165
17
                                     int duplicate_rows, std::string col_name) {
1166
17
    auto num_cols = block->columns();
1167
17
    block->insert({std::move(filter_column), std::make_shared<DataTypeUInt8>(), col_name});
1168
17
    RETURN_IF_ERROR(Block::filter_block(block, num_cols, num_cols));
1169
17
    DCHECK_EQ(num_cols, block->columns());
1170
17
    size_t merged_rows = num_rows - block->rows();
1171
17
    if (duplicate_rows != merged_rows) {
1172
0
        auto msg = fmt::format(
1173
0
                "filter_block_for_flexible_partial_update {}: duplicate_rows != merged_rows, "
1174
0
                "duplicate_keys={}, merged_rows={}, num_rows={}, mutable_block->rows()={}",
1175
0
                col_name, duplicate_rows, merged_rows, num_rows, block->rows());
1176
0
        DCHECK(false) << msg;
1177
0
        return Status::InternalError<false>(msg);
1178
0
    }
1179
17
    return Status::OK();
1180
17
}
1181
1182
Status BlockAggregator::convert_pk_columns(Block* block, size_t row_pos, size_t num_rows,
1183
559
                                           std::vector<IOlapColumnDataAccessor*>& key_columns) {
1184
559
    key_columns.clear();
1185
1.48k
    for (uint32_t cid {0}; cid < _tablet_schema.num_key_columns(); cid++) {
1186
923
        RETURN_IF_ERROR(_writer._olap_data_convertor->set_source_content_with_specifid_column(
1187
923
                block->get_by_position(cid), row_pos, num_rows, cid));
1188
923
        auto [status, column] = _writer._olap_data_convertor->convert_column_data(cid);
1189
923
        if (!status.ok()) {
1190
0
            return status;
1191
0
        }
1192
923
        key_columns.push_back(column);
1193
923
    }
1194
559
    return Status::OK();
1195
559
}
1196
1197
Status BlockAggregator::convert_seq_column(Block* block, size_t row_pos, size_t num_rows,
1198
561
                                           IOlapColumnDataAccessor*& seq_column) {
1199
561
    seq_column = nullptr;
1200
561
    if (_tablet_schema.has_sequence_col()) {
1201
73
        auto seq_col_idx = _tablet_schema.sequence_col_idx();
1202
73
        RETURN_IF_ERROR(_writer._olap_data_convertor->set_source_content_with_specifid_column(
1203
73
                block->get_by_position(seq_col_idx), row_pos, num_rows, seq_col_idx));
1204
73
        auto [status, column] = _writer._olap_data_convertor->convert_column_data(seq_col_idx);
1205
73
        if (!status.ok()) {
1206
0
            return status;
1207
0
        }
1208
73
        seq_column = column;
1209
73
    }
1210
561
    return Status::OK();
1211
561
};
1212
1213
Status BlockAggregator::aggregate_for_flexible_partial_update(
1214
        Block* block, size_t num_rows, const std::vector<RowsetSharedPtr>& specified_rowsets,
1215
271
        std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches) {
1216
271
    std::vector<IOlapColumnDataAccessor*> key_columns {};
1217
271
    IOlapColumnDataAccessor* seq_column {nullptr};
1218
1219
271
    RETURN_IF_ERROR(convert_pk_columns(block, 0, num_rows, key_columns));
1220
271
    RETURN_IF_ERROR(convert_seq_column(block, 0, num_rows, seq_column));
1221
1222
    // 1. merge duplicate rows when table has sequence column
1223
    // When there are multiple rows with the same keys in memtable, some of them specify specify the sequence column,
1224
    // some of them don't. We can't do the de-duplication in memtable because we don't know the historical data. We must
1225
    // de-duplicate them here.
1226
271
    if (_tablet_schema.has_sequence_col()) {
1227
29
        RETURN_IF_ERROR(aggregate_for_sequence_column(block, static_cast<int>(num_rows),
1228
29
                                                      key_columns, seq_column, specified_rowsets,
1229
29
                                                      segment_caches));
1230
29
    }
1231
1232
    // 2. merge duplicate rows and handle insert after delete
1233
271
    if (block->rows() != num_rows) {
1234
15
        num_rows = block->rows();
1235
        // data in block has changed, should re-encode key columns, sequence column
1236
15
        _writer._olap_data_convertor->clear_source_content();
1237
15
        RETURN_IF_ERROR(convert_pk_columns(block, 0, num_rows, key_columns));
1238
15
        RETURN_IF_ERROR(convert_seq_column(block, 0, num_rows, seq_column));
1239
15
    }
1240
271
    RETURN_IF_ERROR(aggregate_for_insert_after_delete(block, num_rows, key_columns,
1241
271
                                                      specified_rowsets, segment_caches));
1242
271
    return Status::OK();
1243
271
}
1244
1245
} // namespace doris