Coverage Report

Created: 2025-05-09 17:05

/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
1.04k
void set_last_failure_time(Tablet* tablet, const Compaction& compaction, int64_t ms) {
166
1.04k
    switch (compaction.compaction_type()) {
167
1.02k
    case ReaderType::READER_CUMULATIVE_COMPACTION:
168
1.02k
        tablet->set_last_cumu_compaction_failure_time(ms);
169
1.02k
        return;
170
12
    case ReaderType::READER_BASE_COMPACTION:
171
12
        tablet->set_last_base_compaction_failure_time(ms);
172
12
        return;
173
10
    case ReaderType::READER_FULL_COMPACTION:
174
10
        tablet->set_last_full_compaction_failure_time(ms);
175
10
        return;
176
0
    default:
177
0
        LOG(FATAL) << "invalid compaction type " << compaction.compaction_name()
178
0
                   << " tablet_id: " << tablet->tablet_id();
179
1.04k
    }
180
1.04k
};
181
182
} // namespace
183
184
WriteCooldownMetaExecutors::WriteCooldownMetaExecutors(size_t executor_nums)
185
4
        : _executor_nums(executor_nums) {
186
24
    for (size_t i = 0; i < _executor_nums; i++) {
187
20
        std::unique_ptr<PriorityThreadPool> pool;
188
20
        static_cast<void>(ThreadPoolBuilder("WriteCooldownMetaExecutor")
189
20
                                  .set_min_threads(1)
190
20
                                  .set_max_threads(1)
191
20
                                  .set_max_queue_size(std::numeric_limits<int>::max())
192
20
                                  .build(&pool));
193
20
        _executors.emplace_back(std::move(pool));
194
20
    }
195
4
}
196
197
1
void WriteCooldownMetaExecutors::stop() {
198
5
    for (auto& pool_ptr : _executors) {
199
5
        if (pool_ptr) {
200
5
            pool_ptr->shutdown();
201
5
        }
202
5
    }
203
1
}
204
205
33
void WriteCooldownMetaExecutors::WriteCooldownMetaExecutors::submit(TabletSharedPtr tablet) {
206
33
    auto tablet_id = tablet->tablet_id();
207
208
33
    {
209
33
        std::shared_lock rdlock(tablet->get_header_lock());
210
33
        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
33
        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
33
    }
219
33
    {
220
        // one tablet could at most have one cooldown task to be done
221
33
        std::unique_lock<std::mutex> lck {_latch};
222
33
        if (_pending_tablets.count(tablet_id) > 0) {
223
0
            return;
224
0
        }
225
33
        _pending_tablets.insert(tablet_id);
226
33
    }
227
228
33
    auto async_write_task = [this, t = std::move(tablet)]() {
229
33
        {
230
33
            std::unique_lock<std::mutex> lck {_latch};
231
33
            _pending_tablets.erase(t->tablet_id());
232
33
        }
233
33
        auto s = t->write_cooldown_meta();
234
33
        if (s.ok()) {
235
33
            return;
236
33
        }
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
33
    _executors[_get_executor_pos(tablet_id)]->offer(
247
33
            [task = std::move(async_write_task)]() { task(); });
248
33
}
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
219k
          _last_missed_time_s(0) {
269
219k
    if (_data_dir != nullptr) {
270
219k
        _tablet_path = fmt::format("{}/{}/{}/{}/{}", _data_dir->path(), DATA_PREFIX,
271
219k
                                   _tablet_meta->shard_id(), tablet_id(), schema_hash());
272
219k
    }
273
    // construct _timestamped_versioned_tracker from rs and stale rs meta
274
219k
    _timestamped_version_tracker.construct_versioned_tracker(_tablet_meta->all_rs_metas(),
275
219k
                                                             _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
219k
    if (_tablet_meta->all_rs_metas().empty() || !_tablet_meta->all_rs_metas()[0]->tablet_schema()) {
282
216k
        _max_version_schema = _tablet_meta->tablet_schema();
283
216k
    } else {
284
2.61k
        _max_version_schema =
285
2.61k
                tablet_schema_with_merged_max_schema_version(_tablet_meta->all_rs_metas());
286
2.61k
    }
287
219k
    DCHECK(_max_version_schema);
288
219k
}
289
290
2.01k
bool Tablet::set_tablet_schema_into_rowset_meta() {
291
2.01k
    bool flag = false;
292
6.02k
    for (auto&& rowset_meta : _tablet_meta->all_mutable_rs_metas()) {
293
6.02k
        if (!rowset_meta->tablet_schema()) {
294
0
            rowset_meta->set_tablet_schema(_tablet_meta->tablet_schema());
295
0
            flag = true;
296
0
        }
297
6.02k
    }
298
2.01k
    return flag;
299
2.01k
}
300
301
219k
Status Tablet::_init_once_action() {
302
219k
    Status res = Status::OK();
303
18.4E
    VLOG_NOTICE << "begin to load tablet. tablet=" << tablet_id()
304
18.4E
                << ", version_size=" << _tablet_meta->version_count();
305
306
#ifdef BE_TEST
307
    // init cumulative compaction policy by type
308
    _cumulative_compaction_policy =
309
            CumulativeCompactionPolicyFactory::create_cumulative_compaction_policy(
310
                    _tablet_meta->compaction_policy());
311
#endif
312
313
219k
    for (const auto& rs_meta : _tablet_meta->all_rs_metas()) {
314
7.45k
        Version version = rs_meta->version();
315
7.45k
        RowsetSharedPtr rowset;
316
7.45k
        res = create_rowset(rs_meta, &rowset);
317
7.45k
        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
7.45k
        _rs_version_map[version] = std::move(rowset);
324
7.45k
    }
325
326
    // init stale rowset
327
219k
    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
219k
    return res;
341
219k
}
342
343
219k
Status Tablet::init() {
344
219k
    return _init_once.call([this] { return _init_once_action(); });
345
219k
}
346
347
// should save tablet meta to remote meta store
348
// if it's a primary replica
349
530k
void Tablet::save_meta() {
350
530k
    auto res = _tablet_meta->save_meta(_data_dir);
351
530k
    CHECK_EQ(res, Status::OK()) << "fail to save tablet_meta. res=" << res
352
0
                                << ", root=" << _data_dir->path();
353
530k
}
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
230k
Status Tablet::add_rowset(RowsetSharedPtr rowset) {
507
230k
    DCHECK(rowset != nullptr);
508
230k
    std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
509
230k
    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
230k
    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
230k
    RETURN_IF_ERROR(_contains_version(rowset->version()));
517
518
230k
    RETURN_IF_ERROR(_tablet_meta->add_rs_meta(rowset->rowset_meta()));
519
230k
    _rs_version_map[rowset->version()] = rowset;
520
230k
    _timestamped_version_tracker.add_version(rowset->version());
521
522
230k
    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
263k
    for (auto& it : _rs_version_map) {
526
263k
        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
263k
    }
534
230k
    std::vector<RowsetSharedPtr> empty_vec;
535
230k
    RETURN_IF_ERROR(modify_rowsets(empty_vec, rowsets_to_delete));
536
230k
    ++_newly_created_rowset_num;
537
230k
    return Status::OK();
538
230k
}
539
540
5.97k
bool Tablet::rowset_exists_unlocked(const RowsetSharedPtr& rowset) {
541
5.97k
    if (auto it = _rs_version_map.find(rowset->version()); it == _rs_version_map.end()) {
542
0
        return false;
543
5.97k
    } else if (rowset->rowset_id() != it->second->rowset_id()) {
544
0
        return false;
545
0
    }
546
5.97k
    return true;
547
5.97k
}
548
549
Status Tablet::modify_rowsets(std::vector<RowsetSharedPtr>& to_add,
550
232k
                              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
232k
    if (to_add.empty() && to_delete.empty()) {
564
230k
        return Status::OK();
565
230k
    }
566
567
2.50k
    if (check_delete) {
568
21.9k
        for (auto&& rs : to_delete) {
569
21.9k
            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
21.9k
            } 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
21.9k
        }
581
2.50k
    }
582
583
2.41k
    bool same_version = true;
584
2.41k
    std::sort(to_add.begin(), to_add.end(), Rowset::comparator);
585
2.41k
    std::sort(to_delete.begin(), to_delete.end(), Rowset::comparator);
586
2.41k
    if (to_add.size() == to_delete.size()) {
587
5.12k
        for (int i = 0; i < to_add.size(); ++i) {
588
3.98k
            if (to_add[i]->version() != to_delete[i]->version()) {
589
0
                same_version = false;
590
0
                break;
591
0
            }
592
3.98k
        }
593
1.27k
    } else {
594
1.27k
        same_version = false;
595
1.27k
    }
596
597
2.41k
    std::vector<RowsetMetaSharedPtr> rs_metas_to_delete;
598
21.9k
    for (auto& rs : to_delete) {
599
21.9k
        rs_metas_to_delete.push_back(rs->rowset_meta());
600
21.9k
        _rs_version_map.erase(rs->version());
601
602
21.9k
        if (!same_version) {
603
            // put compaction rowsets in _stale_rs_version_map.
604
17.9k
            _stale_rs_version_map[rs->version()] = rs;
605
17.9k
        }
606
21.9k
    }
607
608
2.41k
    std::vector<RowsetMetaSharedPtr> rs_metas_to_add;
609
5.34k
    for (auto& rs : to_add) {
610
5.34k
        rs_metas_to_add.push_back(rs->rowset_meta());
611
5.34k
        _rs_version_map[rs->version()] = rs;
612
613
5.34k
        if (!same_version) {
614
            // If version are same, then _timestamped_version_tracker
615
            // already has this version, no need to add again.
616
1.36k
            _timestamped_version_tracker.add_version(rs->version());
617
1.36k
        }
618
5.34k
        ++_newly_created_rowset_num;
619
5.34k
    }
620
621
2.41k
    _tablet_meta->modify_rs_metas(rs_metas_to_add, rs_metas_to_delete, same_version);
622
623
2.41k
    if (!same_version) {
624
        // add rs_metas_to_delete to tracker
625
1.36k
        _timestamped_version_tracker.add_stale_path_version(rs_metas_to_delete);
626
1.36k
    } else {
627
        // delete rowset in "to_delete" directly
628
3.98k
        for (auto& rs : to_delete) {
629
3.98k
            LOG(INFO) << "add unused rowset " << rs->rowset_id() << " because of same version";
630
3.98k
            _engine.add_unused_rowset(rs);
631
3.98k
        }
632
1.04k
    }
633
2.41k
    return Status::OK();
634
2.41k
}
635
636
33
void Tablet::add_rowsets(const std::vector<RowsetSharedPtr>& to_add) {
637
33
    if (to_add.empty()) {
638
0
        return;
639
0
    }
640
33
    std::vector<RowsetMetaSharedPtr> rs_metas;
641
33
    rs_metas.reserve(to_add.size());
642
33
    for (auto& rs : to_add) {
643
33
        _rs_version_map.emplace(rs->version(), rs);
644
33
        _timestamped_version_tracker.add_version(rs->version());
645
33
        rs_metas.push_back(rs->rowset_meta());
646
33
    }
647
33
    _tablet_meta->modify_rs_metas(rs_metas, {});
648
33
}
649
650
7.26k
Status Tablet::delete_rowsets(const std::vector<RowsetSharedPtr>& to_delete, bool move_to_stale) {
651
7.26k
    if (to_delete.empty()) {
652
0
        return Status::OK();
653
0
    }
654
7.26k
    std::vector<RowsetMetaSharedPtr> rs_metas;
655
7.26k
    rs_metas.reserve(to_delete.size());
656
7.29k
    for (const auto& rs : to_delete) {
657
7.29k
        rs_metas.push_back(rs->rowset_meta());
658
7.29k
        _rs_version_map.erase(rs->version());
659
7.29k
    }
660
7.26k
    _tablet_meta->modify_rs_metas({}, rs_metas, !move_to_stale);
661
7.26k
    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
7.26k
    } else {
667
7.29k
        for (const auto& rs : to_delete) {
668
7.29k
            _timestamped_version_tracker.delete_version(rs->version());
669
7.29k
            _engine.add_unused_rowset(rs);
670
7.29k
            RETURN_IF_ERROR(RowsetMetaManager::remove(_data_dir->get_meta(), tablet_uid(),
671
7.29k
                                                      rs->rowset_meta()->rowset_id()));
672
7.29k
        }
673
7.26k
    }
674
7.26k
    return Status::OK();
675
7.26k
}
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
13.3k
const RowsetSharedPtr Tablet::rowset_with_max_version() const {
702
13.3k
    Version max_version = _tablet_meta->max_version();
703
13.3k
    if (max_version.first == -1) {
704
0
        return nullptr;
705
0
    }
706
707
13.3k
    auto iter = _rs_version_map.find(max_version);
708
13.3k
    if (iter == _rs_version_map.end()) {
709
0
        DCHECK(false) << "invalid version:" << max_version;
710
0
        return nullptr;
711
0
    }
712
13.3k
    return iter->second;
713
13.3k
}
714
715
TabletSchemaSPtr Tablet::tablet_schema_with_merged_max_schema_version(
716
4.25k
        const std::vector<RowsetMetaSharedPtr>& rowset_metas) {
717
4.25k
    RowsetMetaSharedPtr max_schema_version_rs = *std::max_element(
718
4.25k
            rowset_metas.begin(), rowset_metas.end(),
719
21.1k
            [](const RowsetMetaSharedPtr& a, const RowsetMetaSharedPtr& b) {
720
21.1k
                return !a->tablet_schema()
721
21.1k
                               ? true
722
21.1k
                               : (!b->tablet_schema()
723
21.1k
                                          ? false
724
21.1k
                                          : a->tablet_schema()->schema_version() <
725
21.1k
                                                    b->tablet_schema()->schema_version());
726
21.1k
            });
727
4.25k
    TabletSchemaSPtr target_schema = max_schema_version_rs->tablet_schema();
728
4.25k
    if (target_schema->num_variant_columns() > 0) {
729
        // For variant columns tablet schema need to be the merged wide tablet schema
730
93
        std::vector<TabletSchemaSPtr> schemas;
731
93
        std::transform(rowset_metas.begin(), rowset_metas.end(), std::back_inserter(schemas),
732
885
                       [](const RowsetMetaSharedPtr& rs_meta) { return rs_meta->tablet_schema(); });
733
93
        static_cast<void>(
734
93
                vectorized::schema_util::get_least_common_schema(schemas, nullptr, target_schema));
735
93
        VLOG_DEBUG << "dump schema: " << target_schema->dump_structure();
736
93
    }
737
4.25k
    return target_schema;
738
4.25k
}
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
245k
Status Tablet::add_inc_rowset(const RowsetSharedPtr& rowset) {
757
245k
    DCHECK(rowset != nullptr);
758
245k
    std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
759
245k
    SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
760
245k
    if (_contains_rowset(rowset->rowset_id())) {
761
0
        return Status::OK();
762
0
    }
763
245k
    RETURN_IF_ERROR(_contains_version(rowset->version()));
764
765
245k
    RETURN_IF_ERROR(_tablet_meta->add_rs_meta(rowset->rowset_meta()));
766
245k
    _rs_version_map[rowset->version()] = rowset;
767
768
245k
    _timestamped_version_tracker.add_version(rowset->version());
769
770
245k
    ++_newly_created_rowset_num;
771
245k
    return Status::OK();
772
245k
}
773
774
17.2k
void Tablet::_delete_stale_rowset_by_version(const Version& version) {
775
17.2k
    RowsetMetaSharedPtr rowset_meta = _tablet_meta->acquire_stale_rs_meta_by_version(version);
776
17.2k
    if (rowset_meta == nullptr) {
777
8
        return;
778
8
    }
779
17.2k
    _tablet_meta->delete_stale_rs_meta_by_version(version);
780
17.2k
    VLOG_NOTICE << "delete stale rowset. tablet=" << tablet_id() << ", version=" << version;
781
17.2k
}
782
783
1.77M
void Tablet::delete_expired_stale_rowset() {
784
1.77M
    int64_t now = UnixSeconds();
785
    // hold write lock while processing stable rowset
786
1.77M
    {
787
1.77M
        std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
788
1.77M
        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.77M
        double expired_stale_sweep_endtime =
791
1.77M
                ::difftime(now, config::tablet_rowset_stale_sweep_time_sec);
792
1.77M
        if (config::tablet_rowset_stale_sweep_by_size) {
793
0
            expired_stale_sweep_endtime = now;
794
0
        }
795
796
1.77M
        std::vector<int64_t> path_id_vec;
797
        // capture the path version to delete
798
1.77M
        _timestamped_version_tracker.capture_expired_paths(
799
1.77M
                static_cast<int64_t>(expired_stale_sweep_endtime), &path_id_vec);
800
801
1.77M
        if (path_id_vec.empty()) {
802
1.77M
            return;
803
1.77M
        }
804
805
1.14k
        const RowsetSharedPtr lastest_delta = rowset_with_max_version();
806
1.14k
        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.14k
        std::vector<Version> missed_versions;
813
1.14k
        calc_missed_versions_unlocked(lastest_delta->end_version(), &missed_versions);
814
815
1.14k
        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.14k
        auto path_id_iter = path_id_vec.begin();
824
825
1.14k
        std::map<int64_t, PathVersionListSharedPtr> stale_version_path_map;
826
2.41k
        while (path_id_iter != path_id_vec.end()) {
827
1.27k
            PathVersionListSharedPtr version_path =
828
1.27k
                    _timestamped_version_tracker.fetch_and_delete_path_by_id(*path_id_iter);
829
830
1.27k
            Version test_version = Version(0, lastest_delta->end_version());
831
1.27k
            stale_version_path_map[*path_id_iter] = version_path;
832
833
1.27k
            Status status = capture_consistent_versions(test_version, nullptr, false, false);
834
            // 1. When there is no consistent versions, we must reconstruct the tracker.
835
1.27k
            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
1.27k
            path_id_iter++;
895
1.27k
        }
896
897
1.14k
        auto old_size = _stale_rs_version_map.size();
898
1.14k
        auto old_meta_size = _tablet_meta->all_stale_rs_metas().size();
899
900
        // do delete operation
901
1.14k
        auto to_delete_iter = stale_version_path_map.begin();
902
2.41k
        while (to_delete_iter != stale_version_path_map.end()) {
903
1.27k
            std::vector<TimestampedVersionSharedPtr>& to_delete_version =
904
1.27k
                    to_delete_iter->second->timestamped_versions();
905
17.2k
            for (auto& timestampedVersion : to_delete_version) {
906
17.2k
                auto it = _stale_rs_version_map.find(timestampedVersion->version());
907
17.2k
                if (it != _stale_rs_version_map.end()) {
908
                    // delete rowset
909
17.2k
                    it->second->clear_cache();
910
17.2k
                    _engine.add_unused_rowset(it->second);
911
17.2k
                    _stale_rs_version_map.erase(it);
912
17.2k
                    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
17.2k
                } 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
17.2k
                _delete_stale_rowset_by_version(timestampedVersion->version());
924
17.2k
            }
925
1.27k
            to_delete_iter++;
926
1.27k
        }
927
928
1.14k
        bool reconstructed = _reconstruct_version_tracker_if_necessary();
929
930
1.14k
        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.14k
    }
936
0
#ifndef BE_TEST
937
0
    {
938
1.14k
        std::shared_lock<std::shared_mutex> rlock(_meta_lock);
939
1.14k
        save_meta();
940
1.14k
    }
941
1.14k
#endif
942
1.14k
}
943
944
1.14k
bool Tablet::_reconstruct_version_tracker_if_necessary() {
945
1.14k
    double orphan_vertex_ratio = _timestamped_version_tracker.get_orphan_vertex_ratio();
946
1.14k
    if (orphan_vertex_ratio >= config::tablet_version_graph_orphan_vertex_ratio) {
947
1.11k
        _timestamped_version_tracker.construct_versioned_tracker(
948
1.11k
                _tablet_meta->all_rs_metas(), _tablet_meta->all_stale_rs_metas());
949
1.11k
        return true;
950
1.11k
    }
951
24
    return false;
952
1.14k
}
953
954
Status Tablet::capture_consistent_versions(const Version& spec_version,
955
                                           std::vector<Version>* version_path,
956
3.16M
                                           bool skip_missing_version, bool quiet) const {
957
3.16M
    Status status =
958
3.16M
            _timestamped_version_tracker.capture_consistent_versions(spec_version, version_path);
959
3.16M
    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
3.16M
    DBUG_EXECUTE_IF("TTablet::capture_consistent_versions.inject_failure", {
988
3.16M
        auto tablet_id = dp->param<int64>("tablet_id", -1);
989
3.16M
        if (tablet_id != -1 && tablet_id == _tablet_meta->tablet_id()) {
990
3.16M
            status = Status::Error<VERSION_ALREADY_MERGED>("version already merged");
991
3.16M
        }
992
3.16M
    });
993
994
3.16M
    return status;
995
3.16M
}
996
997
7.16k
Status Tablet::check_version_integrity(const Version& version, bool quiet) {
998
7.16k
    std::shared_lock rdlock(_meta_lock);
999
7.16k
    return capture_consistent_versions(version, nullptr, false, quiet);
1000
7.16k
}
1001
1002
55.5k
bool Tablet::exceed_version_limit(int32_t limit) const {
1003
55.5k
    if (_tablet_meta->version_count() > limit) {
1004
0
        exceed_version_limit_counter << 1;
1005
0
        return true;
1006
0
    }
1007
55.5k
    return false;
1008
55.5k
}
1009
1010
// If any rowset contains the specific version, it means the version already exist
1011
4.24M
bool Tablet::check_version_exist(const Version& version) const {
1012
4.24M
    std::shared_lock rdlock(_meta_lock);
1013
258M
    for (auto& it : _rs_version_map) {
1014
258M
        if (it.first.contains(version)) {
1015
255k
            return true;
1016
255k
        }
1017
258M
    }
1018
3.99M
    return false;
1019
4.24M
}
1020
1021
// The meta read lock should be held before calling
1022
void Tablet::acquire_version_and_rowsets(
1023
70.3k
        std::vector<std::pair<Version, RowsetSharedPtr>>* version_rowsets) const {
1024
144k
    for (const auto& it : _rs_version_map) {
1025
144k
        version_rowsets->emplace_back(it.first, it.second);
1026
144k
    }
1027
70.3k
}
1028
1029
Status Tablet::capture_consistent_rowsets(const Version& spec_version,
1030
1.67k
                                          std::vector<RowsetSharedPtr>* rowsets) const {
1031
1.67k
    std::vector<Version> version_path;
1032
1.67k
    RETURN_IF_ERROR(capture_consistent_versions(spec_version, &version_path, false, false));
1033
1.67k
    RETURN_IF_ERROR(_capture_consistent_rowsets_unlocked(version_path, rowsets));
1034
1.67k
    return Status::OK();
1035
1.67k
}
1036
1037
Status Tablet::_capture_consistent_rowsets_unlocked(const std::vector<Version>& version_path,
1038
1.67k
                                                    std::vector<RowsetSharedPtr>* rowsets) const {
1039
1.67k
    DCHECK(rowsets != nullptr);
1040
1.67k
    rowsets->reserve(version_path.size());
1041
2.18k
    for (auto& version : version_path) {
1042
2.18k
        bool is_find = false;
1043
2.18k
        do {
1044
2.18k
            auto it = _rs_version_map.find(version);
1045
2.18k
            if (it != _rs_version_map.end()) {
1046
2.18k
                is_find = true;
1047
2.18k
                rowsets->push_back(it->second);
1048
2.18k
                break;
1049
2.18k
            }
1050
1051
1
            auto it_expired = _stale_rs_version_map.find(version);
1052
1
            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
1
        } while (false);
1058
1059
2.18k
        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
2.18k
    }
1065
1.67k
    return Status::OK();
1066
1.67k
}
1067
1068
Status Tablet::capture_rs_readers(const Version& spec_version, std::vector<RowSetSplits>* rs_splits,
1069
2.99M
                                  bool skip_missing_version) const {
1070
2.99M
    std::vector<Version> version_path;
1071
2.99M
    RETURN_IF_ERROR(
1072
2.99M
            capture_consistent_versions(spec_version, &version_path, skip_missing_version, false));
1073
2.99M
    RETURN_IF_ERROR(capture_rs_readers(version_path, rs_splits));
1074
2.99M
    return Status::OK();
1075
2.99M
}
1076
1077
Status Tablet::capture_rs_readers(const std::vector<Version>& version_path,
1078
3.00M
                                  std::vector<RowSetSplits>* rs_splits) const {
1079
3.00M
    DCHECK(rs_splits != nullptr && rs_splits->empty());
1080
16.4M
    for (auto version : version_path) {
1081
16.4M
        auto it = _rs_version_map.find(version);
1082
16.4M
        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
16.4M
        RowsetReaderSharedPtr rs_reader;
1095
16.4M
        auto res = it->second->create_reader(&rs_reader);
1096
16.4M
        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
16.4M
        rs_splits->push_back(RowSetSplits(std::move(rs_reader)));
1101
16.4M
    }
1102
3.00M
    return Status::OK();
1103
3.00M
}
1104
1105
8.09M
bool Tablet::can_do_compaction(size_t path_hash, CompactionType compaction_type) {
1106
8.09M
    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
9.49k
        return false;
1110
9.49k
    }
