Coverage Report

Created: 2026-03-06 15:08

/root/doris/be/src/olap/tablet.cpp
Line
Count
Source (jump to first uncovered line)
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 "olap/tablet.h"
19
20
#include <butil/logging.h>
21
#include <bvar/reducer.h>
22
#include <bvar/window.h>
23
#include <fmt/format.h>
24
#include <gen_cpp/FrontendService_types.h>
25
#include <gen_cpp/MasterService_types.h>
26
#include <gen_cpp/Metrics_types.h>
27
#include <gen_cpp/olap_file.pb.h>
28
#include <gen_cpp/types.pb.h>
29
#include <rapidjson/document.h>
30
#include <rapidjson/encodings.h>
31
#include <rapidjson/prettywriter.h>
32
#include <rapidjson/rapidjson.h>
33
#include <rapidjson/stringbuffer.h>
34
35
#include <algorithm>
36
#include <atomic>
37
#include <boost/container/detail/std_fwd.hpp>
38
#include <roaring/roaring.hh>
39
40
#include "common/compiler_util.h" // IWYU pragma: keep
41
// IWYU pragma: no_include <bits/chrono.h>
42
#include <chrono> // IWYU pragma: keep
43
#include <filesystem>
44
#include <iterator>
45
#include <limits>
46
#include <map>
47
#include <memory>
48
#include <mutex>
49
#include <set>
50
#include <shared_mutex>
51
#include <string>
52
#include <tuple>
53
#include <type_traits>
54
#include <unordered_map>
55
#include <unordered_set>
56
57
#include "agent/utils.h"
58
#include "common/config.h"
59
#include "common/consts.h"
60
#include "common/exception.h"
61
#include "common/logging.h"
62
#include "common/signal_handler.h"
63
#include "common/status.h"
64
#include "exprs/runtime_filter.h"
65
#include "gutil/ref_counted.h"
66
#include "gutil/strings/stringpiece.h"
67
#include "gutil/strings/substitute.h"
68
#include "io/fs/file_reader.h"
69
#include "io/fs/file_reader_writer_fwd.h"
70
#include "io/fs/file_system.h"
71
#include "io/fs/file_writer.h"
72
#include "io/fs/path.h"
73
#include "io/fs/remote_file_system.h"
74
#include "io/io_common.h"
75
#include "olap/base_compaction.h"
76
#include "olap/base_tablet.h"
77
#include "olap/binlog.h"
78
#include "olap/cumulative_compaction.h"
79
#include "olap/cumulative_compaction_policy.h"
80
#include "olap/cumulative_compaction_time_series_policy.h"
81
#include "olap/delete_bitmap_calculator.h"
82
#include "olap/full_compaction.h"
83
#include "olap/memtable.h"
84
#include "olap/olap_common.h"
85
#include "olap/olap_define.h"
86
#include "olap/olap_meta.h"
87
#include "olap/primary_key_index.h"
88
#include "olap/rowid_conversion.h"
89
#include "olap/rowset/beta_rowset.h"
90
#include "olap/rowset/rowset.h"
91
#include "olap/rowset/rowset_factory.h"
92
#include "olap/rowset/rowset_meta.h"
93
#include "olap/rowset/rowset_meta_manager.h"
94
#include "olap/rowset/rowset_writer.h"
95
#include "olap/rowset/rowset_writer_context.h"
96
#include "olap/rowset/segment_v2/column_reader.h"
97
#include "olap/rowset/segment_v2/common.h"
98
#include "olap/rowset/segment_v2/indexed_column_reader.h"
99
#include "olap/rowset/vertical_beta_rowset_writer.h"
100
#include "olap/schema_change.h"
101
#include "olap/single_replica_compaction.h"
102
#include "olap/storage_engine.h"
103
#include "olap/storage_policy.h"
104
#include "olap/tablet_manager.h"
105
#include "olap/tablet_meta.h"
106
#include "olap/tablet_meta_manager.h"
107
#include "olap/tablet_schema.h"
108
#include "olap/txn_manager.h"
109
#include "olap/types.h"
110
#include "olap/utils.h"
111
#include "segment_loader.h"
112
#include "service/point_query_executor.h"
113
#include "tablet.h"
114
#include "util/bvar_helper.h"
115
#include "util/crc32c.h"
116
#include "util/debug_points.h"
117
#include "util/defer_op.h"
118
#include "util/doris_metrics.h"
119
#include "util/pretty_printer.h"
120
#include "util/scoped_cleanup.h"
121
#include "util/stopwatch.hpp"
122
#include "util/threadpool.h"
123
#include "util/time.h"
124
#include "util/trace.h"
125
#include "util/uid_util.h"
126
#include "util/work_thread_pool.hpp"
127
#include "vec/columns/column.h"
128
#include "vec/columns/column_string.h"
129
#include "vec/common/schema_util.h"
130
#include "vec/common/string_ref.h"
131
#include "vec/data_types/data_type.h"
132
#include "vec/data_types/data_type_factory.hpp"
133
#include "vec/data_types/serde/data_type_serde.h"
134
#include "vec/jsonb/serialize.h"
135
136
namespace doris {
137
class TupleDescriptor;
138
139
namespace vectorized {
140
class Block;
141
} // namespace vectorized
142
143
using namespace ErrorCode;
144
using namespace std::chrono_literals;
145
146
using std::pair;
147
using std::string;
148
using std::vector;
149
using io::FileSystemSPtr;
150
151
namespace {
152
153
bvar::LatencyRecorder g_tablet_lookup_rowkey_latency("doris_pk", "tablet_lookup_rowkey");
154
bvar::LatencyRecorder g_tablet_commit_phase_update_delete_bitmap_latency(
155
        "doris_pk", "commit_phase_update_delete_bitmap");
156
bvar::LatencyRecorder g_tablet_update_delete_bitmap_latency("doris_pk", "update_delete_bitmap");
157
bvar::Adder<uint64_t> g_tablet_pk_not_found("doris_pk", "lookup_not_found");
158
bvar::PerSecond<bvar::Adder<uint64_t>> g_tablet_pk_not_found_per_second(
159
        "doris_pk", "lookup_not_found_per_second", &g_tablet_pk_not_found, 60);
160
161
bvar::Adder<uint64_t> exceed_version_limit_counter;
162
bvar::Window<bvar::Adder<uint64_t>> exceed_version_limit_counter_minute(
163
        &exceed_version_limit_counter, 60);
164
165
0
void set_last_failure_time(Tablet* tablet, const Compaction& compaction, int64_t ms) {
166
0
    switch (compaction.compaction_type()) {
167
0
    case ReaderType::READER_CUMULATIVE_COMPACTION:
168
0
        tablet->set_last_cumu_compaction_failure_time(ms);
169
0
        return;
170
0
    case ReaderType::READER_BASE_COMPACTION:
171
0
        tablet->set_last_base_compaction_failure_time(ms);
172
0
        return;
173
0
    case ReaderType::READER_FULL_COMPACTION:
174
0
        tablet->set_last_full_compaction_failure_time(ms);
175
0
        return;
176
0
    default:
177
0
        LOG(FATAL) << "invalid compaction type " << compaction.compaction_name()
178
0
                   << " tablet_id: " << tablet->tablet_id();
179
0
    }
180
0
};
181
182
} // namespace
183
184
WriteCooldownMetaExecutors::WriteCooldownMetaExecutors(size_t executor_nums)
185
1
        : _executor_nums(executor_nums) {
186
6
    for (size_t i = 0; i < _executor_nums; i++) {
187
5
        std::unique_ptr<PriorityThreadPool> pool;
188
5
        static_cast<void>(ThreadPoolBuilder("WriteCooldownMetaExecutor")
189
5
                                  .set_min_threads(1)
190
5
                                  .set_max_threads(1)
191
5
                                  .set_max_queue_size(std::numeric_limits<int>::max())
192
5
                                  .build(&pool));
193
5
        _executors.emplace_back(std::move(pool));
194
5
    }
195
1
}
196
197
0
void WriteCooldownMetaExecutors::stop() {
198
0
    for (auto& pool_ptr : _executors) {
199
0
        if (pool_ptr) {
200
0
            pool_ptr->shutdown();
201
0
        }
202
0
    }
203
0
}
204
205
5
void WriteCooldownMetaExecutors::WriteCooldownMetaExecutors::submit(TabletSharedPtr tablet) {
206
5
    auto tablet_id = tablet->tablet_id();
207
208
5
    {
209
5
        std::shared_lock rdlock(tablet->get_header_lock());
210
5
        if (!tablet->tablet_meta()->cooldown_meta_id().initialized()) {
211
0
            VLOG_NOTICE << "tablet " << tablet_id << " is not cooldown replica";
212
0
            return;
213
0
        }
214
5
        if (tablet->tablet_state() == TABLET_SHUTDOWN) [[unlikely]] {
215
0
            LOG_INFO("tablet {} has been dropped, don't do cooldown", tablet_id);
216
0
            return;
217
0
        }
218
5
    }
219
5
    {
220
        // one tablet could at most have one cooldown task to be done
221
5
        std::unique_lock<std::mutex> lck {_latch};
222
5
        if (_pending_tablets.count(tablet_id) > 0) {
223
0
            return;
224
0
        }
225
5
        _pending_tablets.insert(tablet_id);
226
5
    }
227
228
5
    auto async_write_task = [this, t = std::move(tablet)]() {
229
5
        {
230
5
            std::unique_lock<std::mutex> lck {_latch};
231
5
            _pending_tablets.erase(t->tablet_id());
232
5
        }
233
5
        auto s = t->write_cooldown_meta();
234
5
        if (s.ok()) {
235
5
            return;
236
5
        }
237
0
        if (!s.is<ABORTED>()) {
238
0
            LOG_EVERY_SECOND(WARNING)
239
0
                    << "write tablet " << t->tablet_id() << " cooldown meta failed because: " << s;
240
0
            submit(t);
241
0
            return;
242
0
        }
243
0
        VLOG_DEBUG << "tablet " << t->tablet_id() << " is not cooldown replica";
244
0
    };
245
246
5
    _executors[_get_executor_pos(tablet_id)]->offer(
247
5
            [task = std::move(async_write_task)]() { task(); });
248
5
}
249
250
Tablet::Tablet(StorageEngine& engine, TabletMetaSharedPtr tablet_meta, DataDir* data_dir,
251
               const std::string_view& cumulative_compaction_type)
252
        : BaseTablet(std::move(tablet_meta)),
253
          _engine(engine),
254
          _data_dir(data_dir),
255
          _is_bad(false),
256
          _last_cumu_compaction_failure_millis(0),
257
          _last_base_compaction_failure_millis(0),
258
          _last_full_compaction_failure_millis(0),
259
          _last_cumu_compaction_success_millis(0),
260
          _last_base_compaction_success_millis(0),
261
          _last_full_compaction_success_millis(0),
262
          _cumulative_point(K_INVALID_CUMULATIVE_POINT),
263
          _newly_created_rowset_num(0),
264
          _last_checkpoint_time(0),
265
          _cumulative_compaction_type(cumulative_compaction_type),
266
          _is_tablet_path_exists(true),
267
          _last_missed_version(-1),
268
502
          _last_missed_time_s(0) {
269
502
    if (_data_dir != nullptr) {
270
364
        _tablet_path = fmt::format("{}/{}/{}/{}/{}", _data_dir->path(), DATA_PREFIX,
271
364
                                   _tablet_meta->shard_id(), tablet_id(), schema_hash());
272
364
    }
273
    // construct _timestamped_versioned_tracker from rs and stale rs meta
274
502
    _timestamped_version_tracker.construct_versioned_tracker(_tablet_meta->all_rs_metas(),
275
502
                                                             _tablet_meta->all_stale_rs_metas());
276
    // if !_tablet_meta->all_rs_metas()[0]->tablet_schema(),
277
    // that mean the tablet_meta is still no upgrade to doris 1.2 versions.
278
    // Before doris 1.2 version, rowset metas don't have tablet schema.
279
    // And when upgrade to doris 1.2 version,
280
    // all rowset metas will be set the tablet schmea from tablet meta.
281
502
    if (_tablet_meta->all_rs_metas().empty() || !_tablet_meta->all_rs_metas()[0]->tablet_schema()) {
282
465
        _max_version_schema = _tablet_meta->tablet_schema();
283
465
    } else {
284
37
        _max_version_schema =
285
37
                tablet_schema_with_merged_max_schema_version(_tablet_meta->all_rs_metas());
286
37
    }
287
502
    DCHECK(_max_version_schema);
288
502
}
289
290
0
bool Tablet::set_tablet_schema_into_rowset_meta() {
291
0
    bool flag = false;
292
0
    for (auto&& rowset_meta : _tablet_meta->all_mutable_rs_metas()) {
293
0
        if (!rowset_meta->tablet_schema()) {
294
0
            rowset_meta->set_tablet_schema(_tablet_meta->tablet_schema());
295
0
            flag = true;
296
0
        }
297
0
    }
298
0
    return flag;
299
0
}
300
301
466
Status Tablet::_init_once_action() {
302
466
    Status res = Status::OK();
303
466
    VLOG_NOTICE << "begin to load tablet. tablet=" << tablet_id()
304
0
                << ", version_size=" << _tablet_meta->version_count();
305
306
466
#ifdef BE_TEST
307
    // init cumulative compaction policy by type
308
466
    _cumulative_compaction_policy =
309
466
            CumulativeCompactionPolicyFactory::create_cumulative_compaction_policy(
310
466
                    _tablet_meta->compaction_policy());
311
466
#endif
312
313
466
    for (const auto& rs_meta : _tablet_meta->all_rs_metas()) {
314
205
        Version version = rs_meta->version();
315
205
        RowsetSharedPtr rowset;
316
205
        res = create_rowset(rs_meta, &rowset);
317
205
        if (!res.ok()) {
318
0
            LOG(WARNING) << "fail to init rowset. tablet_id=" << tablet_id()
319
0
                         << ", schema_hash=" << schema_hash() << ", version=" << version
320
0
                         << ", res=" << res;
321
0
            return res;
322
0
        }
323
205
        _rs_version_map[version] = std::move(rowset);
324
205
    }
325
326
    // init stale rowset
327
466
    for (const auto& stale_rs_meta : _tablet_meta->all_stale_rs_metas()) {
328
0
        Version version = stale_rs_meta->version();
329
0
        RowsetSharedPtr rowset;
330
0
        res = create_rowset(stale_rs_meta, &rowset);
331
0
        if (!res.ok()) {
332
0
            LOG(WARNING) << "fail to init stale rowset. tablet_id:" << tablet_id()
333
0
                         << ", schema_hash:" << schema_hash() << ", version=" << version
334
0
                         << ", res:" << res;
335
0
            return res;
336
0
        }
337
0
        _stale_rs_version_map[version] = std::move(rowset);
338
0
    }
339
340
466
    return res;
341
466
}
342
343
692
Status Tablet::init() {
344
692
    return _init_once.call([this] { return _init_once_action(); });
345
692
}
346
347
// should save tablet meta to remote meta store
348
// if it's a primary replica
349
554
void Tablet::save_meta() {
350
554
    auto res = _tablet_meta->save_meta(_data_dir);
351
554
    CHECK_EQ(res, Status::OK()) << "fail to save tablet_meta. res=" << res
352
0
                                << ", root=" << _data_dir->path();
353
554
}
354
355
// Caller should hold _meta_lock.
356
Status Tablet::revise_tablet_meta(const std::vector<RowsetSharedPtr>& to_add,
357
                                  const std::vector<RowsetSharedPtr>& to_delete,
358
0
                                  bool is_incremental_clone) {
359
0
    LOG(INFO) << "begin to revise tablet. tablet_id=" << tablet_id();
360
    // 1. for incremental clone, we have to add the rowsets first to make it easy to compute
361
    //    all the delete bitmaps, and it's easy to delete them if we end up with a failure
362
    // 2. for full clone, we can calculate delete bitmaps on the cloned rowsets directly.
363
0
    if (is_incremental_clone) {
364
0
        CHECK(to_delete.empty()); // don't need to delete rowsets
365
0
        add_rowsets(to_add);
366
        // reconstruct from tablet meta
367
0
        _timestamped_version_tracker.construct_versioned_tracker(_tablet_meta->all_rs_metas());
368
0
    }
369
370
0
    Status calc_bm_status;
371
0
    std::vector<RowsetSharedPtr> base_rowsets_for_full_clone = to_add; // copy vector
372
0
    while (keys_type() == UNIQUE_KEYS && enable_unique_key_merge_on_write()) {
373
0
        std::vector<RowsetSharedPtr> calc_delete_bitmap_rowsets;
374
0
        int64_t to_add_min_version = INT64_MAX;
375
0
        int64_t to_add_max_version = INT64_MIN;
376
0
        for (auto& rs : to_add) {
377
0
            if (to_add_min_version > rs->start_version()) {
378
0
                to_add_min_version = rs->start_version();
379
0
            }
380
0
            if (to_add_max_version < rs->end_version()) {
381
0
                to_add_max_version = rs->end_version();
382
0
            }
383
0
        }
384
0
        Version calc_delete_bitmap_ver;
385
0
        if (is_incremental_clone) {
386
            // From the rowset of to_add with smallest version, all other rowsets
387
            // need to recalculate the delete bitmap
388
            // For example:
389
            // local tablet: [0-1] [2-5] [6-6] [9-10]
390
            // clone tablet: [7-7] [8-8]
391
            // new tablet:   [0-1] [2-5] [6-6] [7-7] [8-8] [9-10]
392
            // [7-7] [8-8] [9-10] need to recalculate delete bitmap
393
0
            calc_delete_bitmap_ver = Version(to_add_min_version, max_version_unlocked().second);
394
0
        } else {
395
            // the delete bitmap of to_add's rowsets has clone from remote when full clone.
396
            // only other rowsets in local need to recalculate the delete bitmap.
397
            // For example:
398
            // local tablet: [0-1]x [2-5]x [6-6]x [7-7]x [9-10]
399
            // clone tablet: [0-1]  [2-4]  [5-6]  [7-8]
400
            // new tablet:   [0-1]  [2-4]  [5-6]  [7-8] [9-10]
401
            // only [9-10] need to recalculate delete bitmap
402
0
            CHECK_EQ(to_add_min_version, 0) << "to_add_min_version is: " << to_add_min_version;
403
0
            calc_delete_bitmap_ver = Version(to_add_max_version + 1, max_version_unlocked().second);
404
0
        }
405
406
0
        if (calc_delete_bitmap_ver.first <= calc_delete_bitmap_ver.second) {
407
0
            calc_bm_status =
408
0
                    capture_consistent_rowsets(calc_delete_bitmap_ver, &calc_delete_bitmap_rowsets);
409
0
            if (!calc_bm_status.ok()) {
410
0
                LOG(WARNING) << "fail to capture_consistent_rowsets, res: " << calc_bm_status;
411
0
                break;
412
0
            }
413
0
            for (auto rs : calc_delete_bitmap_rowsets) {
414
0
                if (is_incremental_clone) {
415
0
                    calc_bm_status = update_delete_bitmap_without_lock(rs);
416
0
                } else {
417
0
                    calc_bm_status =
418
0
                            update_delete_bitmap_without_lock(rs, &base_rowsets_for_full_clone);
419
0
                    base_rowsets_for_full_clone.push_back(rs);
420
0
                }
421
0
                if (!calc_bm_status.ok()) {
422
0
                    LOG(WARNING) << "fail to update_delete_bitmap_without_lock, res: "
423
0
                                 << calc_bm_status;
424
0
                    break;
425
0
                }
426
0
            }
427
0
        }
428
0
        break; // while (keys_type() == UNIQUE_KEYS && enable_unique_key_merge_on_write())
429
0
    }
430
431
0
    DBUG_EXECUTE_IF("Tablet.revise_tablet_meta_fail", {
432
0
        auto ptablet_id = dp->param("tablet_id", 0);
433
0
        if (tablet_id() == ptablet_id) {
434
0
            LOG(INFO) << "injected revies_tablet_meta failure for tabelt: " << ptablet_id;
435
0
            calc_bm_status = Status::InternalError("fault injection error");
436
0
        }
437
0
    });
438
439
    // error handling
440
0
    if (!calc_bm_status.ok()) {
441
0
        if (is_incremental_clone) {
442
0
            RETURN_IF_ERROR(delete_rowsets(to_add, false));
443
0
            LOG(WARNING) << "incremental clone on tablet: " << tablet_id() << " failed due to "
444
0
                         << calc_bm_status.msg() << ", revert " << to_add.size()
445
0
                         << " rowsets added before.";
446
0
        } else {
447
0
            LOG(WARNING) << "full clone on tablet: " << tablet_id() << " failed due to "
448
0
                         << calc_bm_status.msg() << ", will not update tablet meta.";
449
0
        }
450
0
        return calc_bm_status;
451
0
    }
452
453
    // full clone, calculate delete bitmap succeeded, update rowset
454
0
    if (!is_incremental_clone) {
455
0
        RETURN_IF_ERROR(delete_rowsets(to_delete, false));
456
0
        add_rowsets(to_add);
457
        // reconstruct from tablet meta
458
0
        _timestamped_version_tracker.construct_versioned_tracker(_tablet_meta->all_rs_metas());
459
460
        // check the rowsets used for delete bitmap calculation is equal to the rowsets
461
        // that we can capture by version
462
0
        if (keys_type() == UNIQUE_KEYS && enable_unique_key_merge_on_write()) {
463
0
            Version full_version = Version(0, max_version_unlocked().second);
464
0
            std::vector<RowsetSharedPtr> expected_rowsets;
465
0
            auto st = capture_consistent_rowsets(full_version, &expected_rowsets);
466
0
            DCHECK(st.ok()) << st;
467
0
            DCHECK_EQ(base_rowsets_for_full_clone.size(), expected_rowsets.size());
468
0
            if (st.ok() && base_rowsets_for_full_clone.size() != expected_rowsets.size())
469
0
                    [[unlikely]] {
470
0
                LOG(WARNING) << "full clone succeeded, but the count("
471
0
                             << base_rowsets_for_full_clone.size()
472
0
                             << ") of base rowsets used for delete bitmap calculation is not match "
473
0
                                "expect count("
474
0
                             << expected_rowsets.size() << ") we capture from tablet meta";
475
0
            }
476
0
        }
477
0
    }
478
479
    // clear stale rowset
480
0
    for (auto& [v, rs] : _stale_rs_version_map) {
481
0
        _engine.add_unused_rowset(rs);
482
0
    }
483
0
    _stale_rs_version_map.clear();
484
0
    _tablet_meta->clear_stale_rowset();
485
0
    save_meta();
486
487
0
    LOG(INFO) << "finish to revise tablet. tablet_id=" << tablet_id();
488
0
    return Status::OK();
489
0
}
490
491
0
RowsetSharedPtr Tablet::get_rowset(const RowsetId& rowset_id) {
492
0
    std::shared_lock rdlock(_meta_lock);
493
0
    for (auto& version_rowset : _rs_version_map) {
494
0
        if (version_rowset.second->rowset_id() == rowset_id) {
495
0
            return version_rowset.second;
496
0
        }
497
0
    }
498
0
    for (auto& stale_version_rowset : _stale_rs_version_map) {
499
0
        if (stale_version_rowset.second->rowset_id() == rowset_id) {
500
0
            return stale_version_rowset.second;
501
0
        }
502
0
    }
503
0
    return nullptr;
504
0
}
505
506
328
Status Tablet::add_rowset(RowsetSharedPtr rowset) {
507
328
    DCHECK(rowset != nullptr);
508
328
    std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
509
328
    SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
510
    // If the rowset already exist, just return directly.  The rowset_id is an unique-id,
511
    // we can use it to check this situation.
512
328
    if (_contains_rowset(rowset->rowset_id())) {
513
0
        return Status::OK();
514
0
    }
515
    // Otherwise, the version should be not contained in any existing rowset.
516
328
    RETURN_IF_ERROR(_contains_version(rowset->version()));
517
518
328
    RETURN_IF_ERROR(_tablet_meta->add_rs_meta(rowset->rowset_meta()));
519
328
    _rs_version_map[rowset->version()] = rowset;
520
328
    _timestamped_version_tracker.add_version(rowset->version());
521
522
328
    std::vector<RowsetSharedPtr> rowsets_to_delete;
523
    // yiguolei: temp code, should remove the rowset contains by this rowset
524
    // but it should be removed in multi path version
525
353
    for (auto& it : _rs_version_map) {
526
353
        if (rowset->version().contains(it.first) && rowset->version() != it.first) {
527
0
            CHECK(it.second != nullptr)
528
0
                    << "there exist a version=" << it.first
529
0
                    << " contains the input rs with version=" << rowset->version()
530
0
                    << ", but the related rs is null";
531
0
            rowsets_to_delete.push_back(it.second);
532
0
        }
533
353
    }
534
328
    std::vector<RowsetSharedPtr> empty_vec;
535
328
    RETURN_IF_ERROR(modify_rowsets(empty_vec, rowsets_to_delete));
536
328
    ++_newly_created_rowset_num;
537
328
    return Status::OK();
538
328
}
539
540
0
bool Tablet::rowset_exists_unlocked(const RowsetSharedPtr& rowset) {
541
0
    if (auto it = _rs_version_map.find(rowset->version()); it == _rs_version_map.end()) {
542
0
        return false;
543
0
    } else if (rowset->rowset_id() != it->second->rowset_id()) {
544
0
        return false;
545
0
    }
546
0
    return true;
547
0
}
548
549
Status Tablet::modify_rowsets(std::vector<RowsetSharedPtr>& to_add,
550
342
                              std::vector<RowsetSharedPtr>& to_delete, bool check_delete) {
551
    // the compaction process allow to compact the single version, eg: version[4-4].
552
    // this kind of "single version compaction" has same "input version" and "output version".
553
    // which means "to_add->version()" equals to "to_delete->version()".
554
    // So we should delete the "to_delete" before adding the "to_add",
555
    // otherwise, the "to_add" will be deleted from _rs_version_map, eventually.
556
    //
557
    // And if the version of "to_add" and "to_delete" are exactly same. eg:
558
    // to_add:      [7-7]
559
    // to_delete:   [7-7]
560
    // In this case, we no longer need to add the rowset in "to_delete" to
561
    // _stale_rs_version_map, but can delete it directly.
562
563
342
    if (to_add.empty() && to_delete.empty()) {
564
328
        return Status::OK();
565
328
    }
566
567
14
    if (check_delete) {
568
13
        for (auto&& rs : to_delete) {
569
13
            if (auto it = _rs_version_map.find(rs->version()); it == _rs_version_map.end()) {
570
0
                return Status::Error<DELETE_VERSION_ERROR>(
571
0
                        "try to delete not exist version {} from {}", rs->version().to_string(),
572
0
                        tablet_id());
573
13
            } else if (rs->rowset_id() != it->second->rowset_id()) {
574
0
                return Status::Error<DELETE_VERSION_ERROR>(
575
0
                        "try to delete version {} from {}, but rowset id changed, delete rowset id "
576
0
                        "is {}, exists rowsetid is {}",
577
0
                        rs->version().to_string(), tablet_id(), rs->rowset_id().to_string(),
578
0
                        it->second->rowset_id().to_string());
579
0
            }
580
13
        }
581
13
    }
582
583
14
    bool same_version = true;
584
14
    std::sort(to_add.begin(), to_add.end(), Rowset::comparator);
585
14
    std::sort(to_delete.begin(), to_delete.end(), Rowset::comparator);
586
14
    if (to_add.size() == to_delete.size()) {
587
26
        for (int i = 0; i < to_add.size(); ++i) {
588
13
            if (to_add[i]->version() != to_delete[i]->version()) {
589
0
                same_version = false;
590
0
                break;
591
0
            }
592
13
        }
593
13
    } else {
594
1
        same_version = false;
595
1
    }
596
597
14
    std::vector<RowsetMetaSharedPtr> rs_metas_to_delete;
598
14
    for (auto& rs : to_delete) {
599
13
        rs_metas_to_delete.push_back(rs->rowset_meta());
600
13
        _rs_version_map.erase(rs->version());
601
602
13
        if (!same_version) {
603
            // put compaction rowsets in _stale_rs_version_map.
604
0
            _stale_rs_version_map[rs->version()] = rs;
605
0
        }
606
13
    }
607
608
14
    std::vector<RowsetMetaSharedPtr> rs_metas_to_add;
609
14
    for (auto& rs : to_add) {
610
14
        rs_metas_to_add.push_back(rs->rowset_meta());
611
14
        _rs_version_map[rs->version()] = rs;
612
613
14
        if (!same_version) {
614
            // If version are same, then _timestamped_version_tracker
615
            // already has this version, no need to add again.
616
1
            _timestamped_version_tracker.add_version(rs->version());
617
1
        }
618
14
        ++_newly_created_rowset_num;
619
14
    }
620
621
14
    _tablet_meta->modify_rs_metas(rs_metas_to_add, rs_metas_to_delete, same_version);
622
623
14
    if (!same_version) {
624
        // add rs_metas_to_delete to tracker
625
1
        _timestamped_version_tracker.add_stale_path_version(rs_metas_to_delete);
626
13
    } else {
627
        // delete rowset in "to_delete" directly
628
13
        for (auto& rs : to_delete) {
629
13
            LOG(INFO) << "add unused rowset " << rs->rowset_id() << " because of same version";
630
13
            _engine.add_unused_rowset(rs);
631
13
        }
632
13
    }
633
14
    return Status::OK();
634
14
}
635
636
5
void Tablet::add_rowsets(const std::vector<RowsetSharedPtr>& to_add) {
637
5
    if (to_add.empty()) {
638
0
        return;
639
0
    }
640
5
    std::vector<RowsetMetaSharedPtr> rs_metas;
641
5
    rs_metas.reserve(to_add.size());
642
5
    for (auto& rs : to_add) {
643
5
        _rs_version_map.emplace(rs->version(), rs);
644
5
        _timestamped_version_tracker.add_version(rs->version());
645
5
        rs_metas.push_back(rs->rowset_meta());
646
5
    }
647
5
    _tablet_meta->modify_rs_metas(rs_metas, {});
648
5
}
649
650
5
Status Tablet::delete_rowsets(const std::vector<RowsetSharedPtr>& to_delete, bool move_to_stale) {
651
5
    if (to_delete.empty()) {
652
0
        return Status::OK();
653
0
    }
654
5
    std::vector<RowsetMetaSharedPtr> rs_metas;
655
5
    rs_metas.reserve(to_delete.size());
656
5
    for (const auto& rs : to_delete) {
657
5
        rs_metas.push_back(rs->rowset_meta());
658
5
        _rs_version_map.erase(rs->version());
659
5
    }
660
5
    _tablet_meta->modify_rs_metas({}, rs_metas, !move_to_stale);
661
5
    if (move_to_stale) {
662
0
        for (const auto& rs : to_delete) {
663
0
            _stale_rs_version_map[rs->version()] = rs;
664
0
        }
665
0
        _timestamped_version_tracker.add_stale_path_version(rs_metas);
666
5
    } else {
667
5
        for (const auto& rs : to_delete) {
668
5
            _timestamped_version_tracker.delete_version(rs->version());
669
5
            _engine.add_unused_rowset(rs);
670
5
            RETURN_IF_ERROR(RowsetMetaManager::remove(_data_dir->get_meta(), tablet_uid(),
671
5
                                                      rs->rowset_meta()->rowset_id()));
672
5
        }
673
5
    }
674
5
    return Status::OK();
675
5
}
676
677
// snapshot manager may call this api to check if version exists, so that
678
// the version maybe not exist
679
const RowsetSharedPtr Tablet::get_rowset_by_version(const Version& version,
680
11
                                                    bool find_in_stale) const {
681
11
    auto iter = _rs_version_map.find(version);
682
11
    if (iter == _rs_version_map.end()) {
683
0
        if (find_in_stale) {
684
0
            return get_stale_rowset_by_version(version);
685
0
        }
686
0
        return nullptr;
687
0
    }
688
11
    return iter->second;
689
11
}
690
691
0
const RowsetSharedPtr Tablet::get_stale_rowset_by_version(const Version& version) const {
692
0
    auto iter = _stale_rs_version_map.find(version);
693
0
    if (iter == _stale_rs_version_map.end()) {
694
0
        VLOG_NOTICE << "no rowset for version:" << version << ", tablet: " << tablet_id();
695
0
        return nullptr;
696
0
    }
697
0
    return iter->second;
698
0
}
699
700
// Already under _meta_lock
701
28
const RowsetSharedPtr Tablet::rowset_with_max_version() const {
702
28
    Version max_version = _tablet_meta->max_version();
703
28
    if (max_version.first == -1) {
704
0
        return nullptr;
705
0
    }
706
707
28
    auto iter = _rs_version_map.find(max_version);
708
28
    if (iter == _rs_version_map.end()) {
709
0
        DCHECK(false) << "invalid version:" << max_version;
710
0
        return nullptr;
711
0
    }
712
28
    return iter->second;
713
28
}
714
715
TabletSchemaSPtr Tablet::tablet_schema_with_merged_max_schema_version(
716
40
        const std::vector<RowsetMetaSharedPtr>& rowset_metas) {
717
40
    RowsetMetaSharedPtr max_schema_version_rs = *std::max_element(
718
40
            rowset_metas.begin(), rowset_metas.end(),
719
173
            [](const RowsetMetaSharedPtr& a, const RowsetMetaSharedPtr& b) {
720
173
                return !a->tablet_schema()
721
173
                               ? true
722
173
                               : (!b->tablet_schema()
723
173
                                          ? false
724
173
                                          : a->tablet_schema()->schema_version() <
725
173
                                                    b->tablet_schema()->schema_version());
726
173
            });
727
40
    TabletSchemaSPtr target_schema = max_schema_version_rs->tablet_schema();
728
40
    if (target_schema->num_variant_columns() > 0) {
729
        // For variant columns tablet schema need to be the merged wide tablet schema
730
0
        std::vector<TabletSchemaSPtr> schemas;
731
0
        std::transform(rowset_metas.begin(), rowset_metas.end(), std::back_inserter(schemas),
732
0
                       [](const RowsetMetaSharedPtr& rs_meta) { return rs_meta->tablet_schema(); });
733
0
        static_cast<void>(
734
0
                vectorized::schema_util::get_least_common_schema(schemas, nullptr, target_schema));
735
0
        VLOG_DEBUG << "dump schema: " << target_schema->dump_structure();
736
0
    }
737
40
    return target_schema;
738
40
}
739
740
0
RowsetSharedPtr Tablet::_rowset_with_largest_size() {
741
0
    RowsetSharedPtr largest_rowset = nullptr;
742
0
    for (auto& it : _rs_version_map) {
743
0
        if (it.second->empty() || it.second->zero_num_rows()) {
744
0
            continue;
745
0
        }
746
0
        if (largest_rowset == nullptr || it.second->rowset_meta()->index_disk_size() >
747
0
                                                 largest_rowset->rowset_meta()->index_disk_size()) {
748
0
            largest_rowset = it.second;
749
0
        }
750
0
    }
751
752
0
    return largest_rowset;
753
0
}
754
755
// add inc rowset should not persist tablet meta, because it will be persisted when publish txn.
756
10.3k
Status Tablet::add_inc_rowset(const RowsetSharedPtr& rowset) {
757
10.3k
    DCHECK(rowset != nullptr);
758
10.3k
    std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
759
10.3k
    SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
760
10.3k
    if (_contains_rowset(rowset->rowset_id())) {
761
0
        return Status::OK();
762
0
    }
763
10.3k
    RETURN_IF_ERROR(_contains_version(rowset->version()));
764
765
10.3k
    RETURN_IF_ERROR(_tablet_meta->add_rs_meta(rowset->rowset_meta()));
766
10.3k
    _rs_version_map[rowset->version()] = rowset;
767
768
10.3k
    _timestamped_version_tracker.add_version(rowset->version());
769
770
10.3k
    ++_newly_created_rowset_num;
771
10.3k
    return Status::OK();
772
10.3k
}
773
774
8
void Tablet::_delete_stale_rowset_by_version(const Version& version) {
775
8
    RowsetMetaSharedPtr rowset_meta = _tablet_meta->acquire_stale_rs_meta_by_version(version);
776
8
    if (rowset_meta == nullptr) {
777
8
        return;
778
8
    }
779
0
    _tablet_meta->delete_stale_rs_meta_by_version(version);
780
0
    VLOG_NOTICE << "delete stale rowset. tablet=" << tablet_id() << ", version=" << version;
781
0
}
782
783
1
void Tablet::delete_expired_stale_rowset() {
784
1
    int64_t now = UnixSeconds();
785
    // hold write lock while processing stable rowset
786
1
    {
787
1
        std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
788
1
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
789
        // Compute the end time to delete rowsets, when a expired rowset createtime less then this time, it will be deleted.
790
1
        double expired_stale_sweep_endtime =
791
1
                ::difftime(now, config::tablet_rowset_stale_sweep_time_sec);
792
1
        if (config::tablet_rowset_stale_sweep_by_size) {
793
0
            expired_stale_sweep_endtime = now;
794
0
        }
795
796
1
        std::vector<int64_t> path_id_vec;
797
        // capture the path version to delete
798
1
        _timestamped_version_tracker.capture_expired_paths(
799
1
                static_cast<int64_t>(expired_stale_sweep_endtime), &path_id_vec);
800
801
1
        if (path_id_vec.empty()) {
802
0
            return;
803
0
        }
804
805
1
        const RowsetSharedPtr lastest_delta = rowset_with_max_version();
806
1
        if (lastest_delta == nullptr) {
807
0
            LOG(WARNING) << "lastest_delta is null " << tablet_id();
808
0
            return;
809
0
        }
810
811
        // fetch missing version before delete
812
1
        std::vector<Version> missed_versions;
813
1
        calc_missed_versions_unlocked(lastest_delta->end_version(), &missed_versions);
814
815
1
        if (!missed_versions.empty()) {
816
0
            LOG(WARNING) << "tablet:" << tablet_id()
817
0
                         << ", missed version for version:" << lastest_delta->end_version();
818
0
            _print_missed_versions(missed_versions);
819
0
            return;
820
0
        }
821
822
        // do check consistent operation
823
1
        auto path_id_iter = path_id_vec.begin();
824
825
1
        std::map<int64_t, PathVersionListSharedPtr> stale_version_path_map;
826
5
        while (path_id_iter != path_id_vec.end()) {
827
4
            PathVersionListSharedPtr version_path =
828
4
                    _timestamped_version_tracker.fetch_and_delete_path_by_id(*path_id_iter);
829
830
4
            Version test_version = Version(0, lastest_delta->end_version());
831
4
            stale_version_path_map[*path_id_iter] = version_path;
832
833
4
            Status status = capture_consistent_versions(test_version, nullptr, false, false);
834
            // 1. When there is no consistent versions, we must reconstruct the tracker.
835
4
            if (!status.ok()) {
836
                // 2. fetch missing version after delete
837
0
                std::vector<Version> after_missed_versions;
838
0
                calc_missed_versions_unlocked(lastest_delta->end_version(), &after_missed_versions);
839
840
                // 2.1 check whether missed_versions and after_missed_versions are the same.
841
                // when they are the same, it means we can delete the path securely.
842
0
                bool is_missing = missed_versions.size() != after_missed_versions.size();
843
844
0
                if (!is_missing) {
845
0
                    for (int ver_index = 0; ver_index < missed_versions.size(); ver_index++) {
846
0
                        if (missed_versions[ver_index] != after_missed_versions[ver_index]) {
847
0
                            is_missing = true;
848
0
                            break;
849
0
                        }
850
0
                    }
851
0
                }
852
853
0
                if (is_missing) {
854
0
                    LOG(WARNING) << "The consistent version check fails, there are bugs. "
855
0
                                 << "Reconstruct the tracker to recover versions in tablet="
856
0
                                 << tablet_id();
857
858
                    // 3. try to recover
859
0
                    _timestamped_version_tracker.recover_versioned_tracker(stale_version_path_map);
860
861
                    // 4. double check the consistent versions
862
                    // fetch missing version after recover
863
0
                    std::vector<Version> recover_missed_versions;
864
0
                    calc_missed_versions_unlocked(lastest_delta->end_version(),
865
0
                                                  &recover_missed_versions);
866
867
                    // 4.1 check whether missed_versions and recover_missed_versions are the same.
868
                    // when they are the same, it means we recover successfully.
869
0
                    bool is_recover_missing =
870
0
                            missed_versions.size() != recover_missed_versions.size();
871
872
0
                    if (!is_recover_missing) {
873
0
                        for (int ver_index = 0; ver_index < missed_versions.size(); ver_index++) {
874
0
                            if (missed_versions[ver_index] != recover_missed_versions[ver_index]) {
875
0
                                is_recover_missing = true;
876
0
                                break;
877
0
                            }
878
0
                        }
879
0
                    }
880
881
                    // 5. check recover fail, version is mission
882
0
                    if (is_recover_missing) {
883
0
                        if (!config::ignore_rowset_stale_unconsistent_delete) {
884
0
                            LOG(FATAL)
885
0
                                    << "rowset stale unconsistent delete. tablet= " << tablet_id();
886
0
                        } else {
887
0
                            LOG(WARNING)
888
0
                                    << "rowset stale unconsistent delete. tablet= " << tablet_id();
889
0
                        }
890
0
                    }
891
0
                }
892
0
                return;
893
0
            }
894
4
            path_id_iter++;
895
4
        }
896
897
1
        auto old_size = _stale_rs_version_map.size();
898
1
        auto old_meta_size = _tablet_meta->all_stale_rs_metas().size();
899
900
        // do delete operation
901
1
        auto to_delete_iter = stale_version_path_map.begin();
902
5
        while (to_delete_iter != stale_version_path_map.end()) {
903
4
            std::vector<TimestampedVersionSharedPtr>& to_delete_version =
904
4
                    to_delete_iter->second->timestamped_versions();
905
8
            for (auto& timestampedVersion : to_delete_version) {
906
8
                auto it = _stale_rs_version_map.find(timestampedVersion->version());
907
8
                if (it != _stale_rs_version_map.end()) {
908
                    // delete rowset
909
0
                    it->second->clear_cache();
910
0
                    _engine.add_unused_rowset(it->second);
911
0
                    _stale_rs_version_map.erase(it);
912
0
                    VLOG_NOTICE << "delete stale rowset tablet=" << tablet_id() << " version["
913
0
                                << timestampedVersion->version().first << ","
914
0
                                << timestampedVersion->version().second
915
0
                                << "] move to unused_rowset success " << std::fixed
916
0
                                << expired_stale_sweep_endtime;
917
8
                } else {
918
8
                    LOG(WARNING) << "delete stale rowset tablet=" << tablet_id() << " version["
919
8
                                 << timestampedVersion->version().first << ","
920
8
                                 << timestampedVersion->version().second
921
8
                                 << "] not find in stale rs version map";
922
8
                }
923
8
                _delete_stale_rowset_by_version(timestampedVersion->version());
924
8
            }
925
4
            to_delete_iter++;
926
4
        }
927
928
1
        bool reconstructed = _reconstruct_version_tracker_if_necessary();
929
930
1
        VLOG_NOTICE << "delete stale rowset _stale_rs_version_map tablet=" << tablet_id()
931
0
                    << " current_size=" << _stale_rs_version_map.size() << " old_size=" << old_size
932
0
                    << " current_meta_size=" << _tablet_meta->all_stale_rs_metas().size()
933
0
                    << " old_meta_size=" << old_meta_size << " sweep endtime " << std::fixed
934
0
                    << expired_stale_sweep_endtime << ", reconstructed=" << reconstructed;
935
1
    }
936
#ifndef BE_TEST
937
    {
938
        std::shared_lock<std::shared_mutex> rlock(_meta_lock);
939
        save_meta();
940
    }
941
#endif
942
1
}
943
944
1
bool Tablet::_reconstruct_version_tracker_if_necessary() {
945
1
    double orphan_vertex_ratio = _timestamped_version_tracker.get_orphan_vertex_ratio();
946
1
    if (orphan_vertex_ratio >= config::tablet_version_graph_orphan_vertex_ratio) {
947
1
        _timestamped_version_tracker.construct_versioned_tracker(
948
1
                _tablet_meta->all_rs_metas(), _tablet_meta->all_stale_rs_metas());
949
1
        return true;
950
1
    }
951
0
    return false;
952
1
}
953
954
Status Tablet::capture_consistent_versions(const Version& spec_version,
955
                                           std::vector<Version>* version_path,
956
14
                                           bool skip_missing_version, bool quiet) const {
957
14
    Status status =
958
14
            _timestamped_version_tracker.capture_consistent_versions(spec_version, version_path);
959
14
    if (!status.ok() && !quiet) {
960
1
        std::vector<Version> missed_versions;
961
1
        calc_missed_versions_unlocked(spec_version.second, &missed_versions);
962
1
        if (missed_versions.empty()) {
963
            // if version_path is null, it may be a compaction check logic.
964
            // so to avoid print too many logs.
965
0
            if (version_path != nullptr) {
966
0
                LOG(WARNING) << "tablet:" << tablet_id()
967
0
                             << ", version already has been merged. spec_version: " << spec_version
968
0
                             << ", max_version: " << max_version_unlocked();
969
0
            }
970
0
            status = Status::Error<VERSION_ALREADY_MERGED>(
971
0
                    "missed_versions is empty, spec_version "
972
0
                    "{}, max_version {}, tablet_id {}",
973
0
                    spec_version.second, max_version_unlocked().second, tablet_id());
974
1
        } else {
975
1
            if (version_path != nullptr) {
976
1
                LOG(WARNING) << "status:" << status << ", tablet:" << tablet_id()
977
1
                             << ", missed version for version:" << spec_version;
978
1
                _print_missed_versions(missed_versions);
979
1
                if (skip_missing_version) {
980
0
                    LOG(WARNING) << "force skipping missing version for tablet:" << tablet_id();
981
0
                    return Status::OK();
982
0
                }
983
1
            }
984
1
        }
985
1
    }
986
987
14
    DBUG_EXECUTE_IF("TTablet::capture_consistent_versions.inject_failure", {
988
14
        auto tablet_id = dp->param<int64>("tablet_id", -1);
989
14
        if (tablet_id != -1 && tablet_id == _tablet_meta->tablet_id()) {
990
14
            status = Status::Error<VERSION_ALREADY_MERGED>("version already merged");
991
14
        }
992
14
    });
993
994
14
    return status;
995
14
}
996
997
0
Status Tablet::check_version_integrity(const Version& version, bool quiet) {
998
0
    std::shared_lock rdlock(_meta_lock);
999
0
    return capture_consistent_versions(version, nullptr, false, quiet);
1000
0
}
1001
1002
24
bool Tablet::exceed_version_limit(int32_t limit) const {
1003
24
    if (_tablet_meta->version_count() > limit) {
1004
0
        exceed_version_limit_counter << 1;
1005
0
        return true;
1006
0
    }
1007
24
    return false;
1008
24
}
1009
1010
// If any rowset contains the specific version, it means the version already exist
1011
1
bool Tablet::check_version_exist(const Version& version) const {
1012
1
    std::shared_lock rdlock(_meta_lock);
1013
3
    for (auto& it : _rs_version_map) {
1014
3
        if (it.first.contains(version)) {
1015
0
            return true;
1016
0
        }
1017
3
    }
1018
1
    return false;
1019
1
}
1020
1021
// The meta read lock should be held before calling
1022
void Tablet::acquire_version_and_rowsets(
1023
0
        std::vector<std::pair<Version, RowsetSharedPtr>>* version_rowsets) const {
1024
0
    for (const auto& it : _rs_version_map) {
1025
0
        version_rowsets->emplace_back(it.first, it.second);
1026
0
    }
1027
0
}
1028
1029
Status Tablet::capture_consistent_rowsets(const Version& spec_version,
1030
2
                                          std::vector<RowsetSharedPtr>* rowsets) const {
1031
2
    std::vector<Version> version_path;
1032
2
    RETURN_IF_ERROR(capture_consistent_versions(spec_version, &version_path, false, false));
1033
2
    RETURN_IF_ERROR(_capture_consistent_rowsets_unlocked(version_path, rowsets));
1034
2
    return Status::OK();
1035
2
}
1036
1037
Status Tablet::_capture_consistent_rowsets_unlocked(const std::vector<Version>& version_path,
1038
2
                                                    std::vector<RowsetSharedPtr>* rowsets) const {
1039
2
    DCHECK(rowsets != nullptr);
1040
2
    rowsets->reserve(version_path.size());
1041
4
    for (auto& version : version_path) {
1042
4
        bool is_find = false;
1043
4
        do {
1044
4
            auto it = _rs_version_map.find(version);
1045
4
            if (it != _rs_version_map.end()) {
1046
4
                is_find = true;
1047
4
                rowsets->push_back(it->second);
1048
4
                break;
1049
4
            }
1050
1051
0
            auto it_expired = _stale_rs_version_map.find(version);
1052
0
            if (it_expired != _stale_rs_version_map.end()) {
1053
0
                is_find = true;
1054
0
                rowsets->push_back(it_expired->second);
1055
0
                break;
1056
0
            }
1057
0
        } while (false);
1058
1059
4
        if (!is_find) {
1060
0
            return Status::Error<CAPTURE_ROWSET_ERROR>(
1061
0
                    "fail to find Rowset for version. tablet={}, version={}", tablet_id(),
1062
0
                    version.to_string());
1063
0
        }
1064
4
    }
1065
2
    return Status::OK();
1066
2
}
1067
1068
Status Tablet::capture_rs_readers(const Version& spec_version, std::vector<RowSetSplits>* rs_splits,
1069
2
                                  bool skip_missing_version) const {
1070
2
    std::vector<Version> version_path;
1071
2
    RETURN_IF_ERROR(
1072
2
            capture_consistent_versions(spec_version, &version_path, skip_missing_version, false));
1073
1
    RETURN_IF_ERROR(capture_rs_readers(version_path, rs_splits));
1074
1
    return Status::OK();
1075
1
}
1076
1077
Status Tablet::capture_rs_readers(const std::vector<Version>& version_path,
1078
1
                                  std::vector<RowSetSplits>* rs_splits) const {
1079
1
    DCHECK(rs_splits != nullptr && rs_splits->empty());
1080
1
    for (auto version : version_path) {
1081
1
        auto it = _rs_version_map.find(version);
1082
1
        if (it == _rs_version_map.end()) {
1083
0
            VLOG_NOTICE << "fail to find Rowset in rs_version for version. tablet=" << tablet_id()
1084
0
                        << ", version='" << version.first << "-" << version.second;
1085
1086
0
            it = _stale_rs_version_map.find(version);
1087
0
            if (it == _stale_rs_version_map.end()) {
1088
0
                return Status::Error<CAPTURE_ROWSET_READER_ERROR>(
1089
0
                        "fail to find Rowset in stale_rs_version for version. tablet={}, "
1090
0
                        "version={}-{}",
1091
0
                        tablet_id(), version.first, version.second);
1092
0
            }
1093
0
        }
1094
1
        RowsetReaderSharedPtr rs_reader;
1095
1
        auto res = it->second->create_reader(&rs_reader);
1096
1
        if (!res.ok()) {
1097
0
            return Status::Error<CAPTURE_ROWSET_READER_ERROR>(
1098
0
                    "failed to create reader for rowset:{}", it->second->rowset_id().to_string());
1099
0
        }
1100
1
        rs_splits->push_back(RowSetSplits(std::move(rs_reader)));
1101
1
    }
1102
1
    return Status::OK();
1103
1
}
1104
1105
256
bool Tablet::can_do_compaction(size_t path_hash, CompactionType compaction_type) {
1106
256
    if (compaction_type == CompactionType::BASE_COMPACTION && tablet_state() != TABLET_RUNNING) {
1107
        // base compaction can only be done for tablet in TABLET_RUNNING state.
1108
        // but cumulative compaction can be done for TABLET_NOTREADY, such as tablet under alter process.
1109
0
        return false;
1110
0
    }
1111
1112
256
    if (data_dir()->path_hash() != path_hash || !is_used() || !init_succeeded()) {
1113
0
        return false;
1114
0
    }
1115
1116
    // In TABLET_NOTREADY, we keep last 10 versions in new tablet so base tablet max_version
1117
    // not merged in new tablet and then we can do compaction
1118
256
    return tablet_state() == TABLET_RUNNING || tablet_state() == TABLET_NOTREADY;
1119
256
}
1120
1121
uint32_t Tablet::calc_compaction_score(
1122
        CompactionType compaction_type,
1123
283
        std::shared_ptr<CumulativeCompactionPolicy> cumulative_compaction_policy) {
1124
    // Need meta lock, because it will iterator "all_rs_metas" of tablet meta.
1125
283
    std::shared_lock rdlock(_meta_lock);
1126
283
    if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) {
1127
283
        return _calc_cumulative_compaction_score(cumulative_compaction_policy);
1128
283
    } else {
1129
0
        DCHECK_EQ(compaction_type, CompactionType::BASE_COMPACTION);
1130
0
        return _calc_base_compaction_score();
1131
0
    }
1132
283
}
1133
1134
0
uint32_t Tablet::calc_cold_data_compaction_score() const {
1135
0
    uint32_t score = 0;
1136
0
    std::vector<RowsetMetaSharedPtr> cooldowned_rowsets;
1137
0
    int64_t max_delete_version = 0;
1138
0
    {
1139
0
        std::shared_lock rlock(_meta_lock);
1140
0
        for (auto& rs_meta : _tablet_meta->all_rs_metas()) {
1141
0
            if (!rs_meta->is_local()) {
1142
0
                cooldowned_rowsets.push_back(rs_meta);
1143
0
                if (rs_meta->has_delete_predicate() &&
1144
0
                    rs_meta->end_version() > max_delete_version) {
1145
0
                    max_delete_version = rs_meta->end_version();
1146
0
                }
1147
0
            }
1148
0
        }
1149
0
    }
1150
0
    for (auto& rs_meta : cooldowned_rowsets) {
1151
0
        if (rs_meta->end_version() < max_delete_version) {
1152
0
            score += rs_meta->num_segments();
1153
0
        } else {
1154
0
            score += rs_meta->get_compaction_score();
1155
0
        }
1156
0
    }
1157
0
    return (keys_type() != KeysType::DUP_KEYS) ? score * 2 : score;
1158
0
}
1159
1160
uint32_t Tablet::_calc_cumulative_compaction_score(
1161
283
        std::shared_ptr<CumulativeCompactionPolicy> cumulative_compaction_policy) {
1162
283
    if (cumulative_compaction_policy == nullptr) [[unlikely]] {
1163
0
        return 0;
1164
0
    }
1165
#ifndef BE_TEST
1166
    if (_cumulative_compaction_policy == nullptr ||
1167
        _cumulative_compaction_policy->name() != cumulative_compaction_policy->name()) {
1168
        _cumulative_compaction_policy = cumulative_compaction_policy;
1169
    }
1170
#endif
1171
283
    DBUG_EXECUTE_IF("Tablet._calc_cumulative_compaction_score.return", {
1172
283
        LOG_WARNING("Tablet._calc_cumulative_compaction_score.return")
1173
283
                .tag("tablet id", tablet_id());
1174
283
        return 0;
1175
283
    });
1176
283
    return _cumulative_compaction_policy->calc_cumulative_compaction_score(this);
1177
283
}
1178
1179
0
uint32_t Tablet::_calc_base_compaction_score() const {
1180
0
    uint32_t score = 0;
1181
0
    const int64_t point = cumulative_layer_point();
1182
0
    bool base_rowset_exist = false;
1183
0
    bool has_delete = false;
1184
0
    for (auto& rs_meta : _tablet_meta->all_rs_metas()) {
1185
0
        if (rs_meta->start_version() == 0) {
1186
0
            base_rowset_exist = true;
1187
0
        }
1188
0
        if (rs_meta->start_version() >= point || !rs_meta->is_local()) {
1189
            // all_rs_metas() is not sorted, so we use _continue_ other than _break_ here.
1190
0
            continue;
1191
0
        }
1192
0
        if (rs_meta->has_delete_predicate()) {
1193
0
            has_delete = true;
1194
0
        }
1195
0
        score += rs_meta->get_compaction_score();
1196
0
    }
1197
1198
    // In the time series compaction policy, we want the base compaction to be triggered
1199
    // when there are delete versions present.
1200
0
    if (_tablet_meta->compaction_policy() == CUMULATIVE_TIME_SERIES_POLICY) {
1201
0
        return (base_rowset_exist && has_delete) ? score : 0;
1202
0
    }
1203
1204
    // base不存在可能是tablet正在做alter table,先不选它,设score=0
1205
0
    return base_rowset_exist ? score : 0;
1206
0
}
1207
1208
0
void Tablet::calc_missed_versions(int64_t spec_version, std::vector<Version>* missed_versions) {
1209
0
    std::shared_lock rdlock(_meta_lock);
1210
0
    calc_missed_versions_unlocked(spec_version, missed_versions);
1211
0
}
1212
1213
// for example:
1214
//     [0-4][5-5][8-8][9-9]
1215
// if spec_version = 6, we still return {7} other than {6, 7}
1216
void Tablet::calc_missed_versions_unlocked(int64_t spec_version,
1217
2
                                           std::vector<Version>* missed_versions) const {
1218
2
    DCHECK(spec_version > 0) << "invalid spec_version: " << spec_version;
1219
2
    std::list<Version> existing_versions;
1220
8
    for (auto& rs : _tablet_meta->all_rs_metas()) {
1221
8
        existing_versions.emplace_back(rs->version());
1222
8
    }
1223
1224
    // sort the existing versions in ascending order
1225
11
    existing_versions.sort([](const Version& a, const Version& b) {
1226
        // simple because 2 versions are certainly not overlapping
1227
11
        return a.first < b.first;
1228
11
    });
1229
1230
    // From the first version(=0),  find the missing version until spec_version
1231
2
    int64_t last_version = -1;
1232
8
    for (const Version& version : existing_versions) {
1233
8
        if (version.first > last_version + 1) {
1234
4
            for (int64_t i = last_version + 1; i < version.first && i <= spec_version; ++i) {
1235
2
                missed_versions->emplace_back(Version(i, i));
1236
2
            }
1237
2
        }
1238
8
        last_version = version.second;
1239
8
        if (last_version >= spec_version) {
1240
2
            break;
1241
2
        }
1242
8
    }
1243
2
    for (int64_t i = last_version + 1; i <= spec_version; ++i) {
1244
0
        missed_versions->emplace_back(Version(i, i));
1245
0
    }
1246
2
}
1247
1248
0
void Tablet::max_continuous_version_from_beginning(Version* version, Version* max_version) {
1249
0
    bool has_version_cross;
1250
0
    std::shared_lock rdlock(_meta_lock);
1251
0
    _max_continuous_version_from_beginning_unlocked(version, max_version, &has_version_cross);
1252
0
}
1253
1254
void Tablet::_max_continuous_version_from_beginning_unlocked(Version* version, Version* max_version,
1255
0
                                                             bool* has_version_cross) const {
1256
0
    std::vector<Version> existing_versions;
1257
0
    *has_version_cross = false;
1258
0
    for (auto& rs : _tablet_meta->all_rs_metas()) {
1259
0
        existing_versions.emplace_back(rs->version());
1260
0
    }
1261
1262
    // sort the existing versions in ascending order
1263
0
    std::sort(existing_versions.begin(), existing_versions.end(),
1264
0
              [](const Version& left, const Version& right) {
1265
                  // simple because 2 versions are certainly not overlapping
1266
0
                  return left.first < right.first;
1267
0
              });
1268
1269
0
    Version max_continuous_version = {-1, -1};
1270
0
    for (int i = 0; i < existing_versions.size(); ++i) {
1271
0
        if (existing_versions[i].first > max_continuous_version.second + 1) {
1272
0
            break;
1273
0
        } else if (existing_versions[i].first <= max_continuous_version.second) {
1274
0
            *has_version_cross = true;
1275
0
        }
1276
0
        max_continuous_version = existing_versions[i];
1277
0
    }
1278
0
    *version = max_continuous_version;
1279
    // tablet may not has rowset, eg, tablet has just been clear for restore.
1280
0
    if (max_version != nullptr && !existing_versions.empty()) {
1281
0
        *max_version = existing_versions.back();
1282
0
    }
1283
0
}
1284
1285
38
void Tablet::calculate_cumulative_point() {
1286
38
    std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
1287
38
    SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
1288
38
    int64_t ret_cumulative_point;
1289
38
    _cumulative_compaction_policy->calculate_cumulative_point(
1290
38
            this, _tablet_meta->all_rs_metas(), _cumulative_point, &ret_cumulative_point);
1291
1292
38
    if (ret_cumulative_point == K_INVALID_CUMULATIVE_POINT) {
1293
10
        return;
1294
10
    }
1295
28
    set_cumulative_layer_point(ret_cumulative_point);
1296
28
}
1297
1298
// NOTE: only used when create_table, so it is sure that there is no concurrent reader and writer.
1299
0
void Tablet::delete_all_files() {
1300
    // Release resources like memory and disk space.
1301
0
    std::shared_lock rdlock(_meta_lock);
1302
0
    for (auto it : _rs_version_map) {
1303
0
        static_cast<void>(it.second->remove());
1304
0
    }
1305
0
    _rs_version_map.clear();
1306
1307
0
    for (auto it : _stale_rs_version_map) {
1308
0
        static_cast<void>(it.second->remove());
1309
0
    }
1310
0
    _stale_rs_version_map.clear();
1311
0
}
1312
1313
0
void Tablet::check_tablet_path_exists() {
1314
0
    if (!tablet_path().empty()) {
1315
0
        std::error_code ec;
1316
0
        if (std::filesystem::is_directory(tablet_path(), ec)) {
1317
0
            _is_tablet_path_exists.store(true, std::memory_order_relaxed);
1318
0
        } else if (ec.value() == ENOENT || ec.value() == 0) {
1319
0
            _is_tablet_path_exists.store(false, std::memory_order_relaxed);
1320
0
        }
1321
0
    }
1322
0
}
1323
1324
0
bool Tablet::check_path(const std::string& path_to_check) const {
1325
0
    std::shared_lock rdlock(_meta_lock);
1326
0
    if (path_to_check == _tablet_path) {
1327
0
        return true;
1328
0
    }
1329
0
    auto tablet_id_dir = io::Path(_tablet_path).parent_path();
1330
0
    if (path_to_check == tablet_id_dir) {
1331
0
        return true;
1332
0
    }
1333
0
    for (auto& version_rowset : _rs_version_map) {
1334
0
        bool ret = version_rowset.second->check_path(path_to_check);
1335
0
        if (ret) {
1336
0
            return true;
1337
0
        }
1338
0
    }
1339
0
    for (auto& stale_version_rowset : _stale_rs_version_map) {
1340
0
        bool ret = stale_version_rowset.second->check_path(path_to_check);
1341
0
        if (ret) {
1342
0
            return true;
1343
0
        }
1344
0
    }
1345
0
    return false;
1346
0
}
1347
1348
1
void Tablet::_print_missed_versions(const std::vector<Version>& missed_versions) const {
1349
1
    std::stringstream ss;
1350
1
    ss << tablet_id() << " has " << missed_versions.size() << " missed version:";
1351
    // print at most 10 version
1352
3
    for (int i = 0; i < 10 && i < missed_versions.size(); ++i) {
1353
2
        ss << missed_versions[i] << ",";
1354
2
    }
1355
1
    LOG(WARNING) << ss.str();
1356
1
}
1357
1358
10.6k
Status Tablet::_contains_version(const Version& version) {
1359
    // check if there exist a rowset contains the added rowset
1360
336k
    for (auto& it : _rs_version_map) {
1361
336k
        if (it.first.contains(version)) {
1362
            // TODO(lingbin): Is this check unnecessary?
1363
            // because the value type is std::shared_ptr, when will it be nullptr?
1364
            // In addition, in this class, there are many places that do not make this judgment
1365
            // when access _rs_version_map's value.
1366
0
            CHECK(it.second != nullptr) << "there exist a version=" << it.first
1367
0
                                        << " contains the input rs with version=" << version
1368
0
                                        << ", but the related rs is null";
1369
0
            return Status::Error<PUSH_VERSION_ALREADY_EXIST>("Tablet push duplicate version {}",
1370
0
                                                             version.to_string());
1371
0
        }
1372
336k
    }
1373
1374
10.6k
    return Status::OK();
1375
10.6k
}
1376
1377
550
TabletInfo Tablet::get_tablet_info() const {
1378
550
    return TabletInfo(tablet_id(), tablet_uid());
1379
550
}
1380
1381
32
std::vector<RowsetSharedPtr> Tablet::pick_candidate_rowsets_to_cumulative_compaction() {
1382
32
    std::vector<RowsetSharedPtr> candidate_rowsets;
1383
32
    if (_cumulative_point == K_INVALID_CUMULATIVE_POINT) {
1384
0
        return candidate_rowsets;
1385
0
    }
1386
32
    return _pick_visible_rowsets_to_compaction(_cumulative_point,
1387
32
                                               std::numeric_limits<int64_t>::max());
1388
32
}
1389
1390
1
std::vector<RowsetSharedPtr> Tablet::pick_candidate_rowsets_to_base_compaction() {
1391
1
    return _pick_visible_rowsets_to_compaction(std::numeric_limits<int64_t>::min(),
1392
1
                                               _cumulative_point - 1);
1393
1
}
1394
1395
std::vector<RowsetSharedPtr> Tablet::_pick_visible_rowsets_to_compaction(
1396
33
        int64_t min_start_version, int64_t max_start_version) {
1397
33
    auto [visible_version, update_ts] = get_visible_version_and_time();
1398
33
    bool update_time_long = MonotonicMillis() - update_ts >
1399
33
                            config::compaction_keep_invisible_version_timeout_sec * 1000L;
1400
33
    int32_t keep_invisible_version_limit =
1401
33
            update_time_long ? config::compaction_keep_invisible_version_min_count
1402
33
                             : config::compaction_keep_invisible_version_max_count;
1403
1404
33
    std::vector<RowsetSharedPtr> candidate_rowsets;
1405
33
    {
1406
33
        std::shared_lock rlock(_meta_lock);
1407
427
        for (const auto& [version, rs] : _rs_version_map) {
1408
427
            int64_t version_start = version.first;
1409
            // rowset is remote or rowset is not in given range
1410
427
            if (!rs->is_local() || version_start < min_start_version ||
1411
427
                version_start > max_start_version) {
1412
37
                continue;
1413
37
            }
1414
1415
            // can compact, met one of the conditions:
1416
            // 1. had been visible;
1417
            // 2. exceeds the limit of keep invisible versions.
1418
390
            int64_t version_end = version.second;
1419
390
            if (version_end <= visible_version ||
1420
390
                version_end > visible_version + keep_invisible_version_limit) {
1421
390
                candidate_rowsets.push_back(rs);
1422
390
            }
1423
390
        }
1424
33
    }
1425
33
    std::sort(candidate_rowsets.begin(), candidate_rowsets.end(), Rowset::comparator);
1426
33
    return candidate_rowsets;
1427
33
}
1428
1429
0
std::vector<RowsetSharedPtr> Tablet::pick_candidate_rowsets_to_full_compaction() {
1430
0
    std::vector<RowsetSharedPtr> candidate_rowsets;
1431
0
    traverse_rowsets([&candidate_rowsets](const auto& rs) {
1432
        // Do full compaction on all local rowsets.
1433
0
        if (rs->is_local()) {
1434
0
            candidate_rowsets.emplace_back(rs);
1435
0
        }
1436
0
    });
1437
0
    std::sort(candidate_rowsets.begin(), candidate_rowsets.end(), Rowset::comparator);
1438
0
    return candidate_rowsets;
1439
0
}
1440
1441
4
std::vector<RowsetSharedPtr> Tablet::pick_first_consecutive_empty_rowsets(int limit) {
1442
4
    std::vector<RowsetSharedPtr> consecutive_empty_rowsets;
1443
4
    std::vector<RowsetSharedPtr> candidate_rowsets =
1444
4
            pick_candidate_rowsets_to_cumulative_compaction();
1445
4
    int len = candidate_rowsets.size();
1446
12
    for (int i = 0; i < len - 1; ++i) {
1447
9
        auto rowset = candidate_rowsets[i];
1448
9
        auto next_rowset = candidate_rowsets[i + 1];
1449
1450
        // identify two consecutive rowsets that are empty
1451
9
        if (rowset->num_segments() == 0 && next_rowset->num_segments() == 0 &&
1452
9
            !rowset->rowset_meta()->has_delete_predicate() &&
1453
9
            !next_rowset->rowset_meta()->has_delete_predicate() &&
1454
9
            rowset->end_version() == next_rowset->start_version() - 1) {
1455
1
            consecutive_empty_rowsets.emplace_back(rowset);
1456
1
            consecutive_empty_rowsets.emplace_back(next_rowset);
1457
1
            rowset = next_rowset;
1458
1
            int next_index = i + 2;
1459
1460
            // keep searching for consecutive empty rowsets
1461
6
            while (next_index < len && candidate_rowsets[next_index]->num_segments() == 0 &&
1462
6
                   !candidate_rowsets[next_index]->rowset_meta()->has_delete_predicate() &&
1463
6
                   rowset->end_version() == candidate_rowsets[next_index]->start_version() - 1) {
1464
5
                consecutive_empty_rowsets.emplace_back(candidate_rowsets[next_index]);
1465
5
                rowset = candidate_rowsets[next_index++];
1466
5
            }
1467
            // if the number of consecutive empty rowset reach the limit,
1468
            // and there are still rowsets following them
1469
1
            if (consecutive_empty_rowsets.size() >= limit && next_index < len) {
1470
1
                return consecutive_empty_rowsets;
1471
1
            } else {
1472
                // current rowset is not empty, start searching from that rowset in the next
1473
0
                i = next_index - 1;
1474
0
                consecutive_empty_rowsets.clear();
1475
0
            }
1476
1
        }
1477
9
    }
1478
1479
3
    return consecutive_empty_rowsets;
1480
4
}
1481
1482
std::vector<RowsetSharedPtr> Tablet::pick_candidate_rowsets_to_build_inverted_index(
1483
18
        const std::set<int64_t>& alter_index_uids, bool is_drop_op) {
1484
18
    std::vector<RowsetSharedPtr> candidate_rowsets;
1485
18
    {
1486
18
        std::shared_lock rlock(_meta_lock);
1487
35
        auto has_alter_inverted_index = [&](RowsetSharedPtr rowset) -> bool {
1488
39
            for (const auto& index_id : alter_index_uids) {
1489
39
                if (rowset->tablet_schema()->has_inverted_index_with_index_id(index_id, "")) {
1490
4
                    return true;
1491
4
                }
1492
39
            }
1493
31
            return false;
1494
35
        };
1495
1496
18
        for (const auto& [version, rs] : _rs_version_map) {
1497
18
            if (!has_alter_inverted_index(rs) && is_drop_op) {
1498
1
                continue;
1499
1
            }
1500
17
            if (has_alter_inverted_index(rs) && !is_drop_op) {
1501
0
                continue;
1502
0
            }
1503
1504
17
            if (rs->is_local()) {
1505
17
                candidate_rowsets.push_back(rs);
1506
17
            }
1507
17
        }
1508
18
    }
1509
18
    std::sort(candidate_rowsets.begin(), candidate_rowsets.end(), Rowset::comparator);
1510
18
    return candidate_rowsets;
1511
18
}
1512
1513
0
std::string Tablet::_get_rowset_info_str(RowsetSharedPtr rowset, bool delete_flag) {
1514
0
    const Version& ver = rowset->version();
1515
0
    std::string disk_size = PrettyPrinter::print(
1516
0
            static_cast<uint64_t>(rowset->rowset_meta()->total_disk_size()), TUnit::BYTES);
1517
0
    return strings::Substitute("[$0-$1] $2 $3 $4 $5 $6", ver.first, ver.second,
1518
0
                               rowset->num_segments(), (delete_flag ? "DELETE" : "DATA"),
1519
0
                               SegmentsOverlapPB_Name(rowset->rowset_meta()->segments_overlap()),
1520
0
                               rowset->rowset_id().to_string(), disk_size);
1521
0
}
1522
1523
33
std::tuple<int64_t, int64_t> Tablet::get_visible_version_and_time() const {
1524
    // some old tablet has bug, its partition_id is 0, fe couldn't update its visible version.
1525
    // so let this tablet's visible version become int64 max.
1526
33
    auto version_info = std::atomic_load_explicit(&_visible_version, std::memory_order_relaxed);
1527
33
    if (version_info != nullptr && partition_id() != 0) {
1528
0
        return std::make_tuple(version_info->version.load(std::memory_order_relaxed),
1529
0
                               version_info->update_ts);
1530
33
    } else {
1531
33
        return std::make_tuple(std::numeric_limits<int64_t>::max(),
1532
33
                               std::numeric_limits<int64_t>::max());
1533
33
    }
1534
33
}
1535
1536
// For http compaction action
1537
0
void Tablet::get_compaction_status(std::string* json_result) {
1538
0
    rapidjson::Document root;
1539
0
    root.SetObject();
1540
1541
0
    rapidjson::Document path_arr;
1542
0
    path_arr.SetArray();
1543
1544
0
    std::vector<RowsetSharedPtr> rowsets;
1545
0
    std::vector<RowsetSharedPtr> stale_rowsets;
1546
0
    std::vector<bool> delete_flags;
1547
0
    {
1548
0
        std::shared_lock rdlock(_meta_lock);
1549
0
        rowsets.reserve(_rs_version_map.size());
1550
0
        for (auto& it : _rs_version_map) {
1551
0
            rowsets.push_back(it.second);
1552
0
        }
1553
0
        std::sort(rowsets.begin(), rowsets.end(), Rowset::comparator);
1554
1555
0
        stale_rowsets.reserve(_stale_rs_version_map.size());
1556
0
        for (auto& it : _stale_rs_version_map) {
1557
0
            stale_rowsets.push_back(it.second);
1558
0
        }
1559
0
        std::sort(stale_rowsets.begin(), stale_rowsets.end(), Rowset::comparator);
1560
1561
0
        delete_flags.reserve(rowsets.size());
1562
0
        for (auto& rs : rowsets) {
1563
0
            delete_flags.push_back(rs->rowset_meta()->has_delete_predicate());
1564
0
        }
1565
        // get snapshot version path json_doc
1566
0
        _timestamped_version_tracker.get_stale_version_path_json_doc(path_arr);
1567
0
    }
1568
0
    rapidjson::Value cumulative_policy_type;
1569
0
    std::string policy_type_str = "cumulative compaction policy not initializied";
1570
0
    if (_cumulative_compaction_policy != nullptr) {
1571
0
        policy_type_str = _cumulative_compaction_policy->name();
1572
0
    }
1573
0
    cumulative_policy_type.SetString(policy_type_str.c_str(), policy_type_str.length(),
1574
0
                                     root.GetAllocator());
1575
0
    root.AddMember("cumulative policy type", cumulative_policy_type, root.GetAllocator());
1576
0
    root.AddMember("cumulative point", _cumulative_point.load(), root.GetAllocator());
1577
0
    rapidjson::Value cumu_value;
1578
0
    std::string format_str = ToStringFromUnixMillis(_last_cumu_compaction_failure_millis.load());
1579
0
    cumu_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1580
0
    root.AddMember("last cumulative failure time", cumu_value, root.GetAllocator());
1581
0
    rapidjson::Value base_value;
1582
0
    format_str = ToStringFromUnixMillis(_last_base_compaction_failure_millis.load());
1583
0
    base_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1584
0
    root.AddMember("last base failure time", base_value, root.GetAllocator());
1585
0
    rapidjson::Value full_value;
1586
0
    format_str = ToStringFromUnixMillis(_last_full_compaction_failure_millis.load());
1587
0
    full_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1588
0
    root.AddMember("last full failure time", full_value, root.GetAllocator());
1589
0
    rapidjson::Value cumu_success_value;
1590
0
    format_str = ToStringFromUnixMillis(_last_cumu_compaction_success_millis.load());
1591
0
    cumu_success_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1592
0
    root.AddMember("last cumulative success time", cumu_success_value, root.GetAllocator());
1593
0
    rapidjson::Value base_success_value;
1594
0
    format_str = ToStringFromUnixMillis(_last_base_compaction_success_millis.load());
1595
0
    base_success_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1596
0
    root.AddMember("last base success time", base_success_value, root.GetAllocator());
1597
0
    rapidjson::Value full_success_value;
1598
0
    format_str = ToStringFromUnixMillis(_last_full_compaction_success_millis.load());
1599
0
    full_success_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1600
0
    root.AddMember("last full success time", full_success_value, root.GetAllocator());
1601
0
    rapidjson::Value base_schedule_value;
1602
0
    format_str = ToStringFromUnixMillis(_last_base_compaction_schedule_millis.load());
1603
0
    base_schedule_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1604
0
    root.AddMember("last base schedule time", base_schedule_value, root.GetAllocator());
1605
0
    rapidjson::Value base_compaction_status_value;
1606
0
    base_compaction_status_value.SetString(_last_base_compaction_status.c_str(),
1607
0
                                           _last_base_compaction_status.length(),
1608
0
                                           root.GetAllocator());
1609
0
    root.AddMember("last base status", base_compaction_status_value, root.GetAllocator());
1610
1611
    // last single replica compaction status
1612
    // "single replica compaction status": {
1613
    //     "remote peer": "172.100.1.0:10875",
1614
    //     "last failure status": "",
1615
    //     "last fetched rowset": "[8-10]"
1616
    // }
1617
0
    rapidjson::Document status;
1618
0
    status.SetObject();
1619
0
    TReplicaInfo replica_info;
1620
0
    std::string dummp_token;
1621
0
    if (tablet_meta()->tablet_schema()->enable_single_replica_compaction() &&
1622
0
        StorageEngine::instance()->get_peer_replica_info(tablet_id(), &replica_info,
1623
0
                                                         &dummp_token)) {
1624
        // remote peer
1625
0
        rapidjson::Value peer_addr;
1626
0
        std::string addr = replica_info.host + ":" + std::to_string(replica_info.brpc_port);
1627
0
        peer_addr.SetString(addr.c_str(), addr.length(), status.GetAllocator());
1628
0
        status.AddMember("remote peer", peer_addr, status.GetAllocator());
1629
        // last failure status
1630
0
        rapidjson::Value compaction_status;
1631
0
        compaction_status.SetString(_last_single_compaction_failure_status.c_str(),
1632
0
                                    _last_single_compaction_failure_status.length(),
1633
0
                                    status.GetAllocator());
1634
0
        status.AddMember("last failure status", compaction_status, status.GetAllocator());
1635
        // last fetched rowset
1636
0
        rapidjson::Value version;
1637
0
        std::string fetched_version = _last_fetched_version.to_string();
1638
0
        version.SetString(fetched_version.c_str(), fetched_version.length(), status.GetAllocator());
1639
0
        status.AddMember("last fetched rowset", version, status.GetAllocator());
1640
0
        root.AddMember("single replica compaction status", status, root.GetAllocator());
1641
0
    }
1642
1643
    // print all rowsets' version as an array
1644
0
    rapidjson::Document versions_arr;
1645
0
    rapidjson::Document missing_versions_arr;
1646
0
    versions_arr.SetArray();
1647
0
    missing_versions_arr.SetArray();
1648
0
    int64_t last_version = -1;
1649
0
    for (int i = 0; i < rowsets.size(); ++i) {
1650
0
        const Version& ver = rowsets[i]->version();
1651
0
        if (ver.first != last_version + 1) {
1652
0
            rapidjson::Value miss_value;
1653
0
            miss_value.SetString(
1654
0
                    strings::Substitute("[$0-$1]", last_version + 1, ver.first - 1).c_str(),
1655
0
                    missing_versions_arr.GetAllocator());
1656
0
            missing_versions_arr.PushBack(miss_value, missing_versions_arr.GetAllocator());
1657
0
        }
1658
0
        rapidjson::Value value;
1659
0
        std::string version_str = _get_rowset_info_str(rowsets[i], delete_flags[i]);
1660
0
        value.SetString(version_str.c_str(), version_str.length(), versions_arr.GetAllocator());
1661
0
        versions_arr.PushBack(value, versions_arr.GetAllocator());
1662
0
        last_version = ver.second;
1663
0
    }
1664
0
    root.AddMember("rowsets", versions_arr, root.GetAllocator());
1665
0
    root.AddMember("missing_rowsets", missing_versions_arr, root.GetAllocator());
1666
1667
    // print all stale rowsets' version as an array
1668
0
    rapidjson::Document stale_versions_arr;
1669
0
    stale_versions_arr.SetArray();
1670
0
    for (int i = 0; i < stale_rowsets.size(); ++i) {
1671
0
        const Version& ver = stale_rowsets[i]->version();
1672
0
        rapidjson::Value value;
1673
0
        std::string disk_size = PrettyPrinter::print(
1674
0
                static_cast<uint64_t>(stale_rowsets[i]->rowset_meta()->total_disk_size()),
1675
0
                TUnit::BYTES);
1676
0
        std::string version_str = strings::Substitute(
1677
0
                "[$0-$1] $2 $3 $4", ver.first, ver.second, stale_rowsets[i]->num_segments(),
1678
0
                stale_rowsets[i]->rowset_id().to_string(), disk_size);
1679
0
        value.SetString(version_str.c_str(), version_str.length(),
1680
0
                        stale_versions_arr.GetAllocator());
1681
0
        stale_versions_arr.PushBack(value, stale_versions_arr.GetAllocator());
1682
0
    }
1683
0
    root.AddMember("stale_rowsets", stale_versions_arr, root.GetAllocator());
1684
1685
    // add stale version rowsets
1686
0
    root.AddMember("stale version path", path_arr, root.GetAllocator());
1687
1688
    // to json string
1689
0
    rapidjson::StringBuffer strbuf;
1690
0
    rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(strbuf);
1691
0
    root.Accept(writer);
1692
0
    *json_result = std::string(strbuf.GetString());
1693
0
}
1694
1695
0
bool Tablet::do_tablet_meta_checkpoint() {
1696
0
    std::lock_guard<std::shared_mutex> store_lock(_meta_store_lock);
1697
0
    if (_newly_created_rowset_num == 0) {
1698
0
        return false;
1699
0
    }
1700
0
    if (UnixMillis() - _last_checkpoint_time <
1701
0
                config::tablet_meta_checkpoint_min_interval_secs * 1000 &&
1702
0
        _newly_created_rowset_num < config::tablet_meta_checkpoint_min_new_rowsets_num) {
1703
0
        return false;
1704
0
    }
1705
    // hold read-lock other than write-lock, because it will not modify meta structure
1706
0
    std::shared_lock rdlock(_meta_lock);
1707
0
    if (tablet_state() != TABLET_RUNNING) {
1708
0
        LOG(INFO) << "tablet is under state=" << tablet_state()
1709
0
                  << ", not running, skip do checkpoint"
1710
0
                  << ", tablet=" << tablet_id();
1711
0
        return false;
1712
0
    }
1713
0
    VLOG_NOTICE << "start to do tablet meta checkpoint, tablet=" << tablet_id();
1714
0
    save_meta();
1715
    // if save meta successfully, then should remove the rowset meta existing in tablet
1716
    // meta from rowset meta store
1717
0
    for (auto& rs_meta : _tablet_meta->all_rs_metas()) {
1718
        // If we delete it from rowset manager's meta explicitly in previous checkpoint, just skip.
1719
0
        if (rs_meta->is_remove_from_rowset_meta()) {
1720
0
            continue;
1721
0
        }
1722
0
        if (RowsetMetaManager::check_rowset_meta(_data_dir->get_meta(), tablet_uid(),
1723
0
                                                 rs_meta->rowset_id())) {
1724
0
            RETURN_FALSE_IF_ERROR(RowsetMetaManager::remove(_data_dir->get_meta(), tablet_uid(),
1725
0
                                                            rs_meta->rowset_id()));
1726
0
            VLOG_NOTICE << "remove rowset id from meta store because it is already persistent with "
1727
0
                        << "tablet meta, rowset_id=" << rs_meta->rowset_id();
1728
0
        }
1729
0
        rs_meta->set_remove_from_rowset_meta();
1730
0
    }
1731
1732
    // check _stale_rs_version_map to remove meta from rowset meta store
1733
0
    for (auto& rs_meta : _tablet_meta->all_stale_rs_metas()) {
1734
        // If we delete it from rowset manager's meta explicitly in previous checkpoint, just skip.
1735
0
        if (rs_meta->is_remove_from_rowset_meta()) {
1736
0
            continue;
1737
0
        }
1738
0
        if (RowsetMetaManager::check_rowset_meta(_data_dir->get_meta(), tablet_uid(),
1739
0
                                                 rs_meta->rowset_id())) {
1740
0
            RETURN_FALSE_IF_ERROR(RowsetMetaManager::remove(_data_dir->get_meta(), tablet_uid(),
1741
0
                                                            rs_meta->rowset_id()));
1742
0
            VLOG_NOTICE << "remove rowset id from meta store because it is already persistent with "
1743
0
                        << "tablet meta, rowset_id=" << rs_meta->rowset_id();
1744
0
        }
1745
0
        rs_meta->set_remove_from_rowset_meta();
1746
0
    }
1747
1748
0
    if (keys_type() == UNIQUE_KEYS && enable_unique_key_merge_on_write()) {
1749
0
        static_cast<void>(TabletMetaManager::remove_old_version_delete_bitmap(
1750
0
                _data_dir, tablet_id(), max_version_unlocked().second));
1751
0
    }
1752
1753
0
    _newly_created_rowset_num = 0;
1754
0
    _last_checkpoint_time = UnixMillis();
1755
0
    return true;
1756
0
}
1757
1758
0
bool Tablet::rowset_meta_is_useful(RowsetMetaSharedPtr rowset_meta) {
1759
0
    std::shared_lock rdlock(_meta_lock);
1760
0
    bool find_version = false;
1761
0
    for (auto& version_rowset : _rs_version_map) {
1762
0
        if (version_rowset.second->rowset_id() == rowset_meta->rowset_id()) {
1763
0
            return true;
1764
0
        }
1765
0
        if (version_rowset.second->contains_version(rowset_meta->version())) {
1766
0
            find_version = true;
1767
0
        }
1768
0
    }
1769
0
    for (auto& stale_version_rowset : _stale_rs_version_map) {
1770
0
        if (stale_version_rowset.second->rowset_id() == rowset_meta->rowset_id()) {
1771
0
            return true;
1772
0
        }
1773
0
        if (stale_version_rowset.second->contains_version(rowset_meta->version())) {
1774
0
            find_version = true;
1775
0
        }
1776
0
    }
1777
0
    return !find_version;
1778
0
}
1779
1780
10.6k
bool Tablet::_contains_rowset(const RowsetId rowset_id) {
1781
336k
    for (auto& version_rowset : _rs_version_map) {
1782
336k
        if (version_rowset.second->rowset_id() == rowset_id) {
1783
0
            return true;
1784
0
        }
1785
336k
    }
1786
10.6k
    for (auto& stale_version_rowset : _stale_rs_version_map) {
1787
0
        if (stale_version_rowset.second->rowset_id() == rowset_id) {
1788
0
            return true;
1789
0
        }
1790
0
    }
1791
10.6k
    return false;
1792
10.6k
}
1793
1794
// need check if consecutive version missing in full report
1795
// alter tablet will ignore this check
1796
void Tablet::build_tablet_report_info(TTabletInfo* tablet_info,
1797
                                      bool enable_consecutive_missing_check,
1798
0
                                      bool enable_path_check) {
1799
0
    std::shared_lock rdlock(_meta_lock);
1800
0
    tablet_info->__set_tablet_id(_tablet_meta->tablet_id());
1801
0
    tablet_info->__set_schema_hash(_tablet_meta->schema_hash());
1802
0
    tablet_info->__set_row_count(_tablet_meta->num_rows());
1803
0
    tablet_info->__set_data_size(_tablet_meta->tablet_local_size());
1804
1805
    // Here we need to report to FE if there are any missing versions of tablet.
1806
    // We start from the initial version and traverse backwards until we meet a discontinuous version.
1807
0
    Version cversion;
1808
0
    Version max_version;
1809
0
    bool has_version_cross;
1810
0
    _max_continuous_version_from_beginning_unlocked(&cversion, &max_version, &has_version_cross);
1811
    // cause publish version task runs concurrently, version may be flying
1812
    // so we add a consecutive miss check to solve this problem:
1813
    // if publish version 5 arrives but version 4 flying, we may judge replica miss version
1814
    // and set version miss in tablet_info, which makes fe treat this replica as unhealth
1815
    // and lead to other problems
1816
0
    if (enable_consecutive_missing_check) {
1817
0
        if (cversion.second < max_version.second) {
1818
0
            if (_last_missed_version == cversion.second + 1) {
1819
0
                if (MonotonicSeconds() - _last_missed_time_s >= 60) {
1820
                    // version missed for over 60 seconds
1821
0
                    tablet_info->__set_version_miss(true);
1822
0
                    _last_missed_version = -1;
1823
0
                    _last_missed_time_s = 0;
1824
0
                }
1825
0
            } else {
1826
0
                _last_missed_version = cversion.second + 1;
1827
0
                _last_missed_time_s = MonotonicSeconds();
1828
0
            }
1829
0
        }
1830
0
    } else {
1831
0
        tablet_info->__set_version_miss(cversion.second < max_version.second);
1832
0
    }
1833
1834
0
    DBUG_EXECUTE_IF("Tablet.build_tablet_report_info.version_miss", {
1835
0
        auto tablet_id = dp->param<int64>("tablet_id", -1);
1836
0
        if (tablet_id != -1 && tablet_id == _tablet_meta->tablet_id()) {
1837
0
            auto miss = dp->param<bool>("version_miss", true);
1838
0
            tablet_info->__set_version_miss(miss);
1839
0
        }
1840
0
    });
1841
1842
    // find rowset with max version
1843
0
    auto iter = _rs_version_map.find(max_version);
1844
0
    if (iter == _rs_version_map.end()) {
1845
        // If the tablet is in running state, it must not be doing schema-change. so if we can not
1846
        // access its rowsets, it means that the tablet is bad and needs to be reported to the FE
1847
        // for subsequent repairs (through the cloning task)
1848
0
        if (tablet_state() == TABLET_RUNNING) {
1849
0
            tablet_info->__set_used(false);
1850
0
        }
1851
        // For other states, FE knows that the tablet is in a certain change process, so here
1852
        // still sets the state to normal when reporting. Note that every task has an timeout,
1853
        // so if the task corresponding to this change hangs, when the task timeout, FE will know
1854
        // and perform state modification operations.
1855
0
    }
1856
1857
0
    if (tablet_state() == TABLET_RUNNING) {
1858
0
        if (has_version_cross || is_io_error_too_times() || !data_dir()->is_used()) {
1859
0
            LOG(INFO) << "report " << tablet_id() << " as bad, version_cross=" << has_version_cross
1860
0
                      << ", ioe times=" << get_io_error_times() << ", data_dir used "
1861
0
                      << data_dir()->is_used();
1862
0
            tablet_info->__set_used(false);
1863
0
        }
1864
1865
0
        if (enable_path_check) {
1866
0
            if (!_is_tablet_path_exists.exchange(true, std::memory_order_relaxed)) {
1867
0
                LOG(INFO) << "report " << tablet_id() << " as bad, tablet directory not found";
1868
0
                tablet_info->__set_used(false);
1869
0
            }
1870
0
        }
1871
0
    }
1872
1873
    // There are two cases when tablet state is TABLET_NOTREADY
1874
    // case 1: tablet is doing schema change. Fe knows it's state, doing nothing.
1875
    // case 2: tablet has finished schema change, but failed. Fe will perform recovery.
1876
0
    if (tablet_state() == TABLET_NOTREADY && is_alter_failed()) {
1877
0
        tablet_info->__set_used(false);
1878
0
    }
1879
1880
0
    if (tablet_state() == TABLET_SHUTDOWN) {
1881
0
        tablet_info->__set_used(false);
1882
0
    }
1883
1884
0
    DBUG_EXECUTE_IF("Tablet.build_tablet_report_info.used", {
1885
0
        auto tablet_id = dp->param<int64>("tablet_id", -1);
1886
0
        if (tablet_id != -1 && tablet_id == _tablet_meta->tablet_id()) {
1887
0
            auto used = dp->param<bool>("used", true);
1888
0
            LOG_WARNING("Tablet.build_tablet_report_info.used")
1889
0
                    .tag("tablet id", tablet_id)
1890
0
                    .tag("used", used);
1891
0
            tablet_info->__set_used(used);
1892
0
        } else {
1893
0
            LOG_WARNING("Tablet.build_tablet_report_info.used").tag("tablet id", tablet_id);
1894
0
        }
1895
0
    });
1896
1897
0
    int64_t total_version_count = _tablet_meta->version_count();
1898
1899
    // For compatibility.
1900
    // For old fe, it wouldn't send visible version request to be, then be's visible version is always 0.
1901
    // Let visible_version_count set to total_version_count in be's report.
1902
0
    int64_t visible_version_count = total_version_count;
1903
0
    if (auto [visible_version, _] = get_visible_version_and_time(); visible_version > 0) {
1904
0
        visible_version_count = _tablet_meta->version_count_cross_with_range({0, visible_version});
1905
0
    }
1906
    // the report version is the largest continuous version, same logic as in FE side
1907
0
    tablet_info->__set_version(cversion.second);
1908
    // Useless but it is a required filed in TTabletInfo
1909
0
    tablet_info->__set_version_hash(0);
1910
0
    tablet_info->__set_partition_id(_tablet_meta->partition_id());
1911
0
    tablet_info->__set_storage_medium(_data_dir->storage_medium());
1912
0
    tablet_info->__set_total_version_count(total_version_count);
1913
0
    tablet_info->__set_visible_version_count(visible_version_count);
1914
0
    tablet_info->__set_path_hash(_data_dir->path_hash());
1915
0
    tablet_info->__set_is_in_memory(_tablet_meta->tablet_schema()->is_in_memory());
1916
0
    tablet_info->__set_replica_id(replica_id());
1917
0
    tablet_info->__set_remote_data_size(_tablet_meta->tablet_remote_size());
1918
0
    if (_tablet_meta->cooldown_meta_id().initialized()) { // has cooldowned data
1919
0
        tablet_info->__set_cooldown_term(_cooldown_conf.term);
1920
0
        tablet_info->__set_cooldown_meta_id(_tablet_meta->cooldown_meta_id().to_thrift());
1921
0
    }
1922
0
    if (tablet_state() == TABLET_RUNNING && _tablet_meta->storage_policy_id() > 0) {
1923
        // tablet may not have cooldowned data, but the storage policy is set
1924
0
        tablet_info->__set_cooldown_term(_cooldown_conf.term);
1925
0
    }
1926
0
}
1927
1928
// should use this method to get a copy of current tablet meta
1929
// there are some rowset meta in local meta store and in in-memory tablet meta
1930
// but not in tablet meta in local meta store
1931
0
void Tablet::generate_tablet_meta_copy(TabletMetaSharedPtr new_tablet_meta) const {
1932
0
    std::shared_lock rdlock(_meta_lock);
1933
0
    generate_tablet_meta_copy_unlocked(new_tablet_meta);
1934
0
}
1935
1936
// this is a unlocked version of generate_tablet_meta_copy()
1937
// some method already hold the _meta_lock before calling this,
1938
// such as EngineCloneTask::_finish_clone -> tablet->revise_tablet_meta
1939
2
void Tablet::generate_tablet_meta_copy_unlocked(TabletMetaSharedPtr new_tablet_meta) const {
1940
2
    TabletMetaPB tablet_meta_pb;
1941
2
    _tablet_meta->to_meta_pb(&tablet_meta_pb);
1942
2
    new_tablet_meta->init_from_pb(tablet_meta_pb);
1943
2
}
1944
1945
Status Tablet::prepare_compaction_and_calculate_permits(CompactionType compaction_type,
1946
                                                        const TabletSharedPtr& tablet,
1947
                                                        std::shared_ptr<Compaction>& compaction,
1948
10
                                                        int64_t& permits) {
1949
10
    if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) {
1950
10
        MonotonicStopWatch watch;
1951
10
        watch.start();
1952
1953
10
        compaction = std::make_shared<CumulativeCompaction>(tablet);
1954
10
        DorisMetrics::instance()->cumulative_compaction_request_total->increment(1);
1955
10
        Status res = compaction->prepare_compact();
1956
10
        if (!config::disable_compaction_trace_log &&
1957
10
            watch.elapsed_time() / 1e9 > config::cumulative_compaction_trace_threshold) {
1958
0
            std::stringstream ss;
1959
0
            compaction->runtime_profile()->pretty_print(&ss);
1960
0
            LOG(WARNING) << "prepare cumulative compaction cost " << watch.elapsed_time() / 1e9
1961
0
                         << std::endl
1962
0
                         << ss.str();
1963
0
        }
1964
1965
10
        if (!res.ok()) {
1966
0
            permits = 0;
1967
            // if we meet a delete version, should increase the cumulative point to let base compaction handle the delete version.
1968
            // no need to wait 5s.
1969
0
            if (!(res.msg() == "_last_delete_version.first not equal to -1") ||
1970
0
                config::enable_sleep_between_delete_cumu_compaction) {
1971
0
                tablet->set_last_cumu_compaction_failure_time(UnixMillis());
1972
0
            }
1973
0
            if (!res.is<CUMULATIVE_NO_SUITABLE_VERSION>()) {
1974
0
                DorisMetrics::instance()->cumulative_compaction_request_failed->increment(1);
1975
0
                return Status::InternalError("prepare cumulative compaction with err: {}", res);
1976
0
            }
1977
            // return OK if OLAP_ERR_CUMULATIVE_NO_SUITABLE_VERSION, so that we don't need to
1978
            // print too much useless logs.
1979
            // And because we set permits to 0, so even if we return OK here, nothing will be done.
1980
0
            LOG_INFO(
1981
0
                    "cumulative compaction meet delete rowset, increase cumu point without other "
1982
0
                    "operation.")
1983
0
                    .tag("tablet id:", tablet->tablet_id())
1984
0
                    .tag("after cumulative compaction, cumu point:",
1985
0
                         tablet->cumulative_layer_point());
1986
0
            return Status::OK();
1987
0
        }
1988
10
    } else if (compaction_type == CompactionType::BASE_COMPACTION) {
1989
0
        MonotonicStopWatch watch;
1990
0
        watch.start();
1991
1992
0
        compaction = std::make_shared<BaseCompaction>(tablet);
1993
0
        DorisMetrics::instance()->base_compaction_request_total->increment(1);
1994
0
        Status res = compaction->prepare_compact();
1995
0
        if (!config::disable_compaction_trace_log &&
1996
0
            watch.elapsed_time() / 1e9 > config::base_compaction_trace_threshold) {
1997
0
            std::stringstream ss;
1998
0
            compaction->runtime_profile()->pretty_print(&ss);
1999
0
            LOG(WARNING) << "prepare base compaction cost " << watch.elapsed_time() / 1e9
2000
0
                         << std::endl
2001
0
                         << ss.str();
2002
0
        }
2003
2004
0
        tablet->set_last_base_compaction_status(res.to_string());
2005
0
        if (!res.ok()) {
2006
0
            tablet->set_last_base_compaction_failure_time(UnixMillis());
2007
0
            permits = 0;
2008
0
            if (!res.is<BE_NO_SUITABLE_VERSION>()) {
2009
0
                DorisMetrics::instance()->base_compaction_request_failed->increment(1);
2010
0
                return Status::InternalError("prepare base compaction with err: {}", res);
2011
0
            }
2012
            // return OK if OLAP_ERR_BE_NO_SUITABLE_VERSION, so that we don't need to
2013
            // print too much useless logs.
2014
            // And because we set permits to 0, so even if we return OK here, nothing will be done.
2015
0
            return Status::OK();
2016
0
        }
2017
0
    } else {
2018
0
        DCHECK_EQ(compaction_type, CompactionType::FULL_COMPACTION);
2019
2020
0
        compaction = std::make_shared<FullCompaction>(tablet);
2021
0
        Status res = compaction->prepare_compact();
2022
0
        if (!res.ok()) {
2023
0
            tablet->set_last_full_compaction_failure_time(UnixMillis());
2024
0
            permits = 0;
2025
0
            if (!res.is<FULL_NO_SUITABLE_VERSION>()) {
2026
0
                return Status::InternalError("prepare full compaction with err: {}", res);
2027
0
            }
2028
            // return OK if OLAP_ERR_BE_NO_SUITABLE_VERSION, so that we don't need to
2029
            // print too much useless logs.
2030
            // And because we set permits to 0, so even if we return OK here, nothing will be done.
2031
0
            return Status::OK();
2032
0
        }
2033
0
    }