1111
1112
8.08M
    if (data_dir()->path_hash() != path_hash || !is_used() || !init_succeeded()) {
1113
2.99M
        return false;
1114
2.99M
    }
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
5.08M
    return tablet_state() == TABLET_RUNNING || tablet_state() == TABLET_NOTREADY;
1119
8.08M
}
1120
1121
uint32_t Tablet::calc_compaction_score(
1122
        CompactionType compaction_type,
1123
5.07M
        std::shared_ptr<CumulativeCompactionPolicy> cumulative_compaction_policy) {
1124
    // Need meta lock, because it will iterator "all_rs_metas" of tablet meta.
1125
5.07M
    std::shared_lock rdlock(_meta_lock);
1126
5.07M
    if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) {
1127
3.05M
        return _calc_cumulative_compaction_score(cumulative_compaction_policy);
1128
3.05M
    } else {
1129
2.01M
        DCHECK_EQ(compaction_type, CompactionType::BASE_COMPACTION);
1130
2.01M
        return _calc_base_compaction_score();
1131
2.01M
    }
1132
5.07M
}
1133
1134
14
uint32_t Tablet::calc_cold_data_compaction_score() const {
1135
14
    uint32_t score = 0;
1136
14
    std::vector<RowsetMetaSharedPtr> cooldowned_rowsets;
1137
14
    int64_t max_delete_version = 0;
1138
14
    {
1139
14
        std::shared_lock rlock(_meta_lock);
1140
38
        for (auto& rs_meta : _tablet_meta->all_rs_metas()) {
1141
38
            if (!rs_meta->is_local()) {
1142
38
                cooldowned_rowsets.push_back(rs_meta);
1143
38
                if (rs_meta->has_delete_predicate() &&
1144
38
                    rs_meta->end_version() > max_delete_version) {
1145
0
                    max_delete_version = rs_meta->end_version();
1146
0
                }
1147
38
            }
1148
38
        }
1149
14
    }
1150
38
    for (auto& rs_meta : cooldowned_rowsets) {
1151
38
        if (rs_meta->end_version() < max_delete_version) {
1152
0
            score += rs_meta->num_segments();
1153
38
        } else {
1154
38
            score += rs_meta->get_compaction_score();
1155
38
        }
1156
38
    }
1157
14
    return (keys_type() != KeysType::DUP_KEYS) ? score * 2 : score;
1158
14
}
1159
1160
uint32_t Tablet::_calc_cumulative_compaction_score(
1161
3.05M
        std::shared_ptr<CumulativeCompactionPolicy> cumulative_compaction_policy) {
1162
3.05M
    if (cumulative_compaction_policy == nullptr) [[unlikely]] {
1163
0
        return 0;
1164
0
    }
1165
3.05M
    DBUG_EXECUTE_IF("Tablet._calc_cumulative_compaction_score.return", {
1166
3.05M
        LOG_WARNING("Tablet._calc_cumulative_compaction_score.return")
1167
3.05M
                .tag("tablet id", tablet_id());
1168
3.05M
        return 0;
1169
3.05M
    });
1170
3.05M
#ifndef BE_TEST
1171
3.05M
    if (_cumulative_compaction_policy == nullptr ||
1172
3.05M
        _cumulative_compaction_policy->name() != cumulative_compaction_policy->name()) {
1173
70.0k
        _cumulative_compaction_policy = cumulative_compaction_policy;
1174
70.0k
    }
1175
3.05M
#endif
1176
3.05M
    return _cumulative_compaction_policy->calc_cumulative_compaction_score(this);
1177
3.05M
}
1178
1179
2.01M
uint32_t Tablet::_calc_base_compaction_score() const {
1180
2.01M
    uint32_t score = 0;
1181
2.01M
    const int64_t point = cumulative_layer_point();
1182
2.01M
    bool base_rowset_exist = false;
1183
2.01M
    bool has_delete = false;
1184
3.17M
    for (auto& rs_meta : _tablet_meta->all_rs_metas()) {
1185
3.17M
        if (rs_meta->start_version() == 0) {
1186
2.01M
            base_rowset_exist = true;
1187
2.01M
        }
1188
3.17M
        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
1.23M
            continue;
1191
1.23M
        }
1192
1.93M
        if (rs_meta->has_delete_predicate()) {
1193
720
            has_delete = true;
1194
720
        }
1195
1.93M
        score += rs_meta->get_compaction_score();
1196
1.93M
    }
1197
1198
    // In the time series compaction policy, we want the base compaction to be triggered
1199
    // when there are delete versions present.
1200
2.01M
    if (_tablet_meta->compaction_policy() == CUMULATIVE_TIME_SERIES_POLICY) {
1201
27
        return (base_rowset_exist && has_delete) ? score : 0;
1202
27
    }
1203
1204
    // base不存在可能是tablet正在做alter table,先不选它,设score=0
1205
2.01M
    return base_rowset_exist ? score : 0;
1206
2.01M
}
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
1.14k
                                           std::vector<Version>* missed_versions) const {
1218
1.14k
    DCHECK(spec_version > 0) << "invalid spec_version: " << spec_version;
1219
1.14k
    std::list<Version> existing_versions;
1220
5.19k
    for (auto& rs : _tablet_meta->all_rs_metas()) {
1221
5.19k
        existing_versions.emplace_back(rs->version());
1222
5.19k
    }
1223
1224
    // sort the existing versions in ascending order
1225
13.1k
    existing_versions.sort([](const Version& a, const Version& b) {
1226
        // simple because 2 versions are certainly not overlapping
1227
13.1k
        return a.first < b.first;
1228
13.1k
    });
1229
1230
    // From the first version(=0),  find the missing version until spec_version
1231
1.14k
    int64_t last_version = -1;
1232
5.19k
    for (const Version& version : existing_versions) {
1233
5.19k
        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
5.19k
        last_version = version.second;
1239
5.19k
        if (last_version >= spec_version) {
1240
1.14k
            break;
1241
1.14k
        }
1242
5.19k
    }
1243
1.14k
    for (int64_t i = last_version + 1; i <= spec_version; ++i) {
1244
0
        missed_versions->emplace_back(Version(i, i));
1245
0
    }
1246
1.14k
}
1247
1248
7.61k
void Tablet::max_continuous_version_from_beginning(Version* version, Version* max_version) {
1249
7.61k
    bool has_version_cross;
1250
7.61k
    std::shared_lock rdlock(_meta_lock);
1251
7.61k
    _max_continuous_version_from_beginning_unlocked(version, max_version, &has_version_cross);
1252
7.61k
}
1253
1254
void Tablet::_max_continuous_version_from_beginning_unlocked(Version* version, Version* max_version,
1255
18.1M
                                                             bool* has_version_cross) const {
1256
18.1M
    std::vector<Version> existing_versions;
1257
18.1M
    *has_version_cross = false;
1258
40.6M
    for (auto& rs : _tablet_meta->all_rs_metas()) {
1259
40.6M
        existing_versions.emplace_back(rs->version());
1260
40.6M
    }
1261
1262
    // sort the existing versions in ascending order
1263
18.1M
    std::sort(existing_versions.begin(), existing_versions.end(),
1264
73.4M
              [](const Version& left, const Version& right) {
1265
                  // simple because 2 versions are certainly not overlapping
1266
73.4M
                  return left.first < right.first;
1267
73.4M
              });
1268
1269
18.1M
    Version max_continuous_version = {-1, -1};
1270
58.8M
    for (int i = 0; i < existing_versions.size(); ++i) {
1271
40.6M
        if (existing_versions[i].first > max_continuous_version.second + 1) {
1272
6
            break;
1273
40.6M
        } else if (existing_versions[i].first <= max_continuous_version.second) {
1274
0
            *has_version_cross = true;
1275
0
        }
1276
40.6M
        max_continuous_version = existing_versions[i];
1277
40.6M
    }
1278
18.1M
    *version = max_continuous_version;
1279
    // tablet may not has rowset, eg, tablet has just been clear for restore.
1280
18.1M
    if (max_version != nullptr && !existing_versions.empty()) {
1281
18.1M
        *max_version = existing_versions.back();
1282
18.1M
    }
1283
18.1M
}
1284
1285
1.37k
void Tablet::calculate_cumulative_point() {
1286
1.37k
    std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
1287
1.37k
    SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
1288
1.37k
    int64_t ret_cumulative_point;
1289
1.37k
    _cumulative_compaction_policy->calculate_cumulative_point(
1290
1.37k
            this, _tablet_meta->all_rs_metas(), _cumulative_point, &ret_cumulative_point);
1291
1292
1.37k
    if (ret_cumulative_point == K_INVALID_CUMULATIVE_POINT) {
1293
1.02k
        return;
1294
1.02k
    }
1295
347
    set_cumulative_layer_point(ret_cumulative_point);
1296
347
}
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
476k
Status Tablet::_contains_version(const Version& version) {
1359
    // check if there exist a rowset contains the added rowset
1360
32.6M
    for (auto& it : _rs_version_map) {
1361
32.6M
        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
32.6M
    }
1373
1374
476k
    return Status::OK();
1375
476k
}
1376
1377
309k
TabletInfo Tablet::get_tablet_info() const {
1378
309k
    return TabletInfo(tablet_id(), tablet_uid());
1379
309k
}
1380
1381
1.40k
std::vector<RowsetSharedPtr> Tablet::pick_candidate_rowsets_to_cumulative_compaction() {
1382
1.40k
    std::vector<RowsetSharedPtr> candidate_rowsets;
1383
1.40k
    if (_cumulative_point == K_INVALID_CUMULATIVE_POINT) {
1384
0
        return candidate_rowsets;
1385
0
    }
1386
1.40k
    return _pick_visible_rowsets_to_compaction(_cumulative_point,
1387
1.40k
                                               std::numeric_limits<int64_t>::max());
1388
1.40k
}
1389
1390
116
std::vector<RowsetSharedPtr> Tablet::pick_candidate_rowsets_to_base_compaction() {
1391
116
    return _pick_visible_rowsets_to_compaction(std::numeric_limits<int64_t>::min(),
1392
116
                                               _cumulative_point - 1);
1393
116
}
1394
1395
std::vector<RowsetSharedPtr> Tablet::_pick_visible_rowsets_to_compaction(
1396
1.51k
        int64_t min_start_version, int64_t max_start_version) {
1397
1.51k
    auto [visible_version, update_ts] = get_visible_version_and_time();
1398
1.51k
    bool update_time_long = MonotonicMillis() - update_ts >
1399
1.51k
                            config::compaction_keep_invisible_version_timeout_sec * 1000L;
1400
1.51k
    int32_t keep_invisible_version_limit =
1401
1.51k
            update_time_long ? config::compaction_keep_invisible_version_min_count
1402
1.51k
                             : config::compaction_keep_invisible_version_max_count;
1403
1404
1.51k
    std::vector<RowsetSharedPtr> candidate_rowsets;
1405
1.51k
    {
1406
1.51k
        std::shared_lock rlock(_meta_lock);
1407
21.6k
        for (const auto& [version, rs] : _rs_version_map) {
1408
21.6k
            int64_t version_start = version.first;
1409
            // rowset is remote or rowset is not in given range
1410
21.6k
            if (!rs->is_local() || version_start < min_start_version ||
1411
21.6k
                version_start > max_start_version) {
1412
1.81k
                continue;
1413
1.81k
            }
1414
1415
            // can compact, met one of the conditions:
1416
            // 1. had been visible;
1417
            // 2. exceeds the limit of keep invisible versions.
1418
19.8k
            int64_t version_end = version.second;
1419
19.8k
            if (version_end <= visible_version ||
1420
19.8k
                version_end > visible_version + keep_invisible_version_limit) {
1421
19.7k
                candidate_rowsets.push_back(rs);
1422
19.7k
            }
1423
19.8k
        }
1424
1.51k
    }
1425
1.51k
    std::sort(candidate_rowsets.begin(), candidate_rowsets.end(), Rowset::comparator);
1426
1.51k
    return candidate_rowsets;
1427
1.51k
}
1428
1429
146
std::vector<RowsetSharedPtr> Tablet::pick_candidate_rowsets_to_full_compaction() {
1430
146
    std::vector<RowsetSharedPtr> candidate_rowsets;
1431
390
    traverse_rowsets([&candidate_rowsets](const auto& rs) {
1432
        // Do full compaction on all local rowsets.
1433
390
        if (rs->is_local()) {
1434
390
            candidate_rowsets.emplace_back(rs);
1435
390
        }
1436
390
    });
1437
146
    std::sort(candidate_rowsets.begin(), candidate_rowsets.end(), Rowset::comparator);
1438
146
    return candidate_rowsets;
1439
146
}
1440
1441
39
std::vector<RowsetSharedPtr> Tablet::pick_first_consecutive_empty_rowsets(int limit) {
1442
39
    std::vector<RowsetSharedPtr> consecutive_empty_rowsets;
1443
39
    std::vector<RowsetSharedPtr> candidate_rowsets =
1444
39
            pick_candidate_rowsets_to_cumulative_compaction();
1445
39
    int len = candidate_rowsets.size();
1446
76
    for (int i = 0; i < len - 1; ++i) {
1447
41
        auto rowset = candidate_rowsets[i];
1448
41
        auto next_rowset = candidate_rowsets[i + 1];
1449
1450
        // identify two consecutive rowsets that are empty
1451
41
        if (rowset->num_segments() == 0 && next_rowset->num_segments() == 0 &&
1452
41
            !rowset->rowset_meta()->has_delete_predicate() &&
1453
41
            !next_rowset->rowset_meta()->has_delete_predicate() &&
1454
41
            rowset->end_version() == next_rowset->start_version() - 1) {
1455
4
            consecutive_empty_rowsets.emplace_back(rowset);
1456
4
            consecutive_empty_rowsets.emplace_back(next_rowset);
1457
4
            rowset = next_rowset;
1458
4
            int next_index = i + 2;
1459
1460
            // keep searching for consecutive empty rowsets
1461
18
            while (next_index < len && candidate_rowsets[next_index]->num_segments() == 0 &&
1462
18
                   !candidate_rowsets[next_index]->rowset_meta()->has_delete_predicate() &&
1463
18
                   rowset->end_version() == candidate_rowsets[next_index]->start_version() - 1) {
1464
14
                consecutive_empty_rowsets.emplace_back(candidate_rowsets[next_index]);
1465
14
                rowset = candidate_rowsets[next_index++];
1466
14
            }
1467
            // if the number of consecutive empty rowset reach the limit,
1468
            // and there are still rowsets following them
1469
4
            if (consecutive_empty_rowsets.size() >= limit && next_index < len) {
1470
4
                return consecutive_empty_rowsets;
1471
4
            } 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
4
        }
1477
41
    }
1478
1479
35
    return consecutive_empty_rowsets;
1480
39
}
1481
1482
std::vector<RowsetSharedPtr> Tablet::pick_candidate_rowsets_to_build_inverted_index(
1483
1.28k
        const std::set<int64_t>& alter_index_uids, bool is_drop_op) {
1484
1.28k
    std::vector<RowsetSharedPtr> candidate_rowsets;
1485
1.28k
    {
1486
1.28k
        std::shared_lock rlock(_meta_lock);
1487
8.33k
        auto has_alter_inverted_index = [&](RowsetSharedPtr rowset) -> bool {
1488
8.33k
            for (const auto& index_id : alter_index_uids) {
1489
8.33k
                if (rowset->tablet_schema()->has_inverted_index_with_index_id(index_id, "")) {
1490
4.46k
                    return true;
1491
4.46k
                }
1492
8.33k
            }
1493
3.87k
            return false;
1494
8.33k
        };
1495
1496
4.26k
        for (const auto& [version, rs] : _rs_version_map) {
1497
4.26k
            if (!has_alter_inverted_index(rs) && is_drop_op) {
1498
202
                continue;
1499
202
            }
1500
4.06k
            if (has_alter_inverted_index(rs) && !is_drop_op) {
1501
82
                continue;
1502
82
            }
1503
1504
3.98k
            if (rs->is_local()) {
1505
3.98k
                candidate_rowsets.push_back(rs);
1506
3.98k
            }
1507
3.98k
        }
1508
1.28k
    }
1509
1.28k
    std::sort(candidate_rowsets.begin(), candidate_rowsets.end(), Rowset::comparator);
1510
1.28k
    return candidate_rowsets;
1511
1.28k
}
1512
1513
3.95k
std::string Tablet::_get_rowset_info_str(RowsetSharedPtr rowset, bool delete_flag) {
1514
3.95k
    const Version& ver = rowset->version();
1515
3.95k
    std::string disk_size = PrettyPrinter::print(
1516
3.95k
            static_cast<uint64_t>(rowset->rowset_meta()->total_disk_size()), TUnit::BYTES);
1517
3.95k
    return strings::Substitute("[$0-$1] $2 $3 $4 $5 $6", ver.first, ver.second,
1518
3.95k
                               rowset->num_segments(), (delete_flag ? "DELETE" : "DATA"),
1519
3.95k
                               SegmentsOverlapPB_Name(rowset->rowset_meta()->segments_overlap()),
1520
3.95k
                               rowset->rowset_id().to_string(), disk_size);
1521
3.95k
}
1522
1523
18.1M
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
18.1M
    auto version_info = std::atomic_load_explicit(&_visible_version, std::memory_order_relaxed);
1527
18.1M
    if (version_info != nullptr && partition_id() != 0) {
1528
18.1M
        return std::make_tuple(version_info->version.load(std::memory_order_relaxed),
1529
18.1M
                               version_info->update_ts);
1530
18.1M
    } else {
1531
42
        return std::make_tuple(std::numeric_limits<int64_t>::max(),
1532
42
                               std::numeric_limits<int64_t>::max());
1533
42
    }
1534
18.1M
}
1535
1536
// For http compaction action
1537
634
void Tablet::get_compaction_status(std::string* json_result) {
1538
634
    rapidjson::Document root;
1539
634
    root.SetObject();
1540
1541
634
    rapidjson::Document path_arr;
1542
634
    path_arr.SetArray();
1543
1544
634
    std::vector<RowsetSharedPtr> rowsets;
1545
634
    std::vector<RowsetSharedPtr> stale_rowsets;
1546
634
    std::vector<bool> delete_flags;
1547
634
    {
1548
634
        std::shared_lock rdlock(_meta_lock);
1549
634
        rowsets.reserve(_rs_version_map.size());
1550
3.95k
        for (auto& it : _rs_version_map) {
1551
3.95k
            rowsets.push_back(it.second);
1552
3.95k
        }
1553
634
        std::sort(rowsets.begin(), rowsets.end(), Rowset::comparator);
1554
1555
634
        stale_rowsets.reserve(_stale_rs_version_map.size());
1556
3.02k
        for (auto& it : _stale_rs_version_map) {
1557
3.02k
            stale_rowsets.push_back(it.second);
1558
3.02k
        }
1559
634
        std::sort(stale_rowsets.begin(), stale_rowsets.end(), Rowset::comparator);
1560
1561
634
        delete_flags.reserve(rowsets.size());
1562
3.95k
        for (auto& rs : rowsets) {
1563
3.95k
            delete_flags.push_back(rs->rowset_meta()->has_delete_predicate());
1564
3.95k
        }
1565
        // get snapshot version path json_doc
1566
634
        _timestamped_version_tracker.get_stale_version_path_json_doc(path_arr);
1567
634
    }
1568
634
    rapidjson::Value cumulative_policy_type;
1569
634
    std::string policy_type_str = "cumulative compaction policy not initializied";
1570
634
    if (_cumulative_compaction_policy != nullptr) {
1571
397
        policy_type_str = _cumulative_compaction_policy->name();
1572
397
    }
1573
634
    cumulative_policy_type.SetString(policy_type_str.c_str(), policy_type_str.length(),
1574
634
                                     root.GetAllocator());
1575
634
    root.AddMember("cumulative policy type", cumulative_policy_type, root.GetAllocator());
1576
634
    root.AddMember("cumulative point", _cumulative_point.load(), root.GetAllocator());
1577
634
    rapidjson::Value cumu_value;
1578
634
    std::string format_str = ToStringFromUnixMillis(_last_cumu_compaction_failure_millis.load());
1579
634
    cumu_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1580
634
    root.AddMember("last cumulative failure time", cumu_value, root.GetAllocator());
1581
634
    rapidjson::Value base_value;
1582
634
    format_str = ToStringFromUnixMillis(_last_base_compaction_failure_millis.load());
1583
634
    base_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1584
634
    root.AddMember("last base failure time", base_value, root.GetAllocator());
1585
634
    rapidjson::Value full_value;
1586
634
    format_str = ToStringFromUnixMillis(_last_full_compaction_failure_millis.load());
1587
634
    full_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1588
634
    root.AddMember("last full failure time", full_value, root.GetAllocator());
1589
634
    rapidjson::Value cumu_success_value;
1590
634
    format_str = ToStringFromUnixMillis(_last_cumu_compaction_success_millis.load());
1591
634
    cumu_success_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1592
634
    root.AddMember("last cumulative success time", cumu_success_value, root.GetAllocator());
1593
634
    rapidjson::Value base_success_value;
1594
634
    format_str = ToStringFromUnixMillis(_last_base_compaction_success_millis.load());
1595
634
    base_success_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1596
634
    root.AddMember("last base success time", base_success_value, root.GetAllocator());
1597
634
    rapidjson::Value full_success_value;
1598
634
    format_str = ToStringFromUnixMillis(_last_full_compaction_success_millis.load());
1599
634
    full_success_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1600
634
    root.AddMember("last full success time", full_success_value, root.GetAllocator());
1601
634
    rapidjson::Value base_schedule_value;
1602
634
    format_str = ToStringFromUnixMillis(_last_base_compaction_schedule_millis.load());
1603
634
    base_schedule_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1604
634
    root.AddMember("last base schedule time", base_schedule_value, root.GetAllocator());
1605
634
    rapidjson::Value base_compaction_status_value;
1606
634
    base_compaction_status_value.SetString(_last_base_compaction_status.c_str(),
1607
634
                                           _last_base_compaction_status.length(),
1608
634
                                           root.GetAllocator());
1609
634
    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
634
    rapidjson::Document status;
1618
634
    status.SetObject();
1619
634
    TReplicaInfo replica_info;
1620
634
    std::string dummp_token;
1621
634
    if (tablet_meta()->tablet_schema()->enable_single_replica_compaction() &&
1622
634
        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
634
    rapidjson::Document versions_arr;
1645
634
    rapidjson::Document missing_versions_arr;
1646
634
    versions_arr.SetArray();
1647
634
    missing_versions_arr.SetArray();
1648
634
    int64_t last_version = -1;
1649
4.58k
    for (int i = 0; i < rowsets.size(); ++i) {
1650
3.95k
        const Version& ver = rowsets[i]->version();
1651
3.95k
        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
3.95k
        rapidjson::Value value;
1659
3.95k
        std::string version_str = _get_rowset_info_str(rowsets[i], delete_flags[i]);
1660
3.95k
        value.SetString(version_str.c_str(), version_str.length(), versions_arr.GetAllocator());
1661
3.95k
        versions_arr.PushBack(value, versions_arr.GetAllocator());
1662
3.95k
        last_version = ver.second;
1663
3.95k
    }
1664
634
    root.AddMember("rowsets", versions_arr, root.GetAllocator());
1665
634
    root.AddMember("missing_rowsets", missing_versions_arr, root.GetAllocator());
1666
1667
    // print all stale rowsets' version as an array
1668
634
    rapidjson::Document stale_versions_arr;
1669
634
    stale_versions_arr.SetArray();
1670
3.65k
    for (int i = 0; i < stale_rowsets.size(); ++i) {
1671
3.02k
        const Version& ver = stale_rowsets[i]->version();
1672
3.02k
        rapidjson::Value value;
1673
3.02k
        std::string disk_size = PrettyPrinter::print(
1674
3.02k
                static_cast<uint64_t>(stale_rowsets[i]->rowset_meta()->total_disk_size()),
1675
3.02k
                TUnit::BYTES);
1676
3.02k
        std::string version_str = strings::Substitute(
1677
3.02k
                "[$0-$1] $2 $3 $4", ver.first, ver.second, stale_rowsets[i]->num_segments(),
1678
3.02k
                stale_rowsets[i]->rowset_id().to_string(), disk_size);
1679
3.02k
        value.SetString(version_str.c_str(), version_str.length(),
1680
3.02k
                        stale_versions_arr.GetAllocator());
1681
3.02k
        stale_versions_arr.PushBack(value, stale_versions_arr.GetAllocator());
1682
3.02k
    }
1683
634
    root.AddMember("stale_rowsets", stale_versions_arr, root.GetAllocator());
1684
1685
    // add stale version rowsets
1686
634
    root.AddMember("stale version path", path_arr, root.GetAllocator());
1687
1688
    // to json string
1689
634
    rapidjson::StringBuffer strbuf;
1690
634
    rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(strbuf);
1691
634
    root.Accept(writer);
1692
634
    *json_result = std::string(strbuf.GetString());
1693
634
}
1694
1695
772k
bool Tablet::do_tablet_meta_checkpoint() {
1696
772k
    std::lock_guard<std::shared_mutex> store_lock(_meta_store_lock);
1697
772k
    if (_newly_created_rowset_num == 0) {
1698
568k
        return false;
1699
568k
    }
1700
204k
    if (UnixMillis() - _last_checkpoint_time <
1701
204k
                config::tablet_meta_checkpoint_min_interval_secs * 1000 &&
1702
204k
        _newly_created_rowset_num < config::tablet_meta_checkpoint_min_new_rowsets_num) {
1703
1.56k
        return false;
1704
1.56k
    }
1705
    // hold read-lock other than write-lock, because it will not modify meta structure
1706
202k
    std::shared_lock rdlock(_meta_lock);
1707
202k
    if (tablet_state() != TABLET_RUNNING) {
1708
584
        LOG(INFO) << "tablet is under state=" << tablet_state()
1709
584
                  << ", not running, skip do checkpoint"
1710
584
                  << ", tablet=" << tablet_id();
1711
584
        return false;
1712
584
    }
1713
202k
    VLOG_NOTICE << "start to do tablet meta checkpoint, tablet=" << tablet_id();
1714
202k
    save_meta();
1715
    // if save meta successfully, then should remove the rowset meta existing in tablet
1716
    // meta from rowset meta store
1717
476k
    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
476k
        if (rs_meta->is_remove_from_rowset_meta()) {
1720
57.7k
            continue;
1721
57.7k
        }
1722
418k
        if (RowsetMetaManager::check_rowset_meta(_data_dir->get_meta(), tablet_uid(),
1723
418k
                                                 rs_meta->rowset_id())) {
1724
405k
            RETURN_FALSE_IF_ERROR(RowsetMetaManager::remove(_data_dir->get_meta(), tablet_uid(),
1725
405k
                                                            rs_meta->rowset_id()));
1726
405k
            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
405k
        }
1729
418k
        rs_meta->set_remove_from_rowset_meta();
1730
418k
    }
1731
1732
    // check _stale_rs_version_map to remove meta from rowset meta store
1733
202k
    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
7.13k
        if (rs_meta->is_remove_from_rowset_meta()) {
1736
35
            continue;
1737
35
        }
1738
7.09k
        if (RowsetMetaManager::check_rowset_meta(_data_dir->get_meta(), tablet_uid(),
1739
7.09k
                                                 rs_meta->rowset_id())) {
1740
7.03k
            RETURN_FALSE_IF_ERROR(RowsetMetaManager::remove(_data_dir->get_meta(), tablet_uid(),
1741
7.03k
                                                            rs_meta->rowset_id()));
1742
7.03k
            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
7.03k
        }
1745
7.09k
        rs_meta->set_remove_from_rowset_meta();
1746
7.09k
    }
1747
1748
202k
    if (keys_type() == UNIQUE_KEYS && enable_unique_key_merge_on_write()) {
1749
37.3k
        static_cast<void>(TabletMetaManager::remove_old_version_delete_bitmap(
1750
37.3k
                _data_dir, tablet_id(), max_version_unlocked().second));
1751
37.3k
    }
1752
1753
202k
    _newly_created_rowset_num = 0;
1754
202k
    _last_checkpoint_time = UnixMillis();
1755
202k
    return true;
1756
202k
}
1757
1758
204k
bool Tablet::rowset_meta_is_useful(RowsetMetaSharedPtr rowset_meta) {
1759
204k
    std::shared_lock rdlock(_meta_lock);
1760
204k
    bool find_version = false;
1761
14.1M
    for (auto& version_rowset : _rs_version_map) {
1762
14.1M
        if (version_rowset.second->rowset_id() == rowset_meta->rowset_id()) {
1763
193k
            return true;
1764
193k
        }
1765
13.9M
        if (version_rowset.second->contains_version(rowset_meta->version())) {
1766
10.6k
            find_version = true;
1767
10.6k
        }
1768
13.9M
    }
1769
395k
    for (auto& stale_version_rowset : _stale_rs_version_map) {
1770
395k
        if (stale_version_rowset.second->rowset_id() == rowset_meta->rowset_id()) {
1771
7.96k
            return true;
1772
7.96k
        }
1773
387k
        if (stale_version_rowset.second->contains_version(rowset_meta->version())) {
1774
8.94k
            find_version = true;
1775
8.94k
        }
1776
387k
    }
1777
2.72k
    return !find_version;
1778
10.6k
}
1779
1780
476k
bool Tablet::_contains_rowset(const RowsetId rowset_id) {
1781
30.1M
    for (auto& version_rowset : _rs_version_map) {
1782
30.1M
        if (version_rowset.second->rowset_id() == rowset_id) {
1783
0
            return true;
1784
0
        }
1785
30.1M
    }
1786
580k
    for (auto& stale_version_rowset : _stale_rs_version_map) {
1787
580k
        if (stale_version_rowset.second->rowset_id() == rowset_id) {
1788
0
            return true;
1789
0
        }
1790
580k
    }
1791
476k
    return false;
1792
476k
}
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
18.1M
                                      bool enable_path_check) {
1799
18.1M
    std::shared_lock rdlock(_meta_lock);
1800
18.1M
    tablet_info->__set_tablet_id(_tablet_meta->tablet_id());
1801
18.1M
    tablet_info->__set_schema_hash(_tablet_meta->schema_hash());
1802
18.1M
    tablet_info->__set_row_count(_tablet_meta->num_rows());
1803
18.1M
    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
18.1M
    Version cversion;
1808
18.1M
    Version max_version;
1809
18.1M
    bool has_version_cross;
1810
18.1M
    _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
18.1M
    if (enable_consecutive_missing_check) {
1817
18.1M
        if (cversion.second < max_version.second) {
1818
12
            if (_last_missed_version == cversion.second + 1) {
1819
4
                if (MonotonicSeconds() - _last_missed_time_s >= 60) {
1820
                    // version missed for over 60 seconds
1821
1
                    tablet_info->__set_version_miss(true);
1822
1
                    _last_missed_version = -1;
1823
1
                    _last_missed_time_s = 0;
1824
1
                }
1825
8
            } else {
1826
8
                _last_missed_version = cversion.second + 1;
1827
8
                _last_missed_time_s = MonotonicSeconds();
1828
8
            }
1829
12
        }
1830
18.1M
    } else {
1831
10.4k
        tablet_info->__set_version_miss(cversion.second < max_version.second);
1832
10.4k
    }
1833
1834
18.1M
    DBUG_EXECUTE_IF("Tablet.build_tablet_report_info.version_miss", {
1835
18.1M
        auto tablet_id = dp->param<int64>("tablet_id", -1);
1836
18.1M
        if (tablet_id != -1 && tablet_id == _tablet_meta->tablet_id()) {
1837
18.1M
            auto miss = dp->param<bool>("version_miss", true);
1838
18.1M
            tablet_info->__set_version_miss(miss);
1839
18.1M
        }
1840
18.1M
    });
1841
1842
    // find rowset with max version
1843
18.1M
    auto iter = _rs_version_map.find(max_version);
1844
18.1M
    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
6
        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
6
    }
1856
1857
18.1M
    if (tablet_state() == TABLET_RUNNING) {
1858
18.1M
        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
18.1M
        if (enable_path_check) {
1866
18.1M
            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
18.1M
        }
1871
18.1M
    }
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
18.1M
    if (tablet_state() == TABLET_NOTREADY && is_alter_failed()) {
1877
424
        tablet_info->__set_used(false);
1878
424
    }
1879
1880
18.1M
    if (tablet_state() == TABLET_SHUTDOWN) {
1881
16
        tablet_info->__set_used(false);
1882
16
    }
1883
1884
18.1M
    DBUG_EXECUTE_IF("Tablet.build_tablet_report_info.used", {
1885
18.1M
        auto tablet_id = dp->param<int64>("tablet_id", -1);
1886
18.1M
        if (tablet_id != -1 && tablet_id == _tablet_meta->tablet_id()) {
1887
18.1M
            auto used = dp->param<bool>("used", true);
1888
18.1M
            LOG_WARNING("Tablet.build_tablet_report_info.used")
1889
18.1M
                    .tag("tablet id", tablet_id)
1890
18.1M
                    .tag("used", used);
1891
18.1M
            tablet_info->__set_used(used);
1892
18.1M
        } else {
1893
18.1M
            LOG_WARNING("Tablet.build_tablet_report_info.used").tag("tablet id", tablet_id);
1894
18.1M
        }
1895
18.1M
    });
1896
1897
18.1M
    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
18.1M
    int64_t visible_version_count = total_version_count;
1903
18.1M
    if (auto [visible_version, _] = get_visible_version_and_time(); visible_version > 0) {
1904
16.2M
        visible_version_count = _tablet_meta->version_count_cross_with_range({0, visible_version});
1905
16.2M
    }
1906
    // the report version is the largest continuous version, same logic as in FE side
1907
18.1M
    tablet_info->__set_version(cversion.second);
1908
    // Useless but it is a required filed in TTabletInfo
1909
18.1M
    tablet_info->__set_version_hash(0);
1910
18.1M
    tablet_info->__set_partition_id(_tablet_meta->partition_id());
1911
18.1M
    tablet_info->__set_storage_medium(_data_dir->storage_medium());
1912
18.1M
    tablet_info->__set_total_version_count(total_version_count);
1913
18.1M
    tablet_info->__set_visible_version_count(visible_version_count);
1914
18.1M
    tablet_info->__set_path_hash(_data_dir->path_hash());
1915
18.1M
    tablet_info->__set_is_in_memory(_tablet_meta->tablet_schema()->is_in_memory());
1916
18.1M
    tablet_info->__set_replica_id(replica_id());
1917
18.1M
    tablet_info->__set_remote_data_size(_tablet_meta->tablet_remote_size());
1918
18.1M
    if (_tablet_meta->cooldown_meta_id().initialized()) { // has cooldowned data
1919
234
        tablet_info->__set_cooldown_term(_cooldown_conf.term);
1920
234
        tablet_info->__set_cooldown_meta_id(_tablet_meta->cooldown_meta_id().to_thrift());
1921
234
    }
1922
18.1M
    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
31.7k
        tablet_info->__set_cooldown_term(_cooldown_conf.term);
1925
31.7k
    }