2034
2035
10
    permits = 0;
2036
    // Time series policy does not rely on permits, it uses goal size to control memory
2037
10
    if (tablet->tablet_meta()->compaction_policy() != CUMULATIVE_TIME_SERIES_POLICY) {
2038
280
        for (auto&& rowset : compaction->input_rowsets()) {
2039
280
            permits += rowset->rowset_meta()->get_compaction_score();
2040
280
        }
2041
10
    } else {
2042
        // permits = 0 means that prepare_compaction failed
2043
0
        permits = 1;
2044
0
    }
2045
10
    return Status::OK();
2046
10
}
2047
2048
0
void Tablet::execute_single_replica_compaction(SingleReplicaCompaction& compaction) {
2049
0
    Status res = compaction.execute_compact();
2050
0
    if (!res.ok()) {
2051
0
        set_last_failure_time(this, compaction, UnixMillis());
2052
0
        set_last_single_compaction_failure_status(res.to_string());
2053
0
        if (res.is<CANCELLED>()) {
2054
0
            DorisMetrics::instance()->single_compaction_request_cancelled->increment(1);
2055
0
            VLOG_CRITICAL << "Cannel fetching from the remote peer. res=" << res
2056
0
                          << ", tablet=" << tablet_id();
2057
0
        } else {
2058
0
            DorisMetrics::instance()->single_compaction_request_failed->increment(1);
2059
0
            LOG(WARNING) << "failed to do single replica compaction. res=" << res
2060
0
                         << ", tablet=" << tablet_id();
2061
0
        }
2062
0
        return;
2063
0
    }
2064
0
    set_last_failure_time(this, compaction, 0);
2065
0
}
2066
2067
0
bool Tablet::should_fetch_from_peer() {
2068
0
    return tablet_meta()->tablet_schema()->enable_single_replica_compaction() &&
2069
0
           StorageEngine::instance()->should_fetch_from_peer(tablet_id());
2070
0
}
2071
2072
3
std::vector<Version> Tablet::get_all_local_versions() {
2073
3
    std::vector<Version> local_versions;
2074
3
    {
2075
3
        std::shared_lock rlock(_meta_lock);
2076
63
        for (const auto& [version, rs] : _rs_version_map) {
2077
63
            if (rs->is_local()) {
2078
53
                local_versions.emplace_back(version);
2079
53
            }
2080
63
        }
2081
3
    }
2082
3
    std::sort(local_versions.begin(), local_versions.end(),
2083
318
              [](const Version& left, const Version& right) { return left.first < right.first; });
2084
3
    return local_versions;
2085
3
}
2086
2087
0
void Tablet::execute_compaction(Compaction& compaction) {
2088
0
    signal::tablet_id = tablet_id();
2089
2090
0
    MonotonicStopWatch watch;
2091
0
    watch.start();
2092
2093
0
    Status res = [&]() { RETURN_IF_CATCH_EXCEPTION({ return compaction.execute_compact(); }); }();
2094
0
    if (!res.ok()) [[unlikely]] {
2095
0
        set_last_failure_time(this, compaction, UnixMillis());
2096
0
        LOG(WARNING) << "failed to do " << compaction.compaction_name()
2097
0
                     << ", tablet=" << tablet_id() << " : " << res;
2098
0
    } else {
2099
0
        set_last_failure_time(this, compaction, 0);
2100
0
    }
2101
2102
0
    if (!config::disable_compaction_trace_log) {
2103
0
        auto need_trace = [&compaction, &watch] {
2104
0
            return compaction.compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION
2105
0
                           ? watch.elapsed_time() / 1e9 >
2106
0
                                     config::cumulative_compaction_trace_threshold
2107
0
                   : compaction.compaction_type() == ReaderType::READER_BASE_COMPACTION
2108
0
                           ? watch.elapsed_time() / 1e9 > config::base_compaction_trace_threshold
2109
0
                           : false;
2110
0
        };
2111
0
        if (need_trace()) {
2112
0
            std::stringstream ss;
2113
0
            compaction.runtime_profile()->pretty_print(&ss);
2114
0
            LOG(WARNING) << "execute " << compaction.compaction_name() << " cost "
2115
0
                         << watch.elapsed_time() / 1e9 << std::endl
2116
0
                         << ss.str();
2117
0
        }
2118
0
    }
2119
0
}
2120
2121
295
Status Tablet::create_initial_rowset(const int64_t req_version) {
2122
295
    if (req_version < 1) {
2123
0
        return Status::Error<CE_CMD_PARAMS_ERROR>(
2124
0
                "init version of tablet should at least 1. req.ver={}", req_version);
2125
0
    }
2126
295
    Version version(0, req_version);
2127
295
    RowsetSharedPtr new_rowset;
2128
    // there is no data in init rowset, so overlapping info is unknown.
2129
295
    RowsetWriterContext context;
2130
295
    context.version = version;
2131
295
    context.rowset_state = VISIBLE;
2132
295
    context.segments_overlap = OVERLAP_UNKNOWN;
2133
295
    context.tablet_schema = tablet_schema();
2134
295
    context.newest_write_timestamp = UnixSeconds();
2135
295
    auto rs_writer = DORIS_TRY(create_rowset_writer(context, false));
2136
295
    RETURN_IF_ERROR(rs_writer->flush());
2137
295
    RETURN_IF_ERROR(rs_writer->build(new_rowset));
2138
295
    RETURN_IF_ERROR(add_rowset(std::move(new_rowset)));
2139
295
    set_cumulative_layer_point(req_version + 1);
2140
295
    return Status::OK();
2141
295
}
2142
2143
Result<std::unique_ptr<RowsetWriter>> Tablet::create_rowset_writer(RowsetWriterContext& context,
2144
340
                                                                   bool vertical) {
2145
340
    context.rowset_id = _engine.next_rowset_id();
2146
340
    _init_context_common_fields(context);
2147
340
    std::unique_ptr<RowsetWriter> rowset_writer;
2148
340
    if (auto st = RowsetFactory::create_rowset_writer(context, vertical, &rowset_writer); !st.ok())
2149
0
            [[unlikely]] {
2150
0
        return unexpected(std::move(st));
2151
0
    }
2152
340
    return rowset_writer;
2153
340
}
2154
2155
// create a rowset writer with rowset_id and seg_id
2156
// after writer, merge this transient rowset with original rowset
2157
Status Tablet::create_transient_rowset_writer(
2158
        RowsetSharedPtr rowset_ptr, std::unique_ptr<RowsetWriter>* rowset_writer,
2159
2
        std::shared_ptr<PartialUpdateInfo> partial_update_info) {
2160
2
    RowsetWriterContext context;
2161
2
    context.rowset_state = PREPARED;
2162
2
    context.segments_overlap = OVERLAPPING;
2163
2
    context.tablet_schema = std::make_shared<TabletSchema>();
2164
    // During a partial update, the extracted columns of a variant should not be included in the tablet schema.
2165
    // This is because the partial update for a variant needs to ignore the extracted columns.
2166
    // Otherwise, the schema types in different rowsets might be inconsistent. When performing a partial update,
2167
    // the complete variant is constructed by reading all the sub-columns of the variant.
2168
2
    context.tablet_schema = rowset_ptr->tablet_schema()->copy_without_variant_extracted_columns();
2169
2
    context.newest_write_timestamp = UnixSeconds();
2170
2
    context.tablet_id = table_id();
2171
2
    context.enable_segcompaction = false;
2172
    // ATTN: context.tablet is a shared_ptr, can't simply set it's value to `this`. We should
2173
    // get the shared_ptr from tablet_manager.
2174
2
    auto tablet = _engine.tablet_manager()->get_tablet(tablet_id());
2175
2
    if (!tablet) {
2176
0
        LOG(WARNING) << "cant find tablet by tablet_id=" << tablet_id();
2177
0
        return Status::NotFound(fmt::format("cant find tablet by tablet_id= {}", tablet_id()));
2178
0
    }
2179
2
    context.tablet = tablet;
2180
2
    context.write_type = DataWriteType::TYPE_DIRECT;
2181
2
    context.partial_update_info = partial_update_info;
2182
2
    context.is_transient_rowset_writer = true;
2183
2
    RETURN_IF_ERROR(
2184
2
            create_transient_rowset_writer(context, rowset_ptr->rowset_id(), rowset_writer));
2185
2
    (*rowset_writer)->set_segment_start_id(rowset_ptr->num_segments());
2186
2
    return Status::OK();
2187
2
}
2188
2189
Status Tablet::create_transient_rowset_writer(RowsetWriterContext& context,
2190
                                              const RowsetId& rowset_id,
2191
2
                                              std::unique_ptr<RowsetWriter>* rowset_writer) {
2192
2
    context.rowset_id = rowset_id;
2193
2
    _init_context_common_fields(context);
2194
2
    return RowsetFactory::create_rowset_writer(context, false, rowset_writer);
2195
2
}
2196
2197
342
void Tablet::_init_context_common_fields(RowsetWriterContext& context) {
2198
342
    context.tablet_uid = tablet_uid();
2199
2200
342
    context.tablet_id = tablet_id();
2201
342
    context.partition_id = partition_id();
2202
342
    context.tablet_schema_hash = schema_hash();
2203
342
    context.rowset_type = tablet_meta()->preferred_rowset_type();
2204
    // Alpha Rowset will be removed in the future, so that if the tablet's default rowset type is
2205
    // alpah rowset, then set the newly created rowset to storage engine's default rowset.
2206
342
    if (context.rowset_type == ALPHA_ROWSET) {
2207
0
        context.rowset_type = _engine.default_rowset_type();
2208
0
    }
2209
342
    if (context.fs != nullptr && context.fs->type() != io::FileSystemType::LOCAL) {
2210
0
        context.rowset_dir = remote_tablet_path(tablet_id());
2211
342
    } else {
2212
342
        context.rowset_dir = tablet_path();
2213
342
    }
2214
342
    context.data_dir = data_dir();
2215
342
    context.enable_unique_key_merge_on_write = enable_unique_key_merge_on_write();
2216
342
}
2217
2218
205
Status Tablet::create_rowset(const RowsetMetaSharedPtr& rowset_meta, RowsetSharedPtr* rowset) {
2219
205
    return RowsetFactory::create_rowset(
2220
205
            _tablet_meta->tablet_schema(),
2221
205
            rowset_meta->is_local() ? _tablet_path : remote_tablet_path(tablet_id()), rowset_meta,
2222
205
            rowset);
2223
205
}
2224
2225
7
Status Tablet::cooldown(RowsetSharedPtr rowset) {
2226
7
    std::unique_lock schema_change_lock(_schema_change_lock, std::try_to_lock);
2227
7
    if (!schema_change_lock.owns_lock()) {
2228
0
        return Status::Error<TRY_LOCK_FAILED>("try schema_change_lock failed");
2229
0
    }
2230
    // Check executing serially with compaction task.
2231
7
    std::unique_lock base_compaction_lock(_base_compaction_lock, std::try_to_lock);
2232
7
    if (!base_compaction_lock.owns_lock()) {
2233
0
        return Status::Error<TRY_LOCK_FAILED>("try base_compaction_lock failed");
2234
0
    }
2235
7
    std::unique_lock cumu_compaction_lock(_cumulative_compaction_lock, std::try_to_lock);
2236
7
    if (!cumu_compaction_lock.owns_lock()) {
2237
0
        return Status::Error<TRY_LOCK_FAILED>("try cumu_compaction_lock failed");
2238
0
    }
2239
7
    std::shared_lock cooldown_conf_rlock(_cooldown_conf_lock);
2240
7
    if (_cooldown_conf.cooldown_replica_id <= 0) { // wait for FE to push cooldown conf
2241
2
        return Status::InternalError("invalid cooldown_replica_id");
2242
2
    }
2243
2244
5
    if (_cooldown_conf.cooldown_replica_id == replica_id()) {
2245
        // this replica is cooldown replica
2246
5
        RETURN_IF_ERROR(_cooldown_data(std::move(rowset)));
2247
5
    } else {
2248
0
        Status st = _follow_cooldowned_data();
2249
0
        if (UNLIKELY(!st.ok())) {
2250
0
            _last_failed_follow_cooldown_time = time(nullptr);
2251
0
            return st;
2252
0
        }
2253
0
        _last_failed_follow_cooldown_time = 0;
2254
0
    }
2255
5
    return Status::OK();
2256
5
}
2257
2258
// hold SHARED `cooldown_conf_lock`
2259
5
Status Tablet::_cooldown_data(RowsetSharedPtr rowset) {
2260
5
    DCHECK(_cooldown_conf.cooldown_replica_id == replica_id());
2261
2262
5
    std::shared_ptr<io::RemoteFileSystem> dest_fs;
2263
5
    RETURN_IF_ERROR(get_remote_file_system(storage_policy_id(), &dest_fs));
2264
5
    RowsetSharedPtr old_rowset = nullptr;
2265
2266
5
    if (rowset) {
2267
0
        const auto& rowset_id = rowset->rowset_id();
2268
0
        const auto& rowset_version = rowset->version();
2269
0
        std::shared_lock meta_rlock(_meta_lock);
2270
0
        auto iter = _rs_version_map.find(rowset_version);
2271
0
        if (iter != _rs_version_map.end() && iter->second->rowset_id() == rowset_id) {
2272
0
            old_rowset = rowset;
2273
0
        }
2274
0
    }
2275
2276
5
    if (!old_rowset) {
2277
5
        old_rowset = pick_cooldown_rowset();
2278
5
    }
2279
2280
5
    if (!old_rowset) {
2281
0
        LOG(INFO) << "cannot pick cooldown rowset in tablet " << tablet_id();
2282
0
        return Status::OK();
2283
0
    }
2284
2285
5
    RowsetId new_rowset_id = _engine.next_rowset_id();
2286
5
    auto pending_rs_guard = _engine.pending_remote_rowsets().add(new_rowset_id);
2287
5
    Status st;
2288
5
    Defer defer {[&] {
2289
5
        if (!st.ok()) {
2290
            // reclaim the incomplete rowset data in remote storage
2291
0
            record_unused_remote_rowset(new_rowset_id, dest_fs->id(), old_rowset->num_segments());
2292
0
        }
2293
5
    }};
2294
5
    auto start = std::chrono::steady_clock::now();
2295
5
    if (st = old_rowset->upload_to(dest_fs.get(), new_rowset_id); !st.ok()) {
2296
0
        return st;
2297
0
    }
2298
2299
5
    auto duration = std::chrono::duration<float>(std::chrono::steady_clock::now() - start);
2300
5
    LOG(INFO) << "Upload rowset " << old_rowset->version() << " " << new_rowset_id.to_string()
2301
5
              << " to " << dest_fs->root_path().native() << ", tablet_id=" << tablet_id()
2302
5
              << ", duration=" << duration.count() << ", capacity=" << old_rowset->data_disk_size()
2303
5
              << ", tp=" << old_rowset->data_disk_size() / duration.count()
2304
5
              << ", old rowset_id=" << old_rowset->rowset_id().to_string();
2305
2306
    // gen a new rowset
2307
5
    auto new_rowset_meta = std::make_shared<RowsetMeta>();
2308
5
    new_rowset_meta->init(old_rowset->rowset_meta().get());
2309
5
    new_rowset_meta->set_rowset_id(new_rowset_id);
2310
5
    new_rowset_meta->set_fs(dest_fs);
2311
5
    new_rowset_meta->set_creation_time(time(nullptr));
2312
5
    UniqueId cooldown_meta_id = UniqueId::gen_uid();
2313
5
    RowsetSharedPtr new_rowset;
2314
5
    RETURN_IF_ERROR(RowsetFactory::create_rowset(_tablet_meta->tablet_schema(),
2315
5
                                                 remote_tablet_path(tablet_id()), new_rowset_meta,
2316
5
                                                 &new_rowset));
2317
2318
5
    {
2319
5
        std::unique_lock meta_wlock(_meta_lock);
2320
5
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
2321
5
        if (tablet_state() == TABLET_RUNNING) {
2322
5
            RETURN_IF_ERROR(delete_rowsets({std::move(old_rowset)}, false));
2323
5
            add_rowsets({std::move(new_rowset)});
2324
            // TODO(plat1ko): process primary key
2325
5
            _tablet_meta->set_cooldown_meta_id(cooldown_meta_id);
2326
5
        }
2327
5
    }
2328
5
    {
2329
5
        std::shared_lock meta_rlock(_meta_lock);
2330
5
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
2331
5
        save_meta();
2332
5
    }
2333
    // Upload cooldowned rowset meta to remote fs
2334
    // ATTN: Even if it is an empty rowset, in order for the followers to synchronize, the coolown meta must be
2335
    // uploaded, otherwise followers may never completely cooldown.
2336
5
    if (auto t = _engine.tablet_manager()->get_tablet(tablet_id());
2337
5
        t != nullptr) { // `t` can be nullptr if it has been dropped
2338
5
        async_write_cooldown_meta(std::move(t));
2339
5
    }
2340
5
    return Status::OK();
2341
5
}
2342
2343
// hold SHARED `cooldown_conf_lock`
2344
Status Tablet::_read_cooldown_meta(const std::shared_ptr<io::RemoteFileSystem>& fs,
2345
0
                                   TabletMetaPB* tablet_meta_pb) {
2346
0
    std::string remote_meta_path = remote_tablet_meta_path(
2347
0
            tablet_id(), _cooldown_conf.cooldown_replica_id, _cooldown_conf.term);
2348
0
    io::FileReaderSPtr tablet_meta_reader;
2349
0
    RETURN_IF_ERROR(fs->open_file(remote_meta_path, &tablet_meta_reader));
2350
0
    auto file_size = tablet_meta_reader->size();
2351
0
    size_t bytes_read;
2352
0
    auto buf = std::unique_ptr<uint8_t[]>(new uint8_t[file_size]);
2353
0
    RETURN_IF_ERROR(tablet_meta_reader->read_at(0, {buf.get(), file_size}, &bytes_read));
2354
0
    RETURN_IF_ERROR(tablet_meta_reader->close());
2355
0
    if (!tablet_meta_pb->ParseFromArray(buf.get(), file_size)) {
2356
0
        return Status::InternalError("malformed tablet meta, path={}/{}", fs->root_path().native(),
2357
0
                                     remote_meta_path);
2358
0
    }
2359
0
    return Status::OK();
2360
0
}
2361
2362
// `rs_metas` MUST already be sorted by `RowsetMeta::comparator`
2363
5
Status check_version_continuity(const std::vector<RowsetMetaSharedPtr>& rs_metas) {
2364
5
    if (rs_metas.size() < 2) {
2365
2
        return Status::OK();
2366
2
    }
2367
3
    auto prev = rs_metas.begin();
2368
7
    for (auto it = rs_metas.begin() + 1; it != rs_metas.end(); ++it) {
2369
4
        if ((*prev)->end_version() + 1 != (*it)->start_version()) {
2370
0
            return Status::InternalError("versions are not continuity: prev={} cur={}",
2371
0
                                         (*prev)->version().to_string(),
2372
0
                                         (*it)->version().to_string());
2373
0
        }
2374
4
        prev = it;
2375
4
    }
2376
3
    return Status::OK();
2377
3
}
2378
2379
// It's guaranteed the write cooldown meta task would be invoked at the end unless BE crashes
2380
// one tablet would at most have one async task to be done
2381
5
void Tablet::async_write_cooldown_meta(TabletSharedPtr tablet) {
2382
5
    ExecEnv::GetInstance()->write_cooldown_meta_executors()->submit(std::move(tablet));
2383
5
}
2384
2385
2
bool Tablet::update_cooldown_conf(int64_t cooldown_term, int64_t cooldown_replica_id) {
2386
2
    std::unique_lock wlock(_cooldown_conf_lock, std::try_to_lock);
2387
2
    if (!wlock.owns_lock()) {
2388
0
        LOG(INFO) << "try cooldown_conf_lock failed, tablet_id=" << tablet_id();
2389
0
        return false;
2390
0
    }
2391
2
    if (cooldown_term <= _cooldown_conf.term) {
2392
0
        return false;
2393
0
    }
2394
2
    LOG(INFO) << "update cooldown conf. tablet_id=" << tablet_id()
2395
2
              << " cooldown_replica_id: " << _cooldown_conf.cooldown_replica_id << " -> "
2396
2
              << cooldown_replica_id << ", cooldown_term: " << _cooldown_conf.term << " -> "
2397
2
              << cooldown_term;
2398
2
    _cooldown_conf.cooldown_replica_id = cooldown_replica_id;
2399
2
    _cooldown_conf.term = cooldown_term;
2400
2
    return true;
2401
2
}
2402
2403
5
Status Tablet::write_cooldown_meta() {
2404
5
    std::shared_lock rlock(_cooldown_conf_lock);
2405
5
    if (_cooldown_conf.cooldown_replica_id != _tablet_meta->replica_id()) {
2406
0
        return Status::Aborted<false>("not cooldown replica({} vs {}) tablet_id={}",
2407
0
                                      _tablet_meta->replica_id(),
2408
0
                                      _cooldown_conf.cooldown_replica_id, tablet_id());
2409
0
    }
2410
2411
5
    std::shared_ptr<io::RemoteFileSystem> fs;
2412
5
    RETURN_IF_ERROR(get_remote_file_system(storage_policy_id(), &fs));
2413
2414
5
    std::vector<RowsetMetaSharedPtr> cooldowned_rs_metas;
2415
5
    UniqueId cooldown_meta_id;
2416
5
    {
2417
5
        std::shared_lock meta_rlock(_meta_lock);
2418
11
        for (auto& rs_meta : _tablet_meta->all_rs_metas()) {
2419
11
            if (!rs_meta->is_local()) {
2420
9
                cooldowned_rs_metas.push_back(rs_meta);
2421
9
            }
2422
11
        }
2423
5
        cooldown_meta_id = _tablet_meta->cooldown_meta_id();
2424
5
    }
2425
5
    if (cooldowned_rs_metas.empty()) {
2426
0
        LOG(INFO) << "no cooldown meta to write, tablet_id=" << tablet_id();
2427
0
        return Status::OK();
2428
0
    }
2429
5
    std::sort(cooldowned_rs_metas.begin(), cooldowned_rs_metas.end(), RowsetMeta::comparator);
2430
5
    DCHECK(cooldowned_rs_metas.front()->start_version() == 0);
2431
    // If version not continuous, it must be a bug
2432
5
    if (auto st = check_version_continuity(cooldowned_rs_metas); !st.ok()) {
2433
0
        DCHECK(st.ok()) << st << " tablet_id=" << tablet_id();
2434
0
        st.set_code(ABORTED);
2435
0
        return st;
2436
0
    }
2437
2438
5
    TabletMetaPB tablet_meta_pb;
2439
5
    auto rs_metas = tablet_meta_pb.mutable_rs_metas();
2440
5
    rs_metas->Reserve(cooldowned_rs_metas.size());
2441
9
    for (auto& rs_meta : cooldowned_rs_metas) {
2442
9
        rs_metas->Add(rs_meta->get_rowset_pb());
2443
9
    }
2444
5
    tablet_meta_pb.mutable_cooldown_meta_id()->set_hi(cooldown_meta_id.hi);
2445
5
    tablet_meta_pb.mutable_cooldown_meta_id()->set_lo(cooldown_meta_id.lo);
2446
2447
5
    std::string remote_meta_path = remote_tablet_meta_path(
2448
5
            tablet_id(), _cooldown_conf.cooldown_replica_id, _cooldown_conf.term);
2449
5
    io::FileWriterPtr tablet_meta_writer;
2450
    // FIXME(plat1ko): What if object store permanently unavailable?
2451
5
    RETURN_IF_ERROR(fs->create_file(remote_meta_path, &tablet_meta_writer));
2452
5
    auto val = tablet_meta_pb.SerializeAsString();
2453
5
    RETURN_IF_ERROR(tablet_meta_writer->append({val.data(), val.size()}));
2454
5
    return tablet_meta_writer->close();
2455
5
}
2456
2457
// hold SHARED `cooldown_conf_lock`
2458
0
Status Tablet::_follow_cooldowned_data() {
2459
0
    DCHECK(_cooldown_conf.cooldown_replica_id != replica_id());
2460
0
    LOG(INFO) << "try to follow cooldowned data. tablet_id=" << tablet_id()
2461
0
              << " cooldown_replica_id=" << _cooldown_conf.cooldown_replica_id
2462
0
              << " local replica=" << replica_id();
2463
2464
0
    std::shared_ptr<io::RemoteFileSystem> fs;
2465
0
    RETURN_IF_ERROR(get_remote_file_system(storage_policy_id(), &fs));
2466
    // MUST executing serially with cold data compaction, because compaction input rowsets may be deleted by this function
2467
0
    std::unique_lock cold_compaction_lock(_cold_compaction_lock, std::try_to_lock);
2468
0
    if (!cold_compaction_lock.owns_lock()) {
2469
0
        return Status::Error<TRY_LOCK_FAILED>("try cold_compaction_lock failed");
2470
0
    }
2471
2472
0
    TabletMetaPB cooldown_meta_pb;
2473
0
    auto st = _read_cooldown_meta(fs, &cooldown_meta_pb);
2474
0
    if (!st.ok()) {
2475
0
        LOG(INFO) << "cannot read cooldown meta: " << st;
2476
0
        return Status::InternalError<false>("cannot read cooldown meta");
2477
0
    }
2478
0
    DCHECK(cooldown_meta_pb.rs_metas_size() > 0);
2479
0
    if (_tablet_meta->cooldown_meta_id() == cooldown_meta_pb.cooldown_meta_id()) {
2480
        // cooldowned rowsets are same, no need to follow
2481
0
        return Status::OK();
2482
0
    }
2483
2484
0
    int64_t cooldowned_version = cooldown_meta_pb.rs_metas().rbegin()->end_version();
2485
2486
0
    std::vector<RowsetSharedPtr> overlap_rowsets;
2487
0
    bool version_aligned = false;
2488
2489
0
    {
2490
0
        std::lock_guard wlock(_meta_lock);
2491
0
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
2492
0
        if (tablet_state() != TABLET_RUNNING) {
2493
0
            return Status::InternalError<false>("tablet not running");
2494
0
        }
2495
2496
0
        for (auto& [v, rs] : _rs_version_map) {
2497
0
            if (v.second <= cooldowned_version) {
2498
0
                overlap_rowsets.push_back(rs);
2499
0
                if (!version_aligned && v.second == cooldowned_version) {
2500
0
                    version_aligned = true;
2501
0
                }
2502
0
            } else if (!rs->is_local()) {
2503
0
                return Status::InternalError<false>(
2504
0
                        "cooldowned version larger than that to follow with cooldown version {}",
2505
0
                        cooldowned_version);
2506
0
            }
2507
0
        }
2508
2509
0
        if (!version_aligned) {
2510
0
            return Status::InternalError<false>("cooldowned version is not aligned with version {}",
2511
0
                                                cooldowned_version);
2512
0
        }
2513
2514
0
        std::sort(overlap_rowsets.begin(), overlap_rowsets.end(), Rowset::comparator);
2515
0
        auto rs_pb_it = cooldown_meta_pb.rs_metas().begin();
2516
0
        auto rs_it = overlap_rowsets.begin();
2517
0
        for (; rs_pb_it != cooldown_meta_pb.rs_metas().end() && rs_it != overlap_rowsets.end();
2518
0
             ++rs_pb_it, ++rs_it) {
2519
            // skip cooldowned rowset with same version in BE
2520
0
            if ((*rs_it)->is_local() || rs_pb_it->end_version() != (*rs_it)->end_version()) {
2521
0
                break;
2522
0
            }
2523
0
        }
2524
0
        std::vector<RowsetSharedPtr> to_delete(rs_it, overlap_rowsets.end());
2525
0
        std::vector<RowsetSharedPtr> to_add;
2526
0
        to_add.reserve(cooldown_meta_pb.rs_metas().end() - rs_pb_it);
2527
0
        for (; rs_pb_it != cooldown_meta_pb.rs_metas().end(); ++rs_pb_it) {
2528
0
            auto rs_meta = std::make_shared<RowsetMeta>();
2529
0
            rs_meta->init_from_pb(*rs_pb_it);
2530
0
            RowsetSharedPtr rs;
2531
0
            RETURN_IF_ERROR(RowsetFactory::create_rowset(
2532
0
                    _tablet_meta->tablet_schema(), remote_tablet_path(tablet_id()), rs_meta, &rs));
2533
0
            to_add.push_back(std::move(rs));
2534
0
        }
2535
        // Note: We CANNOT call `modify_rowsets` here because `modify_rowsets` cannot process version graph correctly.
2536
0
        RETURN_IF_ERROR(delete_rowsets(to_delete, false));
2537
0
        add_rowsets(to_add);
2538
        // TODO(plat1ko): process primary key
2539
0
        _tablet_meta->set_cooldown_meta_id(cooldown_meta_pb.cooldown_meta_id());
2540
0
    }
2541
0
    {
2542
0
        std::lock_guard rlock(_meta_lock);
2543
0
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
2544
0
        save_meta();
2545
0
    }
2546
2547
0
    return Status::OK();
2548
0
}
2549
2550
10
bool Tablet::_has_data_to_cooldown() {
2551
10
    int64_t min_local_version = std::numeric_limits<int64_t>::max();
2552
10
    RowsetSharedPtr rowset;
2553
10
    std::shared_lock meta_rlock(_meta_lock);
2554
    // Ususally once the tablet has done cooldown successfully then the first
2555
    // rowset would always be remote rowset
2556
10
    bool has_cooldowned = false;
2557
29
    for (const auto& [_, rs] : _rs_version_map) {
2558
29
        if (!rs->is_local()) {
2559
3
            has_cooldowned = true;
2560
3
            break;
2561
3
        }
2562
29
    }
2563
32
    for (auto& [v, rs] : _rs_version_map) {
2564
32
        auto predicate = rs->is_local() && v.first < min_local_version;
2565
32
        if (!has_cooldowned) {
2566
25
            predicate = predicate && (rs->data_disk_size() > 0);
2567
25
        }
2568
32
        if (predicate) {
2569
            // this is a local rowset and has data
2570
25
            min_local_version = v.first;
2571
25
            rowset = rs;
2572
25
        }
2573
32
    }
2574
2575
10
    int64_t newest_cooldown_time = 0;
2576
10
    if (rowset != nullptr) {
2577
9
        newest_cooldown_time = _get_newest_cooldown_time(rowset);
2578
9
    }
2579
2580
10
    return (newest_cooldown_time != 0) && (newest_cooldown_time < UnixSeconds());
2581
10
}
2582
2583
9
RowsetSharedPtr Tablet::pick_cooldown_rowset() {
2584
9
    RowsetSharedPtr rowset;
2585
2586
9
    if (!_has_data_to_cooldown()) {
2587
1
        return nullptr;
2588
1
    }
2589
2590
    // TODO(plat1ko): should we maintain `cooldowned_version` in `Tablet`?
2591
8
    int64_t cooldowned_version = -1;
2592
    // We pick the rowset with smallest start version in local.
2593
8
    int64_t min_local_version = std::numeric_limits<int64_t>::max();
2594
8
    {
2595
8
        std::shared_lock meta_rlock(_meta_lock);
2596
26
        for (auto& [v, rs] : _rs_version_map) {
2597
26
            if (!rs->is_local()) {
2598
4
                cooldowned_version = std::max(cooldowned_version, v.second);
2599
22
            } else if (v.first < min_local_version) { // this is a local rowset
2600
22
                min_local_version = v.first;
2601
22
                rowset = rs;
2602
22
            }
2603
26
        }
2604
8
    }
2605
8
    if (!rowset) {
2606
0
        return nullptr;
2607
0
    }
2608
8
    if (tablet_footprint() == 0) {
2609
0
        VLOG_DEBUG << "skip cooldown due to empty tablet_id = " << tablet_id();
2610
0
        return nullptr;
2611
0
    }
2612
8
    if (min_local_version != cooldowned_version + 1) { // ensure version continuity
2613
0
        if (UNLIKELY(cooldowned_version != -1)) {
2614
0
            LOG(WARNING) << "version not continuous. tablet_id=" << tablet_id()
2615
0
                         << " cooldowned_version=" << cooldowned_version
2616
0
                         << " min_local_version=" << min_local_version;
2617
0
        }
2618
0
        return nullptr;
2619
0
    }
2620
8
    return rowset;
2621
8
}
2622
2623
12
int64_t Tablet::_get_newest_cooldown_time(const RowsetSharedPtr& rowset) {
2624
12
    int64_t id = storage_policy_id();
2625
12
    if (id <= 0) {
2626
0
        VLOG_DEBUG << "tablet does not need cooldown, tablet id: " << tablet_id();
2627
0
        return 0;
2628
0
    }
2629
12
    auto storage_policy = get_storage_policy(id);
2630
12
    if (!storage_policy) {
2631
0
        LOG(WARNING) << "Cannot get storage policy: " << id;
2632
0
        return 0;
2633
0
    }
2634
12
    auto cooldown_ttl_sec = storage_policy->cooldown_ttl;
2635
12
    auto cooldown_datetime = storage_policy->cooldown_datetime;
2636
12
    int64_t newest_cooldown_time = std::numeric_limits<int64_t>::max();
2637
2638
12
    if (cooldown_ttl_sec >= 0) {
2639
9
        newest_cooldown_time = rowset->newest_write_timestamp() + cooldown_ttl_sec;
2640
9
    }
2641
12
    if (cooldown_datetime > 0) {
2642
10
        newest_cooldown_time = std::min(newest_cooldown_time, cooldown_datetime);
2643
10
    }
2644
2645
12
    return newest_cooldown_time;
2646
12
}
2647
2648
4
RowsetSharedPtr Tablet::need_cooldown(int64_t* cooldown_timestamp, size_t* file_size) {
2649
4
    RowsetSharedPtr rowset = pick_cooldown_rowset();
2650
4
    if (!rowset) {
2651
1
        VLOG_DEBUG << "pick cooldown rowset, get null, tablet id: " << tablet_id();
2652
1
        return nullptr;
2653
1
    }
2654
2655
3
    auto newest_cooldown_time = _get_newest_cooldown_time(rowset);
2656
2657
    // the rowset should do cooldown job only if it's cooldown ttl plus newest write time is less than
2658
    // current time or it's datatime is less than current time
2659
3
    if (newest_cooldown_time != 0 && newest_cooldown_time < UnixSeconds()) {
2660
3
        *cooldown_timestamp = newest_cooldown_time;
2661
3
        *file_size = rowset->data_disk_size();
2662
3
        VLOG_DEBUG << "tablet need cooldown, tablet id: " << tablet_id()
2663
0
                   << " file_size: " << *file_size;
2664
3
        return rowset;
2665
3
    }
2666
2667
0
    VLOG_DEBUG << "tablet does not need cooldown, tablet id: " << tablet_id()
2668
0
               << " newest write time: " << rowset->newest_write_timestamp();
2669
0
    return nullptr;
2670
3
}
2671
2672
void Tablet::record_unused_remote_rowset(const RowsetId& rowset_id, const std::string& resource,
2673
0
                                         int64_t num_segments) {
2674
0
    auto gc_key = REMOTE_ROWSET_GC_PREFIX + rowset_id.to_string();
2675
0
    RemoteRowsetGcPB gc_pb;
2676
0
    gc_pb.set_resource_id(resource);
2677
0
    gc_pb.set_tablet_id(tablet_id());
2678
0
    gc_pb.set_num_segments(num_segments);
2679
0
    auto st =
2680
0
            _data_dir->get_meta()->put(META_COLUMN_FAMILY_INDEX, gc_key, gc_pb.SerializeAsString());
2681
0
    if (!st.ok()) {
2682
0
        LOG(WARNING) << "failed to record unused remote rowset. tablet_id=" << tablet_id()
2683
0
                     << " rowset_id=" << rowset_id << " resource_id=" << resource;
2684
0
    }
2685
0
}
2686
2687
0
Status Tablet::remove_all_remote_rowsets() {
2688
0
    DCHECK(tablet_state() == TABLET_SHUTDOWN);
2689
0
    std::set<std::string> resource_ids;
2690
0
    for (auto& rs_meta : _tablet_meta->all_rs_metas()) {
2691
0
        if (!rs_meta->is_local()) {
2692
0
            resource_ids.insert(rs_meta->resource_id());
2693
0
        }
2694
0
    }
2695
0
    if (resource_ids.empty()) {
2696
0
        return Status::OK();
2697
0
    }
2698
0
    auto tablet_gc_key = REMOTE_TABLET_GC_PREFIX + std::to_string(tablet_id());
2699
0
    RemoteTabletGcPB gc_pb;
2700
0
    for (auto& resource_id : resource_ids) {
2701
0
        gc_pb.add_resource_ids(resource_id);
2702
0
    }
2703
0
    return _data_dir->get_meta()->put(META_COLUMN_FAMILY_INDEX, tablet_gc_key,
2704
0
                                      gc_pb.SerializeAsString());
2705
0
}
2706
2707
0
void Tablet::update_max_version_schema(const TabletSchemaSPtr& tablet_schema) {
2708
0
    std::lock_guard wrlock(_meta_lock);
2709
0
    SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
2710
    // Double Check for concurrent update
2711
0
    if (!_max_version_schema ||
2712
0
        tablet_schema->schema_version() > _max_version_schema->schema_version()) {
2713
0
        _max_version_schema = tablet_schema;
2714
0
    }
2715
0
}
2716
2717
Status Tablet::_get_segment_column_iterator(
2718
        const BetaRowsetSharedPtr& rowset, uint32_t segid, const TabletColumn& target_column,
2719
        SegmentCacheHandle* segment_cache_handle,
2720
0
        std::unique_ptr<segment_v2::ColumnIterator>* column_iterator, OlapReaderStatistics* stats) {
2721
0
    RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(rowset, segment_cache_handle, true));