1926
18.1M
}
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
1.67k
void Tablet::generate_tablet_meta_copy_unlocked(TabletMetaSharedPtr new_tablet_meta) const {
1940
1.67k
    TabletMetaPB tablet_meta_pb;
1941
1.67k
    _tablet_meta->to_meta_pb(&tablet_meta_pb);
1942
1.67k
    new_tablet_meta->init_from_pb(tablet_meta_pb);
1943
1.67k
}
1944
1945
Status Tablet::prepare_compaction_and_calculate_permits(CompactionType compaction_type,
1946
                                                        const TabletSharedPtr& tablet,
1947
                                                        std::shared_ptr<Compaction>& compaction,
1948
1.27k
                                                        int64_t& permits) {
1949
1.27k
    if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) {
1950
1.04k
        MonotonicStopWatch watch;
1951
1.04k
        watch.start();
1952
1953
1.04k
        compaction = std::make_shared<CumulativeCompaction>(tablet);
1954
1.04k
        DorisMetrics::instance()->cumulative_compaction_request_total->increment(1);
1955
1.04k
        Status res = compaction->prepare_compact();
1956
1.04k
        if (!config::disable_compaction_trace_log &&
1957
1.04k
            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
1.04k
        if (!res.ok()) {
1966
17
            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
17
            if (!(res.msg() == "_last_delete_version.first not equal to -1") ||
1970
17
                config::enable_sleep_between_delete_cumu_compaction) {
1971
1
                tablet->set_last_cumu_compaction_failure_time(UnixMillis());
1972
1
            }
1973
17
            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
17
            LOG_INFO(
1981
17
                    "cumulative compaction meet delete rowset, increase cumu point without other "
1982
17
                    "operation.")
1983
17
                    .tag("tablet id:", tablet->tablet_id())
1984
17
                    .tag("after cumulative compaction, cumu point:",
1985
17
                         tablet->cumulative_layer_point());
1986
17
            return Status::OK();
1987
17
        }
1988
1.04k
    } else if (compaction_type == CompactionType::BASE_COMPACTION) {
1989
114
        MonotonicStopWatch watch;
1990
114
        watch.start();
1991
1992
114
        compaction = std::make_shared<BaseCompaction>(tablet);
1993
114
        DorisMetrics::instance()->base_compaction_request_total->increment(1);
1994
114
        Status res = compaction->prepare_compact();
1995
114
        if (!config::disable_compaction_trace_log &&
1996
114
            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
114
        tablet->set_last_base_compaction_status(res.to_string());
2005
114
        if (!res.ok()) {
2006
102
            tablet->set_last_base_compaction_failure_time(UnixMillis());
2007
102
            permits = 0;
2008
102
            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
102
            return Status::OK();
2016
102
        }
2017
117
    } else {
2018
117
        DCHECK_EQ(compaction_type, CompactionType::FULL_COMPACTION);
2019
2020
117
        compaction = std::make_shared<FullCompaction>(tablet);
2021
117
        Status res = compaction->prepare_compact();
2022
117
        if (!res.ok()) {
2023
107
            tablet->set_last_full_compaction_failure_time(UnixMillis());
2024
107
            permits = 0;
2025
107
            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
107
            return Status::OK();
2032
107
        }
2033
117
    }
2034
2035
1.05k
    permits = 0;
2036
    // Time series policy does not rely on permits, it uses goal size to control memory
2037
1.05k
    if (tablet->tablet_meta()->compaction_policy() != CUMULATIVE_TIME_SERIES_POLICY) {
2038
15.4k
        for (auto&& rowset : compaction->input_rowsets()) {
2039
15.4k
            permits += rowset->rowset_meta()->get_compaction_score();
2040
15.4k
        }
2041
1.05k
    } else {
2042
        // permits = 0 means that prepare_compaction failed
2043
0
        permits = 1;
2044
0
    }
2045
1.05k
    return Status::OK();
2046
1.27k
}
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
1.04k
void Tablet::execute_compaction(Compaction& compaction) {
2088
1.04k
    signal::tablet_id = tablet_id();
2089
2090
1.04k
    MonotonicStopWatch watch;
2091
1.04k
    watch.start();
2092
2093
1.04k
    Status res = [&]() { RETURN_IF_CATCH_EXCEPTION({ return compaction.execute_compact(); }); }();
2094
1.04k
    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
1.04k
    } else {
2099
1.04k
        set_last_failure_time(this, compaction, 0);
2100
1.04k
    }
2101
2102
1.04k
    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
1.04k
}
2120
2121
216k
Status Tablet::create_initial_rowset(const int64_t req_version) {
2122
216k
    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
216k
    Version version(0, req_version);
2127
216k
    RowsetSharedPtr new_rowset;
2128
    // there is no data in init rowset, so overlapping info is unknown.
2129
216k
    RowsetWriterContext context;
2130
216k
    context.version = version;
2131
216k
    context.rowset_state = VISIBLE;
2132
216k
    context.segments_overlap = OVERLAP_UNKNOWN;
2133
216k
    context.tablet_schema = tablet_schema();
2134
216k
    context.newest_write_timestamp = UnixSeconds();
2135
216k
    auto rs_writer = DORIS_TRY(create_rowset_writer(context, false));
2136
216k
    RETURN_IF_ERROR(rs_writer->flush());
2137
216k
    RETURN_IF_ERROR(rs_writer->build(new_rowset));
2138
216k
    RETURN_IF_ERROR(add_rowset(std::move(new_rowset)));
2139
216k
    set_cumulative_layer_point(req_version + 1);
2140
216k
    return Status::OK();
2141
216k
}
2142
2143
Result<std::unique_ptr<RowsetWriter>> Tablet::create_rowset_writer(RowsetWriterContext& context,
2144
474k
                                                                   bool vertical) {
2145
474k
    context.rowset_id = _engine.next_rowset_id();
2146
474k
    _init_context_common_fields(context);
2147
474k
    std::unique_ptr<RowsetWriter> rowset_writer;
2148
474k
    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
474k
    return rowset_writer;
2153
474k
}
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
51.2k
        std::shared_ptr<PartialUpdateInfo> partial_update_info) {
2160
51.2k
    RowsetWriterContext context;
2161
51.2k
    context.rowset_state = PREPARED;
2162
51.2k
    context.segments_overlap = OVERLAPPING;
2163
51.2k
    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
51.2k
    context.tablet_schema = rowset_ptr->tablet_schema()->copy_without_variant_extracted_columns();
2169
51.2k
    context.newest_write_timestamp = UnixSeconds();
2170
51.2k
    context.tablet_id = table_id();
2171
51.2k
    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
51.2k
    auto tablet = _engine.tablet_manager()->get_tablet(tablet_id());
2175
51.2k
    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
51.2k
    context.tablet = tablet;
2180
51.2k
    context.write_type = DataWriteType::TYPE_DIRECT;
2181
51.2k
    context.partial_update_info = partial_update_info;
2182
51.2k
    context.is_transient_rowset_writer = true;
2183
51.2k
    RETURN_IF_ERROR(
2184
51.2k
            create_transient_rowset_writer(context, rowset_ptr->rowset_id(), rowset_writer));
2185
51.2k
    (*rowset_writer)->set_segment_start_id(rowset_ptr->num_segments());
2186
51.2k
    return Status::OK();
2187
51.2k
}
2188
2189
Status Tablet::create_transient_rowset_writer(RowsetWriterContext& context,
2190
                                              const RowsetId& rowset_id,
2191
51.2k
                                              std::unique_ptr<RowsetWriter>* rowset_writer) {
2192
51.2k
    context.rowset_id = rowset_id;
2193
51.2k
    _init_context_common_fields(context);
2194
51.2k
    return RowsetFactory::create_rowset_writer(context, false, rowset_writer);
2195
51.2k
}
2196
2197
525k
void Tablet::_init_context_common_fields(RowsetWriterContext& context) {
2198
525k
    context.tablet_uid = tablet_uid();
2199
2200
525k
    context.tablet_id = tablet_id();
2201
525k
    context.partition_id = partition_id();
2202
525k
    context.tablet_schema_hash = schema_hash();
2203
525k
    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
525k
    if (context.rowset_type == ALPHA_ROWSET) {
2207
0
        context.rowset_type = _engine.default_rowset_type();
2208
0
    }
2209
525k
    if (context.fs != nullptr && context.fs->type() != io::FileSystemType::LOCAL) {
2210
2
        context.rowset_dir = remote_tablet_path(tablet_id());
2211
525k
    } else {
2212
525k
        context.rowset_dir = tablet_path();
2213
525k
    }
2214
525k
    context.data_dir = data_dir();
2215
525k
    context.enable_unique_key_merge_on_write = enable_unique_key_merge_on_write();
2216
525k
}
2217
2218
8.80k
Status Tablet::create_rowset(const RowsetMetaSharedPtr& rowset_meta, RowsetSharedPtr* rowset) {
2219
8.80k
    return RowsetFactory::create_rowset(
2220
8.80k
            _tablet_meta->tablet_schema(),
2221
8.80k
            rowset_meta->is_local() ? _tablet_path : remote_tablet_path(tablet_id()), rowset_meta,
2222
8.80k
            rowset);
2223
8.80k
}
2224
2225
46
Status Tablet::cooldown(RowsetSharedPtr rowset) {
2226
46
    std::unique_lock schema_change_lock(_schema_change_lock, std::try_to_lock);
2227
46
    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
46
    std::unique_lock base_compaction_lock(_base_compaction_lock, std::try_to_lock);
2232
46
    if (!base_compaction_lock.owns_lock()) {
2233
0
        return Status::Error<TRY_LOCK_FAILED>("try base_compaction_lock failed");
2234
0
    }
2235
46
    std::unique_lock cumu_compaction_lock(_cumulative_compaction_lock, std::try_to_lock);
2236
46
    if (!cumu_compaction_lock.owns_lock()) {
2237
0
        return Status::Error<TRY_LOCK_FAILED>("try cumu_compaction_lock failed");
2238
0
    }
2239
46
    std::shared_lock cooldown_conf_rlock(_cooldown_conf_lock);
2240
46
    if (_cooldown_conf.cooldown_replica_id <= 0) { // wait for FE to push cooldown conf
2241
15
        return Status::InternalError("invalid cooldown_replica_id");
2242
15
    }
2243
2244
31
    if (_cooldown_conf.cooldown_replica_id == replica_id()) {
2245
        // this replica is cooldown replica
2246
31
        RETURN_IF_ERROR(_cooldown_data(std::move(rowset)));
2247
31
    } 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
31
    return Status::OK();
2256
31
}
2257
2258
// hold SHARED `cooldown_conf_lock`
2259
31
Status Tablet::_cooldown_data(RowsetSharedPtr rowset) {
2260
31
    DCHECK(_cooldown_conf.cooldown_replica_id == replica_id());
2261
2262
31
    std::shared_ptr<io::RemoteFileSystem> dest_fs;
2263
31
    RETURN_IF_ERROR(get_remote_file_system(storage_policy_id(), &dest_fs));
2264
31
    RowsetSharedPtr old_rowset = nullptr;
2265
2266
31
    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
31
    if (!old_rowset) {
2277
31
        old_rowset = pick_cooldown_rowset();
2278
31
    }
2279
2280
31
    if (!old_rowset) {
2281
0
        LOG(INFO) << "cannot pick cooldown rowset in tablet " << tablet_id();
2282
0
        return Status::OK();
2283
0
    }
2284
2285
31
    RowsetId new_rowset_id = _engine.next_rowset_id();
2286
31
    auto pending_rs_guard = _engine.pending_remote_rowsets().add(new_rowset_id);
2287
31
    Status st;
2288
31
    Defer defer {[&] {
2289
31
        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
31
    }};
2294
31
    auto start = std::chrono::steady_clock::now();
2295
31
    if (st = old_rowset->upload_to(dest_fs.get(), new_rowset_id); !st.ok()) {
2296
0
        return st;
2297
0
    }
2298
2299
31
    auto duration = std::chrono::duration<float>(std::chrono::steady_clock::now() - start);
2300
31
    LOG(INFO) << "Upload rowset " << old_rowset->version() << " " << new_rowset_id.to_string()
2301
31
              << " to " << dest_fs->root_path().native() << ", tablet_id=" << tablet_id()
2302
31
              << ", duration=" << duration.count() << ", capacity=" << old_rowset->data_disk_size()
2303
31
              << ", tp=" << old_rowset->data_disk_size() / duration.count()
2304
31
              << ", old rowset_id=" << old_rowset->rowset_id().to_string();
2305
2306
    // gen a new rowset
2307
31
    auto new_rowset_meta = std::make_shared<RowsetMeta>();
2308
31
    new_rowset_meta->init(old_rowset->rowset_meta().get());
2309
31
    new_rowset_meta->set_rowset_id(new_rowset_id);
2310
31
    new_rowset_meta->set_fs(dest_fs);
2311
31
    new_rowset_meta->set_creation_time(time(nullptr));
2312
31
    UniqueId cooldown_meta_id = UniqueId::gen_uid();
2313
31
    RowsetSharedPtr new_rowset;
2314
31
    RETURN_IF_ERROR(RowsetFactory::create_rowset(_tablet_meta->tablet_schema(),
2315
31
                                                 remote_tablet_path(tablet_id()), new_rowset_meta,
2316
31
                                                 &new_rowset));
2317
2318
31
    {
2319
31
        std::unique_lock meta_wlock(_meta_lock);
2320
31
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
2321
31
        if (tablet_state() == TABLET_RUNNING) {
2322
31
            RETURN_IF_ERROR(delete_rowsets({std::move(old_rowset)}, false));
2323
31
            add_rowsets({std::move(new_rowset)});
2324
            // TODO(plat1ko): process primary key
2325
31
            _tablet_meta->set_cooldown_meta_id(cooldown_meta_id);
2326
31
        }
2327
31
    }
2328
31
    {
2329
31
        std::shared_lock meta_rlock(_meta_lock);
2330
31
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
2331
31
        save_meta();
2332
31
    }
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
31
    if (auto t = _engine.tablet_manager()->get_tablet(tablet_id());
2337
31
        t != nullptr) { // `t` can be nullptr if it has been dropped
2338
31
        async_write_cooldown_meta(std::move(t));
2339
31
    }
2340
31
    return Status::OK();
2341
31
}
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
33
Status check_version_continuity(const std::vector<RowsetMetaSharedPtr>& rs_metas) {
2364
33
    if (rs_metas.size() < 2) {
2365
6
        return Status::OK();
2366
6
    }
2367
27
    auto prev = rs_metas.begin();
2368
236
    for (auto it = rs_metas.begin() + 1; it != rs_metas.end(); ++it) {
2369
209
        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
209
        prev = it;
2375
209
    }
2376
27
    return Status::OK();
2377
27
}
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
33
void Tablet::async_write_cooldown_meta(TabletSharedPtr tablet) {
2382
33
    ExecEnv::GetInstance()->write_cooldown_meta_executors()->submit(std::move(tablet));
2383
33
}
2384
2385
164
bool Tablet::update_cooldown_conf(int64_t cooldown_term, int64_t cooldown_replica_id) {
2386
164
    std::unique_lock wlock(_cooldown_conf_lock, std::try_to_lock);
2387
164
    if (!wlock.owns_lock()) {
2388
0
        LOG(INFO) << "try cooldown_conf_lock failed, tablet_id=" << tablet_id();
2389
0
        return false;
2390
0
    }
2391
164
    if (cooldown_term <= _cooldown_conf.term) {
2392
0
        return false;
2393
0
    }
2394
164
    LOG(INFO) << "update cooldown conf. tablet_id=" << tablet_id()
2395
164
              << " cooldown_replica_id: " << _cooldown_conf.cooldown_replica_id << " -> "
2396
164
              << cooldown_replica_id << ", cooldown_term: " << _cooldown_conf.term << " -> "
2397
164
              << cooldown_term;
2398
164
    _cooldown_conf.cooldown_replica_id = cooldown_replica_id;
2399
164
    _cooldown_conf.term = cooldown_term;
2400
164
    return true;
2401
164
}
2402
2403
33
Status Tablet::write_cooldown_meta() {
2404
33
    std::shared_lock rlock(_cooldown_conf_lock);
2405
33
    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
33
    std::shared_ptr<io::RemoteFileSystem> fs;
2412
33
    RETURN_IF_ERROR(get_remote_file_system(storage_policy_id(), &fs));
2413
2414
33
    std::vector<RowsetMetaSharedPtr> cooldowned_rs_metas;
2415
33
    UniqueId cooldown_meta_id;
2416
33
    {
2417
33
        std::shared_lock meta_rlock(_meta_lock);
2418
449
        for (auto& rs_meta : _tablet_meta->all_rs_metas()) {
2419
449
            if (!rs_meta->is_local()) {
2420
242
                cooldowned_rs_metas.push_back(rs_meta);
2421
242
            }
2422
449
        }
2423
33
        cooldown_meta_id = _tablet_meta->cooldown_meta_id();
2424
33
    }
2425
33
    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
33
    std::sort(cooldowned_rs_metas.begin(), cooldowned_rs_metas.end(), RowsetMeta::comparator);
2430
33
    DCHECK(cooldowned_rs_metas.front()->start_version() == 0);
2431
    // If version not continuous, it must be a bug
2432
33
    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
33
    TabletMetaPB tablet_meta_pb;
2439
33
    auto rs_metas = tablet_meta_pb.mutable_rs_metas();
2440
33
    rs_metas->Reserve(cooldowned_rs_metas.size());
2441
242
    for (auto& rs_meta : cooldowned_rs_metas) {
2442
242
        rs_metas->Add(rs_meta->get_rowset_pb());
2443
242
    }
2444
33
    tablet_meta_pb.mutable_cooldown_meta_id()->set_hi(cooldown_meta_id.hi);
2445
33
    tablet_meta_pb.mutable_cooldown_meta_id()->set_lo(cooldown_meta_id.lo);
2446
2447
33
    std::string remote_meta_path = remote_tablet_meta_path(
2448
33
            tablet_id(), _cooldown_conf.cooldown_replica_id, _cooldown_conf.term);
2449
33
    io::FileWriterPtr tablet_meta_writer;
2450
    // FIXME(plat1ko): What if object store permanently unavailable?
2451
33
    RETURN_IF_ERROR(fs->create_file(remote_meta_path, &tablet_meta_writer));
2452
33
    auto val = tablet_meta_pb.SerializeAsString();
2453
33
    RETURN_IF_ERROR(tablet_meta_writer->append({val.data(), val.size()}));
2454
33
    return tablet_meta_writer->close();
2455
33
}
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
23.2M
bool Tablet::_has_data_to_cooldown() {
2551
23.2M
    int64_t min_local_version = std::numeric_limits<int64_t>::max();
2552
23.2M
    RowsetSharedPtr rowset;
2553
23.2M
    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
23.2M
    bool has_cooldowned = false;
2557
52.2M
    for (const auto& [_, rs] : _rs_version_map) {
2558
52.2M
        if (!rs->is_local()) {
2559
291
            has_cooldowned = true;
2560
291
            break;
2561
291
        }
2562
52.2M
    }
2563
52.2M
    for (auto& [v, rs] : _rs_version_map) {
2564
52.2M
        auto predicate = rs->is_local() && v.first < min_local_version;
2565
52.2M
        if (!has_cooldowned) {
2566
52.2M
            predicate = predicate && (rs->data_disk_size() > 0);
2567
52.2M
        }
2568
52.2M
        if (predicate) {
2569
            // this is a local rowset and has data
2570
4.73M
            min_local_version = v.first;
2571
4.73M
            rowset = rs;
2572
4.73M
        }
2573
52.2M
    }
2574
2575
23.2M
    int64_t newest_cooldown_time = 0;
2576
23.2M
    if (rowset != nullptr) {
2577
3.74M
        newest_cooldown_time = _get_newest_cooldown_time(rowset);
2578
3.74M
    }
2579
2580
23.2M
    return (newest_cooldown_time != 0) && (newest_cooldown_time < UnixSeconds());
2581
23.2M
}
2582
2583
23.2M
RowsetSharedPtr Tablet::pick_cooldown_rowset() {
2584
23.2M
    RowsetSharedPtr rowset;
2585
2586
23.2M
    if (!_has_data_to_cooldown()) {
2587
23.2M
        return nullptr;
2588
23.2M
    }
2589
2590
    // TODO(plat1ko): should we maintain `cooldowned_version` in `Tablet`?
2591
73
    int64_t cooldowned_version = -1;
2592
    // We pick the rowset with smallest start version in local.
2593
73
    int64_t min_local_version = std::numeric_limits<int64_t>::max();
2594
73
    {
2595
73
        std::shared_lock meta_rlock(_meta_lock);
2596
1.01k
        for (auto& [v, rs] : _rs_version_map) {
2597
1.01k
            if (!rs->is_local()) {
2598
414
                cooldowned_version = std::max(cooldowned_version, v.second);
2599
598
            } else if (v.first < min_local_version) { // this is a local rowset
2600
299
                min_local_version = v.first;
2601
299
                rowset = rs;
2602
299
            }
2603
1.01k
        }
2604
73
    }
2605
73
    if (!rowset) {
2606
0
        return nullptr;
2607
0
    }
2608
73
    if (tablet_footprint() == 0) {
2609
0
        VLOG_DEBUG << "skip cooldown due to empty tablet_id = " << tablet_id();
2610
0
        return nullptr;
2611
0
    }
2612
73
    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
73
    return rowset;
2621
73
}
2622
2623
3.74M
int64_t Tablet::_get_newest_cooldown_time(const RowsetSharedPtr& rowset) {
2624
3.74M
    int64_t id = storage_policy_id();
2625
3.74M
    if (id <= 0) {
2626
3.74M
        VLOG_DEBUG << "tablet does not need cooldown, tablet id: " << tablet_id();
2627
3.74M
        return 0;
2628
3.74M
    }
2629
144
    auto storage_policy = get_storage_policy(id);
2630
144
    if (!storage_policy) {
2631
28
        LOG(WARNING) << "Cannot get storage policy: " << id;
2632
28
        return 0;
2633
28
    }
2634
116
    auto cooldown_ttl_sec = storage_policy->cooldown_ttl;
2635
116
    auto cooldown_datetime = storage_policy->cooldown_datetime;
2636
116
    int64_t newest_cooldown_time = std::numeric_limits<int64_t>::max();
2637
2638
116
    if (cooldown_ttl_sec >= 0) {
2639
113
        newest_cooldown_time = rowset->newest_write_timestamp() + cooldown_ttl_sec;
2640
113
    }
2641
116
    if (cooldown_datetime > 0) {
2642
10
        newest_cooldown_time = std::min(newest_cooldown_time, cooldown_datetime);
2643
10
    }
2644
2645
116
    return newest_cooldown_time;
2646
144
}
2647
2648
23.2M
RowsetSharedPtr Tablet::need_cooldown(int64_t* cooldown_timestamp, size_t* file_size) {
2649
23.2M
    RowsetSharedPtr rowset = pick_cooldown_rowset();
2650
23.2M
    if (!rowset) {
2651
23.2M
        VLOG_DEBUG << "pick cooldown rowset, get null, tablet id: " << tablet_id();
2652
23.2M
        return nullptr;
2653
23.2M
    }
2654
2655
42
    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
42
    if (newest_cooldown_time != 0 && newest_cooldown_time < UnixSeconds()) {
2660
42
        *cooldown_timestamp = newest_cooldown_time;
2661
42
        *file_size = rowset->data_disk_size();
2662
42
        VLOG_DEBUG << "tablet need cooldown, tablet id: " << tablet_id()
2663
0
                   << " file_size: " << *file_size;
2664
42
        return rowset;
2665
42
    }
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
42
}
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
86.0k
Status Tablet::remove_all_remote_rowsets() {
2688
86.0k
    DCHECK(tablet_state() == TABLET_SHUTDOWN);
2689
86.0k
    std::set<std::string> resource_ids;
2690
145k
    for (auto& rs_meta : _tablet_meta->all_rs_metas()) {
2691
145k
        if (!rs_meta->is_local()) {
2692
1
            resource_ids.insert(rs_meta->resource_id());
2693
1
        }
2694
145k
    }
2695
86.0k
    if (resource_ids.empty()) {
2696
86.0k
        return Status::OK();
2697
86.0k
    }
2698
18.4E
    auto tablet_gc_key = REMOTE_TABLET_GC_PREFIX + std::to_string(tablet_id());
2699
18.4E
    RemoteTabletGcPB gc_pb;
2700
18.4E
    for (auto& resource_id : resource_ids) {
2701
1
        gc_pb.add_resource_ids(resource_id);
2702
1
    }
2703
18.4E
    return _data_dir->get_meta()->put(META_COLUMN_FAMILY_INDEX, tablet_gc_key,
2704
18.4E
                                      gc_pb.SerializeAsString());
2705
86.0k
}
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
1.69k
        std::unique_ptr<segment_v2::ColumnIterator>* column_iterator, OlapReaderStatistics* stats) {
2721
1.69k
    RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(rowset, segment_cache_handle, true));