2722
    // find segment
2723
0
    auto it = std::find_if(
2724
0
            segment_cache_handle->get_segments().begin(),
2725
0
            segment_cache_handle->get_segments().end(),
2726
0
            [&segid](const segment_v2::SegmentSharedPtr& seg) { return seg->id() == segid; });
2727
0
    if (it == segment_cache_handle->get_segments().end()) {
2728
0
        return Status::NotFound(fmt::format("rowset {} 's segemnt not found, seg_id {}",
2729
0
                                            rowset->rowset_id().to_string(), segid));
2730
0
    }
2731
0
    segment_v2::SegmentSharedPtr segment = *it;
2732
0
    StorageReadOptions opts;
2733
0
    opts.stats = stats;
2734
0
    RETURN_IF_ERROR(segment->new_column_iterator(target_column, column_iterator, &opts));
2735
0
    segment_v2::ColumnIteratorOptions opt {
2736
0
            .use_page_cache = !config::disable_storage_page_cache,
2737
0
            .file_reader = segment->file_reader().get(),
2738
0
            .stats = stats,
2739
0
            .io_ctx = io::IOContext {.reader_type = ReaderType::READER_QUERY},
2740
0
    };
2741
0
    RETURN_IF_ERROR((*column_iterator)->init(opt));
2742
0
    return Status::OK();