2722
    // find segment
2723
1.69k
    auto it = std::find_if(
2724
1.69k
            segment_cache_handle->get_segments().begin(),
2725
1.69k
            segment_cache_handle->get_segments().end(),
2726
1.71k
            [&segid](const segment_v2::SegmentSharedPtr& seg) { return seg->id() == segid; });
2727
1.69k
    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
1.69k
    segment_v2::SegmentSharedPtr segment = *it;
2732
1.69k
    StorageReadOptions opts;
2733
1.69k
    opts.stats = stats;
2734
1.69k
    RETURN_IF_ERROR(segment->new_column_iterator(target_column, column_iterator, &opts));
2735
1.69k
    segment_v2::ColumnIteratorOptions opt {
2736
1.69k
            .use_page_cache = !config::disable_storage_page_cache,
2737
1.69k
            .file_reader = segment->file_reader().get(),
2738
1.69k
            .stats = stats,
2739
1.69k
            .io_ctx = io::IOContext {.reader_type = ReaderType::READER_QUERY},
2740
1.69k
    };
2741
1.69k
    RETURN_IF_ERROR((*column_iterator)->init(opt));
2742
1.69k
    return Status::OK();
2743
1.69k
}
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
160
                                              vectorized::Block& block) {
2751
160
    MonotonicStopWatch watch;
2752
160
    watch.start();
2753
160
    Defer _defer([&]() {
2754
160
        LOG_EVERY_N(INFO, 500) << "fetch_value_by_rowids, cost(us):" << watch.elapsed_time() / 1000
2755
1
                               << ", row_batch_size:" << rowids.size();
2756
160
    });
2757
2758
160
    BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(input_rowset);
2759
160
    CHECK(rowset);
2760
160
    CHECK(tablet_schema.store_row_column());
2761
160
    SegmentCacheHandle segment_cache_handle;
2762
160
    std::unique_ptr<segment_v2::ColumnIterator> column_iterator;
2763
160
    OlapReaderStatistics stats;
2764
160
    RETURN_IF_ERROR(_get_segment_column_iterator(rowset, segid,
2765
160
                                                 tablet_schema.column(BeConsts::ROW_STORE_COL),
2766
160
                                                 &segment_cache_handle, &column_iterator, &stats));
2767
    // get and parse tuple row
2768
160
    vectorized::MutableColumnPtr column_ptr = vectorized::ColumnString::create();
2769
160
    RETURN_IF_ERROR(column_iterator->read_by_rowids(rowids.data(), rowids.size(), column_ptr));
2770
160
    assert(column_ptr->size() == rowids.size());
2771
0
    auto string_column = static_cast<vectorized::ColumnString*>(column_ptr.get());
2772
160
    vectorized::DataTypeSerDeSPtrs serdes;
2773
160
    serdes.resize(cids.size());
2774
160
    std::unordered_map<uint32_t, uint32_t> col_uid_to_idx;
2775
160
    std::vector<std::string> default_values;
2776
160
    default_values.resize(cids.size());
2777
1.15k
    for (int i = 0; i < cids.size(); ++i) {
2778
993
        const TabletColumn& column = tablet_schema.column(cids[i]);
2779
993
        vectorized::DataTypePtr type =
2780
993
                vectorized::DataTypeFactory::instance().create_data_type(column);
2781
993
        col_uid_to_idx[column.unique_id()] = i;
2782
993
        default_values[i] = column.default_value();
2783
993
        serdes[i] = type->get_serde();
2784
993
    }
2785
160
    vectorized::JsonbSerializeUtil::jsonb_to_block(serdes, *string_column, col_uid_to_idx, block,
2786
160
                                                   default_values);
2787
160
    return Status::OK();
2788
160
}
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
1.47k
                                     vectorized::MutableColumnPtr& dst) {
2794
1.47k
    MonotonicStopWatch watch;
2795
1.47k
    watch.start();
2796
1.47k
    Defer _defer([&]() {
2797
1.47k
        LOG_EVERY_N(INFO, 500) << "fetch_value_by_rowids, cost(us):" << watch.elapsed_time() / 1000
2798
3
                               << ", row_batch_size:" << rowids.size();
2799
1.47k
    });
2800
2801
    // read row data
2802
1.47k
    BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(input_rowset);
2803
1.47k
    CHECK(rowset);
2804
1.47k
    SegmentCacheHandle segment_cache_handle;
2805
1.47k
    std::unique_ptr<segment_v2::ColumnIterator> column_iterator;
2806
1.47k
    OlapReaderStatistics stats;
2807
1.47k
    RETURN_IF_ERROR(_get_segment_column_iterator(rowset, segid, tablet_column,
2808
1.47k
                                                 &segment_cache_handle, &column_iterator, &stats));
2809
1.47k
    RETURN_IF_ERROR(column_iterator->read_by_rowids(rowids.data(), rowids.size(), dst));
2810
1.47k
    return Status::OK();
2811
1.47k
}
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
63
                               bool write_to_cache) {
2817
63
    MonotonicStopWatch watch;
2818
63
    size_t row_size = 1;
2819
63
    watch.start();
2820
63
    Defer _defer([&]() {
2821
63
        LOG_EVERY_N(INFO, 500) << "get a single_row, cost(us):" << watch.elapsed_time() / 1000
2822
1
                               << ", row_size:" << row_size;
2823
63
    });
2824
2825
63
    BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(input_rowset);
2826
63
    CHECK(rowset);
2827
63
    const TabletSchemaSPtr tablet_schema = rowset->tablet_schema();
2828
63
    CHECK(tablet_schema->store_row_column());
2829
63
    SegmentCacheHandle segment_cache_handle;
2830
63
    std::unique_ptr<segment_v2::ColumnIterator> column_iterator;
2831
63
    RETURN_IF_ERROR(_get_segment_column_iterator(rowset, row_location.segment_id,
2832
63
                                                 tablet_schema->column(BeConsts::ROW_STORE_COL),
2833
63
                                                 &segment_cache_handle, &column_iterator, &stats));
2834
    // get and parse tuple row
2835
63
    vectorized::MutableColumnPtr column_ptr = vectorized::ColumnString::create();
2836
63
    std::vector<segment_v2::rowid_t> rowids {static_cast<segment_v2::rowid_t>(row_location.row_id)};
2837
63
    RETURN_IF_ERROR(column_iterator->read_by_rowids(rowids.data(), 1, column_ptr));
2838
63
    assert(column_ptr->size() == 1);
2839
0
    auto string_column = static_cast<vectorized::ColumnString*>(column_ptr.get());
2840
63
    StringRef value = string_column->get_data_at(0);
2841
63
    values = value.to_string();
2842
63
    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
63
    return Status::OK();
2847
63
}
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
17.0M
                              RowsetSharedPtr* rowset, bool with_rowid, bool is_partial_update) {
2855
17.0M
    SCOPED_BVAR_LATENCY(g_tablet_lookup_rowkey_latency);
2856
17.0M
    size_t seq_col_length = 0;
2857
    // use the latest tablet schema to decide if the tablet has sequence column currently
2858
17.0M
    const TabletSchema* schema =
2859
17.0M
            (latest_schema == nullptr ? _tablet_meta->tablet_schema().get() : latest_schema);
2860
17.0M
    if (schema->has_sequence_col() && with_seq_col) {
2861
1.88M
        seq_col_length = schema->column(schema->sequence_col_idx()).length() + 1;
2862
1.88M
    }
2863
17.0M
    size_t rowid_length = 0;
2864
17.0M
    if (with_rowid && !schema->cluster_key_idxes().empty()) {
2865
0
        rowid_length = PrimaryKeyIndexReader::ROW_ID_LENGTH;
2866
0
    }
2867
17.0M
    Slice key_without_seq =
2868
17.0M
            Slice(encoded_key.get_data(), encoded_key.get_size() - seq_col_length - rowid_length);
2869
17.0M
    RowLocation loc;
2870
2871
17.0M
    bool need_to_check_delete_bitmap = is_partial_update || with_seq_col;
2872
2873
245M
    for (size_t i = 0; i < specified_rowsets.size(); i++) {
2874
230M
        auto& rs = specified_rowsets[i];
2875
230M
        auto& segments_key_bounds = rs->rowset_meta()->get_segments_key_bounds();
2876
230M
        int num_segments = rs->num_segments();
2877
230M
        DCHECK_EQ(segments_key_bounds.size(), num_segments);
2878
230M
        std::vector<uint32_t> picked_segments;
2879
467M
        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
236M
            if (schema->cluster_key_idxes().empty()) {
2883
228M
                if (key_without_seq.compare(segments_key_bounds[i].max_key()) > 0 ||
2884
228M
                    key_without_seq.compare(segments_key_bounds[i].min_key()) < 0) {
2885
206M
                    continue;
2886
206M
                }
2887
228M
            }
2888
30.3M
            picked_segments.emplace_back(i);
2889
30.3M
        }
2890
230M
        if (picked_segments.empty()) {
2891
207M
            continue;
2892
207M
        }
2893
2894
23.8M
        if (UNLIKELY(segment_caches[i] == nullptr)) {
2895
15.1k
            segment_caches[i] = std::make_unique<SegmentCacheHandle>();
2896
15.1k
            RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(
2897
15.1k
                    std::static_pointer_cast<BetaRowset>(rs), segment_caches[i].get(), true));
2898
15.1k
        }
2899
23.8M
        auto& segments = segment_caches[i]->get_segments();
2900
23.8M
        DCHECK_EQ(segments.size(), num_segments);
2901
2902
23.8M
        for (auto id : picked_segments) {
2903
13.4M
            Status s = segments[id]->lookup_row_key(encoded_key, schema, with_seq_col, with_rowid,
2904
13.4M
                                                    &loc);
2905
13.4M
            if (s.is<KEY_NOT_FOUND>()) {
2906
11.2M
                continue;
2907
11.2M
            }
2908
2.29M
            if (!s.ok() && !s.is<KEY_ALREADY_EXISTS>()) {
2909
0
                return s;
2910
0
            }
2911
2.29M
            if (s.ok() && need_to_check_delete_bitmap) {
2912
                // check if the key is already mark deleted
2913
2.27M
                if (_tablet_meta->delete_bitmap().contains_agg_without_cache(
2914
2.27M
                            {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
78
                    if (with_seq_col) {
2918
66
                        continue;
2919
66
                    }
2920
                    // The key is deleted, we need to break the loop and return
2921
                    // KEY_NOT_FOUND.
2922
12
                    break;
2923
78
                }
2924
2.27M
            }
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.29M
            *row_location = loc;
2929
2.29M
            if (rowset) {
2930
                // return it's rowset
2931
2.27M
                *rowset = rs;
2932
2.27M
            }
2933
            // find it and return
2934
2.29M
            return s;
2935
2.29M
        }
2936
23.8M
    }
2937
14.7M
    g_tablet_pk_not_found << 1;
2938
14.7M
    return Status::Error<ErrorCode::KEY_NOT_FOUND>("can't find key in all rowsets");
2939
17.0M
}
2940
2941
// load segment may do io so it should out lock
2942
Status Tablet::_load_rowset_segments(const RowsetSharedPtr& rowset,
2943
51.2k
                                     std::vector<segment_v2::SegmentSharedPtr>* segments) {
2944
51.2k
    auto beta_rowset = reinterpret_cast<BetaRowset*>(rowset.get());
2945
51.2k
    RETURN_IF_ERROR(beta_rowset->load_segments(segments));
2946
51.2k
    return Status::OK();
2947
51.2k
}
2948
2949
13
Status Tablet::sort_block(vectorized::Block& in_block, vectorized::Block& output_block) {
2950
13
    vectorized::MutableBlock mutable_input_block =
2951
13
            vectorized::MutableBlock::build_mutable_block(&in_block);
2952
13
    vectorized::MutableBlock mutable_output_block =
2953
13
            vectorized::MutableBlock::build_mutable_block(&output_block);
2954
2955
13
    std::shared_ptr<RowInBlockComparator> vec_row_comparator =
2956
13
            std::make_shared<RowInBlockComparator>(_tablet_meta->tablet_schema());
2957
13
    vec_row_comparator->set_block(&mutable_input_block);
2958
2959
13
    std::vector<std::unique_ptr<RowInBlock>> row_in_blocks;
2960
13
    DCHECK(in_block.rows() <= std::numeric_limits<int>::max());
2961
13
    row_in_blocks.reserve(in_block.rows());
2962
76
    for (size_t i = 0; i < in_block.rows(); ++i) {
2963
63
        row_in_blocks.emplace_back(std::make_unique<RowInBlock>(i));
2964
63
    }
2965
13
    std::sort(row_in_blocks.begin(), row_in_blocks.end(),
2966
13
              [&](const std::unique_ptr<RowInBlock>& l,
2967
100
                  const std::unique_ptr<RowInBlock>& r) -> bool {
2968
100
                  auto value = (*vec_row_comparator)(l.get(), r.get());
2969
100
                  DCHECK(value != 0) << "value equel when sort block, l_pos: " << l->_row_pos
2970
0
                                     << " r_pos: " << r->_row_pos;
2971
100
                  return value < 0;
2972
100
              });
2973
13
    std::vector<uint32_t> row_pos_vec;
2974
13
    row_pos_vec.reserve(in_block.rows());
2975
76
    for (int i = 0; i < row_in_blocks.size(); i++) {
2976
63
        row_pos_vec.emplace_back(row_in_blocks[i]->_row_pos);
2977
63
    }
2978
13
    return mutable_output_block.add_rows(&in_block, row_pos_vec.data(),
2979
13
                                         row_pos_vec.data() + in_block.rows());
2980
13
}
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
21.0k
                                          RowsetWriter* rowset_writer) {
2987
21.0k
    OlapStopWatch watch;
2988
21.0k
    auto rowset_id = rowset->rowset_id();
2989
21.0k
    Version dummy_version(end_version + 1, end_version + 1);
2990
21.0k
    auto rowset_schema = rowset->tablet_schema();
2991
21.0k
    bool is_partial_update = rowset_writer && rowset_writer->is_partial_update();
2992
21.0k
    bool have_input_seq_column = false;
2993
21.0k
    if (is_partial_update && rowset_schema->has_sequence_col()) {
2994
4
        std::vector<uint32_t> including_cids =
2995
4
                rowset_writer->get_partial_update_info()->update_cids;
2996
4
        have_input_seq_column =
2997
4
                rowset_schema->has_sequence_col() &&
2998
4
                (std::find(including_cids.cbegin(), including_cids.cend(),
2999
4
                           rowset_schema->sequence_col_idx()) != including_cids.cend());
3000
4
    }
3001
21.0k
    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
850
        rowset_schema = rowset_schema->copy_without_variant_extracted_columns();
3007
850
    }
3008
    // use for partial update
3009
21.0k
    PartialUpdateReadPlan read_plan_ori;
3010
21.0k
    PartialUpdateReadPlan read_plan_update;
3011
21.0k
    int64_t conflict_rows = 0;
3012
21.0k
    int64_t new_generated_rows = 0;
3013
3014
21.0k
    std::map<RowsetId, RowsetSharedPtr> rsid_to_rowset;
3015
21.0k
    rsid_to_rowset[rowset_id] = rowset;
3016
21.0k
    vectorized::Block block = rowset_schema->create_block();
3017
21.0k
    vectorized::Block ordered_block = block.clone_empty();
3018
21.0k
    uint32_t pos = 0;
3019
3020
21.0k
    RETURN_IF_ERROR(seg->load_pk_index_and_bf()); // We need index blocks to iterate
3021
21.0k
    auto pk_idx = seg->get_primary_key_index();
3022
21.0k
    int total = pk_idx->num_rows();
3023
21.0k
    uint32_t row_id = 0;
3024
21.0k
    int32_t remaining = total;
3025
21.0k
    bool exact_match = false;
3026
21.0k
    std::string last_key;
3027
21.0k
    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
21.0k
    std::vector<std::unique_ptr<SegmentCacheHandle>> segment_caches(specified_rowsets.size());
3032
57.6k
    while (remaining > 0) {
3033
36.6k
        std::unique_ptr<segment_v2::IndexedColumnIterator> iter;
3034
36.6k
        RETURN_IF_ERROR(pk_idx->new_iterator(&iter));
3035
3036
36.6k
        size_t num_to_read = std::min(batch_size, remaining);
3037
36.6k
        auto index_type = vectorized::DataTypeFactory::instance().create_data_type(
3038
36.6k
                pk_idx->type_info()->type(), 1, 0);
3039
36.6k
        auto index_column = index_type->create_column();
3040
36.6k
        Slice last_key_slice(last_key);
3041
36.6k
        RETURN_IF_ERROR(iter->seek_at_or_after(&last_key_slice, &exact_match));
3042
36.6k
        auto current_ordinal = iter->get_current_ordinal();
3043
18.4E
        DCHECK(total == remaining + current_ordinal)
3044
18.4E
                << "total: " << total << ", remaining: " << remaining
3045
18.4E
                << ", current_ordinal: " << current_ordinal;
3046
3047
36.6k
        size_t num_read = num_to_read;
3048
36.6k
        RETURN_IF_ERROR(iter->next_batch(&num_read, index_column));
3049
18.4E
        DCHECK(num_to_read == num_read)
3050
18.4E
                << "num_to_read: " << num_to_read << ", num_read: " << num_read;
3051
36.6k
        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
36.6k
        if (num_read == batch_size && num_read != remaining) {
3055
15.6k
            num_read -= 1;
3056
15.6k
        }
3057
17.1M
        for (size_t i = 0; i < num_read; i++, row_id++) {
3058
17.0M
            Slice key = Slice(index_column->get_data_at(i).data, index_column->get_data_at(i).size);
3059
17.0M
            RowLocation loc;
3060
            // calculate row id
3061
17.0M
            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
17.0M
            if (delete_bitmap->contains({rowset_id, seg->id(), DeleteBitmap::TEMP_VERSION_COMMON},
3084
17.0M
                                        row_id)) {
3085
0
                continue;
3086
0
            }
3087
3088
17.0M
            RowsetSharedPtr rowset_find;
3089
17.0M
            auto st = lookup_row_key(key, rowset_schema.get(), true, specified_rowsets, &loc,
3090
17.0M
                                     dummy_version.first - 1, segment_caches, &rowset_find, false,
3091
17.0M
                                     is_partial_update);
3092
17.0M
            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
18.4E
            DCHECK(expected_st || st.is<MEM_LIMIT_EXCEEDED>())
3096
18.4E
                    << "unexpected error status while lookup_row_key:" << st;
3097
17.0M
            if (!expected_st) {
3098
0
                return st;
3099
0
            }
3100
17.0M
            if (st.is<KEY_NOT_FOUND>()) {
3101
14.8M
                continue;
3102
14.8M
            }
3103
3104
2.23M
            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
114
                delete_bitmap->add({rowset_id, seg->id(), DeleteBitmap::TEMP_VERSION_COMMON},
3118
114
                                   row_id);
3119
114
                ++conflict_rows;
3120
114
                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
114
            }
3124
2.23M
            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
63
                prepare_to_read(loc, pos, &read_plan_ori);
3133
63
                prepare_to_read(RowLocation {rowset_id, seg->id(), row_id}, pos, &read_plan_update);
3134
63
                rsid_to_rowset[rowset_find->rowset_id()] = rowset_find;
3135
63
                ++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
63
                delete_bitmap->add(
3145
63
                        {loc.rowset_id, loc.segment_id, DeleteBitmap::TEMP_VERSION_COMMON},
3146
63
                        loc.row_id);
3147
63
                delete_bitmap->add({rowset_id, seg->id(), DeleteBitmap::TEMP_VERSION_COMMON},
3148
63
                                   row_id);
3149
63
                ++conflict_rows;
3150
63
                ++new_generated_rows;
3151
63
                continue;
3152
63
            }
3153
            // when st = ok
3154
2.23M
            delete_bitmap->add({loc.rowset_id, loc.segment_id, DeleteBitmap::TEMP_VERSION_COMMON},
3155
2.23M
                               loc.row_id);
3156
2.23M
            ++conflict_rows;
3157
2.23M
        }
3158
36.6k
        remaining -= num_read;
3159
36.6k
    }
3160
    // DCHECK_EQ(total, row_id) << "segment total rows: " << total << " row_id:" << row_id;
3161
3162
21.0k
    if (config::enable_merge_on_write_correctness_check) {
3163
21.0k
        RowsetIdUnorderedSet rowsetids;
3164
11.7M
        for (const auto& rowset : specified_rowsets) {
3165
11.7M
            rowsetids.emplace(rowset->rowset_id());
3166
11.7M
            VLOG_NOTICE << "[tabletID:" << tablet_id() << "]"
3167
12.9k
                        << "[add_sentinel_mark_to_delete_bitmap][end_version:" << end_version << "]"
3168
12.9k
                        << "add:" << rowset->rowset_id();
3169
11.7M
        }
3170
21.0k
        add_sentinel_mark_to_delete_bitmap(delete_bitmap.get(), rowsetids);
3171
21.0k
    }
3172
3173
21.0k
    if (pos > 0) {
3174
13
        auto partial_update_info = rowset_writer->get_partial_update_info();
3175
13
        DCHECK(partial_update_info);
3176
13
        RETURN_IF_ERROR(generate_new_block_for_partial_update(
3177
13
                rowset_schema, partial_update_info.get(), read_plan_ori, read_plan_update,
3178
13
                rsid_to_rowset, &block));
3179
13
        RETURN_IF_ERROR(sort_block(block, ordered_block));
3180
13
        RETURN_IF_ERROR(rowset_writer->flush_single_block(&ordered_block));
3181
13
        auto cost_us = watch.get_elapse_time_us();
3182
13
        if (cost_us > 10 * 1000) {
3183
13
            LOG(INFO) << "calc segment delete bitmap for partial update, tablet: " << tablet_id()
3184
13
                      << " rowset: " << rowset_id << " seg_id: " << seg->id()
3185
13
                      << " dummy_version: " << end_version + 1 << " rows: " << seg->num_rows()
3186
13
                      << " conflict rows: " << conflict_rows
3187
13
                      << " new generated rows: " << new_generated_rows
3188
13
                      << " bimap num: " << delete_bitmap->delete_bitmap.size()
3189
13
                      << " cost: " << cost_us << "(us)";
3190
13
        }
3191
13
        return Status::OK();
3192
13
    }
3193
21.0k
    auto cost_us = watch.get_elapse_time_us();
3194
21.0k
    if (cost_us > 10 * 1000) {
3195
11.1k
        LOG(INFO) << "calc segment delete bitmap, tablet: " << tablet_id()
3196
11.1k
                  << " rowset: " << rowset_id << " seg_id: " << seg->id()
3197
11.1k
                  << " dummy_version: " << end_version + 1 << " rows: " << seg->num_rows()
3198
11.1k
                  << " conflict rows: " << conflict_rows
3199
11.1k
                  << " bimap num: " << delete_bitmap->delete_bitmap.size() << " cost: " << cost_us
3200
11.1k
                  << "(us)";
3201
11.1k
    }
3202
21.0k
    return Status::OK();
3203
21.0k
}
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
124k
                                  CalcDeleteBitmapToken* token, RowsetWriter* rowset_writer) {
3214
124k
    if (specified_rowsets.empty() || segments.empty()) {
3215
103k
        return Status::OK();
3216
103k
    }
3217
3218
21.0k
    OlapStopWatch watch;
3219
21.0k
    doris::TabletSharedPtr tablet_ptr = _engine.tablet_manager()->get_tablet(tablet_id());
3220
21.0k
    if (tablet_ptr == nullptr) {
3221
0
        return Status::InternalError("Can't find tablet id: {}, maybe already dropped.",
3222
0
                                     tablet_id());
3223
0
    }
3224
21.0k
    for (const auto& segment : segments) {
3225
21.0k
        auto& seg = segment;
3226
21.0k
        if (token != nullptr) {
3227
6.23k
            RETURN_IF_ERROR(token->submit(tablet_ptr, rowset, seg, specified_rowsets, end_version,
3228
6.23k
                                          delete_bitmap, rowset_writer));
3229
14.7k
        } else {
3230
14.7k
            RETURN_IF_ERROR(calc_segment_delete_bitmap(rowset, segment, specified_rowsets,
3231
14.7k
                                                       delete_bitmap, end_version, rowset_writer));
3232
14.7k
        }
3233
21.0k
    }
3234
3235
21.0k
    return Status::OK();
3236
21.0k
}
3237
3238
std::vector<RowsetSharedPtr> Tablet::get_rowset_by_ids(
3239
177k
        const RowsetIdUnorderedSet* specified_rowset_ids, bool include_stale) {
3240
177k
    std::vector<RowsetSharedPtr> rowsets;
3241
99.0M
    for (auto& rs : _rs_version_map) {
3242
99.0M
        if (!specified_rowset_ids ||
3243
99.0M
            specified_rowset_ids->find(rs.second->rowset_id()) != specified_rowset_ids->end()) {
3244
42.1M
            rowsets.push_back(rs.second);
3245
42.1M
        }
3246
99.0M
    }
3247
3248
177k
    if (include_stale && specified_rowset_ids != nullptr &&
3249
177k
        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
459M
    std::sort(rowsets.begin(), rowsets.end(), [](RowsetSharedPtr& lhs, RowsetSharedPtr& rhs) {
3258
459M
        return lhs->end_version() > rhs->end_version();
3259
459M
    });
3260
177k
    return rowsets;
3261
177k
}
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
13
        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
13
    CHECK(output_block);
3274
13
    auto full_mutable_columns = output_block->mutate_columns();
3275
13
    const auto& missing_cids = partial_update_info->missing_cids;
3276
13
    const auto& update_cids = partial_update_info->update_cids;
3277
13
    auto old_block = rowset_schema->create_block_by_cids(missing_cids);
3278
13
    auto update_block = rowset_schema->create_block_by_cids(update_cids);
3279
3280
13
    auto get_delete_sign_column_data = [](vectorized::Block& block,
3281
22
                                          size_t rows) -> const signed char* {
3282
22
        if (const vectorized::ColumnWithTypeAndName* delete_sign_column =
3283
22
                    block.try_get_by_name(DELETE_SIGN);
3284
22
            delete_sign_column != nullptr) {
3285
14
            const auto& delete_sign_col =
3286
14
                    reinterpret_cast<const vectorized::ColumnInt8&>(*(delete_sign_column->column));
3287
14
            if (delete_sign_col.size() >= rows) {
3288
14
                return delete_sign_col.get_data().data();
3289
14
            }
3290
14
        }
3291
8
        return nullptr;
3292
22
    };
3293
3294
    // rowid in the final block(start from 0, increase continuously) -> rowid to read in update_block
3295
13
    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
13
    RETURN_IF_ERROR(read_columns_by_plan(rowset_schema, update_cids, read_plan_update,
3300
13
                                         rsid_to_rowset, update_block, &read_index_update, false));
3301
3302
13
    size_t update_rows = read_index_update.size();
3303
46
    for (auto i = 0; i < update_cids.size(); ++i) {
3304
194
        for (auto idx = 0; idx < update_rows; ++idx) {
3305
161
            full_mutable_columns[update_cids[i]]->insert_from(
3306
161
                    *update_block.get_columns_with_type_and_name()[i].column.get(),
3307
161
                    read_index_update[idx]);
3308
161
        }
3309
33
    }
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
13
    const auto* __restrict new_block_delete_signs =
3314
13
            rowset_schema->has_sequence_col()
3315
13
                    ? nullptr
3316
13
                    : 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
13
    std::map<uint32_t, uint32_t> read_index_old;
3320
13
    RETURN_IF_ERROR(read_columns_by_plan(rowset_schema, missing_cids, read_plan_ori, rsid_to_rowset,
3321
13
                                         old_block, &read_index_old, true, new_block_delete_signs));
3322
13
    size_t old_rows = read_index_old.size();
3323
13
    const auto* __restrict old_block_delete_signs =
3324
13
            get_delete_sign_column_data(old_block, old_rows);
3325
3326
    // build default value block
3327
13
    auto default_value_block = old_block.clone_empty();
3328
13
    auto mutable_default_value_columns = default_value_block.mutate_columns();
3329
13
    if (old_block_delete_signs != nullptr || new_block_delete_signs != nullptr) {
3330
83
        for (auto i = 0; i < missing_cids.size(); ++i) {
3331
70
            const auto& column = rowset_schema->column(missing_cids[i]);
3332
70
            if (column.has_default_value()) {
3333
46
                const auto& default_value = partial_update_info->default_values[i];
3334
46
                vectorized::ReadBuffer rb(const_cast<char*>(default_value.c_str()),
3335
46
                                          default_value.size());
3336
46
                RETURN_IF_ERROR(old_block.get_by_position(i).type->from_string(
3337
46
                        rb, mutable_default_value_columns[i].get()));
3338
46
            }
3339
70
        }
3340
13
    }
3341
3342
13
    CHECK(update_rows >= old_rows);
3343
3344
    // build full block
3345
83
    for (auto i = 0; i < missing_cids.size(); ++i) {
3346
70
        const auto& rs_column = rowset_schema->column(missing_cids[i]);
3347
70
        auto& mutable_column = full_mutable_columns[missing_cids[i]];
3348
410
        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
340
            if (new_block_delete_signs != nullptr && new_block_delete_signs[idx]) {
3359
15
                mutable_column->insert_default();
3360
325
            } else if (old_block_delete_signs != nullptr &&
3361
325
                       old_block_delete_signs[read_index_old[idx]] != 0) {
3362
15
                if (rs_column.has_default_value()) {
3363
12
                    mutable_column->insert_from(*mutable_default_value_columns[i].get(), 0);
3364
12
                } else if (rs_column.is_nullable()) {
3365
3
                    assert_cast<vectorized::ColumnNullable*>(mutable_column.get())
3366
3
                            ->insert_null_elements(1);
3367
3
                } else {
3368
0
                    mutable_column->insert_default();
3369
0
                }
3370
310
            } else {
3371
310
                mutable_column->insert_from(
3372
310
                        *old_block.get_columns_with_type_and_name()[i].column.get(),
3373
310
                        read_index_old[idx]);
3374
310
            }
3375
340
        }
3376
70
    }
3377
13
    output_block->set_columns(std::move(full_mutable_columns));
3378
13
    VLOG_DEBUG << "full block when publish: " << output_block->dump_data();
3379
13
    return Status::OK();
3380
13
}
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
26
                                    const signed char* __restrict skip_map) {
3392
26
    if (force_read_old_delete_signs) {
3393
        // always read delete sign column from historical data
3394
13
        if (const vectorized::ColumnWithTypeAndName* old_delete_sign_column =
3395
13
                    block.try_get_by_name(DELETE_SIGN);
3396
13
            old_delete_sign_column == nullptr) {
3397
1
            auto del_col_cid = tablet_schema->field_index(DELETE_SIGN);
3398
1
            cids_to_read.emplace_back(del_col_cid);
3399
1
            block.swap(tablet_schema->create_block_by_cids(cids_to_read));
3400
1
        }
3401
13
    }
3402
26
    bool has_row_column = tablet_schema->store_row_column();
3403
26
    auto mutable_columns = block.mutate_columns();
3404
26
    size_t read_idx = 0;
3405
26
    for (auto rs_it : read_plan) {
3406
26
        for (auto seg_it : rs_it.second) {
3407
26
            auto rowset_iter = rsid_to_rowset.find(rs_it.first);
3408
26
            CHECK(rowset_iter != rsid_to_rowset.end());
3409
26
            std::vector<uint32_t> rids;
3410
126
            for (auto [rid, pos] : seg_it.second) {
3411
126
                if (skip_map && skip_map[pos]) {
3412
3
                    continue;
3413
3
                }
3414
123
                rids.emplace_back(rid);
3415
123
                (*read_index)[pos] = read_idx++;
3416
123
            }
3417
26
            if (has_row_column) {
3418
12
                auto st = fetch_value_through_row_column(rowset_iter->second, *tablet_schema,
3419
12
                                                         seg_it.first, rids, cids_to_read, block);
3420
12
                if (!st.ok()) {
3421
0
                    LOG(WARNING) << "failed to fetch value through row column";
3422
0
                    return st;
3423
0
                }
3424
12
                continue;
3425
12
            }
3426
66
            for (size_t cid = 0; cid < mutable_columns.size(); ++cid) {
3427
52
                TabletColumn tablet_column = tablet_schema->column(cids_to_read[cid]);
3428
52
                auto st = fetch_value_by_rowids(rowset_iter->second, seg_it.first, rids,
3429
52
                                                tablet_column, mutable_columns[cid]);
3430
                // set read value to output block
3431
52
                if (!st.ok()) {
3432
0
                    LOG(WARNING) << "failed to fetch value";
3433
0
                    return st;
3434
0
                }
3435
52
            }
3436
14
        }
3437
26
    }
3438
26
    block.set_columns(std::move(mutable_columns));
3439
26
    return Status::OK();
3440
26
}
3441
3442
void Tablet::prepare_to_read(const RowLocation& row_location, size_t pos,
3443
22.5k
                             PartialUpdateReadPlan* read_plan) {
3444
22.5k
    auto rs_it = read_plan->find(row_location.rowset_id);
3445
22.5k
    if (rs_it == read_plan->end()) {
3446
466
        std::map<uint32_t, std::vector<RidAndPos>> segid_to_rid;
3447
466
        std::vector<RidAndPos> rid_pos;
3448
466
        rid_pos.emplace_back(RidAndPos {row_location.row_id, pos});
3449
466
        segid_to_rid.emplace(row_location.segment_id, rid_pos);
3450
466
        read_plan->emplace(row_location.rowset_id, segid_to_rid);
3451
466
        return;
3452
466
    }
3453
22.0k
    auto seg_it = rs_it->second.find(row_location.segment_id);
3454
22.0k
    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
22.0k
    seg_it->second.emplace_back(RidAndPos {row_location.row_id, pos});
3461
22.0k
}
3462
3463
void Tablet::_rowset_ids_difference(const RowsetIdUnorderedSet& cur,
3464
                                    const RowsetIdUnorderedSet& pre, RowsetIdUnorderedSet* to_add,
3465
102k
                                    RowsetIdUnorderedSet* to_del) {
3466
55.6M
    for (const auto& id : cur) {
3467
55.6M
        if (pre.find(id) == pre.end()) {
3468
23.0k
            to_add->insert(id);
3469
23.0k
        }
3470
55.6M
    }
3471
56.2M
    for (const auto& id : pre) {
3472
56.2M
        if (cur.find(id) == cur.end()) {
3473
1.62k
            to_del->insert(id);
3474
1.62k
        }
3475
56.2M
    }
3476
102k
}
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, segments, delete_bitmap));
3507
3508
    // get all base rowsets to calculate on
3509
0
    std::vector<RowsetSharedPtr> specified_rowsets;
3510
0
    RowsetIdUnorderedSet cur_rowset_ids;
3511
0
    if (specified_base_rowsets == nullptr) {
3512
0
        RETURN_IF_ERROR(all_rs_id(cur_version - 1, &cur_rowset_ids));
3513
0
        specified_rowsets = get_rowset_by_ids(&cur_rowset_ids);
3514
0
    } else {
3515
0
        specified_rowsets = *specified_base_rowsets;
3516
0
    }
3517
3518
0
    OlapStopWatch watch;
3519
0
    auto token = _engine.calc_delete_bitmap_executor()->create_token();
3520
0
    RETURN_IF_ERROR(calc_delete_bitmap(rowset, segments, specified_rowsets, delete_bitmap,
3521
0
                                       cur_version - 1, token.get()));
3522
0
    RETURN_IF_ERROR(token->wait());
3523
0
    size_t total_rows = std::accumulate(
3524
0
            segments.begin(), segments.end(), 0,
3525
0
            [](size_t sum, const segment_v2::SegmentSharedPtr& s) { return sum += s->num_rows(); });
3526
0
    LOG(INFO) << "[Schema Change or Clone] construct delete bitmap tablet: " << tablet_id()
3527
0
              << ", rowset_ids: " << cur_rowset_ids.size() << ", cur max_version: " << cur_version
3528
0
              << ", transaction_id: " << -1 << ", cost: " << watch.get_elapse_time_us()
3529
0
              << "(us), total rows: " << total_rows;
3530
0
    if (config::enable_merge_on_write_correctness_check) {
3531
        // check if all the rowset has ROWSET_SENTINEL_MARK
3532
0
        auto st = check_delete_bitmap_correctness(delete_bitmap, cur_version - 1, -1,
3533
0
                                                  cur_rowset_ids, &specified_rowsets);
3534
0
        if (!st.ok()) {
3535
0
            LOG(WARNING) << fmt::format("delete bitmap correctness check failed in publish phase!");
3536
0
        }
3537
0
        _remove_sentinel_mark_from_delete_bitmap(delete_bitmap);
3538
0
    }