2743
0
}
2744
2745
// fetch value by row column
2746
Status Tablet::fetch_value_through_row_column(RowsetSharedPtr input_rowset,
2747
                                              const TabletSchema& tablet_schema, uint32_t segid,
2748
                                              const std::vector<uint32_t>& rowids,
2749
                                              const std::vector<uint32_t>& cids,
2750
0
                                              vectorized::Block& block) {
2751
0
    MonotonicStopWatch watch;
2752
0
    watch.start();
2753
0
    Defer _defer([&]() {
2754
0
        LOG_EVERY_N(INFO, 500) << "fetch_value_by_rowids, cost(us):" << watch.elapsed_time() / 1000
2755
0
                               << ", row_batch_size:" << rowids.size();
2756
0
    });
2757
2758
0
    BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(input_rowset);
2759
0
    CHECK(rowset);
2760
0
    CHECK(tablet_schema.store_row_column());
2761
0
    SegmentCacheHandle segment_cache_handle;
2762
0
    std::unique_ptr<segment_v2::ColumnIterator> column_iterator;
2763
0
    OlapReaderStatistics stats;
2764
0
    RETURN_IF_ERROR(_get_segment_column_iterator(rowset, segid,
2765
0
                                                 tablet_schema.column(BeConsts::ROW_STORE_COL),
2766
0
                                                 &segment_cache_handle, &column_iterator, &stats));
2767
    // get and parse tuple row
2768
0
    vectorized::MutableColumnPtr column_ptr = vectorized::ColumnString::create();
2769
0
    RETURN_IF_ERROR(column_iterator->read_by_rowids(rowids.data(), rowids.size(), column_ptr));
2770
0
    assert(column_ptr->size() == rowids.size());
2771
0
    auto string_column = static_cast<vectorized::ColumnString*>(column_ptr.get());
2772
0
    vectorized::DataTypeSerDeSPtrs serdes;
2773
0
    serdes.resize(cids.size());
2774
0
    std::unordered_map<uint32_t, uint32_t> col_uid_to_idx;
2775
0
    std::vector<std::string> default_values;
2776
0
    default_values.resize(cids.size());
2777
0
    for (int i = 0; i < cids.size(); ++i) {
2778
0
        const TabletColumn& column = tablet_schema.column(cids[i]);
2779
0
        vectorized::DataTypePtr type =
2780
0
                vectorized::DataTypeFactory::instance().create_data_type(column);
2781
0
        col_uid_to_idx[column.unique_id()] = i;
2782
0
        default_values[i] = column.default_value();
2783
0
        serdes[i] = type->get_serde();
2784
0
    }
2785
0
    vectorized::JsonbSerializeUtil::jsonb_to_block(serdes, *string_column, col_uid_to_idx, block,
2786
0
                                                   default_values);
2787
0
    return Status::OK();
2788
0
}
2789
2790
Status Tablet::fetch_value_by_rowids(RowsetSharedPtr input_rowset, uint32_t segid,
2791
                                     const std::vector<uint32_t>& rowids,
2792
                                     const TabletColumn& tablet_column,
2793
0
                                     vectorized::MutableColumnPtr& dst) {
2794
0
    MonotonicStopWatch watch;
2795
0
    watch.start();
2796
0
    Defer _defer([&]() {
2797
0
        LOG_EVERY_N(INFO, 500) << "fetch_value_by_rowids, cost(us):" << watch.elapsed_time() / 1000
2798
0
                               << ", row_batch_size:" << rowids.size();
2799
0
    });
2800
2801
    // read row data
2802
0
    BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(input_rowset);
2803
0
    CHECK(rowset);
2804
0
    SegmentCacheHandle segment_cache_handle;
2805
0
    std::unique_ptr<segment_v2::ColumnIterator> column_iterator;
2806
0
    OlapReaderStatistics stats;
2807
0
    RETURN_IF_ERROR(_get_segment_column_iterator(rowset, segid, tablet_column,
2808
0
                                                 &segment_cache_handle, &column_iterator, &stats));
2809
0
    RETURN_IF_ERROR(column_iterator->read_by_rowids(rowids.data(), rowids.size(), dst));
2810
0
    return Status::OK();
2811
0
}
2812
2813
Status Tablet::lookup_row_data(const Slice& encoded_key, const RowLocation& row_location,
2814
                               RowsetSharedPtr input_rowset, const TupleDescriptor* desc,
2815
                               OlapReaderStatistics& stats, std::string& values,
2816
0
                               bool write_to_cache) {
2817
0
    MonotonicStopWatch watch;
2818
0
    size_t row_size = 1;
2819
0
    watch.start();
2820
0
    Defer _defer([&]() {
2821
0
        LOG_EVERY_N(INFO, 500) << "get a single_row, cost(us):" << watch.elapsed_time() / 1000
2822
0
                               << ", row_size:" << row_size;
2823
0
    });
2824
2825
0
    BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(input_rowset);
2826
0
    CHECK(rowset);
2827
0
    const TabletSchemaSPtr tablet_schema = rowset->tablet_schema();
2828
0
    CHECK(tablet_schema->store_row_column());
2829
0
    SegmentCacheHandle segment_cache_handle;
2830
0
    std::unique_ptr<segment_v2::ColumnIterator> column_iterator;
2831
0
    RETURN_IF_ERROR(_get_segment_column_iterator(rowset, row_location.segment_id,
2832
0
                                                 tablet_schema->column(BeConsts::ROW_STORE_COL),
2833
0
                                                 &segment_cache_handle, &column_iterator, &stats));
2834
    // get and parse tuple row
2835
0
    vectorized::MutableColumnPtr column_ptr = vectorized::ColumnString::create();
2836
0
    std::vector<segment_v2::rowid_t> rowids {static_cast<segment_v2::rowid_t>(row_location.row_id)};
2837
0
    RETURN_IF_ERROR(column_iterator->read_by_rowids(rowids.data(), 1, column_ptr));
2838
0
    assert(column_ptr->size() == 1);
2839
0
    auto string_column = static_cast<vectorized::ColumnString*>(column_ptr.get());
2840
0
    StringRef value = string_column->get_data_at(0);
2841
0
    values = value.to_string();
2842
0
    if (write_to_cache) {
2843
0
        StringRef value = string_column->get_data_at(0);
2844
0
        RowCache::instance()->insert({tablet_id(), encoded_key}, Slice {value.data, value.size});
2845
0
    }
2846
0
    return Status::OK();
2847
0
}
2848
2849
Status Tablet::lookup_row_key(const Slice& encoded_key, TabletSchema* latest_schema,
2850
                              bool with_seq_col,
2851
                              const std::vector<RowsetSharedPtr>& specified_rowsets,
2852
                              RowLocation* row_location, uint32_t version,
2853
                              std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches,
2854
2
                              RowsetSharedPtr* rowset, bool with_rowid, bool is_partial_update) {
2855
2
    SCOPED_BVAR_LATENCY(g_tablet_lookup_rowkey_latency);
2856
2
    size_t seq_col_length = 0;
2857
    // use the latest tablet schema to decide if the tablet has sequence column currently
2858
2
    const TabletSchema* schema =
2859
2
            (latest_schema == nullptr ? _tablet_meta->tablet_schema().get() : latest_schema);
2860
2
    if (schema->has_sequence_col() && with_seq_col) {
2861
2
        seq_col_length = schema->column(schema->sequence_col_idx()).length() + 1;
2862
2
    }
2863
2
    size_t rowid_length = 0;
2864
2
    if (with_rowid && !schema->cluster_key_idxes().empty()) {
2865
0
        rowid_length = PrimaryKeyIndexReader::ROW_ID_LENGTH;
2866
0
    }
2867
2
    Slice key_without_seq =
2868
2
            Slice(encoded_key.get_data(), encoded_key.get_size() - seq_col_length - rowid_length);
2869
2
    RowLocation loc;
2870
2871
2
    bool need_to_check_delete_bitmap = is_partial_update || with_seq_col;
2872
2873
2
    for (size_t i = 0; i < specified_rowsets.size(); i++) {
2874
2
        auto& rs = specified_rowsets[i];
2875
2
        auto& segments_key_bounds = rs->rowset_meta()->get_segments_key_bounds();
2876
2
        int num_segments = rs->num_segments();
2877
2
        DCHECK_EQ(segments_key_bounds.size(), num_segments);
2878
2
        std::vector<uint32_t> picked_segments;
2879
4
        for (int i = num_segments - 1; i >= 0; i--) {
2880
            // If mow table has cluster keys, the key bounds is short keys, not primary keys
2881
            // use PrimaryKeyIndexMetaPB in primary key index?
2882
2
            if (schema->cluster_key_idxes().empty()) {
2883
2
                if (key_without_seq.compare(segments_key_bounds[i].max_key()) > 0 ||
2884
2
                    key_without_seq.compare(segments_key_bounds[i].min_key()) < 0) {
2885
0
                    continue;
2886
0
                }
2887
2
            }
2888
2
            picked_segments.emplace_back(i);
2889
2
        }
2890
2
        if (picked_segments.empty()) {
2891
0
            continue;
2892
0
        }
2893
2894
2
        if (UNLIKELY(segment_caches[i] == nullptr)) {
2895
1
            segment_caches[i] = std::make_unique<SegmentCacheHandle>();
2896
1
            RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(
2897
1
                    std::static_pointer_cast<BetaRowset>(rs), segment_caches[i].get(), true));
2898
1
        }
2899
2
        auto& segments = segment_caches[i]->get_segments();
2900
2
        DCHECK_EQ(segments.size(), num_segments);
2901
2902
2
        for (auto id : picked_segments) {
2903
2
            Status s = segments[id]->lookup_row_key(encoded_key, schema, with_seq_col, with_rowid,
2904
2
                                                    &loc);
2905
2
            if (s.is<KEY_NOT_FOUND>()) {
2906
0
                continue;
2907
0
            }
2908
2
            if (!s.ok() && !s.is<KEY_ALREADY_EXISTS>()) {
2909
0
                return s;
2910
0
            }
2911
2
            if (s.ok() && need_to_check_delete_bitmap) {
2912
                // check if the key is already mark deleted
2913
1
                if (_tablet_meta->delete_bitmap().contains_agg_without_cache(
2914
1
                            {loc.rowset_id, loc.segment_id, version}, loc.row_id)) {
2915
                    // if has sequence col, we continue to compare the sequence_id of
2916
                    // all rowsets, util we find an existing key.
2917
0
                    if (with_seq_col) {
2918
0
                        continue;
2919
0
                    }
2920
                    // The key is deleted, we need to break the loop and return
2921
                    // KEY_NOT_FOUND.
2922
0
                    break;
2923
0
                }
2924
1
            }
2925
            // `st` is either OK or KEY_ALREADY_EXISTS now.
2926
            // for partial update, even if the key is already exists, we still need to
2927
            // read it's original values to keep all columns align.
2928
2
            *row_location = loc;
2929
2
            if (rowset) {
2930
                // return it's rowset
2931
2
                *rowset = rs;
2932
2
            }
2933
            // find it and return
2934
2
            return s;
2935
2
        }
2936
2
    }
2937
0
    g_tablet_pk_not_found << 1;
2938
0
    return Status::Error<ErrorCode::KEY_NOT_FOUND>("can't find key in all rowsets");
2939
2
}
2940
2941
// load segment may do io so it should out lock
2942
Status Tablet::_load_rowset_segments(const RowsetSharedPtr& rowset,
2943
2
                                     std::vector<segment_v2::SegmentSharedPtr>* segments) {
2944
2
    auto beta_rowset = reinterpret_cast<BetaRowset*>(rowset.get());
2945
2
    RETURN_IF_ERROR(beta_rowset->load_segments(segments));
2946
2
    return Status::OK();
2947
2
}
2948
2949
0
Status Tablet::sort_block(vectorized::Block& in_block, vectorized::Block& output_block) {
2950
0
    vectorized::MutableBlock mutable_input_block =
2951
0
            vectorized::MutableBlock::build_mutable_block(&in_block);
2952
0
    vectorized::MutableBlock mutable_output_block =
2953
0
            vectorized::MutableBlock::build_mutable_block(&output_block);
2954
2955
0
    std::shared_ptr<RowInBlockComparator> vec_row_comparator =
2956
0
            std::make_shared<RowInBlockComparator>(_tablet_meta->tablet_schema());
2957
0
    vec_row_comparator->set_block(&mutable_input_block);
2958
2959
0
    std::vector<std::unique_ptr<RowInBlock>> row_in_blocks;
2960
0
    DCHECK(in_block.rows() <= std::numeric_limits<int>::max());
2961
0
    row_in_blocks.reserve(in_block.rows());
2962
0
    for (size_t i = 0; i < in_block.rows(); ++i) {
2963
0
        row_in_blocks.emplace_back(std::make_unique<RowInBlock>(i));
2964
0
    }
2965
0
    std::sort(row_in_blocks.begin(), row_in_blocks.end(),
2966
0
              [&](const std::unique_ptr<RowInBlock>& l,
2967
0
                  const std::unique_ptr<RowInBlock>& r) -> bool {
2968
0
                  auto value = (*vec_row_comparator)(l.get(), r.get());
2969
0
                  DCHECK(value != 0) << "value equel when sort block, l_pos: " << l->_row_pos
2970
0
                                     << " r_pos: " << r->_row_pos;
2971
0
                  return value < 0;
2972
0
              });
2973
0
    std::vector<uint32_t> row_pos_vec;
2974
0
    row_pos_vec.reserve(in_block.rows());
2975
0
    for (int i = 0; i < row_in_blocks.size(); i++) {
2976
0
        row_pos_vec.emplace_back(row_in_blocks[i]->_row_pos);
2977
0
    }
2978
0
    return mutable_output_block.add_rows(&in_block, row_pos_vec.data(),
2979
0
                                         row_pos_vec.data() + in_block.rows());
2980
0
}
2981
2982
Status Tablet::calc_segment_delete_bitmap(RowsetSharedPtr rowset,
2983
                                          const segment_v2::SegmentSharedPtr& seg,
2984
                                          const std::vector<RowsetSharedPtr>& specified_rowsets,
2985
                                          DeleteBitmapPtr delete_bitmap, int64_t end_version,
2986
1
                                          RowsetWriter* rowset_writer) {
2987
1
    OlapStopWatch watch;
2988
1
    auto rowset_id = rowset->rowset_id();
2989
1
    Version dummy_version(end_version + 1, end_version + 1);
2990
1
    auto rowset_schema = rowset->tablet_schema();
2991
1
    bool is_partial_update = rowset_writer && rowset_writer->is_partial_update();
2992
1
    bool have_input_seq_column = false;
2993
1
    if (is_partial_update && rowset_schema->has_sequence_col()) {
2994
0
        std::vector<uint32_t> including_cids =
2995
0
                rowset_writer->get_partial_update_info()->update_cids;
2996
0
        have_input_seq_column =
2997
0
                rowset_schema->has_sequence_col() &&
2998
0
                (std::find(including_cids.cbegin(), including_cids.cend(),
2999
0
                           rowset_schema->sequence_col_idx()) != including_cids.cend());
3000
0
    }
3001
1
    if (rowset_schema->num_variant_columns() > 0) {
3002
        // During partial updates, the extracted columns of a variant should not be included in the rowset schema.
3003
        // This is because the partial update for a variant needs to ignore the extracted columns.
3004
        // Otherwise, the schema types in different rowsets might be inconsistent. When performing a partial update,
3005
        // the complete variant is constructed by reading all the sub-columns of the variant.
3006
0
        rowset_schema = rowset_schema->copy_without_variant_extracted_columns();
3007
0
    }
3008
    // use for partial update
3009
1
    PartialUpdateReadPlan read_plan_ori;
3010
1
    PartialUpdateReadPlan read_plan_update;
3011
1
    int64_t conflict_rows = 0;
3012
1
    int64_t new_generated_rows = 0;
3013
3014
1
    std::map<RowsetId, RowsetSharedPtr> rsid_to_rowset;
3015
1
    rsid_to_rowset[rowset_id] = rowset;
3016
1
    vectorized::Block block = rowset_schema->create_block();
3017
1
    vectorized::Block ordered_block = block.clone_empty();
3018
1
    uint32_t pos = 0;
3019
3020
1
    RETURN_IF_ERROR(seg->load_pk_index_and_bf()); // We need index blocks to iterate
3021
1
    auto pk_idx = seg->get_primary_key_index();
3022
1
    int total = pk_idx->num_rows();
3023
1
    uint32_t row_id = 0;
3024
1
    int32_t remaining = total;
3025
1
    bool exact_match = false;
3026
1
    std::string last_key;
3027
1
    int batch_size = 1024;
3028
    // The data for each segment may be lookup multiple times. Creating a SegmentCacheHandle
3029
    // will update the lru cache, and there will be obvious lock competition in multithreading
3030
    // scenarios, so using a segment_caches to cache SegmentCacheHandle.
3031
1
    std::vector<std::unique_ptr<SegmentCacheHandle>> segment_caches(specified_rowsets.size());
3032
2
    while (remaining > 0) {
3033
1
        std::unique_ptr<segment_v2::IndexedColumnIterator> iter;
3034
1
        RETURN_IF_ERROR(pk_idx->new_iterator(&iter));
3035
3036
1
        size_t num_to_read = std::min(batch_size, remaining);
3037
1
        auto index_type = vectorized::DataTypeFactory::instance().create_data_type(
3038
1
                pk_idx->type_info()->type(), 1, 0);
3039
1
        auto index_column = index_type->create_column();
3040
1
        Slice last_key_slice(last_key);
3041
1
        RETURN_IF_ERROR(iter->seek_at_or_after(&last_key_slice, &exact_match));
3042
1
        auto current_ordinal = iter->get_current_ordinal();
3043
1
        DCHECK(total == remaining + current_ordinal)
3044
0
                << "total: " << total << ", remaining: " << remaining
3045
0
                << ", current_ordinal: " << current_ordinal;
3046
3047
1
        size_t num_read = num_to_read;
3048
1
        RETURN_IF_ERROR(iter->next_batch(&num_read, index_column));
3049
1
        DCHECK(num_to_read == num_read)
3050
0
                << "num_to_read: " << num_to_read << ", num_read: " << num_read;
3051
1
        last_key = index_column->get_data_at(num_read - 1).to_string();
3052
3053
        // exclude last_key, last_key will be read in next batch.
3054
1
        if (num_read == batch_size && num_read != remaining) {
3055
0
            num_read -= 1;
3056
0
        }
3057
3
        for (size_t i = 0; i < num_read; i++, row_id++) {
3058
2
            Slice key = Slice(index_column->get_data_at(i).data, index_column->get_data_at(i).size);
3059
2
            RowLocation loc;
3060
            // calculate row id
3061
2
            if (!_tablet_meta->tablet_schema()->cluster_key_idxes().empty()) {
3062
0
                size_t seq_col_length = 0;
3063
0
                if (_tablet_meta->tablet_schema()->has_sequence_col()) {
3064
0
                    seq_col_length =
3065
0
                            _tablet_meta->tablet_schema()
3066
0
                                    ->column(_tablet_meta->tablet_schema()->sequence_col_idx())
3067
0
                                    .length() +
3068
0
                            1;
3069
0
                }
3070
0
                size_t rowid_length = PrimaryKeyIndexReader::ROW_ID_LENGTH;
3071
0
                Slice key_without_seq =
3072
0
                        Slice(key.get_data(), key.get_size() - seq_col_length - rowid_length);
3073
0
                Slice rowid_slice =
3074
0
                        Slice(key.get_data() + key_without_seq.get_size() + seq_col_length + 1,
3075
0
                              rowid_length - 1);
3076
0
                const auto* type_info =
3077
0
                        get_scalar_type_info<FieldType::OLAP_FIELD_TYPE_UNSIGNED_INT>();
3078
0
                auto rowid_coder = get_key_coder(type_info->type());
3079
0
                RETURN_IF_ERROR(rowid_coder->decode_ascending(&rowid_slice, rowid_length,
3080
0
                                                              (uint8_t*)&row_id));
3081
0
            }
3082
            // same row in segments should be filtered
3083
2
            if (delete_bitmap->contains({rowset_id, seg->id(), DeleteBitmap::TEMP_VERSION_COMMON},
3084
2
                                        row_id)) {
3085
0
                continue;
3086
0
            }
3087
3088
2
            RowsetSharedPtr rowset_find;
3089
2
            auto st = lookup_row_key(key, rowset_schema.get(), true, specified_rowsets, &loc,
3090
2
                                     dummy_version.first - 1, segment_caches, &rowset_find, false,
3091
2
                                     is_partial_update);
3092
2
            bool expected_st = st.ok() || st.is<KEY_NOT_FOUND>() || st.is<KEY_ALREADY_EXISTS>();
3093
            // It's a defensive DCHECK, we need to exclude some common errors to avoid core-dump
3094
            // while stress test
3095
2
            DCHECK(expected_st || st.is<MEM_LIMIT_EXCEEDED>())
3096
0
                    << "unexpected error status while lookup_row_key:" << st;
3097
2
            if (!expected_st) {
3098
0
                return st;
3099
0
            }
3100
2
            if (st.is<KEY_NOT_FOUND>()) {
3101
0
                continue;
3102
0
            }
3103
3104
2
            if (st.is<KEY_ALREADY_EXISTS>() && (!is_partial_update || have_input_seq_column)) {
3105
                // `st.is<KEY_ALREADY_EXISTS>()` means that there exists a row with the same key and larger value
3106
                // in seqeunce column.
3107
                // - If the current load is not a partial update, we just delete current row.
3108
                // - Otherwise, it means that we are doing the alignment process in publish phase due to conflicts
3109
                // during concurrent partial updates. And there exists another load which introduces a row with
3110
                // the same keys and larger sequence column value published successfully after the commit phase
3111
                // of the current load.
3112
                //     - If the columns we update include sequence column, we should delete the current row becase the
3113
                //       partial update on the current row has been `overwritten` by the previous one with larger sequence
3114
                //       column value.
3115
                //     - Otherwise, we should combine the values of the missing columns in the previous row and the values
3116
                //       of the including columns in the current row into a new row.
3117
1
                delete_bitmap->add({rowset_id, seg->id(), DeleteBitmap::TEMP_VERSION_COMMON},
3118
1
                                   row_id);
3119
1
                ++conflict_rows;
3120
1
                continue;
3121
                // NOTE: for partial update which doesn't specify the sequence column, we can't use the sequence column value filled in flush phase
3122
                // as its final value. Otherwise it may cause inconsistency between replicas.
3123
1
            }
3124
1
            if (is_partial_update && rowset_writer != nullptr) {
3125
                // In publish version, record rows to be deleted for concurrent update
3126
                // For example, if version 5 and 6 update a row, but version 6 only see
3127
                // version 4 when write, and when publish version, version 5's value will
3128
                // be marked as deleted and it's update is losed.
3129
                // So here we should read version 5's columns and build a new row, which is
3130
                // consists of version 6's update columns and version 5's origin columns
3131
                // here we build 2 read plan for ori values and update values
3132
0
                prepare_to_read(loc, pos, &read_plan_ori);
3133
0
                prepare_to_read(RowLocation {rowset_id, seg->id(), row_id}, pos, &read_plan_update);
3134
0
                rsid_to_rowset[rowset_find->rowset_id()] = rowset_find;
3135
0
                ++pos;
3136
                // delete bitmap will be calculate when memtable flush and
3137
                // publish. The two stages may see different versions.
3138
                // When there is sequence column, the currently imported data
3139
                // of rowset may be marked for deletion at memtablet flush or
3140
                // publish because the seq column is smaller than the previous
3141
                // rowset.
3142
                // just set 0 as a unified temporary version number, and update to
3143
                // the real version number later.
3144
0
                delete_bitmap->add(
3145
0
                        {loc.rowset_id, loc.segment_id, DeleteBitmap::TEMP_VERSION_COMMON},
3146
0
                        loc.row_id);
3147
0
                delete_bitmap->add({rowset_id, seg->id(), DeleteBitmap::TEMP_VERSION_COMMON},
3148
0
                                   row_id);
3149
0
                ++conflict_rows;
3150
0
                ++new_generated_rows;
3151
0
                continue;
3152
0
            }
3153
            // when st = ok
3154
1
            delete_bitmap->add({loc.rowset_id, loc.segment_id, DeleteBitmap::TEMP_VERSION_COMMON},
3155
1
                               loc.row_id);
3156
1
            ++conflict_rows;
3157
1
        }
3158
1
        remaining -= num_read;
3159
1
    }
3160
    // DCHECK_EQ(total, row_id) << "segment total rows: " << total << " row_id:" << row_id;
3161
3162
1
    if (config::enable_merge_on_write_correctness_check) {
3163
1
        RowsetIdUnorderedSet rowsetids;
3164
1
        for (const auto& rowset : specified_rowsets) {
3165
1
            rowsetids.emplace(rowset->rowset_id());
3166
1
            VLOG_NOTICE << "[tabletID:" << tablet_id() << "]"
3167
0
                        << "[add_sentinel_mark_to_delete_bitmap][end_version:" << end_version << "]"
3168
0
                        << "add:" << rowset->rowset_id();
3169
1
        }
3170
1
        add_sentinel_mark_to_delete_bitmap(delete_bitmap.get(), rowsetids);
3171
1
    }
3172
3173
1
    if (pos > 0) {
3174
0
        auto partial_update_info = rowset_writer->get_partial_update_info();
3175
0
        DCHECK(partial_update_info);
3176
0
        RETURN_IF_ERROR(generate_new_block_for_partial_update(
3177
0
                rowset_schema, partial_update_info.get(), read_plan_ori, read_plan_update,
3178
0
                rsid_to_rowset, &block));
3179
0
        RETURN_IF_ERROR(sort_block(block, ordered_block));
3180
0
        RETURN_IF_ERROR(rowset_writer->flush_single_block(&ordered_block));
3181
0
        auto cost_us = watch.get_elapse_time_us();
3182
0
        if (cost_us > 10 * 1000) {
3183
0
            LOG(INFO) << "calc segment delete bitmap for partial update, tablet: " << tablet_id()
3184
0
                      << " rowset: " << rowset_id << " seg_id: " << seg->id()
3185
0
                      << " dummy_version: " << end_version + 1 << " rows: " << seg->num_rows()
3186
0
                      << " conflict rows: " << conflict_rows
3187
0
                      << " new generated rows: " << new_generated_rows
3188
0
                      << " bimap num: " << delete_bitmap->delete_bitmap.size()
3189
0
                      << " cost: " << cost_us << "(us)";
3190
0
        }
3191
0
        return Status::OK();
3192
0
    }
3193
1
    auto cost_us = watch.get_elapse_time_us();
3194
1
    if (cost_us > 10 * 1000) {
3195
0
        LOG(INFO) << "calc segment delete bitmap, tablet: " << tablet_id()
3196
0
                  << " rowset: " << rowset_id << " seg_id: " << seg->id()
3197
0
                  << " dummy_version: " << end_version + 1 << " rows: " << seg->num_rows()
3198
0
                  << " conflict rows: " << conflict_rows
3199
0
                  << " bimap num: " << delete_bitmap->delete_bitmap.size() << " cost: " << cost_us
3200
0
                  << "(us)";
3201
0
    }
3202
1
    return Status::OK();
3203
1
}
3204
3205
// if user pass a token, then all calculation works will submit to a threadpool,
3206
// user can get all delete bitmaps from that token.
3207
// if `token` is nullptr, the calculation will run in local, and user can get the result
3208
// delete bitmap from `delete_bitmap` directly.
3209
Status Tablet::calc_delete_bitmap(RowsetSharedPtr rowset,
3210
                                  const std::vector<segment_v2::SegmentSharedPtr>& segments,
3211
                                  const std::vector<RowsetSharedPtr>& specified_rowsets,
3212
                                  DeleteBitmapPtr delete_bitmap, int64_t end_version,
3213
66
                                  CalcDeleteBitmapToken* token, RowsetWriter* rowset_writer) {
3214
66
    if (specified_rowsets.empty() || segments.empty()) {
3215
65
        return Status::OK();
3216
65
    }
3217
3218
1
    OlapStopWatch watch;
3219
1
    doris::TabletSharedPtr tablet_ptr = _engine.tablet_manager()->get_tablet(tablet_id());
3220
1
    if (tablet_ptr == nullptr) {
3221
0
        return Status::InternalError("Can't find tablet id: {}, maybe already dropped.",
3222
0
                                     tablet_id());
3223
0
    }
3224
1
    for (const auto& segment : segments) {
3225
1
        auto& seg = segment;
3226
1
        if (token != nullptr) {
3227
1
            RETURN_IF_ERROR(token->submit(tablet_ptr, rowset, seg, specified_rowsets, end_version,
3228
1
                                          delete_bitmap, rowset_writer));
3229
1
        } else {
3230
0
            RETURN_IF_ERROR(calc_segment_delete_bitmap(rowset, segment, specified_rowsets,
3231
0
                                                       delete_bitmap, end_version, rowset_writer));
3232
0
        }
3233
1
    }
3234
3235
1
    return Status::OK();
3236
1
}
3237
3238
std::vector<RowsetSharedPtr> Tablet::get_rowset_by_ids(
3239
68
        const RowsetIdUnorderedSet* specified_rowset_ids, bool include_stale) {
3240
68
    std::vector<RowsetSharedPtr> rowsets;
3241
68
    for (auto& rs : _rs_version_map) {
3242
11
        if (!specified_rowset_ids ||
3243
11
            specified_rowset_ids->find(rs.second->rowset_id()) != specified_rowset_ids->end()) {
3244
1
            rowsets.push_back(rs.second);
3245
1
        }
3246
11
    }
3247
3248
68
    if (include_stale && specified_rowset_ids != nullptr &&
3249
68
        rowsets.size() != specified_rowset_ids->size()) {
3250
0
        for (auto& rs : _stale_rs_version_map) {
3251
0
            if (specified_rowset_ids->find(rs.second->rowset_id()) != specified_rowset_ids->end()) {
3252
0
                rowsets.push_back(rs.second);
3253
0
            }
3254
0
        }
3255
0
    }
3256
3257
68
    std::sort(rowsets.begin(), rowsets.end(), [](RowsetSharedPtr& lhs, RowsetSharedPtr& rhs) {
3258
0
        return lhs->end_version() > rhs->end_version();
3259
0
    });
3260
68
    return rowsets;
3261
68
}
3262
3263
Status Tablet::generate_new_block_for_partial_update(
3264
        TabletSchemaSPtr rowset_schema, const PartialUpdateInfo* partial_update_info,
3265
        const PartialUpdateReadPlan& read_plan_ori, const PartialUpdateReadPlan& read_plan_update,
3266
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset,
3267
0
        vectorized::Block* output_block) {
3268
    // do partial update related works
3269
    // 1. read columns by read plan
3270
    // 2. generate new block
3271
    // 3. write a new segment and modify rowset meta
3272
    // 4. mark current keys deleted
3273
0
    CHECK(output_block);
3274
0
    auto full_mutable_columns = output_block->mutate_columns();
3275
0
    const auto& missing_cids = partial_update_info->missing_cids;
3276
0
    const auto& update_cids = partial_update_info->update_cids;
3277
0
    auto old_block = rowset_schema->create_block_by_cids(missing_cids);
3278
0
    auto update_block = rowset_schema->create_block_by_cids(update_cids);
3279
3280
0
    auto get_delete_sign_column_data = [](vectorized::Block& block,
3281
0
                                          size_t rows) -> const signed char* {
3282
0
        if (const vectorized::ColumnWithTypeAndName* delete_sign_column =
3283
0
                    block.try_get_by_name(DELETE_SIGN);
3284
0
            delete_sign_column != nullptr) {
3285
0
            const auto& delete_sign_col =
3286
0
                    reinterpret_cast<const vectorized::ColumnInt8&>(*(delete_sign_column->column));
3287
0
            if (delete_sign_col.size() >= rows) {
3288
0
                return delete_sign_col.get_data().data();
3289
0
            }
3290
0
        }
3291
0
        return nullptr;
3292
0
    };
3293
3294
    // rowid in the final block(start from 0, increase continuously) -> rowid to read in update_block
3295
0
    std::map<uint32_t, uint32_t> read_index_update;
3296
3297
    // read current rowset first, if a row in the current rowset has delete sign mark
3298
    // we don't need to read values from old block
3299
0
    RETURN_IF_ERROR(read_columns_by_plan(rowset_schema, update_cids, read_plan_update,
3300
0
                                         rsid_to_rowset, update_block, &read_index_update, false));
3301
3302
0
    size_t update_rows = read_index_update.size();
3303
0
    for (auto i = 0; i < update_cids.size(); ++i) {
3304
0
        for (auto idx = 0; idx < update_rows; ++idx) {
3305
0
            full_mutable_columns[update_cids[i]]->insert_from(
3306
0
                    *update_block.get_columns_with_type_and_name()[i].column.get(),
3307
0
                    read_index_update[idx]);
3308
0
        }
3309
0
    }
3310
3311
    // if there is sequence column in the table, we need to read the sequence column,
3312
    // otherwise it may cause the merge-on-read based compaction policy to produce incorrect results
3313
0
    const auto* __restrict new_block_delete_signs =
3314
0
            rowset_schema->has_sequence_col()
3315
0
                    ? nullptr
3316
0
                    : get_delete_sign_column_data(update_block, update_rows);
3317
3318
    // rowid in the final block(start from 0, increase, may not continuous becasue we skip to read some rows) -> rowid to read in old_block
3319
0
    std::map<uint32_t, uint32_t> read_index_old;
3320
0
    RETURN_IF_ERROR(read_columns_by_plan(rowset_schema, missing_cids, read_plan_ori, rsid_to_rowset,
3321
0
                                         old_block, &read_index_old, true, new_block_delete_signs));
3322
0
    size_t old_rows = read_index_old.size();
3323
0
    const auto* __restrict old_block_delete_signs =
3324
0
            get_delete_sign_column_data(old_block, old_rows);
3325
3326
    // build default value block
3327
0
    auto default_value_block = old_block.clone_empty();
3328
0
    auto mutable_default_value_columns = default_value_block.mutate_columns();
3329
0
    if (old_block_delete_signs != nullptr || new_block_delete_signs != nullptr) {
3330
0
        for (auto i = 0; i < missing_cids.size(); ++i) {
3331
0
            const auto& column = rowset_schema->column(missing_cids[i]);
3332
0
            if (column.has_default_value()) {
3333
0
                const auto& default_value = partial_update_info->default_values[i];
3334
0
                vectorized::ReadBuffer rb(const_cast<char*>(default_value.c_str()),
3335
0
                                          default_value.size());
3336
0
                RETURN_IF_ERROR(old_block.get_by_position(i).type->from_string(
3337
0
                        rb, mutable_default_value_columns[i].get()));
3338
0
            }
3339
0
        }
3340
0
    }
3341
3342
0
    CHECK(update_rows >= old_rows);
3343
3344
    // build full block
3345
0
    for (auto i = 0; i < missing_cids.size(); ++i) {
3346
0
        const auto& rs_column = rowset_schema->column(missing_cids[i]);
3347
0
        auto& mutable_column = full_mutable_columns[missing_cids[i]];
3348
0
        for (auto idx = 0; idx < update_rows; ++idx) {
3349
            // There are two cases we don't need to read values from old data:
3350
            //     1. if the conflicting new row's delete sign is marked, which means the value columns
3351
            //     of the row will not be read. So we don't need to read the missing values from the previous rows.
3352
            //     2. if the conflicting old row's delete sign is marked, which means that the key is not exist now,
3353
            //     we should not read old values from the deleted data, and should use default value instead.
3354
            //     NOTE: since now we are in the publishing phase, all data is commited
3355
            //         before, even the `strict_mode` is true (which requires partial update
3356
            //         load job can't insert new keys), this "new" key MUST be written into
3357
            //         the new generated segment file.
3358
0
            if (new_block_delete_signs != nullptr && new_block_delete_signs[idx]) {
3359
0
                mutable_column->insert_default();
3360
0
            } else if (old_block_delete_signs != nullptr &&
3361
0
                       old_block_delete_signs[read_index_old[idx]] != 0) {
3362
0
                if (rs_column.has_default_value()) {
3363
0
                    mutable_column->insert_from(*mutable_default_value_columns[i].get(), 0);
3364
0
                } else if (rs_column.is_nullable()) {
3365
0
                    assert_cast<vectorized::ColumnNullable*>(mutable_column.get())
3366
0
                            ->insert_null_elements(1);
3367
0
                } else {
3368
0
                    mutable_column->insert_default();
3369
0
                }
3370
0
            } else {
3371
0
                mutable_column->insert_from(
3372
0
                        *old_block.get_columns_with_type_and_name()[i].column.get(),
3373
0
                        read_index_old[idx]);
3374
0
            }
3375
0
        }
3376
0
    }
3377
0
    output_block->set_columns(std::move(full_mutable_columns));
3378
0
    VLOG_DEBUG << "full block when publish: " << output_block->dump_data();
3379
0
    return Status::OK();
3380
0
}
3381
3382
// read columns by read plan
3383
// read_index: ori_pos-> block_idx
3384
Status Tablet::read_columns_by_plan(TabletSchemaSPtr tablet_schema,
3385
                                    std::vector<uint32_t> cids_to_read,
3386
                                    const PartialUpdateReadPlan& read_plan,
3387
                                    const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset,
3388
                                    vectorized::Block& block,
3389
                                    std::map<uint32_t, uint32_t>* read_index,
3390
                                    bool force_read_old_delete_signs,
3391
0
                                    const signed char* __restrict skip_map) {
3392
0
    if (force_read_old_delete_signs) {
3393
        // always read delete sign column from historical data
3394
0
        if (const vectorized::ColumnWithTypeAndName* old_delete_sign_column =
3395
0
                    block.try_get_by_name(DELETE_SIGN);
3396
0
            old_delete_sign_column == nullptr) {
3397
0
            auto del_col_cid = tablet_schema->field_index(DELETE_SIGN);
3398
0
            cids_to_read.emplace_back(del_col_cid);
3399
0
            block.swap(tablet_schema->create_block_by_cids(cids_to_read));
3400
0
        }
3401
0
    }
3402
0
    bool has_row_column = tablet_schema->store_row_column();
3403
0
    auto mutable_columns = block.mutate_columns();
3404
0
    size_t read_idx = 0;
3405
0
    for (auto rs_it : read_plan) {
3406
0
        for (auto seg_it : rs_it.second) {
3407
0
            auto rowset_iter = rsid_to_rowset.find(rs_it.first);
3408
0
            CHECK(rowset_iter != rsid_to_rowset.end());
3409
0
            std::vector<uint32_t> rids;
3410
0
            for (auto [rid, pos] : seg_it.second) {
3411
0
                if (skip_map && skip_map[pos]) {
3412
0
                    continue;
3413
0
                }
3414
0
                rids.emplace_back(rid);
3415
0
                (*read_index)[pos] = read_idx++;
3416
0
            }
3417
0
            if (has_row_column) {
3418
0
                auto st = fetch_value_through_row_column(rowset_iter->second, *tablet_schema,
3419
0
                                                         seg_it.first, rids, cids_to_read, block);
3420
0
                if (!st.ok()) {
3421
0
                    LOG(WARNING) << "failed to fetch value through row column";
3422
0
                    return st;
3423
0
                }
3424
0
                continue;
3425
0
            }
3426
0
            for (size_t cid = 0; cid < mutable_columns.size(); ++cid) {
3427
0
                TabletColumn tablet_column = tablet_schema->column(cids_to_read[cid]);
3428
0
                auto st = fetch_value_by_rowids(rowset_iter->second, seg_it.first, rids,
3429
0
                                                tablet_column, mutable_columns[cid]);
3430
                // set read value to output block
3431
0
                if (!st.ok()) {
3432
0
                    LOG(WARNING) << "failed to fetch value";
3433
0
                    return st;
3434
0
                }
3435
0
            }
3436
0
        }
3437
0
    }
3438
0
    block.set_columns(std::move(mutable_columns));
3439
0
    return Status::OK();
3440
0
}
3441
3442
void Tablet::prepare_to_read(const RowLocation& row_location, size_t pos,
3443
0
                             PartialUpdateReadPlan* read_plan) {
3444
0
    auto rs_it = read_plan->find(row_location.rowset_id);
3445
0
    if (rs_it == read_plan->end()) {
3446
0
        std::map<uint32_t, std::vector<RidAndPos>> segid_to_rid;
3447
0
        std::vector<RidAndPos> rid_pos;
3448
0
        rid_pos.emplace_back(RidAndPos {row_location.row_id, pos});
3449
0
        segid_to_rid.emplace(row_location.segment_id, rid_pos);
3450
0
        read_plan->emplace(row_location.rowset_id, segid_to_rid);
3451
0
        return;
3452
0
    }
3453
0
    auto seg_it = rs_it->second.find(row_location.segment_id);
3454
0
    if (seg_it == rs_it->second.end()) {
3455
0
        std::vector<RidAndPos> rid_pos;
3456
0
        rid_pos.emplace_back(RidAndPos {row_location.row_id, pos});
3457
0
        rs_it->second.emplace(row_location.segment_id, rid_pos);
3458
0
        return;
3459
0
    }
3460
0
    seg_it->second.emplace_back(RidAndPos {row_location.row_id, pos});
3461
0
}
3462
3463
void Tablet::_rowset_ids_difference(const RowsetIdUnorderedSet& cur,
3464
                                    const RowsetIdUnorderedSet& pre, RowsetIdUnorderedSet* to_add,
3465
4
                                    RowsetIdUnorderedSet* to_del) {
3466
4
    for (const auto& id : cur) {
3467
2
        if (pre.find(id) == pre.end()) {
3468
1
            to_add->insert(id);
3469
1
        }
3470
2
    }
3471
4
    for (const auto& id : pre) {
3472
1
        if (cur.find(id) == cur.end()) {
3473
0
            to_del->insert(id);
3474
0
        }
3475
1
    }
3476
4
}
3477
3478
// The caller should hold _rowset_update_lock and _meta_lock lock.
3479
Status Tablet::update_delete_bitmap_without_lock(
3480
0
        const RowsetSharedPtr& rowset, const std::vector<RowsetSharedPtr>* specified_base_rowsets) {
3481
0
    DBUG_EXECUTE_IF("Tablet.update_delete_bitmap_without_lock.random_failed", {
3482
0
        auto rnd = rand() % 100;
3483
0
        auto percent = dp->param("percent", 0.1);
3484
0
        if (rnd < (100 * percent)) {
3485
0
            LOG(WARNING) << "BaseTablet.update_delete_bitmap_without_lock.random_failed";
3486
0
            return Status::InternalError(
3487
0
                    "debug tablet update delete bitmap without lock random failed");
3488
0
        } else {
3489
0
            LOG(INFO) << "BaseTablet.update_delete_bitmap_without_lock.random_failed not triggered"
3490
0
                      << ", rnd:" << rnd << ", percent: " << percent;
3491
0
        }
3492
0
    });
3493
0
    int64_t cur_version = rowset->end_version();
3494
0
    std::vector<segment_v2::SegmentSharedPtr> segments;
3495
0
    RETURN_IF_ERROR(_load_rowset_segments(rowset, &segments));
3496
3497
    // If this rowset does not have a segment, there is no need for an update.
3498
0
    if (segments.empty()) {
3499
0
        LOG(INFO) << "[Schema Change or Clone] skip to construct delete bitmap tablet: "
3500
0
                  << tablet_id() << " cur max_version: " << cur_version;
3501
0
        return Status::OK();
3502
0
    }
3503
3504
    // calculate delete bitmap between segments if necessary.
3505
0
    DeleteBitmapPtr delete_bitmap = std::make_shared<DeleteBitmap>(tablet_id());
3506
0
    RETURN_IF_ERROR(calc_delete_bitmap_between_segments(rowset->tablet_schema(), rowset, segments,
3507
0
                                                        delete_bitmap));
3508
3509
    // get all base rowsets to calculate on
3510
0
    std::vector<RowsetSharedPtr> specified_rowsets;
3511
0
    RowsetIdUnorderedSet cur_rowset_ids;
3512
0
    if (specified_base_rowsets == nullptr) {
3513
0
        RETURN_IF_ERROR(all_rs_id(cur_version - 1, &cur_rowset_ids));
3514
0
        specified_rowsets = get_rowset_by_ids(&cur_rowset_ids);
3515
0
    } else {
3516
0
        specified_rowsets = *specified_base_rowsets;
3517
0
    }
3518
3519
0
    OlapStopWatch watch;
3520
0
    auto token = _engine.calc_delete_bitmap_executor()->create_token();
3521
0
    RETURN_IF_ERROR(calc_delete_bitmap(rowset, segments, specified_rowsets, delete_bitmap,
3522
0
                                       cur_version - 1, token.get()));
3523
0
    RETURN_IF_ERROR(token->wait());
3524
0
    size_t total_rows = std::accumulate(
3525
0
            segments.begin(), segments.end(), 0,
3526
0
            [](size_t sum, const segment_v2::SegmentSharedPtr& s) { return sum += s->num_rows(); });
3527
0
    LOG(INFO) << "[Schema Change or Clone] construct delete bitmap tablet: " << tablet_id()
3528
0
              << ", rowset_ids: " << cur_rowset_ids.size() << ", cur max_version: " << cur_version
3529
0
              << ", transaction_id: " << -1 << ", cost: " << watch.get_elapse_time_us()
3530
0
              << "(us), total rows: " << total_rows;
3531
0
    if (config::enable_merge_on_write_correctness_check) {
3532
        // check if all the rowset has ROWSET_SENTINEL_MARK
3533
0
        auto st = check_delete_bitmap_correctness(delete_bitmap, cur_version - 1, -1,
3534
0
                                                  cur_rowset_ids, &specified_rowsets);
3535
0
        if (!st.ok()) {
3536
0
            LOG(WARNING) << fmt::format("delete bitmap correctness check failed in publish phase!");
3537
0
        }
3538
0
        _remove_sentinel_mark_from_delete_bitmap(delete_bitmap);
3539
0
    }
3540
0
    for (auto iter = delete_bitmap->delete_bitmap.begin();
3541
0
         iter != delete_bitmap->delete_bitmap.end(); ++iter) {
3542
0
        _tablet_meta->delete_bitmap().merge(
3543
0
                {std::get<0>(iter->first), std::get<1>(iter->first), cur_version}, iter->second);
3544
0
    }
3545
3546
0
    return Status::OK();
3547
0
}
3548
3549
Status Tablet::commit_phase_update_delete_bitmap(
3550
        const RowsetSharedPtr& rowset, RowsetIdUnorderedSet& pre_rowset_ids,
3551
        DeleteBitmapPtr delete_bitmap, const std::vector<segment_v2::SegmentSharedPtr>& segments,
3552
2
        int64_t txn_id, CalcDeleteBitmapToken* token, RowsetWriter* rowset_writer) {
3553
2
    SCOPED_BVAR_LATENCY(g_tablet_commit_phase_update_delete_bitmap_latency);
3554
2
    RowsetIdUnorderedSet cur_rowset_ids;
3555
2
    RowsetIdUnorderedSet rowset_ids_to_add;
3556
2
    RowsetIdUnorderedSet rowset_ids_to_del;
3557
2
    int64_t cur_version;
3558
3559
2
    std::vector<RowsetSharedPtr> specified_rowsets;
3560
2
    {
3561
2
        std::shared_lock meta_rlock(_meta_lock);
3562
2
        cur_version = max_version_unlocked().second;
3563
2
        RETURN_IF_ERROR(all_rs_id(cur_version, &cur_rowset_ids));
3564
2
        _rowset_ids_difference(cur_rowset_ids, pre_rowset_ids, &rowset_ids_to_add,
3565
2
                               &rowset_ids_to_del);
3566
2
        specified_rowsets = get_rowset_by_ids(&rowset_ids_to_add);
3567
2
    }
3568
0
    for (const auto& to_del : rowset_ids_to_del) {
3569
0
        delete_bitmap->remove({to_del, 0, 0}, {to_del, UINT32_MAX, INT64_MAX});
3570
0
    }
3571
3572
2
    RETURN_IF_ERROR(calc_delete_bitmap(rowset, segments, specified_rowsets, delete_bitmap,
3573
2
                                       cur_version, token, rowset_writer));
3574
2
    size_t total_rows = std::accumulate(
3575
2
            segments.begin(), segments.end(), 0,
3576
2
            [](size_t sum, const segment_v2::SegmentSharedPtr& s) { return sum += s->num_rows(); });
3577
2
    LOG(INFO) << "[Before Commit] construct delete bitmap tablet: " << tablet_id()
3578
2
              << ", rowset_ids to add: " << rowset_ids_to_add.size()
3579
2
              << ", rowset_ids to del: " << rowset_ids_to_del.size()
3580
2
              << ", cur max_version: " << cur_version << ", transaction_id: " << txn_id
3581
2
              << ", total rows: " << total_rows;
3582
2
    pre_rowset_ids = cur_rowset_ids;
3583
2
    return Status::OK();
3584
2
}
3585
3586
2
Status Tablet::update_delete_bitmap(TabletTxnInfo* txn_info, int64_t txn_id) {
3587
2
    SCOPED_BVAR_LATENCY(g_tablet_update_delete_bitmap_latency);
3588
2
    RowsetIdUnorderedSet cur_rowset_ids;
3589
2
    RowsetIdUnorderedSet rowset_ids_to_add;
3590
2
    RowsetIdUnorderedSet rowset_ids_to_del;
3591
2
    RowsetSharedPtr rowset = txn_info->rowset;
3592
2
    int64_t cur_version = rowset->start_version();
3593
3594
2
    std::unique_ptr<RowsetWriter> rowset_writer;
3595
2
    RETURN_IF_ERROR(
3596
2
            create_transient_rowset_writer(rowset, &rowset_writer, txn_info->partial_update_info));
3597
3598
2
    DeleteBitmapPtr delete_bitmap = txn_info->delete_bitmap;
3599
    // Partial update might generate new segments when there is conflicts while publish, and mark
3600
    // the same key in original segments as delete.
3601
    // When the new segment flush fails or the rowset build fails, the deletion marker for the
3602
    // duplicate key of the original segment should not remain in `txn_info->delete_bitmap`,
3603
    // so we need to make a copy of `txn_info->delete_bitmap` and make changes on it.
3604
2
    bool is_partial_update =
3605
2
            txn_info->partial_update_info && txn_info->partial_update_info->is_partial_update;
3606
2
    if (is_partial_update) {
3607
0
        delete_bitmap = std::make_shared<DeleteBitmap>(*(txn_info->delete_bitmap));
3608
0
    }
3609
3610
2
    OlapStopWatch watch;
3611
2
    std::vector<segment_v2::SegmentSharedPtr> segments;
3612
2
    RETURN_IF_ERROR(_load_rowset_segments(rowset, &segments));
3613
2
    auto t1 = watch.get_elapse_time_us();
3614
3615
2
    {
3616
2
        std::shared_lock meta_rlock(_meta_lock);
3617
        // tablet is under alter process. The delete bitmap will be calculated after conversion.
3618
2
        if (tablet_state() == TABLET_NOTREADY) {
3619
0
            LOG(INFO) << "tablet is under alter process, update delete bitmap later, tablet_id="
3620
0
                      << tablet_id();
3621
0
            return Status::OK();
3622
0
        }
3623
2
        RETURN_IF_ERROR(all_rs_id(cur_version - 1, &cur_rowset_ids));
3624
2
    }
3625
2
    auto t2 = watch.get_elapse_time_us();
3626
3627
2
    _rowset_ids_difference(cur_rowset_ids, txn_info->rowset_ids, &rowset_ids_to_add,
3628
2
                           &rowset_ids_to_del);
3629
2
    for (const auto& to_del : rowset_ids_to_del) {
3630
0
        delete_bitmap->remove({to_del, 0, 0}, {to_del, UINT32_MAX, INT64_MAX});
3631
0
    }
3632
3633
2
    std::vector<RowsetSharedPtr> specified_rowsets;
3634
2
    {
3635
2
        std::shared_lock meta_rlock(_meta_lock);
3636
2
        specified_rowsets = get_rowset_by_ids(&rowset_ids_to_add);
3637
2
    }
3638
2
    auto t3 = watch.get_elapse_time_us();
3639
3640
    // If a rowset is produced by compaction before the commit phase of the partial update load
3641
    // and is not included in txn_info->rowset_ids, we can skip the alignment process of that rowset
3642
    // because data remains the same before and after compaction. But we still need to calculate the
3643
    // the delete bitmap for that rowset.
3644
2
    std::vector<RowsetSharedPtr> rowsets_skip_alignment;
3645
2
    if (is_partial_update) {
3646
0
        int64_t max_version_in_flush_phase =
3647
0
                txn_info->partial_update_info->max_version_in_flush_phase;
3648
0
        DCHECK(max_version_in_flush_phase != -1);
3649
0
        std::vector<RowsetSharedPtr> remained_rowsets;
3650
0
        for (const auto& rowset : specified_rowsets) {
3651
0
            if (rowset->end_version() <= max_version_in_flush_phase &&
3652
0
                rowset->produced_by_compaction()) {
3653
0
                rowsets_skip_alignment.emplace_back(rowset);
3654
0
            } else {
3655
0
                remained_rowsets.emplace_back(rowset);
3656
0
            }
3657
0
        }
3658
0
        if (!rowsets_skip_alignment.empty()) {
3659
0
            specified_rowsets = std::move(remained_rowsets);
3660
0
        }
3661
0
    }
3662
3663
2
    if (!rowsets_skip_alignment.empty()) {
3664
0
        auto token = _engine.calc_delete_bitmap_executor()->create_token();
3665
        // set rowset_writer to nullptr to skip the alignment process
3666
0
        RETURN_IF_ERROR(calc_delete_bitmap(rowset, segments, rowsets_skip_alignment, delete_bitmap,
3667
0
                                           cur_version - 1, token.get(), nullptr));
3668
0
        RETURN_IF_ERROR(token->wait());
3669
0
    }
3670
3671
2
    auto token = _engine.calc_delete_bitmap_executor()->create_token();
3672
2
    RETURN_IF_ERROR(calc_delete_bitmap(rowset, segments, specified_rowsets, delete_bitmap,
3673
2
                                       cur_version - 1, token.get(), rowset_writer.get()));
3674
2
    RETURN_IF_ERROR(token->wait());
3675
3676
2
    std::stringstream ss;
3677
2
    if (watch.get_elapse_time_us() < 1 * 1000 * 1000) {
3678
2
        ss << "cost: " << watch.get_elapse_time_us() - t3 << "(us)";
3679
2
    } else {
3680
0
        ss << "cost(us): (load segments: " << t1 << ", get all rsid: " << t2 - t1
3681
0
           << ", get rowsets: " << t3 - t2
3682
0
           << ", calc delete bitmap: " << watch.get_elapse_time_us() - t3 << ")";
3683
0
    }
3684
3685
2
    if (config::enable_merge_on_write_correctness_check && rowset->num_rows() != 0) {
3686
        // only do correctness check if the rowset has at least one row written
3687
        // check if all the rowset has ROWSET_SENTINEL_MARK
3688
2
        auto st = check_delete_bitmap_correctness(delete_bitmap, cur_version - 1, -1,
3689
2
                                                  cur_rowset_ids, &specified_rowsets);
3690
2
        if (!st.ok()) {
3691
0
            LOG(WARNING) << fmt::format("delete bitmap correctness check failed in publish phase!");
3692
0
        }
3693
2
        _remove_sentinel_mark_from_delete_bitmap(delete_bitmap);
3694
2
    }
3695
3696
2
    if (txn_info->partial_update_info && txn_info->partial_update_info->is_partial_update) {
3697
0
        DBUG_EXECUTE_IF("Tablet.update_delete_bitmap.partial_update_write_rowset_fail", {
3698
0
            if (rand() % 100 < (100 * dp->param("percent", 0.5))) {
3699
0
                LOG_WARNING("Tablet.update_delete_bitmap.partial_update_write_rowset random failed")
3700
0
                        .tag("txn_id", txn_id);
3701
0
                return Status::InternalError(
3702
0
                        "debug update_delete_bitmap partial update write rowset random failed");
3703
0
            }
3704
0
        });
3705
        // build rowset writer and merge transient rowset
3706
0
        RETURN_IF_ERROR(rowset_writer->flush());
3707
0
        RowsetSharedPtr transient_rowset;
3708
0
        RETURN_IF_ERROR(rowset_writer->build(transient_rowset));
3709
0
        auto old_segments = rowset->num_segments();
3710
0
        rowset->merge_rowset_meta(transient_rowset->rowset_meta());
3711
0
        auto new_segments = rowset->num_segments();
3712
0
        ss << ", partial update flush rowset (old segment num: " << old_segments
3713
0
           << ", new segment num: " << new_segments << ")";
3714
3715
        // update the shared_ptr to new delete bitmap
3716
0
        txn_info->delete_bitmap = delete_bitmap;
3717
3718
        // erase segment cache cause we will add a segment to rowset
3719
0
        SegmentLoader::instance()->erase_segments(rowset->rowset_id(), rowset->num_segments());
3720
0
    }
3721
3722
2
    size_t total_rows = std::accumulate(
3723
2
            segments.begin(), segments.end(), 0,
3724
2
            [](size_t sum, const segment_v2::SegmentSharedPtr& s) { return sum += s->num_rows(); });
3725
2
    LOG(INFO) << "[Publish] construct delete bitmap tablet: " << tablet_id()
3726
2
              << ", rowset_ids to add: "
3727
2
              << (specified_rowsets.size() + rowsets_skip_alignment.size())
3728
2
              << ", rowset_ids to del: " << rowset_ids_to_del.size()
3729
2
              << ", cur version: " << cur_version << ", transaction_id: " << txn_id << ","
3730
2
              << ss.str() << " , total rows: " << total_rows;
3731
3732
    // update version without write lock, compaction and publish_txn
3733
    // will update delete bitmap, handle compaction with _rowset_update_lock
3734
    // and publish_txn runs sequential so no need to lock here
3735
2
    for (auto& [key, bitmap] : delete_bitmap->delete_bitmap) {
3736
2
        _tablet_meta->delete_bitmap().merge({std::get<0>(key), std::get<1>(key), cur_version},
3737
2
                                            bitmap);
3738
2
    }
3739
3740
2
    return Status::OK();
3741
2
}
3742
3743
void Tablet::calc_compaction_output_rowset_delete_bitmap(
3744
        const std::vector<RowsetSharedPtr>& input_rowsets, const RowIdConversion& rowid_conversion,
3745
        uint64_t start_version, uint64_t end_version, std::set<RowLocation>* missed_rows,
3746
        std::map<RowsetSharedPtr, std::list<std::pair<RowLocation, RowLocation>>>* location_map,
3747
0
        const DeleteBitmap& input_delete_bitmap, DeleteBitmap* output_rowset_delete_bitmap) {
3748
0
    RowLocation src;
3749
0
    RowLocation dst;
3750
0
    for (auto& rowset : input_rowsets) {
3751
0
        src.rowset_id = rowset->rowset_id();
3752
0
        for (uint32_t seg_id = 0; seg_id < rowset->num_segments(); ++seg_id) {
3753
0
            src.segment_id = seg_id;
3754
0
            DeleteBitmap subset_map(tablet_id());
3755
0
            input_delete_bitmap.subset({rowset->rowset_id(), seg_id, start_version},
3756
0
                                       {rowset->rowset_id(), seg_id, end_version}, &subset_map);
3757
            // traverse all versions and convert rowid
3758
0
            for (auto iter = subset_map.delete_bitmap.begin();
3759
0
                 iter != subset_map.delete_bitmap.end(); ++iter) {
3760
0
                auto cur_version = std::get<2>(iter->first);
3761
0
                for (auto index = iter->second.begin(); index != iter->second.end(); ++index) {
3762
0
                    src.row_id = *index;
3763
0
                    if (rowid_conversion.get(src, &dst) != 0) {
3764
0
                        VLOG_CRITICAL << "Can't find rowid, may be deleted by the delete_handler, "
3765
0
                                      << " src loaction: |" << src.rowset_id << "|"
3766
0
                                      << src.segment_id << "|" << src.row_id
3767
0
                                      << " version: " << cur_version;
3768
0
                        if (missed_rows) {
3769
0
                            missed_rows->insert(src);
3770
0
                        }
3771
0
                        continue;
3772
0
                    }
3773
0
                    VLOG_DEBUG << "calc_compaction_output_rowset_delete_bitmap dst location: |"
3774
0
                               << dst.rowset_id << "|" << dst.segment_id << "|" << dst.row_id
3775
0
                               << " src location: |" << src.rowset_id << "|" << src.segment_id
3776
0
                               << "|" << src.row_id << " start version: " << start_version
3777
0
                               << "end version" << end_version;
3778
0
                    if (location_map) {
3779
0
                        (*location_map)[rowset].emplace_back(src, dst);
3780
0
                    }
3781
0
                    output_rowset_delete_bitmap->add({dst.rowset_id, dst.segment_id, cur_version},
3782
0
                                                     dst.row_id);
3783
0
                }
3784
0
            }
3785
0
        }
3786
0
    }
3787
0
}
3788
3789
0
void Tablet::merge_delete_bitmap(const DeleteBitmap& delete_bitmap) {
3790
0
    _tablet_meta->delete_bitmap().merge(delete_bitmap);
3791
0
}
3792
3793
Status Tablet::check_rowid_conversion(
3794
        RowsetSharedPtr dst_rowset,
3795
        const std::map<RowsetSharedPtr, std::list<std::pair<RowLocation, RowLocation>>>&
3796
0
                location_map) {
3797
0
    if (location_map.empty()) {
3798
0
        VLOG_DEBUG << "check_rowid_conversion, location_map is empty";
3799
0
        return Status::OK();
3800
0
    }
3801
0
    std::vector<segment_v2::SegmentSharedPtr> dst_segments;
3802
0
    RETURN_IF_ERROR(_load_rowset_segments(dst_rowset, &dst_segments));
3803
0
    std::unordered_map<RowsetId, std::vector<segment_v2::SegmentSharedPtr>> input_rowsets_segment;
3804
3805
0
    VLOG_DEBUG << "check_rowid_conversion, dst_segments size: " << dst_segments.size();
3806
0
    for (auto [src_rowset, locations] : location_map) {
3807
0
        std::vector<segment_v2::SegmentSharedPtr>& segments =
3808
0
                input_rowsets_segment[src_rowset->rowset_id()];
3809
0
        if (segments.empty()) {
3810
0
            RETURN_IF_ERROR(_load_rowset_segments(src_rowset, &segments));
3811
0
        }
3812
0
        for (auto& [src, dst] : locations) {
3813
0
            std::string src_key;
3814
0
            std::string dst_key;
3815
0
            Status s = segments[src.segment_id]->read_key_by_rowid(src.row_id, &src_key);
3816
0
            if (UNLIKELY(s.is<NOT_IMPLEMENTED_ERROR>())) {
3817
0
                LOG(INFO) << "primary key index of old version does not "
3818
0
                             "support reading key by rowid";
3819
0
                break;
3820
0
            }
3821
0
            if (UNLIKELY(!s)) {
3822
0
                LOG(WARNING) << "failed to get src key: |" << src.rowset_id << "|" << src.segment_id
3823
0
                             << "|" << src.row_id << " status: " << s;
3824
0
                DCHECK(false);
3825
0
                return s;
3826
0
            }
3827
3828
0
            s = dst_segments[dst.segment_id]->read_key_by_rowid(dst.row_id, &dst_key);
3829
0
            if (UNLIKELY(!s)) {
3830
0
                LOG(WARNING) << "failed to get dst key: |" << dst.rowset_id << "|" << dst.segment_id
3831
0
                             << "|" << dst.row_id << " status: " << s;
3832
0
                DCHECK(false);
3833
0
                return s;
3834
0
            }
3835
3836
0
            VLOG_DEBUG << "check_rowid_conversion, src: |" << src.rowset_id << "|" << src.segment_id
3837
0
                       << "|" << src.row_id << "|" << src_key << " dst: |" << dst.rowset_id << "|"
3838
0
                       << dst.segment_id << "|" << dst.row_id << "|" << dst_key;
3839
0
            if (UNLIKELY(src_key.compare(dst_key) != 0)) {
3840
0
                LOG(WARNING) << "failed to check key, src key: |" << src.rowset_id << "|"
3841
0
                             << src.segment_id << "|" << src.row_id << "|" << src_key
3842
0
                             << " dst key: |" << dst.rowset_id << "|" << dst.segment_id << "|"
3843
0
                             << dst.row_id << "|" << dst_key;
3844
0
                DCHECK(false);
3845
0
                return Status::InternalError("failed to check rowid conversion");
3846
0
            }
3847
0
        }
3848
0
    }
3849
0
    return Status::OK();
3850
0
}
3851
3852
6
Status Tablet::all_rs_id(int64_t max_version, RowsetIdUnorderedSet* rowset_ids) const {
3853
    //  Ensure that the obtained versions of rowsets are continuous
3854
6
    std::vector<Version> version_path;
3855
6
    RETURN_IF_ERROR(
3856
6
            capture_consistent_versions(Version(0, max_version), &version_path, false, false));
3857
8
    for (auto& ver : version_path) {
3858
8
        if (ver.second == 1) {
3859
            // [0-1] rowset is empty for each tablet, skip it
3860
6
            continue;
3861
6
        }
3862
2
        auto it = _rs_version_map.find(ver);
3863
2
        if (it == _rs_version_map.end()) {
3864
0
            return Status::Error<CAPTURE_ROWSET_ERROR, false>(
3865
0
                    "fail to find Rowset for version. tablet={}, version={}", tablet_id(),
3866
0
                    ver.to_string());
3867
0
        }
3868
2
        rowset_ids->emplace(it->second->rowset_id());
3869
2
    }
3870
6
    return Status::OK();
3871
6
}
3872
3873
0
bool Tablet::check_all_rowset_segment() {
3874
0
    std::shared_lock rdlock(_meta_lock);
3875
0
    for (auto& version_rowset : _rs_version_map) {
3876
0
        RowsetSharedPtr rowset = version_rowset.second;
3877
0
        if (!rowset->check_rowset_segment()) {
3878
0
            LOG(WARNING) << "Tablet Segment Check. find a bad tablet, tablet_id=" << tablet_id();
3879
0
            return false;
3880
0
        }
3881
0
    }
3882
0
    return true;
3883
0
}
3884
3885
11
void Tablet::set_skip_compaction(bool skip, CompactionType compaction_type, int64_t start) {
3886
11
    if (!skip) {
3887
0
        _skip_cumu_compaction = false;
3888
0
        _skip_base_compaction = false;
3889
0
        return;
3890
0
    }
3891
11
    if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) {
3892
11
        _skip_cumu_compaction = true;
3893
11
        _skip_cumu_compaction_ts = start;
3894
11
    } else {
3895
0
        DCHECK(compaction_type == CompactionType::BASE_COMPACTION);
3896
0
        _skip_base_compaction = true;
3897
0
        _skip_base_compaction_ts = start;
3898
0
    }