3539
0
    for (auto iter = delete_bitmap->delete_bitmap.begin();
3540
0
         iter != delete_bitmap->delete_bitmap.end(); ++iter) {
3541
0
        _tablet_meta->delete_bitmap().merge(
3542
0
                {std::get<0>(iter->first), std::get<1>(iter->first), cur_version}, iter->second);
3543
0
    }
3544
3545
0
    return Status::OK();
3546
0
}
3547
3548
Status Tablet::commit_phase_update_delete_bitmap(
3549
        const RowsetSharedPtr& rowset, RowsetIdUnorderedSet& pre_rowset_ids,
3550
        DeleteBitmapPtr delete_bitmap, const std::vector<segment_v2::SegmentSharedPtr>& segments,
3551
51.1k
        int64_t txn_id, CalcDeleteBitmapToken* token, RowsetWriter* rowset_writer) {
3552
51.1k
    SCOPED_BVAR_LATENCY(g_tablet_commit_phase_update_delete_bitmap_latency);
3553
51.1k
    RowsetIdUnorderedSet cur_rowset_ids;
3554
51.1k
    RowsetIdUnorderedSet rowset_ids_to_add;
3555
51.1k
    RowsetIdUnorderedSet rowset_ids_to_del;
3556
51.1k
    int64_t cur_version;
3557
3558
51.1k
    std::vector<RowsetSharedPtr> specified_rowsets;
3559
51.1k
    {
3560
51.1k
        std::shared_lock meta_rlock(_meta_lock);
3561
51.1k
        cur_version = max_version_unlocked().second;
3562
51.1k
        RETURN_IF_ERROR(all_rs_id(cur_version, &cur_rowset_ids));
3563
51.1k
        _rowset_ids_difference(cur_rowset_ids, pre_rowset_ids, &rowset_ids_to_add,
3564
51.1k
                               &rowset_ids_to_del);
3565
51.1k
        specified_rowsets = get_rowset_by_ids(&rowset_ids_to_add);
3566
51.1k
    }
3567
643
    for (const auto& to_del : rowset_ids_to_del) {
3568
643
        delete_bitmap->remove({to_del, 0, 0}, {to_del, UINT32_MAX, INT64_MAX});
3569
643
    }
3570
3571
51.1k
    RETURN_IF_ERROR(calc_delete_bitmap(rowset, segments, specified_rowsets, delete_bitmap,
3572
51.1k
                                       cur_version, token, rowset_writer));
3573
51.1k
    size_t total_rows = std::accumulate(
3574
51.1k
            segments.begin(), segments.end(), 0,
3575
51.1k
            [](size_t sum, const segment_v2::SegmentSharedPtr& s) { return sum += s->num_rows(); });
3576
51.1k
    LOG(INFO) << "[Before Commit] construct delete bitmap tablet: " << tablet_id()
3577
51.1k
              << ", rowset_ids to add: " << rowset_ids_to_add.size()
3578
51.1k
              << ", rowset_ids to del: " << rowset_ids_to_del.size()
3579
51.1k
              << ", cur max_version: " << cur_version << ", transaction_id: " << txn_id
3580
51.1k
              << ", total rows: " << total_rows;
3581
51.1k
    pre_rowset_ids = cur_rowset_ids;
3582
51.1k
    return Status::OK();
3583
51.1k
}
3584
3585
51.2k
Status Tablet::update_delete_bitmap(TabletTxnInfo* txn_info, int64_t txn_id) {
3586
51.2k
    SCOPED_BVAR_LATENCY(g_tablet_update_delete_bitmap_latency);
3587
51.2k
    RowsetIdUnorderedSet cur_rowset_ids;
3588
51.2k
    RowsetIdUnorderedSet rowset_ids_to_add;
3589
51.2k
    RowsetIdUnorderedSet rowset_ids_to_del;
3590
51.2k
    RowsetSharedPtr rowset = txn_info->rowset;
3591
51.2k
    int64_t cur_version = rowset->start_version();
3592
3593
51.2k
    std::unique_ptr<RowsetWriter> rowset_writer;
3594
51.2k
    RETURN_IF_ERROR(
3595
51.2k
            create_transient_rowset_writer(rowset, &rowset_writer, txn_info->partial_update_info));
3596
3597
51.2k
    DeleteBitmapPtr delete_bitmap = txn_info->delete_bitmap;
3598
    // Partial update might generate new segments when there is conflicts while publish, and mark
3599
    // the same key in original segments as delete.
3600
    // When the new segment flush fails or the rowset build fails, the deletion marker for the
3601
    // duplicate key of the original segment should not remain in `txn_info->delete_bitmap`,
3602
    // so we need to make a copy of `txn_info->delete_bitmap` and make changes on it.
3603
51.2k
    bool is_partial_update =
3604
51.2k
            txn_info->partial_update_info && txn_info->partial_update_info->is_partial_update;
3605
51.2k
    if (is_partial_update) {
3606
1.79k
        delete_bitmap = std::make_shared<DeleteBitmap>(*(txn_info->delete_bitmap));
3607
1.79k
    }
3608
3609
51.2k
    OlapStopWatch watch;
3610
51.2k
    std::vector<segment_v2::SegmentSharedPtr> segments;
3611
51.2k
    RETURN_IF_ERROR(_load_rowset_segments(rowset, &segments));
3612
51.2k
    auto t1 = watch.get_elapse_time_us();
3613
3614
51.2k
    {
3615
51.2k
        std::shared_lock meta_rlock(_meta_lock);
3616
        // tablet is under alter process. The delete bitmap will be calculated after conversion.
3617
51.2k
        if (tablet_state() == TABLET_NOTREADY) {
3618
3
            LOG(INFO) << "tablet is under alter process, update delete bitmap later, tablet_id="
3619
3
                      << tablet_id();
3620
3
            return Status::OK();
3621
3
        }
3622
51.2k
        RETURN_IF_ERROR(all_rs_id(cur_version - 1, &cur_rowset_ids));
3623
51.2k
    }
3624
51.2k
    auto t2 = watch.get_elapse_time_us();
3625
3626
51.2k
    _rowset_ids_difference(cur_rowset_ids, txn_info->rowset_ids, &rowset_ids_to_add,
3627
51.2k
                           &rowset_ids_to_del);
3628
51.2k
    for (const auto& to_del : rowset_ids_to_del) {
3629
985
        delete_bitmap->remove({to_del, 0, 0}, {to_del, UINT32_MAX, INT64_MAX});
3630
985
    }
3631
3632
51.2k
    std::vector<RowsetSharedPtr> specified_rowsets;
3633
51.2k
    {
3634
51.2k
        std::shared_lock meta_rlock(_meta_lock);
3635
51.2k
        specified_rowsets = get_rowset_by_ids(&rowset_ids_to_add);
3636
51.2k
    }
3637
51.2k
    auto t3 = watch.get_elapse_time_us();
3638
3639
    // If a rowset is produced by compaction before the commit phase of the partial update load
3640
    // and is not included in txn_info->rowset_ids, we can skip the alignment process of that rowset
3641
    // because data remains the same before and after compaction. But we still need to calculate the
3642
    // the delete bitmap for that rowset.
3643
51.2k
    std::vector<RowsetSharedPtr> rowsets_skip_alignment;
3644
51.2k
    if (is_partial_update) {
3645
1.79k
        int64_t max_version_in_flush_phase =
3646
1.79k
                txn_info->partial_update_info->max_version_in_flush_phase;
3647
1.79k
        DCHECK(max_version_in_flush_phase != -1);
3648
1.79k
        std::vector<RowsetSharedPtr> remained_rowsets;
3649
1.79k
        for (const auto& rowset : specified_rowsets) {
3650
164
            if (rowset->end_version() <= max_version_in_flush_phase &&
3651
164
                rowset->produced_by_compaction()) {
3652
1
                rowsets_skip_alignment.emplace_back(rowset);
3653
163
            } else {
3654
163
                remained_rowsets.emplace_back(rowset);
3655
163
            }
3656
164
        }
3657
1.79k
        if (!rowsets_skip_alignment.empty()) {
3658
1
            specified_rowsets = std::move(remained_rowsets);
3659
1
        }
3660
1.79k
    }
3661
3662
51.2k
    if (!rowsets_skip_alignment.empty()) {
3663
1
        auto token = _engine.calc_delete_bitmap_executor()->create_token();
3664
        // set rowset_writer to nullptr to skip the alignment process
3665
1
        RETURN_IF_ERROR(calc_delete_bitmap(rowset, segments, rowsets_skip_alignment, delete_bitmap,
3666
1
                                           cur_version - 1, token.get(), nullptr));
3667
1
        RETURN_IF_ERROR(token->wait());
3668
1
    }
3669
3670
51.2k
    auto token = _engine.calc_delete_bitmap_executor()->create_token();
3671
51.2k
    RETURN_IF_ERROR(calc_delete_bitmap(rowset, segments, specified_rowsets, delete_bitmap,
3672
51.2k
                                       cur_version - 1, token.get(), rowset_writer.get()));
3673
51.2k
    RETURN_IF_ERROR(token->wait());
3674
3675
51.2k
    std::stringstream ss;
3676
51.2k
    if (watch.get_elapse_time_us() < 1 * 1000 * 1000) {
3677
51.1k
        ss << "cost: " << watch.get_elapse_time_us() - t3 << "(us)";
3678
51.1k
    } else {
3679
88
        ss << "cost(us): (load segments: " << t1 << ", get all rsid: " << t2 - t1
3680
88
           << ", get rowsets: " << t3 - t2
3681
88
           << ", calc delete bitmap: " << watch.get_elapse_time_us() - t3 << ")";
3682
88
    }
3683
3684
51.2k
    if (config::enable_merge_on_write_correctness_check && rowset->num_rows() != 0) {
3685
        // only do correctness check if the rowset has at least one row written
3686
        // check if all the rowset has ROWSET_SENTINEL_MARK
3687
22.5k
        auto st = check_delete_bitmap_correctness(delete_bitmap, cur_version - 1, -1,
3688
22.5k
                                                  cur_rowset_ids, &specified_rowsets);
3689
22.5k
        if (!st.ok()) {
3690
0
            LOG(WARNING) << fmt::format("delete bitmap correctness check failed in publish phase!");
3691
0
        }
3692
22.5k
        _remove_sentinel_mark_from_delete_bitmap(delete_bitmap);
3693
22.5k
    }
3694
3695
51.2k
    if (txn_info->partial_update_info && txn_info->partial_update_info->is_partial_update) {
3696
1.79k
        DBUG_EXECUTE_IF("Tablet.update_delete_bitmap.partial_update_write_rowset_fail", {
3697
1.79k
            if (rand() % 100 < (100 * dp->param("percent", 0.5))) {
3698
1.79k
                LOG_WARNING("Tablet.update_delete_bitmap.partial_update_write_rowset random failed")
3699
1.79k
                        .tag("txn_id", txn_id);
3700
1.79k
                return Status::InternalError(
3701
1.79k
                        "debug update_delete_bitmap partial update write rowset random failed");
3702
1.79k
            }
3703
1.79k
        });
3704
        // build rowset writer and merge transient rowset
3705
1.79k
        RETURN_IF_ERROR(rowset_writer->flush());
3706
1.79k
        RowsetSharedPtr transient_rowset;
3707
1.79k
        RETURN_IF_ERROR(rowset_writer->build(transient_rowset));
3708
1.79k
        auto old_segments = rowset->num_segments();
3709
1.79k
        rowset->merge_rowset_meta(transient_rowset->rowset_meta());
3710
1.79k
        auto new_segments = rowset->num_segments();
3711
1.79k
        ss << ", partial update flush rowset (old segment num: " << old_segments
3712
1.79k
           << ", new segment num: " << new_segments << ")";
3713
3714
        // update the shared_ptr to new delete bitmap
3715
1.79k
        txn_info->delete_bitmap = delete_bitmap;
3716
3717
        // erase segment cache cause we will add a segment to rowset
3718
1.79k
        SegmentLoader::instance()->erase_segments(rowset->rowset_id(), rowset->num_segments());
3719
1.79k
    }
3720
3721
51.2k
    size_t total_rows = std::accumulate(
3722
51.2k
            segments.begin(), segments.end(), 0,
3723
51.2k
            [](size_t sum, const segment_v2::SegmentSharedPtr& s) { return sum += s->num_rows(); });
3724
51.2k
    LOG(INFO) << "[Publish] construct delete bitmap tablet: " << tablet_id()
3725
51.2k
              << ", rowset_ids to add: "
3726
51.2k
              << (specified_rowsets.size() + rowsets_skip_alignment.size())
3727
51.2k
              << ", rowset_ids to del: " << rowset_ids_to_del.size()
3728
51.2k
              << ", cur version: " << cur_version << ", transaction_id: " << txn_id << ","
3729
51.2k
              << ss.str() << " , total rows: " << total_rows;
3730
3731
    // update version without write lock, compaction and publish_txn
3732
    // will update delete bitmap, handle compaction with _rowset_update_lock
3733
    // and publish_txn runs sequential so no need to lock here
3734
51.2k
    for (auto& [key, bitmap] : delete_bitmap->delete_bitmap) {
3735
7.99k
        _tablet_meta->delete_bitmap().merge({std::get<0>(key), std::get<1>(key), cur_version},
3736
7.99k
                                            bitmap);
3737
7.99k
    }
3738
3739
51.2k
    return Status::OK();
3740
51.2k
}
3741
3742
void Tablet::calc_compaction_output_rowset_delete_bitmap(
3743
        const std::vector<RowsetSharedPtr>& input_rowsets, const RowIdConversion& rowid_conversion,
3744
        uint64_t start_version, uint64_t end_version, std::set<RowLocation>* missed_rows,
3745
        std::map<RowsetSharedPtr, std::list<std::pair<RowLocation, RowLocation>>>* location_map,
3746
760
        const DeleteBitmap& input_delete_bitmap, DeleteBitmap* output_rowset_delete_bitmap) {
3747
760
    RowLocation src;
3748
760
    RowLocation dst;
3749
12.8k
    for (auto& rowset : input_rowsets) {
3750
12.8k
        src.rowset_id = rowset->rowset_id();
3751
18.2k
        for (uint32_t seg_id = 0; seg_id < rowset->num_segments(); ++seg_id) {
3752
5.49k
            src.segment_id = seg_id;
3753
5.49k
            DeleteBitmap subset_map(tablet_id());
3754
5.49k
            input_delete_bitmap.subset({rowset->rowset_id(), seg_id, start_version},
3755
5.49k
                                       {rowset->rowset_id(), seg_id, end_version}, &subset_map);
3756
            // traverse all versions and convert rowid
3757
5.49k
            for (auto iter = subset_map.delete_bitmap.begin();
3758
6.44k
                 iter != subset_map.delete_bitmap.end(); ++iter) {
3759
951
                auto cur_version = std::get<2>(iter->first);
3760
12.4k
                for (auto index = iter->second.begin(); index != iter->second.end(); ++index) {
3761
11.5k
                    src.row_id = *index;
3762
11.5k
                    if (rowid_conversion.get(src, &dst) != 0) {
3763
11.5k
                        VLOG_CRITICAL << "Can't find rowid, may be deleted by the delete_handler, "
3764
0
                                      << " src loaction: |" << src.rowset_id << "|"
3765
0
                                      << src.segment_id << "|" << src.row_id
3766
0
                                      << " version: " << cur_version;
3767
11.5k
                        if (missed_rows) {
3768
11.5k
                            missed_rows->insert(src);
3769
11.5k
                        }
3770
11.5k
                        continue;
3771
11.5k
                    }
3772
17
                    VLOG_DEBUG << "calc_compaction_output_rowset_delete_bitmap dst location: |"
3773
0
                               << dst.rowset_id << "|" << dst.segment_id << "|" << dst.row_id
3774
0
                               << " src location: |" << src.rowset_id << "|" << src.segment_id
3775
0
                               << "|" << src.row_id << " start version: " << start_version
3776
0
                               << "end version" << end_version;
3777
17
                    if (location_map) {
3778
0
                        (*location_map)[rowset].emplace_back(src, dst);
3779
0
                    }
3780
17
                    output_rowset_delete_bitmap->add({dst.rowset_id, dst.segment_id, cur_version},
3781
17
                                                     dst.row_id);
3782
17
                }
3783
951
            }
3784
5.49k
        }
3785
12.8k
    }
3786
760
}
3787
3788
361
void Tablet::merge_delete_bitmap(const DeleteBitmap& delete_bitmap) {
3789
361
    _tablet_meta->delete_bitmap().merge(delete_bitmap);
3790
361
}
3791
3792
Status Tablet::check_rowid_conversion(
3793
        RowsetSharedPtr dst_rowset,
3794
        const std::map<RowsetSharedPtr, std::list<std::pair<RowLocation, RowLocation>>>&
3795
0
                location_map) {
3796
0
    if (location_map.empty()) {
3797
0
        VLOG_DEBUG << "check_rowid_conversion, location_map is empty";
3798
0
        return Status::OK();
3799
0
    }
3800
0
    std::vector<segment_v2::SegmentSharedPtr> dst_segments;
3801
0
    RETURN_IF_ERROR(_load_rowset_segments(dst_rowset, &dst_segments));
3802
0
    std::unordered_map<RowsetId, std::vector<segment_v2::SegmentSharedPtr>> input_rowsets_segment;
3803
3804
0
    VLOG_DEBUG << "check_rowid_conversion, dst_segments size: " << dst_segments.size();
3805
0
    for (auto [src_rowset, locations] : location_map) {
3806
0
        std::vector<segment_v2::SegmentSharedPtr>& segments =
3807
0
                input_rowsets_segment[src_rowset->rowset_id()];
3808
0
        if (segments.empty()) {
3809
0
            RETURN_IF_ERROR(_load_rowset_segments(src_rowset, &segments));
3810
0
        }
3811
0
        for (auto& [src, dst] : locations) {
3812
0
            std::string src_key;
3813
0
            std::string dst_key;
3814
0
            Status s = segments[src.segment_id]->read_key_by_rowid(src.row_id, &src_key);
3815
0
            if (UNLIKELY(s.is<NOT_IMPLEMENTED_ERROR>())) {
3816
0
                LOG(INFO) << "primary key index of old version does not "
3817
0
                             "support reading key by rowid";
3818
0
                break;
3819
0
            }
3820
0
            if (UNLIKELY(!s)) {
3821
0
                LOG(WARNING) << "failed to get src key: |" << src.rowset_id << "|" << src.segment_id
3822
0
                             << "|" << src.row_id << " status: " << s;
3823
0
                DCHECK(false);
3824
0
                return s;
3825
0
            }
3826
3827
0
            s = dst_segments[dst.segment_id]->read_key_by_rowid(dst.row_id, &dst_key);
3828
0
            if (UNLIKELY(!s)) {
3829
0
                LOG(WARNING) << "failed to get dst key: |" << dst.rowset_id << "|" << dst.segment_id
3830
0
                             << "|" << dst.row_id << " status: " << s;
3831
0
                DCHECK(false);
3832
0
                return s;
3833
0
            }
3834
3835
0
            VLOG_DEBUG << "check_rowid_conversion, src: |" << src.rowset_id << "|" << src.segment_id
3836
0
                       << "|" << src.row_id << "|" << src_key << " dst: |" << dst.rowset_id << "|"
3837
0
                       << dst.segment_id << "|" << dst.row_id << "|" << dst_key;
3838
0
            if (UNLIKELY(src_key.compare(dst_key) != 0)) {
3839
0
                LOG(WARNING) << "failed to check key, src key: |" << src.rowset_id << "|"
3840
0
                             << src.segment_id << "|" << src.row_id << "|" << src_key
3841
0
                             << " dst key: |" << dst.rowset_id << "|" << dst.segment_id << "|"
3842
0
                             << dst.row_id << "|" << dst_key;
3843
0
                DCHECK(false);
3844
0
                return Status::InternalError("failed to check rowid conversion");
3845
0
            }
3846
0
        }
3847
0
    }
3848
0
    return Status::OK();
3849
0
}
3850
3851
155k
Status Tablet::all_rs_id(int64_t max_version, RowsetIdUnorderedSet* rowset_ids) const {
3852
    //  Ensure that the obtained versions of rowsets are continuous
3853
155k
    std::vector<Version> version_path;
3854
155k
    RETURN_IF_ERROR(
3855
155k
            capture_consistent_versions(Version(0, max_version), &version_path, false, false));
3856
90.0M
    for (auto& ver : version_path) {
3857
90.0M
        if (ver.second == 1) {
3858
            // [0-1] rowset is empty for each tablet, skip it
3859
155k
            continue;
3860
155k
        }
3861
89.8M
        auto it = _rs_version_map.find(ver);
3862
89.8M
        if (it == _rs_version_map.end()) {
3863
0
            return Status::Error<CAPTURE_ROWSET_ERROR, false>(
3864
0
                    "fail to find Rowset for version. tablet={}, version={}", tablet_id(),
3865
0
                    ver.to_string());
3866
0
        }
3867
89.8M
        rowset_ids->emplace(it->second->rowset_id());
3868
89.8M
    }
3869
155k
    return Status::OK();
3870
155k
}
3871
3872
0
bool Tablet::check_all_rowset_segment() {
3873
0
    std::shared_lock rdlock(_meta_lock);
3874
0
    for (auto& version_rowset : _rs_version_map) {
3875
0
        RowsetSharedPtr rowset = version_rowset.second;
3876
0
        if (!rowset->check_rowset_segment()) {
3877
0
            LOG(WARNING) << "Tablet Segment Check. find a bad tablet, tablet_id=" << tablet_id();
3878
0
            return false;
3879
0
        }
3880
0
    }
3881
0
    return true;
3882
0
}
3883
3884
4.23M
void Tablet::set_skip_compaction(bool skip, CompactionType compaction_type, int64_t start) {
3885
4.23M
    if (!skip) {
3886
121
        _skip_cumu_compaction = false;
3887
121
        _skip_base_compaction = false;
3888
121
        return;
3889
121
    }
3890
4.23M
    if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) {
3891
2.21M
        _skip_cumu_compaction = true;
3892
2.21M
        _skip_cumu_compaction_ts = start;
3893
2.21M
    } else {
3894
2.01M
        DCHECK(compaction_type == CompactionType::BASE_COMPACTION);
3895
2.01M
        _skip_base_compaction = true;
3896
2.01M
        _skip_base_compaction_ts = start;
3897
2.01M
    }
3898
4.23M
}
3899
3900
114M
bool Tablet::should_skip_compaction(CompactionType compaction_type, int64_t now) {
3901
114M
    if (compaction_type == CompactionType::CUMULATIVE_COMPACTION && _skip_cumu_compaction &&
3902
114M
        now < _skip_cumu_compaction_ts + config::skip_tablet_compaction_second) {
3903
98.2M
        return true;
3904
98.2M
    } else if (compaction_type == CompactionType::BASE_COMPACTION && _skip_base_compaction &&
3905
16.6M
               now < _skip_base_compaction_ts + config::skip_tablet_compaction_second) {
3906
8.59M
        return true;
3907
8.59M
    }
3908
8.09M
    return false;
3909
114M
}
3910
3911
208
std::pair<std::string, int64_t> Tablet::get_binlog_info(std::string_view binlog_version) const {
3912
208
    return RowsetMetaManager::get_binlog_info(_data_dir->get_meta(), tablet_uid(), binlog_version);
3913
208
}
3914
3915
std::string Tablet::get_rowset_binlog_meta(std::string_view binlog_version,
3916
190
                                           std::string_view rowset_id) const {
3917
190
    return RowsetMetaManager::get_rowset_binlog_meta(_data_dir->get_meta(), tablet_uid(),
3918
190
                                                     binlog_version, rowset_id);
3919
190
}
3920
3921
Status Tablet::get_rowset_binlog_metas(const std::vector<int64_t>& binlog_versions,
3922
0
                                       RowsetBinlogMetasPB* metas_pb) {
3923
0
    return RowsetMetaManager::get_rowset_binlog_metas(_data_dir->get_meta(), tablet_uid(),
3924
0
                                                      binlog_versions, metas_pb);
3925
0
}
3926
3927
4
Status Tablet::get_rowset_binlog_metas(Version binlog_versions, RowsetBinlogMetasPB* metas_pb) {
3928
4
    return RowsetMetaManager::get_rowset_binlog_metas(_data_dir->get_meta(), tablet_uid(),
3929
4
                                                      binlog_versions, metas_pb);
3930
4
}
3931
3932
std::string Tablet::get_segment_filepath(std::string_view rowset_id,
3933
540
                                         std::string_view segment_index) const {
3934
540
    return fmt::format("{}/_binlog/{}_{}.dat", _tablet_path, rowset_id, segment_index);
3935
540
}
3936
3937
0
std::string Tablet::get_segment_filepath(std::string_view rowset_id, int64_t segment_index) const {
3938
0
    return fmt::format("{}/_binlog/{}_{}.dat", _tablet_path, rowset_id, segment_index);
3939
0
}
3940
3941
std::string Tablet::get_segment_index_filepath(std::string_view rowset_id,
3942
                                               std::string_view segment_index,
3943
304
                                               std::string_view index_id) const {
3944
304
    auto format = _tablet_meta->tablet_schema()->get_inverted_index_storage_format();
3945
304
    if (format == doris::InvertedIndexStorageFormatPB::V1) {
3946
228
        return fmt::format("{}/_binlog/{}_{}_{}.idx", _tablet_path, rowset_id, segment_index,
3947
228
                           index_id);
3948
228
    } else {
3949
76
        return fmt::format("{}/_binlog/{}_{}.idx", _tablet_path, rowset_id, segment_index);
3950
76
    }
3951
304
}
3952
3953
std::string Tablet::get_segment_index_filepath(std::string_view rowset_id, int64_t segment_index,
3954
0
                                               int64_t index_id) const {
3955
0
    auto format = _tablet_meta->tablet_schema()->get_inverted_index_storage_format();
3956
0
    if (format == doris::InvertedIndexStorageFormatPB::V1) {
3957
0
        return fmt::format("{}/_binlog/{}_{}_{}.idx", _tablet_path, rowset_id, segment_index,
3958
0
                           index_id);
3959
0
    } else {
3960
0
        DCHECK(index_id == -1);
3961
0
        return fmt::format("{}/_binlog/{}_{}.idx", _tablet_path, rowset_id, segment_index);
3962
0
    }
3963
0
}
3964
3965
0
std::vector<std::string> Tablet::get_binlog_filepath(std::string_view binlog_version) const {
3966
0
    const auto& [rowset_id, num_segments] = get_binlog_info(binlog_version);
3967
0
    std::vector<std::string> binlog_filepath;
3968
0
    for (int i = 0; i < num_segments; ++i) {
3969
        // TODO(Drogon): rewrite by filesystem path
3970
0
        auto segment_file = fmt::format("{}_{}.dat", rowset_id, i);
3971
0
        binlog_filepath.emplace_back(fmt::format("{}/_binlog/{}", _tablet_path, segment_file));
3972
0
    }
3973
0
    return binlog_filepath;
3974
0
}
3975
3976
380
bool Tablet::can_add_binlog(uint64_t total_binlog_size) const {
3977
380
    return !_data_dir->reach_capacity_limit(total_binlog_size);
3978
380
}
3979
3980
235k
bool Tablet::is_enable_binlog() {
3981
235k
    return config::enable_feature_binlog && tablet_meta()->binlog_config().is_enable();
3982
235k
}
3983
3984
29
void Tablet::set_binlog_config(BinlogConfig binlog_config) {
3985
29
    tablet_meta()->set_binlog_config(binlog_config);
3986
29
}
3987
3988
0
void Tablet::gc_binlogs(int64_t version) {
3989
0
    auto meta = _data_dir->get_meta();
3990
0
    DCHECK(meta != nullptr);
3991
3992
0
    const auto& tablet_uid = this->tablet_uid();
3993
0
    const auto tablet_id = this->tablet_id();
3994
0
    std::string begin_key = make_binlog_meta_key_prefix(tablet_uid);
3995
0
    std::string end_key = make_binlog_meta_key_prefix(tablet_uid, version + 1);
3996
0
    LOG(INFO) << fmt::format("gc binlog meta, tablet_id:{}, begin_key:{}, end_key:{}", tablet_id,
3997
0
                             begin_key, end_key);
3998
3999
0
    std::vector<std::string> wait_for_deleted_binlog_keys;
4000
0
    std::vector<std::string> wait_for_deleted_binlog_files;
4001
0
    auto add_to_wait_for_deleted = [&](std::string_view key, std::string_view rowset_id,
4002
0
                                       int64_t num_segments) {
4003
        // add binlog meta key and binlog data key
4004
0
        wait_for_deleted_binlog_keys.emplace_back(key);
4005
0
        wait_for_deleted_binlog_keys.push_back(get_binlog_data_key_from_meta_key(key));
4006
4007
        // add binlog segment files and index files
4008
0
        for (int64_t i = 0; i < num_segments; ++i) {
4009
0
            wait_for_deleted_binlog_files.emplace_back(get_segment_filepath(rowset_id, i));
4010
0
            for (const auto& index : this->tablet_schema()->indexes()) {
4011
0
                if (index.index_type() != IndexType::INVERTED) {
4012
0
                    continue;
4013
0
                }
4014
0
                wait_for_deleted_binlog_files.emplace_back(
4015
0
                        get_segment_index_filepath(rowset_id, i, index.index_id()));
4016
0
            }
4017
0
        }
4018
0
    };
4019
4020
0
    auto check_binlog_ttl = [&](const std::string& key, const std::string& value) mutable -> bool {
4021
0
        if (key >= end_key) {
4022
0
            return false;
4023
0
        }
4024
4025
0
        BinlogMetaEntryPB binlog_meta_entry_pb;
4026
0
        if (!binlog_meta_entry_pb.ParseFromString(value)) {
4027
0
            LOG(WARNING) << "failed to parse binlog meta entry, key:" << key;
4028
0
            return true;
4029
0
        }
4030
4031
0
        auto num_segments = binlog_meta_entry_pb.num_segments();
4032
0
        std::string rowset_id;
4033
0
        if (binlog_meta_entry_pb.has_rowset_id_v2()) {
4034
0
            rowset_id = binlog_meta_entry_pb.rowset_id_v2();
4035
0
        } else {
4036
            // key is 'binlog_meta_6943f1585fe834b5-e542c2b83a21d0b7_00000000000000000069_020000000000000135449d7cd7eadfe672aa0f928fa99593', extract last part '020000000000000135449d7cd7eadfe672aa0f928fa99593'
4037
0
            auto pos = key.rfind('_');
4038
0
            if (pos == std::string::npos) {
4039
0
                LOG(WARNING) << fmt::format("invalid binlog meta key:{}", key);
4040
0
                return false;
4041
0
            }
4042
0
            rowset_id = key.substr(pos + 1);
4043
0
        }
4044
0
        add_to_wait_for_deleted(key, rowset_id, num_segments);
4045
4046
0
        return true;
4047
0
    };
4048
4049
0
    auto status = meta->iterate(META_COLUMN_FAMILY_INDEX, begin_key, check_binlog_ttl);
4050
0
    if (!status.ok()) {
4051
0
        LOG(WARNING) << "failed to iterate binlog meta, status:" << status;
4052
0
        return;
4053
0
    }
4054
4055
    // first remove binlog files, if failed, just break, then retry next time
4056
    // this keep binlog meta in meta store, so that binlog can be removed next time
4057
0
    bool remove_binlog_files_failed = false;
4058
0
    for (auto& file : wait_for_deleted_binlog_files) {
4059
0
        if (unlink(file.c_str()) != 0) {
4060
            // file not exist, continue
4061
0
            if (errno == ENOENT) {
4062
0
                continue;
4063
0
            }
4064
4065
0
            remove_binlog_files_failed = true;
4066
0
            LOG(WARNING) << "failed to remove binlog file:" << file << ", errno:" << errno;
4067
0
            break;
4068
0
        }
4069
0
    }
4070
0
    if (!remove_binlog_files_failed) {
4071
0
        static_cast<void>(meta->remove(META_COLUMN_FAMILY_INDEX, wait_for_deleted_binlog_keys));
4072
0
    }
4073
0
}
4074
4075
0
Status Tablet::ingest_binlog_metas(RowsetBinlogMetasPB* metas_pb) {
4076
0
    return RowsetMetaManager::ingest_binlog_metas(_data_dir->get_meta(), tablet_uid(), metas_pb);
4077
0
}
4078
4079
173k
void Tablet::clear_cache() {
4080
173k
    std::shared_lock rlock(get_header_lock());
4081
173k
    SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
4082
346k
    static auto recycle_segment_cache = [](const auto& rowset_map) {
4083
346k
        for (auto& [_, rowset] : rowset_map) {
4084
313k
            rowset->clear_cache();
4085
313k
        }
4086
346k
    };
4087
173k
    recycle_segment_cache(rowset_map());
4088
173k
    recycle_segment_cache(stale_rowset_map());
4089
173k
}
4090
4091
Status Tablet::calc_delete_bitmap_between_segments(
4092
        RowsetSharedPtr rowset, const std::vector<segment_v2::SegmentSharedPtr>& segments,
4093
3
        DeleteBitmapPtr delete_bitmap) {
4094
3
    size_t const num_segments = segments.size();
4095
3
    if (num_segments < 2) {
4096
0
        return Status::OK();
4097
0
    }
4098
4099
3
    OlapStopWatch watch;
4100
3
    auto const rowset_id = rowset->rowset_id();
4101
3
    size_t seq_col_length = 0;
4102
3
    if (_tablet_meta->tablet_schema()->has_sequence_col()) {
4103
0
        auto seq_col_idx = _tablet_meta->tablet_schema()->sequence_col_idx();
4104
0
        seq_col_length = _tablet_meta->tablet_schema()->column(seq_col_idx).length() + 1;
4105
0
    }
4106
3
    size_t rowid_length = 0;
4107
3
    if (!_tablet_meta->tablet_schema()->cluster_key_idxes().empty()) {
4108
0
        rowid_length = PrimaryKeyIndexReader::ROW_ID_LENGTH;
4109
0
    }
4110
4111
3
    MergeIndexDeleteBitmapCalculator calculator;
4112
3
    RETURN_IF_ERROR(calculator.init(rowset_id, segments, seq_col_length, rowid_length));
4113
4114
3
    RETURN_IF_ERROR(calculator.calculate_all(delete_bitmap));
4115
4116
3
    delete_bitmap->add(
4117
3
            {rowset_id, DeleteBitmap::INVALID_SEGMENT_ID, DeleteBitmap::TEMP_VERSION_COMMON},
4118
3
            DeleteBitmap::ROWSET_SENTINEL_MARK);
4119
3
    LOG(INFO) << fmt::format(
4120
3
            "construct delete bitmap between segments, "
4121
3
            "tablet: {}, rowset: {}, number of segments: {}, bitmap size: {}, cost {} (us)",
4122
3
            tablet_id(), rowset_id.to_string(), num_segments, delete_bitmap->delete_bitmap.size(),
4123
3
            watch.get_elapse_time_us());
4124
3
    return Status::OK();
4125
3
}
4126
4127
void Tablet::add_sentinel_mark_to_delete_bitmap(DeleteBitmap* delete_bitmap,
4128
21.9k
                                                const RowsetIdUnorderedSet& rowsetids) {
4129
12.2M
    for (const auto& rowsetid : rowsetids) {
4130
12.2M
        delete_bitmap->add(
4131
12.2M
                {rowsetid, DeleteBitmap::INVALID_SEGMENT_ID, DeleteBitmap::TEMP_VERSION_COMMON},
4132
12.2M
                DeleteBitmap::ROWSET_SENTINEL_MARK);
4133
12.2M
    }
4134
21.9k
}
4135
4136
22.5k
void Tablet::_remove_sentinel_mark_from_delete_bitmap(DeleteBitmapPtr delete_bitmap) {
4137
22.5k
    for (auto it = delete_bitmap->delete_bitmap.begin(), end = delete_bitmap->delete_bitmap.end();
4138
12.1M
         it != end;) {
4139
12.1M
        if (std::get<1>(it->first) == DeleteBitmap::INVALID_SEGMENT_ID) {
4140
12.1M
            it = delete_bitmap->delete_bitmap.erase(it);
4141
12.1M
        } else {
4142
35.6k
            ++it;
4143
35.6k
        }
4144
12.1M
    }
4145
22.5k
}
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
45.4k
                                               std::vector<RowsetSharedPtr>* rowsets) {
4151
45.4k
    RowsetIdUnorderedSet missing_ids;
4152
24.0M
    for (const auto& rowsetid : rowset_ids) {
4153
24.0M
        if (!delete_bitmap->delete_bitmap.contains({rowsetid, DeleteBitmap::INVALID_SEGMENT_ID,
4154
24.0M
                                                    DeleteBitmap::TEMP_VERSION_COMMON})) {
4155
0
            missing_ids.insert(rowsetid);
4156
0
        }
4157
24.0M
    }
4158
4159
45.4k
    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
45.4k
    return Status::OK();
4214
45.4k
}
4215
Status Tablet::calc_local_file_crc(uint32_t* crc_value, int64_t start_version, int64_t end_version,
4216
2
                                   int32_t* rowset_count, int64_t* file_count) {
4217
2
    Version v(start_version, end_version);
4218
2
    std::vector<RowsetSharedPtr> rowsets;
4219
10
    traverse_rowsets([&rowsets, &v](const auto& rs) {
4220
        // get local rowsets
4221
10
        if (rs->is_local() && v.contains(rs->version())) {
4222
10
            rowsets.emplace_back(rs);
4223
10
        }
4224
10
    });
4225
2
    std::sort(rowsets.begin(), rowsets.end(), Rowset::comparator);
4226
2
    *rowset_count = rowsets.size();
4227
4228
2
    *crc_value = 0;
4229
2
    *file_count = 0;
4230
10
    for (const auto& rs : rowsets) {
4231
10
        uint32_t rs_crc_value;
4232
10
        int64_t rs_file_count = 0;
4233
10
        auto rowset = std::static_pointer_cast<BetaRowset>(rs);
4234
10
        auto st = rowset->calc_local_file_crc(&rs_crc_value, &rs_file_count);
4235
10
        if (!st.ok()) {
4236
0
            return st;
4237
0
        }
4238
        // crc_value is calculated based on the crc_value of each rowset.
4239
10
        *crc_value = crc32c::Extend(*crc_value, reinterpret_cast<const char*>(&rs_crc_value),
4240
10
                                    sizeof(rs_crc_value));
4241
10
        *file_count += rs_file_count;
4242
10
    }
4243
2
    return Status::OK();
4244
2
}
4245
4246
55
Status Tablet::show_nested_index_file(std::string* json_meta) {
4247
55
    Version v(0, max_version_unlocked().second);
4248
55
    std::vector<RowsetSharedPtr> rowsets;
4249
185
    traverse_rowsets([&rowsets, &v](const auto& rs) {
4250
        // get all rowsets
4251
185
        if (v.contains(rs->version())) {
4252
185
            rowsets.emplace_back(rs);
4253
185
        }
4254
185
    });
4255
55
    std::sort(rowsets.begin(), rowsets.end(), Rowset::comparator);
4256
4257
55
    rapidjson::Document doc;
4258
55
    doc.SetObject();
4259
55
    rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();
4260
55
    rapidjson::Value tabletIdValue(tablet_id());
4261
55
    doc.AddMember("tablet_id", tabletIdValue, allocator);
4262
4263
55
    rapidjson::Value rowsets_value(rapidjson::kArrayType);
4264
4265
175
    for (const auto& rs : rowsets) {
4266
175
        rapidjson::Value rowset_value(rapidjson::kObjectType);
4267
4268
175
        auto rowset = std::static_pointer_cast<BetaRowset>(rs);
4269
175
        RETURN_IF_ERROR(rowset->show_nested_index_file(&rowset_value, allocator));
4270
173
        rowsets_value.PushBack(rowset_value, allocator);
4271
173
    }
4272
53
    doc.AddMember("rowsets", rowsets_value, allocator);
4273
4274
53
    rapidjson::StringBuffer buffer;
4275
53
    rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
4276
53
    doc.Accept(writer);
4277
53
    *json_meta = std::string(buffer.GetString());
4278
4279
53
    return Status::OK();
4280
55
}
4281
4282
} // namespace doris