3899
11
}
3900
3901
256
bool Tablet::should_skip_compaction(CompactionType compaction_type, int64_t now) {
3902
256
    if (compaction_type == CompactionType::CUMULATIVE_COMPACTION && _skip_cumu_compaction &&
3903
256
        now < _skip_cumu_compaction_ts + config::skip_tablet_compaction_second) {
3904
2
        return true;
3905
254
    } else if (compaction_type == CompactionType::BASE_COMPACTION && _skip_base_compaction &&
3906
254
               now < _skip_base_compaction_ts + config::skip_tablet_compaction_second) {
3907
0
        return true;
3908
0
    }
3909
254
    return false;
3910
256
}
3911
3912
0
std::pair<std::string, int64_t> Tablet::get_binlog_info(std::string_view binlog_version) const {
3913
0
    return RowsetMetaManager::get_binlog_info(_data_dir->get_meta(), tablet_uid(), binlog_version);
3914
0
}
3915
3916
std::string Tablet::get_rowset_binlog_meta(std::string_view binlog_version,
3917
0
                                           std::string_view rowset_id) const {
3918
0
    return RowsetMetaManager::get_rowset_binlog_meta(_data_dir->get_meta(), tablet_uid(),
3919
0
                                                     binlog_version, rowset_id);
3920
0
}
3921
3922
Status Tablet::get_rowset_binlog_metas(const std::vector<int64_t>& binlog_versions,
3923
0
                                       RowsetBinlogMetasPB* metas_pb) {
3924
0
    return RowsetMetaManager::get_rowset_binlog_metas(_data_dir->get_meta(), tablet_uid(),
3925
0
                                                      binlog_versions, metas_pb);
3926
0
}
3927
3928
4
Status Tablet::get_rowset_binlog_metas(Version binlog_versions, RowsetBinlogMetasPB* metas_pb) {
3929
4
    return RowsetMetaManager::get_rowset_binlog_metas(_data_dir->get_meta(), tablet_uid(),
3930
4
                                                      binlog_versions, metas_pb);
3931
4
}
3932
3933
std::string Tablet::get_segment_filepath(std::string_view rowset_id,
3934
0
                                         std::string_view segment_index) const {
3935
0
    return fmt::format("{}/_binlog/{}_{}.dat", _tablet_path, rowset_id, segment_index);
3936
0
}
3937
3938
0
std::string Tablet::get_segment_filepath(std::string_view rowset_id, int64_t segment_index) const {
3939
0
    return fmt::format("{}/_binlog/{}_{}.dat", _tablet_path, rowset_id, segment_index);
3940
0
}
3941
3942
std::string Tablet::get_segment_index_filepath(std::string_view rowset_id,
3943
                                               std::string_view segment_index,
3944
0
                                               std::string_view index_id) const {
3945
0
    auto format = _tablet_meta->tablet_schema()->get_inverted_index_storage_format();
3946
0
    if (format == doris::InvertedIndexStorageFormatPB::V1) {
3947
0
        return fmt::format("{}/_binlog/{}_{}_{}.idx", _tablet_path, rowset_id, segment_index,
3948
0
                           index_id);
3949
0
    } else {
3950
0
        return fmt::format("{}/_binlog/{}_{}.idx", _tablet_path, rowset_id, segment_index);
3951
0
    }
3952
0
}
3953
3954
std::string Tablet::get_segment_index_filepath(std::string_view rowset_id, int64_t segment_index,
3955
0
                                               int64_t index_id) const {
3956
0
    auto format = _tablet_meta->tablet_schema()->get_inverted_index_storage_format();
3957
0
    if (format == doris::InvertedIndexStorageFormatPB::V1) {
3958
0
        return fmt::format("{}/_binlog/{}_{}_{}.idx", _tablet_path, rowset_id, segment_index,
3959
0
                           index_id);
3960
0
    } else {
3961
0
        DCHECK(index_id == -1);
3962
0
        return fmt::format("{}/_binlog/{}_{}.idx", _tablet_path, rowset_id, segment_index);
3963
0
    }
3964
0
}
3965
3966
0
std::vector<std::string> Tablet::get_binlog_filepath(std::string_view binlog_version) const {
3967
0
    const auto& [rowset_id, num_segments] = get_binlog_info(binlog_version);
3968
0
    std::vector<std::string> binlog_filepath;
3969
0
    for (int i = 0; i < num_segments; ++i) {
3970
        // TODO(Drogon): rewrite by filesystem path
3971
0
        auto segment_file = fmt::format("{}_{}.dat", rowset_id, i);
3972
0
        binlog_filepath.emplace_back(fmt::format("{}/_binlog/{}", _tablet_path, segment_file));
3973
0
    }
3974
0
    return binlog_filepath;
3975
0
}
3976
3977
0
bool Tablet::can_add_binlog(uint64_t total_binlog_size) const {
3978
0
    return !_data_dir->reach_capacity_limit(total_binlog_size);
3979
0
}
3980
3981
10
bool Tablet::is_enable_binlog() {
3982
10
    return config::enable_feature_binlog && tablet_meta()->binlog_config().is_enable();
3983
10
}
3984
3985
0
void Tablet::set_binlog_config(BinlogConfig binlog_config) {
3986
0
    tablet_meta()->set_binlog_config(binlog_config);
3987
0
}
3988
3989
0
void Tablet::gc_binlogs(int64_t version) {
3990
0
    auto meta = _data_dir->get_meta();
3991
0
    DCHECK(meta != nullptr);
3992
3993
0
    const auto& tablet_uid = this->tablet_uid();
3994
0
    const auto tablet_id = this->tablet_id();
3995
0
    std::string begin_key = make_binlog_meta_key_prefix(tablet_uid);
3996
0
    std::string end_key = make_binlog_meta_key_prefix(tablet_uid, version + 1);
3997
0
    LOG(INFO) << fmt::format("gc binlog meta, tablet_id:{}, begin_key:{}, end_key:{}", tablet_id,
3998
0
                             begin_key, end_key);
3999
4000
0
    std::vector<std::string> wait_for_deleted_binlog_keys;
4001
0
    std::vector<std::string> wait_for_deleted_binlog_files;
4002
0
    auto add_to_wait_for_deleted = [&](std::string_view key, std::string_view rowset_id,
4003
0
                                       int64_t num_segments) {
4004
        // add binlog meta key and binlog data key
4005
0
        wait_for_deleted_binlog_keys.emplace_back(key);
4006
0
        wait_for_deleted_binlog_keys.push_back(get_binlog_data_key_from_meta_key(key));
4007
4008
        // add binlog segment files and index files
4009
0
        for (int64_t i = 0; i < num_segments; ++i) {
4010
0
            wait_for_deleted_binlog_files.emplace_back(get_segment_filepath(rowset_id, i));
4011
0
            for (const auto& index : this->tablet_schema()->indexes()) {
4012
0
                if (index.index_type() != IndexType::INVERTED) {
4013
0
                    continue;
4014
0
                }
4015
0
                wait_for_deleted_binlog_files.emplace_back(
4016
0
                        get_segment_index_filepath(rowset_id, i, index.index_id()));
4017
0
            }
4018
0
        }
4019
0
    };
4020
4021
0
    auto check_binlog_ttl = [&](const std::string& key, const std::string& value) mutable -> bool {
4022
0
        if (key >= end_key) {
4023
0
            return false;
4024
0
        }
4025
4026
0
        BinlogMetaEntryPB binlog_meta_entry_pb;
4027
0
        if (!binlog_meta_entry_pb.ParseFromString(value)) {
4028
0
            LOG(WARNING) << "failed to parse binlog meta entry, key:" << key;
4029
0
            return true;
4030
0
        }
4031
4032
0
        auto num_segments = binlog_meta_entry_pb.num_segments();
4033
0
        std::string rowset_id;
4034
0
        if (binlog_meta_entry_pb.has_rowset_id_v2()) {
4035
0
            rowset_id = binlog_meta_entry_pb.rowset_id_v2();
4036
0
        } else {
4037
            // key is 'binlog_meta_6943f1585fe834b5-e542c2b83a21d0b7_00000000000000000069_020000000000000135449d7cd7eadfe672aa0f928fa99593', extract last part '020000000000000135449d7cd7eadfe672aa0f928fa99593'
4038
0
            auto pos = key.rfind('_');
4039
0
            if (pos == std::string::npos) {
4040
0
                LOG(WARNING) << fmt::format("invalid binlog meta key:{}", key);
4041
0
                return false;
4042
0
            }
4043
0
            rowset_id = key.substr(pos + 1);
4044
0
        }
4045
0
        add_to_wait_for_deleted(key, rowset_id, num_segments);
4046
4047
0
        return true;
4048
0
    };
4049
4050
0
    auto status = meta->iterate(META_COLUMN_FAMILY_INDEX, begin_key, check_binlog_ttl);
4051
0
    if (!status.ok()) {
4052
0
        LOG(WARNING) << "failed to iterate binlog meta, status:" << status;
4053
0
        return;
4054
0
    }
4055
4056
    // first remove binlog files, if failed, just break, then retry next time
4057
    // this keep binlog meta in meta store, so that binlog can be removed next time
4058
0
    bool remove_binlog_files_failed = false;
4059
0
    for (auto& file : wait_for_deleted_binlog_files) {
4060
0
        if (unlink(file.c_str()) != 0) {
4061
            // file not exist, continue
4062
0
            if (errno == ENOENT) {
4063
0
                continue;
4064
0
            }
4065
4066
0
            remove_binlog_files_failed = true;
4067
0
            LOG(WARNING) << "failed to remove binlog file:" << file << ", errno:" << errno;
4068
0
            break;
4069
0
        }
4070
0
    }
4071
0
    if (!remove_binlog_files_failed) {
4072
0
        static_cast<void>(meta->remove(META_COLUMN_FAMILY_INDEX, wait_for_deleted_binlog_keys));
4073
0
    }
4074
0
}
4075
4076
0
Status Tablet::ingest_binlog_metas(RowsetBinlogMetasPB* metas_pb) {
4077
0
    return RowsetMetaManager::ingest_binlog_metas(_data_dir->get_meta(), tablet_uid(), metas_pb);
4078
0
}
4079
4080
475
void Tablet::clear_cache() {
4081
475
    std::shared_lock rlock(get_header_lock());
4082
475
    SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
4083
950
    static auto recycle_segment_cache = [](const auto& rowset_map) {
4084
20.9k
        for (auto& [_, rowset] : rowset_map) {
4085
20.9k
            rowset->clear_cache();
4086
20.9k
        }
4087
950
    };
4088
475
    recycle_segment_cache(rowset_map());
4089
475
    recycle_segment_cache(stale_rowset_map());
4090
475
}
4091
4092
Status Tablet::calc_delete_bitmap_between_segments(
4093
        TabletSchemaSPtr schema, RowsetSharedPtr rowset,
4094
0
        const std::vector<segment_v2::SegmentSharedPtr>& segments, DeleteBitmapPtr delete_bitmap) {
4095
0
    size_t const num_segments = segments.size();
4096
0
    if (num_segments < 2) {
4097
0
        return Status::OK();
4098
0
    }
4099
0
    OlapStopWatch watch;
4100
0
    auto const rowset_id = rowset->rowset_id();
4101
0
    size_t seq_col_length = 0;
4102
0
    if (schema->has_sequence_col()) {
4103
0
        auto seq_col_idx = schema->sequence_col_idx();
4104
0
        seq_col_length = schema->column(seq_col_idx).length() + 1;
4105
0
    }
4106
0
    size_t rowid_length = 0;
4107
0
    if (!schema->cluster_key_idxes().empty()) {
4108
0
        rowid_length = PrimaryKeyIndexReader::ROW_ID_LENGTH;
4109
0
    }
4110
4111
0
    MergeIndexDeleteBitmapCalculator calculator;
4112
0
    RETURN_IF_ERROR(calculator.init(rowset_id, segments, seq_col_length, rowid_length));
4113
4114
0
    RETURN_IF_ERROR(calculator.calculate_all(delete_bitmap));
4115
4116
0
    delete_bitmap->add(
4117
0
            {rowset_id, DeleteBitmap::INVALID_SEGMENT_ID, DeleteBitmap::TEMP_VERSION_COMMON},
4118
0
            DeleteBitmap::ROWSET_SENTINEL_MARK);
4119
0
    LOG(INFO) << fmt::format(
4120
0
            "construct delete bitmap between segments, "
4121
0
            "tablet: {}, rowset: {}, number of segments: {}, bitmap size: {}, cost {} (us)",
4122
0
            tablet_id(), rowset_id.to_string(), num_segments, delete_bitmap->delete_bitmap.size(),
4123
0
            watch.get_elapse_time_us());
4124
0
    return Status::OK();
4125
0
}
4126
4127
void Tablet::add_sentinel_mark_to_delete_bitmap(DeleteBitmap* delete_bitmap,
4128
5
                                                const RowsetIdUnorderedSet& rowsetids) {
4129
5
    for (const auto& rowsetid : rowsetids) {
4130
5
        delete_bitmap->add(
4131
5
                {rowsetid, DeleteBitmap::INVALID_SEGMENT_ID, DeleteBitmap::TEMP_VERSION_COMMON},
4132
5
                DeleteBitmap::ROWSET_SENTINEL_MARK);
4133
5
    }
4134
5
}
4135
4136
2
void Tablet::_remove_sentinel_mark_from_delete_bitmap(DeleteBitmapPtr delete_bitmap) {
4137
2
    for (auto it = delete_bitmap->delete_bitmap.begin(), end = delete_bitmap->delete_bitmap.end();
4138
5
         it != end;) {
4139
3
        if (std::get<1>(it->first) == DeleteBitmap::INVALID_SEGMENT_ID) {
4140
1
            it = delete_bitmap->delete_bitmap.erase(it);
4141
2
        } else {
4142
2
            ++it;
4143
2
        }
4144
3
    }
4145
2
}
4146
4147
Status Tablet::check_delete_bitmap_correctness(DeleteBitmapPtr delete_bitmap, int64_t max_version,
4148
                                               int64_t txn_id,
4149
                                               const RowsetIdUnorderedSet& rowset_ids,
4150
4
                                               std::vector<RowsetSharedPtr>* rowsets) {
4151
4
    RowsetIdUnorderedSet missing_ids;
4152
4
    for (const auto& rowsetid : rowset_ids) {
4153
2
        if (!delete_bitmap->delete_bitmap.contains({rowsetid, DeleteBitmap::INVALID_SEGMENT_ID,
4154
2
                                                    DeleteBitmap::TEMP_VERSION_COMMON})) {
4155
0
            missing_ids.insert(rowsetid);
4156
0
        }
4157
2
    }
4158
4159
4
    if (!missing_ids.empty()) {
4160
0
        LOG(WARNING) << "[txn_id:" << txn_id << "][tablet_id:" << tablet_id()
4161
0
                     << "][max_version: " << max_version
4162
0
                     << "] check delete bitmap correctness failed!";
4163
0
        rapidjson::Document root;
4164
0
        root.SetObject();
4165
0
        rapidjson::Document required_rowsets_arr;
4166
0
        required_rowsets_arr.SetArray();
4167
0
        rapidjson::Document missing_rowsets_arr;
4168
0
        missing_rowsets_arr.SetArray();
4169
4170
0
        if (rowsets != nullptr) {
4171
0
            for (const auto& rowset : *rowsets) {
4172
0
                rapidjson::Value value;
4173
0
                std::string version_str =
4174
0
                        _get_rowset_info_str(rowset, rowset->rowset_meta()->has_delete_predicate());
4175
0
                value.SetString(version_str.c_str(), version_str.length(),
4176
0
                                required_rowsets_arr.GetAllocator());
4177
0
                required_rowsets_arr.PushBack(value, required_rowsets_arr.GetAllocator());
4178
0
            }
4179
0
        } else {
4180
0
            std::vector<RowsetSharedPtr> rowsets;
4181
0
            {
4182
0
                std::shared_lock meta_rlock(_meta_lock);
4183
0
                rowsets = get_rowset_by_ids(&rowset_ids);
4184
0
            }
4185
0
            for (const auto& rowset : rowsets) {
4186
0
                rapidjson::Value value;
4187
0
                std::string version_str =
4188
0
                        _get_rowset_info_str(rowset, rowset->rowset_meta()->has_delete_predicate());
4189
0
                value.SetString(version_str.c_str(), version_str.length(),
4190
0
                                required_rowsets_arr.GetAllocator());
4191
0
                required_rowsets_arr.PushBack(value, required_rowsets_arr.GetAllocator());
4192
0
            }
4193
0
        }
4194
0
        for (const auto& missing_rowset_id : missing_ids) {
4195
0
            rapidjson::Value miss_value;
4196
0
            std::string rowset_id_str = missing_rowset_id.to_string();
4197
0
            miss_value.SetString(rowset_id_str.c_str(), rowset_id_str.length(),
4198
0
                                 missing_rowsets_arr.GetAllocator());
4199
0
            missing_rowsets_arr.PushBack(miss_value, missing_rowsets_arr.GetAllocator());
4200
0
        }
4201
4202
0
        root.AddMember("required_rowsets", required_rowsets_arr, root.GetAllocator());
4203
0
        root.AddMember("missing_rowsets", missing_rowsets_arr, root.GetAllocator());
4204
0
        rapidjson::StringBuffer strbuf;
4205
0
        rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(strbuf);
4206
0
        root.Accept(writer);
4207
0
        std::string rowset_status_string = std::string(strbuf.GetString());
4208
0
        LOG_EVERY_SECOND(WARNING) << rowset_status_string;
4209
        // let it crash if correctness check failed in Debug mode
4210
0
        DCHECK(false) << "delete bitmap correctness check failed in publish phase!";
4211
0
        return Status::InternalError("check delete bitmap failed!");
4212
0
    }
4213
4
    return Status::OK();
4214
4
}
4215
Status Tablet::calc_local_file_crc(uint32_t* crc_value, int64_t start_version, int64_t end_version,
4216
0
                                   int32_t* rowset_count, int64_t* file_count) {
4217
0
    Version v(start_version, end_version);
4218
0
    std::vector<RowsetSharedPtr> rowsets;
4219
0
    traverse_rowsets([&rowsets, &v](const auto& rs) {
4220
        // get local rowsets
4221
0
        if (rs->is_local() && v.contains(rs->version())) {
4222
0
            rowsets.emplace_back(rs);
4223
0
        }
4224
0
    });
4225
0
    std::sort(rowsets.begin(), rowsets.end(), Rowset::comparator);
4226
0
    *rowset_count = rowsets.size();
4227
4228
0
    *crc_value = 0;
4229
0
    *file_count = 0;
4230
0
    for (const auto& rs : rowsets) {
4231
0
        uint32_t rs_crc_value;
4232
0
        int64_t rs_file_count = 0;
4233
0
        auto rowset = std::static_pointer_cast<BetaRowset>(rs);
4234
0
        auto st = rowset->calc_local_file_crc(&rs_crc_value, &rs_file_count);
4235
0
        if (!st.ok()) {
4236
0
            return st;
4237
0
        }
4238
        // crc_value is calculated based on the crc_value of each rowset.
4239
0
        *crc_value = crc32c::Extend(*crc_value, reinterpret_cast<const char*>(&rs_crc_value),
4240
0
                                    sizeof(rs_crc_value));
4241
0
        *file_count += rs_file_count;
4242
0
    }
4243
0
    return Status::OK();
4244
0
}
4245
4246
0
Status Tablet::show_nested_index_file(std::string* json_meta) {
4247
0
    Version v(0, max_version_unlocked().second);
4248
0
    std::vector<RowsetSharedPtr> rowsets;
4249
0
    traverse_rowsets([&rowsets, &v](const auto& rs) {
4250
        // get all rowsets
4251
0
        if (v.contains(rs->version())) {
4252
0
            rowsets.emplace_back(rs);
4253
0
        }
4254
0
    });
4255
0
    std::sort(rowsets.begin(), rowsets.end(), Rowset::comparator);
4256
4257
0
    rapidjson::Document doc;
4258
0
    doc.SetObject();
4259
0
    rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();
4260
0
    rapidjson::Value tabletIdValue(tablet_id());
4261
0
    doc.AddMember("tablet_id", tabletIdValue, allocator);
4262
4263
0
    rapidjson::Value rowsets_value(rapidjson::kArrayType);
4264
4265
0
    for (const auto& rs : rowsets) {
4266
0
        rapidjson::Value rowset_value(rapidjson::kObjectType);
4267
4268
0
        auto rowset = std::static_pointer_cast<BetaRowset>(rs);
4269
0
        RETURN_IF_ERROR(rowset->show_nested_index_file(&rowset_value, allocator));
4270
0
        rowsets_value.PushBack(rowset_value, allocator);
4271
0
    }
4272
0
    doc.AddMember("rowsets", rowsets_value, allocator);
4273
4274
0
    rapidjson::StringBuffer buffer;
4275
0
    rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
4276
0
    doc.Accept(writer);
4277
0
    *json_meta = std::string(buffer.GetString());
4278
4279
0
    return Status::OK();
4280
0
}
4281
4282
0
uint64_t Tablet::valid_delete_bitmap_key_count() {
4283
0
    uint64_t ret {0};
4284
0
    std::shared_lock<std::shared_mutex> rlock {_meta_lock};
4285
0
    _tablet_meta->delete_bitmap().traverse_rowset_id_prefix(
4286
0
            [&](const DeleteBitmap& self, const RowsetId& rowset_id) {
4287
0
                if (_contains_rowset(rowset_id)) {
4288
0
                    ret += self.count_key_with_rowset_id_unlocked(rowset_id);
4289
0
                }
4290
0
            });
4291
0
    return ret;
4292
0
}
4293
4294
0
uint64_t Tablet::invalid_delete_bitmap_key_count() {
4295
0
    uint64_t ret {0};
4296
0
    std::shared_lock<std::shared_mutex> rlock {_meta_lock};
4297
0
    _tablet_meta->delete_bitmap().traverse_rowset_id_prefix(
4298
0
            [&](const DeleteBitmap& self, const RowsetId& rowset_id) {
4299
0
                if (!_contains_rowset(rowset_id)) {
4300
0
                    ret += self.count_key_with_rowset_id_unlocked(rowset_id);
4301
0
                }
4302
0
            });
4303
0
    return ret;
4304
0
}
4305
} // namespace doris