Coverage Report

Created: 2026-03-19 07:03

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/cloud/cloud_tablet.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "cloud/cloud_tablet.h"
19
20
#include <bvar/bvar.h>
21
#include <bvar/latency_recorder.h>
22
#include <gen_cpp/Types_types.h>
23
#include <gen_cpp/olap_file.pb.h>
24
#include <rapidjson/document.h>
25
#include <rapidjson/encodings.h>
26
#include <rapidjson/prettywriter.h>
27
#include <rapidjson/rapidjson.h>
28
#include <rapidjson/stringbuffer.h>
29
30
#include <algorithm>
31
#include <atomic>
32
#include <chrono>
33
#include <cstdint>
34
#include <memory>
35
#include <ranges>
36
#include <ratio>
37
#include <shared_mutex>
38
#include <unordered_map>
39
#include <vector>
40
41
#include "cloud/cloud_meta_mgr.h"
42
#include "cloud/cloud_storage_engine.h"
43
#include "cloud/cloud_tablet_mgr.h"
44
#include "cloud/cloud_warm_up_manager.h"
45
#include "cloud/config.h"
46
#include "common/cast_set.h"
47
#include "common/config.h"
48
#include "common/logging.h"
49
#include "cpp/sync_point.h"
50
#include "io/cache/block_file_cache_downloader.h"
51
#include "io/cache/block_file_cache_factory.h"
52
#include "storage/compaction/compaction.h"
53
#include "storage/compaction/cumulative_compaction_time_series_policy.h"
54
#include "storage/index/inverted/inverted_index_desc.h"
55
#include "storage/olap_define.h"
56
#include "storage/rowset/beta_rowset.h"
57
#include "storage/rowset/rowset.h"
58
#include "storage/rowset/rowset_factory.h"
59
#include "storage/rowset/rowset_fwd.h"
60
#include "storage/rowset/rowset_writer.h"
61
#include "storage/storage_policy.h"
62
#include "storage/tablet/base_tablet.h"
63
#include "storage/tablet/tablet_schema.h"
64
#include "storage/txn/txn_manager.h"
65
#include "util/debug_points.h"
66
#include "util/stack_util.h"
67
68
namespace doris {
69
#include "common/compile_check_begin.h"
70
using namespace ErrorCode;
71
72
bvar::LatencyRecorder g_cu_compaction_get_delete_bitmap_lock_time_ms(
73
        "cu_compaction_get_delete_bitmap_lock_time_ms");
74
bvar::LatencyRecorder g_base_compaction_get_delete_bitmap_lock_time_ms(
75
        "base_compaction_get_delete_bitmap_lock_time_ms");
76
77
bvar::Adder<int64_t> g_unused_rowsets_count("unused_rowsets_count");
78
bvar::Adder<int64_t> g_unused_rowsets_bytes("unused_rowsets_bytes");
79
80
bvar::Adder<int64_t> g_capture_prefer_cache_count("capture_prefer_cache_count");
81
bvar::Adder<int64_t> g_capture_with_freshness_tolerance_count(
82
        "capture_with_freshness_tolerance_count");
83
bvar::Adder<int64_t> g_capture_with_freshness_tolerance_fallback_count(
84
        "capture_with_freshness_tolerance_fallback_count");
85
bvar::Window<bvar::Adder<int64_t>> g_capture_prefer_cache_count_window(
86
        "capture_prefer_cache_count_window", &g_capture_prefer_cache_count, 30);
87
bvar::Window<bvar::Adder<int64_t>> g_capture_with_freshness_tolerance_count_window(
88
        "capture_with_freshness_tolerance_count_window", &g_capture_with_freshness_tolerance_count,
89
        30);
90
bvar::Window<bvar::Adder<int64_t>> g_capture_with_freshness_tolerance_fallback_count_window(
91
        "capture_with_freshness_tolerance_fallback_count_window",
92
        &g_capture_with_freshness_tolerance_fallback_count, 30);
93
94
static constexpr int LOAD_INITIATOR_ID = -1;
95
96
bvar::Adder<uint64_t> g_file_cache_cloud_tablet_submitted_segment_size(
97
        "file_cache_cloud_tablet_submitted_segment_size");
98
bvar::Adder<uint64_t> g_file_cache_cloud_tablet_submitted_segment_num(
99
        "file_cache_cloud_tablet_submitted_segment_num");
100
bvar::Adder<uint64_t> g_file_cache_cloud_tablet_submitted_index_size(
101
        "file_cache_cloud_tablet_submitted_index_size");
102
bvar::Adder<uint64_t> g_file_cache_cloud_tablet_submitted_index_num(
103
        "file_cache_cloud_tablet_submitted_index_num");
104
bvar::Adder<uint64_t> g_file_cache_cloud_tablet_finished_segment_size(
105
        "file_cache_cloud_tablet_finished_segment_size");
106
bvar::Adder<uint64_t> g_file_cache_cloud_tablet_finished_segment_num(
107
        "file_cache_cloud_tablet_finished_segment_num");
108
bvar::Adder<uint64_t> g_file_cache_cloud_tablet_finished_index_size(
109
        "file_cache_cloud_tablet_finished_index_size");
110
bvar::Adder<uint64_t> g_file_cache_cloud_tablet_finished_index_num(
111
        "file_cache_cloud_tablet_finished_index_num");
112
113
bvar::Adder<uint64_t> g_file_cache_recycle_cached_data_segment_num(
114
        "file_cache_recycle_cached_data_segment_num");
115
bvar::Adder<uint64_t> g_file_cache_recycle_cached_data_segment_size(
116
        "file_cache_recycle_cached_data_segment_size");
117
bvar::Adder<uint64_t> g_file_cache_recycle_cached_data_index_num(
118
        "file_cache_recycle_cached_data_index_num");
119
120
bvar::Adder<uint64_t> g_file_cache_warm_up_segment_complete_num(
121
        "file_cache_warm_up_segment_complete_num");
122
bvar::Adder<uint64_t> g_file_cache_warm_up_segment_failed_num(
123
        "file_cache_warm_up_segment_failed_num");
124
bvar::Adder<uint64_t> g_file_cache_warm_up_inverted_idx_complete_num(
125
        "file_cache_warm_up_inverted_idx_complete_num");
126
bvar::Adder<uint64_t> g_file_cache_warm_up_inverted_idx_failed_num(
127
        "file_cache_warm_up_inverted_idx_failed_num");
128
bvar::Adder<uint64_t> g_file_cache_warm_up_rowset_complete_num(
129
        "file_cache_warm_up_rowset_complete_num");
130
bvar::Adder<uint64_t> g_file_cache_warm_up_rowset_triggered_by_job_num(
131
        "file_cache_warm_up_rowset_triggered_by_job_num");
132
bvar::Adder<uint64_t> g_file_cache_warm_up_rowset_triggered_by_sync_rowset_num(
133
        "file_cache_warm_up_rowset_triggered_by_sync_rowset_num");
134
bvar::Adder<uint64_t> g_file_cache_warm_up_rowset_triggered_by_event_driven_num(
135
        "file_cache_warm_up_rowset_triggered_by_event_driven_num");
136
bvar::LatencyRecorder g_file_cache_warm_up_rowset_all_segments_latency(
137
        "file_cache_warm_up_rowset_all_segments_latency");
138
139
CloudTablet::CloudTablet(CloudStorageEngine& engine, TabletMetaSharedPtr tablet_meta)
140
129
        : BaseTablet(std::move(tablet_meta)), _engine(engine) {}
141
142
129
CloudTablet::~CloudTablet() = default;
143
144
0
bool CloudTablet::exceed_version_limit(int32_t limit) {
145
0
    return _approximate_num_rowsets.load(std::memory_order_relaxed) > limit;
146
0
}
147
148
19
std::string CloudTablet::tablet_path() const {
149
19
    return "";
150
19
}
151
152
Status CloudTablet::capture_rs_readers(const Version& spec_version,
153
                                       std::vector<RowSetSplits>* rs_splits,
154
0
                                       const CaptureRowsetOps& opts) {
155
0
    DBUG_EXECUTE_IF("CloudTablet.capture_rs_readers.return.e-230", {
156
0
        LOG_WARNING("CloudTablet.capture_rs_readers.return e-230").tag("tablet_id", tablet_id());
157
0
        return Status::Error<false>(-230, "injected error");
158
0
    });
159
0
    std::shared_lock rlock(_meta_lock);
160
0
    *rs_splits = DORIS_TRY(capture_rs_readers_unlocked(
161
0
            spec_version, CaptureRowsetOps {.skip_missing_versions = opts.skip_missing_versions}));
162
0
    return Status::OK();
163
0
}
164
165
[[nodiscard]] Result<std::vector<Version>> CloudTablet::capture_consistent_versions_unlocked(
166
33
        const Version& version_range, const CaptureRowsetOps& options) const {
167
33
    if (options.query_freshness_tolerance_ms > 0) {
168
20
        return capture_versions_with_freshness_tolerance(version_range, options);
169
20
    } else if (options.enable_prefer_cached_rowset && !enable_unique_key_merge_on_write()) {
170
13
        return capture_versions_prefer_cache(version_range);
171
13
    }
172
0
    return BaseTablet::capture_consistent_versions_unlocked(version_range, options);
173
33
}
174
175
Result<std::vector<Version>> CloudTablet::capture_versions_prefer_cache(
176
13
        const Version& spec_version) const {
177
13
    g_capture_prefer_cache_count << 1;
178
13
    Versions version_path;
179
13
    std::shared_lock rlock(_meta_lock);
180
13
    auto st = _timestamped_version_tracker.capture_consistent_versions_prefer_cache(
181
13
            spec_version, version_path,
182
92
            [&](int64_t start, int64_t end) { return rowset_is_warmed_up_unlocked(start, end); });
183
13
    if (!st.ok()) {
184
0
        return ResultError(st);
185
0
    }
186
13
    int64_t path_max_version = version_path.back().second;
187
13
    VLOG_DEBUG << fmt::format(
188
0
            "[verbose] CloudTablet::capture_versions_prefer_cache, capture path: {}, "
189
0
            "tablet_id={}, spec_version={}, path_max_version={}",
190
0
            fmt::join(version_path | std::views::transform([](const auto& version) {
191
0
                          return fmt::format("{}", version.to_string());
192
0
                      }),
193
0
                      ", "),
194
0
            tablet_id(), spec_version.to_string(), path_max_version);
195
13
    return version_path;
196
13
}
197
198
210
bool CloudTablet::rowset_is_warmed_up_unlocked(int64_t start_version, int64_t end_version) const {
199
210
    if (start_version > end_version) {
200
0
        return false;
201
0
    }
202
210
    Version version {start_version, end_version};
203
210
    auto it = _rs_version_map.find(version);
204
210
    if (it == _rs_version_map.end()) {
205
78
        it = _stale_rs_version_map.find(version);
206
78
        if (it == _stale_rs_version_map.end()) {
207
0
            LOG_WARNING(
208
0
                    "fail to find Rowset in rs_version or stale_rs_version for version. "
209
0
                    "tablet={}, version={}",
210
0
                    tablet_id(), version.to_string());
211
0
            return false;
212
0
        }
213
78
    }
214
210
    const auto& rs = it->second;
215
210
    if (rs->visible_timestamp() < _engine.startup_timepoint()) {
216
        // We only care about rowsets that are created after startup time point. For other rowsets,
217
        // we assume they are warmed up.
218
10
        return true;
219
10
    }
220
200
    return is_rowset_warmed_up(rs->rowset_id());
221
210
};
222
223
Result<std::vector<Version>> CloudTablet::capture_versions_with_freshness_tolerance(
224
20
        const Version& spec_version, const CaptureRowsetOps& options) const {
225
20
    g_capture_with_freshness_tolerance_count << 1;
226
20
    using namespace std::chrono;
227
20
    auto query_freshness_tolerance_ms = options.query_freshness_tolerance_ms;
228
20
    auto freshness_limit_tp = system_clock::now() - milliseconds(query_freshness_tolerance_ms);
229
    // find a version path where every edge(rowset) has been warmuped
230
20
    Versions version_path;
231
20
    std::shared_lock rlock(_meta_lock);
232
20
    if (enable_unique_key_merge_on_write()) {
233
        // For merge-on-write table, newly generated delete bitmap marks will be on the rowsets which are in newest layout.
234
        // So we can ony capture rowsets which are in newest data layout. Otherwise there may be data correctness issue.
235
11
        RETURN_IF_ERROR_RESULT(
236
11
                _timestamped_version_tracker.capture_consistent_versions_with_validator_mow(
237
11
                        spec_version, version_path, [&](int64_t start, int64_t end) {
238
11
                            return rowset_is_warmed_up_unlocked(start, end);
239
11
                        }));
240
11
    } else {
241
9
        RETURN_IF_ERROR_RESULT(
242
9
                _timestamped_version_tracker.capture_consistent_versions_with_validator(
243
9
                        spec_version, version_path, [&](int64_t start, int64_t end) {
244
9
                            return rowset_is_warmed_up_unlocked(start, end);
245
9
                        }));
246
9
    }
247
20
    int64_t path_max_version = version_path.back().second;
248
    // use std::views::concat after C++26
249
335
    auto check_fn = [this, path_max_version, freshness_limit_tp](const auto& rs_meta) {
250
335
        return _check_rowset_should_be_visible_but_not_warmed_up(rs_meta, path_max_version,
251
335
                                                                 freshness_limit_tp);
252
335
    };
253
20
    bool should_fallback =
254
20
            std::ranges::any_of(std::views::values(_tablet_meta->all_rs_metas()), check_fn) ||
255
20
            std::ranges::any_of(std::views::values(_tablet_meta->all_stale_rs_metas()), check_fn);
256
20
    if (should_fallback) {
257
5
        rlock.unlock();
258
5
        g_capture_with_freshness_tolerance_fallback_count << 1;
259
        // if there exists a rowset which satisfies freshness tolerance and its start version is larger than the path max version
260
        // but has not been warmuped up yet, fallback to capture rowsets as usual
261
5
        return BaseTablet::capture_consistent_versions_unlocked(spec_version, options);
262
5
    }
263
15
    VLOG_DEBUG << fmt::format(
264
0
            "[verbose] CloudTablet::capture_versions_with_freshness_tolerance, capture path: {}, "
265
0
            "tablet_id={}, spec_version={}, path_max_version={}",
266
0
            fmt::join(version_path | std::views::transform([](const auto& version) {
267
0
                          return fmt::format("{}", version.to_string());
268
0
                      }),
269
0
                      ", "),
270
0
            tablet_id(), spec_version.to_string(), path_max_version);
271
15
    return version_path;
272
20
}
273
274
// There are only two tablet_states RUNNING and NOT_READY in cloud mode
275
// This function will erase the tablet from `CloudTabletMgr` when it can't find this tablet in MS.
276
16
Status CloudTablet::sync_rowsets(const SyncOptions& options, SyncRowsetStats* stats) {
277
16
    RETURN_IF_ERROR(sync_if_not_running(stats));
278
279
16
    if (options.query_version > 0) {
280
0
        auto lock_start = std::chrono::steady_clock::now();
281
0
        std::shared_lock rlock(_meta_lock);
282
0
        if (stats) {
283
0
            stats->meta_lock_wait_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(
284
0
                                                std::chrono::steady_clock::now() - lock_start)
285
0
                                                .count();
286
0
        }
287
0
        if (_max_version >= options.query_version) {
288
0
            return Status::OK();
289
0
        }
290
0
    }
291
292
    // serially execute sync to reduce unnecessary network overhead
293
16
    auto sync_lock_start = std::chrono::steady_clock::now();
294
16
    std::unique_lock lock(_sync_meta_lock);
295
16
    if (stats) {
296
0
        stats->sync_meta_lock_wait_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(
297
0
                                                 std::chrono::steady_clock::now() - sync_lock_start)
298
0
                                                 .count();
299
0
    }
300
16
    if (options.query_version > 0) {
301
0
        auto lock_start = std::chrono::steady_clock::now();
302
0
        std::shared_lock rlock(_meta_lock);
303
0
        if (stats) {
304
0
            stats->meta_lock_wait_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(
305
0
                                                std::chrono::steady_clock::now() - lock_start)
306
0
                                                .count();
307
0
        }
308
0
        if (_max_version >= options.query_version) {
309
0
            return Status::OK();
310
0
        }
311
0
    }
312
313
16
    auto st = _engine.meta_mgr().sync_tablet_rowsets_unlocked(this, lock, options, stats);
314
16
    if (st.is<ErrorCode::NOT_FOUND>()) {
315
0
        clear_cache();
316
0
    }
317
318
16
    return st;
319
16
}
320
321
// Sync tablet meta and all rowset meta if not running.
322
// This could happen when BE didn't finish schema change job and another BE committed this schema change job.
323
// It should be a quite rare situation.
324
16
Status CloudTablet::sync_if_not_running(SyncRowsetStats* stats) {
325
16
    if (tablet_state() == TABLET_RUNNING) {
326
16
        return Status::OK();
327
16
    }
328
329
    // Serially execute sync to reduce unnecessary network overhead
330
0
    auto sync_lock_start = std::chrono::steady_clock::now();
331
0
    std::unique_lock lock(_sync_meta_lock);
332
0
    if (stats) {
333
0
        stats->sync_meta_lock_wait_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(
334
0
                                                 std::chrono::steady_clock::now() - sync_lock_start)
335
0
                                                 .count();
336
0
    }
337
338
0
    {
339
0
        auto lock_start = std::chrono::steady_clock::now();
340
0
        std::shared_lock rlock(_meta_lock);
341
0
        if (stats) {
342
0
            stats->meta_lock_wait_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(
343
0
                                                std::chrono::steady_clock::now() - lock_start)
344
0
                                                .count();
345
0
        }
346
0
        if (tablet_state() == TABLET_RUNNING) {
347
0
            return Status::OK();
348
0
        }
349
0
    }
350
351
0
    TabletMetaSharedPtr tablet_meta;
352
0
    auto st = _engine.meta_mgr().get_tablet_meta(tablet_id(), &tablet_meta);
353
0
    if (!st.ok()) {
354
0
        if (st.is<ErrorCode::NOT_FOUND>()) {
355
0
            clear_cache();
356
0
        }
357
0
        return st;
358
0
    }
359
360
0
    if (tablet_meta->tablet_state() != TABLET_RUNNING) [[unlikely]] {
361
        // MoW may go to here when load while schema change
362
0
        return Status::OK();
363
0
    }
364
365
0
    TimestampedVersionTracker empty_tracker;
366
0
    {
367
0
        auto lock_start = std::chrono::steady_clock::now();
368
0
        std::lock_guard wlock(_meta_lock);
369
0
        if (stats) {
370
0
            stats->meta_lock_wait_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(
371
0
                                                std::chrono::steady_clock::now() - lock_start)
372
0
                                                .count();
373
0
        }
374
0
        RETURN_IF_ERROR(set_tablet_state(TABLET_RUNNING));
375
0
        _rs_version_map.clear();
376
0
        _stale_rs_version_map.clear();
377
0
        std::swap(_timestamped_version_tracker, empty_tracker);
378
0
        _tablet_meta->clear_rowsets();
379
0
        _tablet_meta->clear_stale_rowset();
380
0
        _max_version = -1;
381
0
    }
382
383
0
    st = _engine.meta_mgr().sync_tablet_rowsets_unlocked(this, lock, {}, stats);
384
0
    if (st.is<ErrorCode::NOT_FOUND>()) {
385
0
        clear_cache();
386
0
    }
387
0
    return st;
388
0
}
389
390
void CloudTablet::add_rowsets(std::vector<RowsetSharedPtr> to_add, bool version_overlap,
391
                              std::unique_lock<std::shared_mutex>& meta_lock,
392
268
                              bool warmup_delta_data) {
393
268
    if (to_add.empty()) {
394
0
        return;
395
0
    }
396
397
268
    VLOG_DEBUG << "add_rowsets tablet_id=" << tablet_id() << " stack: " << get_stack_trace();
398
399
268
    if (!version_overlap) {
400
268
        _add_rowsets_directly(to_add, warmup_delta_data);
401
268
        return;
402
268
    }
403
404
    // Filter out existed rowsets
405
0
    auto remove_it =
406
0
            std::remove_if(to_add.begin(), to_add.end(), [this](const RowsetSharedPtr& rs) {
407
0
                if (auto find_it = _rs_version_map.find(rs->version());
408
0
                    find_it == _rs_version_map.end()) {
409
0
                    return false;
410
0
                } else if (find_it->second->rowset_id() == rs->rowset_id()) {
411
0
                    return true; // Same rowset
412
0
                }
413
414
                // If version of rowset in `to_add` is equal to rowset in tablet but rowset_id is not equal,
415
                // replace existed rowset with `to_add` rowset. This may occur when:
416
                //  1. schema change converts rowsets which have been double written to new tablet
417
                //  2. cumu compaction picks single overlapping input rowset to perform compaction
418
419
                // add existed rowset to unused_rowsets to remove delete bitmap and recycle cached data
420
421
0
                std::vector<RowsetSharedPtr> unused_rowsets;
422
0
                if (auto find_it = _rs_version_map.find(rs->version());
423
0
                    find_it != _rs_version_map.end()) {
424
0
                    if (find_it->second->rowset_id() == rs->rowset_id()) {
425
0
                        LOG(WARNING) << "tablet_id=" << tablet_id()
426
0
                                     << ", rowset_id=" << rs->rowset_id().to_string()
427
0
                                     << ", existed rowset_id="
428
0
                                     << find_it->second->rowset_id().to_string();
429
0
                        DCHECK(find_it->second->rowset_id() != rs->rowset_id())
430
0
                                << "tablet_id=" << tablet_id()
431
0
                                << ", rowset_id=" << rs->rowset_id().to_string()
432
0
                                << ", existed rowset_id="
433
0
                                << find_it->second->rowset_id().to_string();
434
0
                    }
435
0
                    unused_rowsets.push_back(find_it->second);
436
0
                }
437
0
                add_unused_rowsets(unused_rowsets);
438
439
0
                _tablet_meta->delete_rs_meta_by_version(rs->version(), nullptr);
440
0
                _rs_version_map[rs->version()] = rs;
441
0
                _tablet_meta->add_rowsets_unchecked({rs});
442
0
                update_base_size(*rs);
443
0
                return true;
444
0
            });
445
446
0
    to_add.erase(remove_it, to_add.end());
447
448
    // delete rowsets with overlapped version
449
0
    std::vector<RowsetSharedPtr> to_add_directly;
450
0
    for (auto& to_add_rs : to_add) {
451
        // delete rowsets with overlapped version
452
0
        std::vector<RowsetSharedPtr> to_delete;
453
0
        Version to_add_v = to_add_rs->version();
454
        // if start_version  > max_version, we can skip checking overlap here.
455
0
        if (to_add_v.first > _max_version) {
456
            // if start_version  > max_version, we can skip checking overlap here.
457
0
            to_add_directly.push_back(to_add_rs);
458
0
        } else {
459
0
            to_add_directly.push_back(to_add_rs);
460
0
            for (auto& [v, rs] : _rs_version_map) {
461
0
                if (to_add_v.contains(v)) {
462
0
                    to_delete.push_back(rs);
463
0
                }
464
0
            }
465
0
            delete_rowsets(to_delete, meta_lock);
466
0
        }
467
0
    }
468
469
0
    _add_rowsets_directly(to_add_directly, warmup_delta_data);
470
0
}
471
472
void CloudTablet::delete_rowsets(const std::vector<RowsetSharedPtr>& to_delete,
473
94
                                 std::unique_lock<std::shared_mutex>&) {
474
94
    if (to_delete.empty()) {
475
0
        return;
476
0
    }
477
94
    std::vector<RowsetMetaSharedPtr> rs_metas;
478
94
    rs_metas.reserve(to_delete.size());
479
94
    int64_t now = ::time(nullptr);
480
540
    for (auto&& rs : to_delete) {
481
540
        rs->rowset_meta()->set_stale_at(now);
482
540
        rs_metas.push_back(rs->rowset_meta());
483
540
        _stale_rs_version_map[rs->version()] = rs;
484
540
    }
485
94
    _timestamped_version_tracker.add_stale_path_version(rs_metas);
486
540
    for (auto&& rs : to_delete) {
487
540
        _rs_version_map.erase(rs->version());
488
540
    }
489
490
94
    _tablet_meta->modify_rs_metas({}, rs_metas, false);
491
94
}
492
493
0
uint64_t CloudTablet::delete_expired_stale_rowsets() {
494
0
    if (config::enable_mow_verbose_log) {
495
0
        LOG_INFO("begin delete_expired_stale_rowset for tablet={}", tablet_id());
496
0
    }
497
0
    std::vector<RowsetSharedPtr> expired_rowsets;
498
    // ATTN: trick, Use stale_rowsets to temporarily increase the reference count of the rowset shared pointer in _stale_rs_version_map so that in the recycle_cached_data function, it checks if the reference count is 2.
499
0
    std::vector<std::pair<Version, std::vector<RowsetSharedPtr>>> deleted_stale_rowsets;
500
0
    int64_t expired_stale_sweep_endtime =
501
0
            ::time(nullptr) - config::tablet_rowset_stale_sweep_time_sec;
502
0
    {
503
0
        std::unique_lock wlock(_meta_lock);
504
505
0
        std::vector<int64_t> path_ids;
506
        // capture the path version to delete
507
0
        _timestamped_version_tracker.capture_expired_paths(expired_stale_sweep_endtime, &path_ids);
508
509
0
        if (path_ids.empty()) {
510
0
            return 0;
511
0
        }
512
513
0
        for (int64_t path_id : path_ids) {
514
0
            int64_t start_version = -1;
515
0
            int64_t end_version = -1;
516
0
            std::vector<RowsetSharedPtr> stale_rowsets;
517
            // delete stale versions in version graph
518
0
            auto version_path = _timestamped_version_tracker.fetch_and_delete_path_by_id(path_id);
519
0
            for (auto& v_ts : version_path->timestamped_versions()) {
520
0
                auto rs_it = _stale_rs_version_map.find(v_ts->version());
521
0
                if (rs_it != _stale_rs_version_map.end()) {
522
0
                    expired_rowsets.push_back(rs_it->second);
523
0
                    stale_rowsets.push_back(rs_it->second);
524
0
                    VLOG_DEBUG << "erase stale rowset, tablet_id=" << tablet_id()
525
0
                               << " rowset_id=" << rs_it->second->rowset_id().to_string()
526
0
                               << " version=" << rs_it->first.to_string();
527
0
                    _stale_rs_version_map.erase(rs_it);
528
0
                } else {
529
0
                    LOG(WARNING) << "cannot find stale rowset " << v_ts->version() << " in tablet "
530
0
                                 << tablet_id();
531
                    // clang-format off
532
0
                    DCHECK(false) << [this, &wlock]() { wlock.unlock(); std::string json; get_compaction_status(&json); return json; }();
533
                    // clang-format on
534
0
                }
535
0
                if (start_version < 0) {
536
0
                    start_version = v_ts->version().first;
537
0
                }
538
0
                end_version = v_ts->version().second;
539
0
                _tablet_meta->delete_stale_rs_meta_by_version(v_ts->version());
540
0
            }
541
0
            Version version(start_version, end_version);
542
0
            if (!stale_rowsets.empty()) {
543
0
                deleted_stale_rowsets.emplace_back(version, std::move(stale_rowsets));
544
0
            }
545
0
        }
546
0
        _reconstruct_version_tracker_if_necessary();
547
0
    }
548
549
    // if the rowset is not used by any query, we can recycle its cached data early.
550
0
    auto recycled_rowsets = recycle_cached_data(expired_rowsets);
551
0
    if (!recycled_rowsets.empty()) {
552
0
        auto& manager = ExecEnv::GetInstance()->storage_engine().to_cloud().cloud_warm_up_manager();
553
0
        manager.recycle_cache(tablet_id(), recycled_rowsets);
554
0
    }
555
0
    if (config::enable_mow_verbose_log) {
556
0
        LOG_INFO("finish delete_expired_stale_rowset for tablet={}", tablet_id());
557
0
    }
558
559
0
    add_unused_rowsets(expired_rowsets);
560
0
    if (config::enable_agg_and_remove_pre_rowsets_delete_bitmap && keys_type() == UNIQUE_KEYS &&
561
0
        enable_unique_key_merge_on_write() && !deleted_stale_rowsets.empty()) {
562
        // agg delete bitmap for pre rowsets; record unused delete bitmap key ranges
563
0
        OlapStopWatch watch;
564
0
        for (const auto& [version, unused_rowsets] : deleted_stale_rowsets) {
565
            // agg delete bitmap for pre rowset
566
0
            DeleteBitmapKeyRanges remove_delete_bitmap_key_ranges;
567
0
            agg_delete_bitmap_for_stale_rowsets(version, remove_delete_bitmap_key_ranges);
568
            // add remove delete bitmap
569
0
            if (!remove_delete_bitmap_key_ranges.empty()) {
570
0
                std::vector<RowsetId> rowset_ids;
571
0
                for (const auto& rs : unused_rowsets) {
572
0
                    rowset_ids.push_back(rs->rowset_id());
573
0
                }
574
0
                std::lock_guard<std::mutex> lock(_gc_mutex);
575
0
                _unused_delete_bitmap.push_back(
576
0
                        std::make_pair(rowset_ids, remove_delete_bitmap_key_ranges));
577
0
            }
578
0
        }
579
0
        LOG(INFO) << "agg pre rowsets delete bitmap. tablet_id=" << tablet_id()
580
0
                  << ", size=" << deleted_stale_rowsets.size()
581
0
                  << ", cost(us)=" << watch.get_elapse_time_us();
582
0
    }
583
0
    return expired_rowsets.size();
584
0
}
585
586
0
bool CloudTablet::need_remove_unused_rowsets() {
587
0
    std::lock_guard<std::mutex> lock(_gc_mutex);
588
0
    return !_unused_rowsets.empty() || !_unused_delete_bitmap.empty();
589
0
}
590
591
0
void CloudTablet::add_unused_rowsets(const std::vector<RowsetSharedPtr>& rowsets) {
592
0
    std::lock_guard<std::mutex> lock(_gc_mutex);
593
0
    for (const auto& rowset : rowsets) {
594
0
        _unused_rowsets[rowset->rowset_id()] = rowset;
595
0
        g_unused_rowsets_bytes << rowset->total_disk_size();
596
0
    }
597
0
    g_unused_rowsets_count << rowsets.size();
598
0
}
599
600
0
void CloudTablet::remove_unused_rowsets() {
601
0
    std::vector<std::shared_ptr<Rowset>> removed_rowsets;
602
0
    int64_t removed_delete_bitmap_num = 0;
603
0
    OlapStopWatch watch;
604
0
    {
605
0
        std::lock_guard<std::mutex> lock(_gc_mutex);
606
        // 1. remove unused rowsets's cache data and delete bitmap
607
0
        for (auto it = _unused_rowsets.begin(); it != _unused_rowsets.end();) {
608
0
            auto& rs = it->second;
609
0
            if (rs.use_count() > 1) {
610
0
                LOG(WARNING) << "tablet_id:" << tablet_id() << " rowset: " << rs->rowset_id()
611
0
                             << " has " << rs.use_count() << " references, it cannot be removed";
612
0
                ++it;
613
0
                continue;
614
0
            }
615
0
            tablet_meta()->remove_rowset_delete_bitmap(rs->rowset_id(), rs->version());
616
0
            _rowset_warm_up_states.erase(rs->rowset_id());
617
0
            rs->clear_cache();
618
0
            g_unused_rowsets_count << -1;
619
0
            g_unused_rowsets_bytes << -rs->total_disk_size();
620
0
            removed_rowsets.push_back(std::move(rs));
621
0
            it = _unused_rowsets.erase(it);
622
0
        }
623
0
    }
624
625
0
    {
626
0
        std::vector<RecycledRowsets> recycled_rowsets;
627
628
0
        for (auto& rs : removed_rowsets) {
629
0
            auto index_names = rs->get_index_file_names();
630
0
            recycled_rowsets.emplace_back(rs->rowset_id(), rs->num_segments(), index_names);
631
0
            int64_t segment_size_sum = 0;
632
0
            for (int32_t i = 0; i < rs->num_segments(); i++) {
633
0
                segment_size_sum += rs->rowset_meta()->segment_file_size(i);
634
0
            }
635
0
            g_file_cache_recycle_cached_data_segment_num << rs->num_segments();
636
0
            g_file_cache_recycle_cached_data_segment_size << segment_size_sum;
637
0
            g_file_cache_recycle_cached_data_index_num << index_names.size();
638
0
        }
639
640
0
        if (recycled_rowsets.size() > 0) {
641
0
            auto& manager =
642
0
                    ExecEnv::GetInstance()->storage_engine().to_cloud().cloud_warm_up_manager();
643
0
            manager.recycle_cache(tablet_id(), recycled_rowsets);
644
0
        }
645
0
    }
646
647
0
    {
648
0
        std::lock_guard<std::mutex> lock(_gc_mutex);
649
        // 2. remove delete bitmap of pre rowsets
650
0
        for (auto it = _unused_delete_bitmap.begin(); it != _unused_delete_bitmap.end();) {
651
0
            auto& rowset_ids = std::get<0>(*it);
652
0
            bool find_unused_rowset = false;
653
0
            for (const auto& rowset_id : rowset_ids) {
654
0
                if (_unused_rowsets.find(rowset_id) != _unused_rowsets.end()) {
655
0
                    LOG(INFO) << "can not remove pre rowset delete bitmap because rowset is in use"
656
0
                              << ", tablet_id=" << tablet_id() << ", rowset_id=" << rowset_id;
657
0
                    find_unused_rowset = true;
658
0
                    break;
659
0
                }
660
0
            }
661
0
            if (find_unused_rowset) {
662
0
                ++it;
663
0
                continue;
664
0
            }
665
0
            auto& key_ranges = std::get<1>(*it);
666
0
            tablet_meta()->delete_bitmap().remove(key_ranges);
667
0
            it = _unused_delete_bitmap.erase(it);
668
0
            removed_delete_bitmap_num++;
669
            // TODO(kaijie): recycle cache for unused delete bitmap
670
0
        }
671
0
    }
672
673
0
    LOG(INFO) << "tablet_id=" << tablet_id() << ", unused_rowset size=" << _unused_rowsets.size()
674
0
              << ", unused_delete_bitmap size=" << _unused_delete_bitmap.size()
675
0
              << ", removed_rowsets_num=" << removed_rowsets.size()
676
0
              << ", removed_delete_bitmap_num=" << removed_delete_bitmap_num
677
0
              << ", cost(us)=" << watch.get_elapse_time_us();
678
0
}
679
680
760
void CloudTablet::update_base_size(const Rowset& rs) {
681
    // Define base rowset as the rowset of version [2-x]
682
760
    if (rs.start_version() == 2) {
683
107
        _base_size = rs.total_disk_size();
684
107
    }
685
760
}
686
687
0
void CloudTablet::clear_cache() {
688
0
    auto recycled_rowsets = CloudTablet::recycle_cached_data(get_snapshot_rowset(true));
689
0
    if (!recycled_rowsets.empty()) {
690
0
        auto& manager = ExecEnv::GetInstance()->storage_engine().to_cloud().cloud_warm_up_manager();
691
0
        manager.recycle_cache(tablet_id(), recycled_rowsets);
692
0
    }
693
0
    _engine.tablet_mgr().erase_tablet(tablet_id());
694
0
}
695
696
std::vector<RecycledRowsets> CloudTablet::recycle_cached_data(
697
0
        const std::vector<RowsetSharedPtr>& rowsets) {
698
0
    std::vector<RecycledRowsets> recycled_rowsets;
699
0
    for (const auto& rs : rowsets) {
700
        // rowsets and tablet._rs_version_map each hold a rowset shared_ptr, so at this point, the reference count of the shared_ptr is at least 2.
701
0
        if (rs.use_count() > 2) {
702
0
            LOG(WARNING) << "Rowset " << rs->rowset_id().to_string() << " has " << rs.use_count()
703
0
                         << " references. File Cache won't be recycled when query is using it.";
704
0
            continue;
705
0
        }
706
0
        rs->clear_cache();
707
0
        auto index_names = rs->get_index_file_names();
708
0
        recycled_rowsets.emplace_back(rs->rowset_id(), rs->num_segments(), index_names);
709
710
0
        int64_t segment_size_sum = 0;
711
0
        for (int32_t i = 0; i < rs->num_segments(); i++) {
712
0
            segment_size_sum += rs->rowset_meta()->segment_file_size(i);
713
0
        }
714
0
        g_file_cache_recycle_cached_data_segment_num << rs->num_segments();
715
0
        g_file_cache_recycle_cached_data_segment_size << segment_size_sum;
716
0
        g_file_cache_recycle_cached_data_index_num << index_names.size();
717
0
    }
718
0
    return recycled_rowsets;
719
0
}
720
721
void CloudTablet::reset_approximate_stats(int64_t num_rowsets, int64_t num_segments,
722
0
                                          int64_t num_rows, int64_t data_size) {
723
0
    _approximate_num_segments.store(num_segments, std::memory_order_relaxed);
724
0
    _approximate_num_rows.store(num_rows, std::memory_order_relaxed);
725
0
    _approximate_data_size.store(data_size, std::memory_order_relaxed);
726
0
    int64_t cumu_num_deltas = 0;
727
0
    int64_t cumu_num_rowsets = 0;
728
0
    auto cp = _cumulative_point.load(std::memory_order_relaxed);
729
0
    for (auto& [v, r] : _rs_version_map) {
730
0
        if (v.second < cp) {
731
0
            continue;
732
0
        }
733
0
        cumu_num_deltas += r->is_segments_overlapping() ? r->num_segments() : 1;
734
0
        ++cumu_num_rowsets;
735
0
    }
736
    // num_rowsets may be less than the size of _rs_version_map when there are some hole rowsets
737
    // in the version map, so we use the max value to ensure that the approximate number
738
    // of rowsets is at least the size of _rs_version_map.
739
    // Note that this is not the exact number of rowsets, but an approximate number.
740
0
    int64_t approximate_num_rowsets =
741
0
            std::max(num_rowsets, static_cast<int64_t>(_rs_version_map.size()));
742
0
    _approximate_num_rowsets.store(approximate_num_rowsets, std::memory_order_relaxed);
743
0
    _approximate_cumu_num_rowsets.store(cumu_num_rowsets, std::memory_order_relaxed);
744
0
    _approximate_cumu_num_deltas.store(cumu_num_deltas, std::memory_order_relaxed);
745
0
}
746
747
Result<std::unique_ptr<RowsetWriter>> CloudTablet::create_rowset_writer(
748
0
        RowsetWriterContext& context, bool vertical) {
749
0
    context.rowset_id = _engine.next_rowset_id();
750
    // FIXME(plat1ko): Seems `tablet_id` and `index_id` has been set repeatedly
751
0
    context.tablet_id = tablet_id();
752
0
    context.index_id = index_id();
753
0
    context.partition_id = partition_id();
754
0
    context.enable_unique_key_merge_on_write = enable_unique_key_merge_on_write();
755
0
    context.encrypt_algorithm = tablet_meta()->encryption_algorithm();
756
0
    return RowsetFactory::create_rowset_writer(_engine, context, vertical);
757
0
}
758
759
// create a rowset writer with rowset_id and seg_id
760
// after writer, merge this transient rowset with original rowset
761
Result<std::unique_ptr<RowsetWriter>> CloudTablet::create_transient_rowset_writer(
762
        const Rowset& rowset, std::shared_ptr<PartialUpdateInfo> partial_update_info,
763
0
        int64_t txn_expiration) {
764
0
    if (rowset.rowset_meta_state() != RowsetStatePB::BEGIN_PARTIAL_UPDATE &&
765
0
        rowset.rowset_meta_state() != RowsetStatePB::COMMITTED) [[unlikely]] {
766
0
        auto msg = fmt::format(
767
0
                "wrong rowset state when create_transient_rowset_writer, rowset state should be "
768
0
                "BEGIN_PARTIAL_UPDATE or COMMITTED, but found {}, rowset_id={}, tablet_id={}",
769
0
                RowsetStatePB_Name(rowset.rowset_meta_state()), rowset.rowset_id().to_string(),
770
0
                tablet_id());
771
        // see `CloudRowsetWriter::build` for detail.
772
        // if this is in a retry task, the rowset state may have been changed to RowsetStatePB::COMMITTED
773
        // in `RowsetMeta::merge_rowset_meta()` in previous trials.
774
0
        LOG(WARNING) << msg;
775
0
        DCHECK(false) << msg;
776
0
    }
777
0
    RowsetWriterContext context;
778
0
    context.rowset_state = PREPARED;
779
0
    context.segments_overlap = OVERLAPPING;
780
    // During a partial update, the extracted columns of a variant should not be included in the tablet schema.
781
    // This is because the partial update for a variant needs to ignore the extracted columns.
782
    // Otherwise, the schema types in different rowsets might be inconsistent. When performing a partial update,
783
    // the complete variant is constructed by reading all the sub-columns of the variant.
784
0
    context.tablet_schema = rowset.tablet_schema()->copy_without_variant_extracted_columns();
785
0
    context.newest_write_timestamp = UnixSeconds();
786
0
    context.tablet_id = table_id();
787
0
    context.enable_segcompaction = false;
788
0
    context.write_type = DataWriteType::TYPE_DIRECT;
789
0
    context.partial_update_info = std::move(partial_update_info);
790
0
    context.is_transient_rowset_writer = true;
791
0
    context.rowset_id = rowset.rowset_id();
792
0
    context.tablet_id = tablet_id();
793
0
    context.index_id = index_id();
794
0
    context.partition_id = partition_id();
795
0
    context.enable_unique_key_merge_on_write = enable_unique_key_merge_on_write();
796
0
    context.txn_expiration = txn_expiration;
797
0
    context.encrypt_algorithm = tablet_meta()->encryption_algorithm();
798
    // TODO(liaoxin) enable packed file for transient rowset
799
0
    context.allow_packed_file = false;
800
801
0
    auto storage_resource = rowset.rowset_meta()->remote_storage_resource();
802
0
    if (!storage_resource) {
803
0
        return ResultError(std::move(storage_resource.error()));
804
0
    }
805
806
0
    context.storage_resource = *storage_resource.value();
807
808
0
    return RowsetFactory::create_rowset_writer(_engine, context, false)
809
0
            .transform([&](auto&& writer) {
810
0
                writer->set_segment_start_id(cast_set<int32_t>(rowset.num_segments()));
811
0
                return writer;
812
0
            });
813
0
}
814
815
3
int64_t CloudTablet::get_cloud_base_compaction_score() const {
816
3
    if (_tablet_meta->compaction_policy() == CUMULATIVE_TIME_SERIES_POLICY) {
817
0
        bool has_delete = false;
818
0
        int64_t point = cumulative_layer_point();
819
0
        std::shared_lock<std::shared_mutex> rlock(_meta_lock);
820
0
        for (const auto& [_, rs_meta] : _tablet_meta->all_rs_metas()) {
821
0
            if (rs_meta->start_version() >= point) {
822
0
                continue;
823
0
            }
824
0
            if (rs_meta->has_delete_predicate()) {
825
0
                has_delete = true;
826
0
                break;
827
0
            }
828
0
        }
829
0
        if (!has_delete) {
830
0
            return 0;
831
0
        }
832
0
    }
833
834
3
    return _approximate_num_rowsets.load(std::memory_order_relaxed) -
835
3
           _approximate_cumu_num_rowsets.load(std::memory_order_relaxed);
836
3
}
837
838
1
int64_t CloudTablet::get_cloud_cumu_compaction_score() const {
839
    // TODO(plat1ko): Propose an algorithm that considers tablet's key type, number of delete rowsets,
840
    //  number of tablet versions simultaneously.
841
1
    return _approximate_cumu_num_deltas.load(std::memory_order_relaxed);
842
1
}
843
844
// return a json string to show the compaction status of this tablet
845
33
void CloudTablet::get_compaction_status(std::string* json_result) {
846
33
    rapidjson::Document root;
847
33
    root.SetObject();
848
849
33
    rapidjson::Document path_arr;
850
33
    path_arr.SetArray();
851
852
33
    std::vector<RowsetSharedPtr> rowsets;
853
33
    std::vector<RowsetSharedPtr> stale_rowsets;
854
33
    {
855
33
        std::shared_lock rdlock(_meta_lock);
856
33
        rowsets.reserve(_rs_version_map.size());
857
148
        for (auto& it : _rs_version_map) {
858
148
            rowsets.push_back(it.second);
859
148
        }
860
33
        stale_rowsets.reserve(_stale_rs_version_map.size());
861
540
        for (auto& it : _stale_rs_version_map) {
862
540
            stale_rowsets.push_back(it.second);
863
540
        }
864
33
    }
865
33
    std::sort(rowsets.begin(), rowsets.end(), Rowset::comparator);
866
33
    std::sort(stale_rowsets.begin(), stale_rowsets.end(), Rowset::comparator);
867
868
    // get snapshot version path json_doc
869
33
    _timestamped_version_tracker.get_stale_version_path_json_doc(path_arr);
870
33
    root.AddMember("cumulative point", _cumulative_point.load(), root.GetAllocator());
871
33
    rapidjson::Value cumu_value;
872
33
    std::string format_str = ToStringFromUnixMillis(_last_cumu_compaction_failure_millis.load());
873
33
    cumu_value.SetString(format_str.c_str(), cast_set<uint>(format_str.length()),
874
33
                         root.GetAllocator());
875
33
    root.AddMember("last cumulative failure time", cumu_value, root.GetAllocator());
876
33
    rapidjson::Value base_value;
877
33
    format_str = ToStringFromUnixMillis(_last_base_compaction_failure_millis.load());
878
33
    base_value.SetString(format_str.c_str(), cast_set<uint>(format_str.length()),
879
33
                         root.GetAllocator());
880
33
    root.AddMember("last base failure time", base_value, root.GetAllocator());
881
33
    rapidjson::Value full_value;
882
33
    format_str = ToStringFromUnixMillis(_last_full_compaction_failure_millis.load());
883
33
    full_value.SetString(format_str.c_str(), cast_set<uint>(format_str.length()),
884
33
                         root.GetAllocator());
885
33
    root.AddMember("last full failure time", full_value, root.GetAllocator());
886
33
    rapidjson::Value cumu_success_value;
887
33
    format_str = ToStringFromUnixMillis(_last_cumu_compaction_success_millis.load());
888
33
    cumu_success_value.SetString(format_str.c_str(), cast_set<uint>(format_str.length()),
889
33
                                 root.GetAllocator());
890
33
    root.AddMember("last cumulative success time", cumu_success_value, root.GetAllocator());
891
33
    rapidjson::Value base_success_value;
892
33
    format_str = ToStringFromUnixMillis(_last_base_compaction_success_millis.load());
893
33
    base_success_value.SetString(format_str.c_str(), cast_set<uint>(format_str.length()),
894
33
                                 root.GetAllocator());
895
33
    root.AddMember("last base success time", base_success_value, root.GetAllocator());
896
33
    rapidjson::Value full_success_value;
897
33
    format_str = ToStringFromUnixMillis(_last_full_compaction_success_millis.load());
898
33
    full_success_value.SetString(format_str.c_str(), cast_set<uint>(format_str.length()),
899
33
                                 root.GetAllocator());
900
33
    root.AddMember("last full success time", full_success_value, root.GetAllocator());
901
33
    rapidjson::Value cumu_schedule_value;
902
33
    format_str = ToStringFromUnixMillis(_last_cumu_compaction_schedule_millis.load());
903
33
    cumu_schedule_value.SetString(format_str.c_str(), cast_set<uint>(format_str.length()),
904
33
                                  root.GetAllocator());
905
33
    root.AddMember("last cumulative schedule time", cumu_schedule_value, root.GetAllocator());
906
33
    rapidjson::Value base_schedule_value;
907
33
    format_str = ToStringFromUnixMillis(_last_base_compaction_schedule_millis.load());
908
33
    base_schedule_value.SetString(format_str.c_str(), cast_set<uint>(format_str.length()),
909
33
                                  root.GetAllocator());
910
33
    root.AddMember("last base schedule time", base_schedule_value, root.GetAllocator());
911
33
    rapidjson::Value full_schedule_value;
912
33
    format_str = ToStringFromUnixMillis(_last_full_compaction_schedule_millis.load());
913
33
    full_schedule_value.SetString(format_str.c_str(), cast_set<uint>(format_str.length()),
914
33
                                  root.GetAllocator());
915
33
    root.AddMember("last full schedule time", full_schedule_value, root.GetAllocator());
916
33
    rapidjson::Value cumu_compaction_status_value;
917
33
    cumu_compaction_status_value.SetString(_last_cumu_compaction_status.c_str(),
918
33
                                           cast_set<uint>(_last_cumu_compaction_status.length()),
919
33
                                           root.GetAllocator());
920
33
    root.AddMember("last cumulative status", cumu_compaction_status_value, root.GetAllocator());
921
33
    rapidjson::Value base_compaction_status_value;
922
33
    base_compaction_status_value.SetString(_last_base_compaction_status.c_str(),
923
33
                                           cast_set<uint>(_last_base_compaction_status.length()),
924
33
                                           root.GetAllocator());
925
33
    root.AddMember("last base status", base_compaction_status_value, root.GetAllocator());
926
33
    rapidjson::Value full_compaction_status_value;
927
33
    full_compaction_status_value.SetString(_last_full_compaction_status.c_str(),
928
33
                                           cast_set<uint>(_last_full_compaction_status.length()),
929
33
                                           root.GetAllocator());
930
33
    root.AddMember("last full status", full_compaction_status_value, root.GetAllocator());
931
33
    rapidjson::Value exec_compaction_time;
932
33
    std::string num_str {std::to_string(exec_compaction_time_us.load())};
933
33
    exec_compaction_time.SetString(num_str.c_str(), cast_set<uint>(num_str.length()),
934
33
                                   root.GetAllocator());
935
33
    root.AddMember("exec compaction time us", exec_compaction_time, root.GetAllocator());
936
33
    rapidjson::Value local_read_time;
937
33
    num_str = std::to_string(local_read_time_us.load());
938
33
    local_read_time.SetString(num_str.c_str(), cast_set<uint>(num_str.length()),
939
33
                              root.GetAllocator());
940
33
    root.AddMember("compaction local read time us", local_read_time, root.GetAllocator());
941
33
    rapidjson::Value remote_read_time;
942
33
    num_str = std::to_string(remote_read_time_us.load());
943
33
    remote_read_time.SetString(num_str.c_str(), cast_set<uint>(num_str.length()),
944
33
                               root.GetAllocator());
945
33
    root.AddMember("compaction remote read time us", remote_read_time, root.GetAllocator());
946
947
    // print all rowsets' version as an array
948
33
    rapidjson::Document versions_arr;
949
33
    rapidjson::Document missing_versions_arr;
950
33
    versions_arr.SetArray();
951
33
    missing_versions_arr.SetArray();
952
33
    int64_t last_version = -1;
953
148
    for (auto& rowset : rowsets) {
954
148
        const Version& ver = rowset->version();
955
148
        if (ver.first != last_version + 1) {
956
0
            rapidjson::Value miss_value;
957
0
            miss_value.SetString(fmt::format("[{}-{}]", last_version + 1, ver.first - 1).c_str(),
958
0
                                 missing_versions_arr.GetAllocator());
959
0
            missing_versions_arr.PushBack(miss_value, missing_versions_arr.GetAllocator());
960
0
        }
961
148
        rapidjson::Value value;
962
148
        std::string version_str = rowset->get_rowset_info_str();
963
148
        value.SetString(version_str.c_str(), cast_set<uint32_t>(version_str.length()),
964
148
                        versions_arr.GetAllocator());
965
148
        versions_arr.PushBack(value, versions_arr.GetAllocator());
966
148
        last_version = ver.second;
967
148
    }
968
33
    root.AddMember("rowsets", versions_arr, root.GetAllocator());
969
33
    root.AddMember("missing_rowsets", missing_versions_arr, root.GetAllocator());
970
971
    // print all stale rowsets' version as an array
972
33
    rapidjson::Document stale_versions_arr;
973
33
    stale_versions_arr.SetArray();
974
540
    for (auto& rowset : stale_rowsets) {
975
540
        rapidjson::Value value;
976
540
        std::string version_str = rowset->get_rowset_info_str();
977
540
        value.SetString(version_str.c_str(), cast_set<uint32_t>(version_str.length()),
978
540
                        stale_versions_arr.GetAllocator());
979
540
        stale_versions_arr.PushBack(value, stale_versions_arr.GetAllocator());
980
540
    }
981
33
    root.AddMember("stale_rowsets", stale_versions_arr, root.GetAllocator());
982
983
    // add stale version rowsets
984
33
    root.AddMember("stale version path", path_arr, root.GetAllocator());
985
986
    // to json string
987
33
    rapidjson::StringBuffer strbuf;
988
33
    rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(strbuf);
989
33
    root.Accept(writer);
990
33
    *json_result = std::string(strbuf.GetString());
991
33
}
992
993
0
void CloudTablet::set_cumulative_layer_point(int64_t new_point) {
994
0
    if (new_point == Tablet::K_INVALID_CUMULATIVE_POINT || new_point >= _cumulative_point) {
995
0
        _cumulative_point = new_point;
996
0
        return;
997
0
    }
998
    // cumulative point should only be reset to -1, or be increased
999
    // FIXME: could happen in currently unresolved race conditions
1000
0
    LOG(WARNING) << "Unexpected cumulative point: " << new_point
1001
0
                 << ", origin: " << _cumulative_point.load();
1002
0
}
1003
1004
Status CloudTablet::check_rowset_schema_for_build_index(std::vector<TColumn>& columns,
1005
10
                                                        int schema_version) {
1006
10
    std::map<std::string, TabletColumn> fe_col_map;
1007
14
    for (int i = 0; i < columns.size(); i++) {
1008
4
        fe_col_map[columns[i].column_name] = TabletColumn(columns[i]);
1009
4
    }
1010
1011
10
    std::shared_lock rlock(_meta_lock);
1012
10
    for (const auto& [version, rs] : _rs_version_map) {
1013
4
        if (version.first == 0) {
1014
0
            continue;
1015
0
        }
1016
1017
4
        if (rs->tablet_schema()->schema_version() >= schema_version) {
1018
0
            continue;
1019
0
        }
1020
1021
4
        for (auto rs_col : rs->tablet_schema()->columns()) {
1022
4
            auto find_ret = fe_col_map.find(rs_col->name());
1023
4
            if (find_ret == fe_col_map.end()) {
1024
1
                return Status::InternalError(
1025
1
                        "check rowset meta failed:rowset's col is dropped in FE.");
1026
1
            }
1027
1028
3
            if (rs_col->unique_id() != find_ret->second.unique_id()) {
1029
1
                return Status::InternalError("check rowset meta failed:col id not match.");
1030
1
            }
1031
1032
2
            if (rs_col->type() != find_ret->second.type()) {
1033
1
                return Status::InternalError("check rowset meta failed:col type not match.");
1034
1
            }
1035
2
        }
1036
4
    }
1037
1038
7
    return Status::OK();
1039
10
}
1040
1041
Result<RowsetSharedPtr> CloudTablet::pick_a_rowset_for_index_change(int schema_version,
1042
9
                                                                    bool& is_base_rowset) {
1043
9
    TEST_SYNC_POINT_RETURN_WITH_VALUE("CloudTablet::pick_a_rowset_for_index_change",
1044
2
                                      Result<RowsetSharedPtr>(nullptr));
1045
2
    RowsetSharedPtr ret_rowset = nullptr;
1046
2
    std::shared_lock rlock(_meta_lock);
1047
2
    for (const auto& [version, rs] : _rs_version_map) {
1048
2
        if (version.first == 0) {
1049
0
            continue;
1050
0
        }
1051
2
        if (rs->num_rows() == 0) {
1052
1
            VLOG_DEBUG << "[index_change]find empty rs, index change may "
1053
0
                          "failed, id="
1054
0
                       << rs->rowset_id().to_string();
1055
1
        }
1056
1057
2
        if (rs->tablet_schema()->schema_version() >= schema_version) {
1058
2
            VLOG_DEBUG << "[index_change] skip rowset " << rs->tablet_schema()->schema_version()
1059
0
                       << "," << schema_version;
1060
2
            continue;
1061
2
        }
1062
1063
0
        if (ret_rowset == nullptr) {
1064
0
            ret_rowset = rs;
1065
0
            continue;
1066
0
        }
1067
1068
0
        if (rs->start_version() > ret_rowset->start_version()) {
1069
0
            ret_rowset = rs;
1070
0
        }
1071
0
    }
1072
1073
2
    if (ret_rowset != nullptr) {
1074
0
        is_base_rowset = ret_rowset->version().first < _cumulative_point;
1075
0
    }
1076
1077
2
    return ret_rowset;
1078
9
}
1079
1080
0
std::vector<RowsetSharedPtr> CloudTablet::pick_candidate_rowsets_to_base_compaction() {
1081
0
    std::vector<RowsetSharedPtr> candidate_rowsets;
1082
0
    {
1083
0
        std::shared_lock rlock(_meta_lock);
1084
0
        for (const auto& [version, rs] : _rs_version_map) {
1085
0
            if (version.first != 0 && version.first < _cumulative_point &&
1086
0
                (_alter_version == -1 || version.second <= _alter_version)) {
1087
0
                candidate_rowsets.push_back(rs);
1088
0
            }
1089
0
        }
1090
0
    }
1091
0
    std::sort(candidate_rowsets.begin(), candidate_rowsets.end(), Rowset::comparator);
1092
0
    return candidate_rowsets;
1093
0
}
1094
1095
0
std::vector<RowsetSharedPtr> CloudTablet::pick_candidate_rowsets_to_full_compaction() {
1096
0
    std::vector<RowsetSharedPtr> candidate_rowsets;
1097
0
    {
1098
0
        std::shared_lock rlock(_meta_lock);
1099
0
        for (auto& [v, rs] : _rs_version_map) {
1100
            // MUST NOT compact rowset [0-1] for some historical reasons (see cloud_schema_change)
1101
0
            if (v.first != 0) {
1102
0
                candidate_rowsets.push_back(rs);
1103
0
            }
1104
0
        }
1105
0
    }
1106
0
    std::sort(candidate_rowsets.begin(), candidate_rowsets.end(), Rowset::comparator);
1107
0
    return candidate_rowsets;
1108
0
}
1109
1110
0
CalcDeleteBitmapExecutor* CloudTablet::calc_delete_bitmap_executor() {
1111
0
    return _engine.calc_delete_bitmap_executor();
1112
0
}
1113
1114
Status CloudTablet::save_delete_bitmap(const TabletTxnInfo* txn_info, int64_t txn_id,
1115
                                       DeleteBitmapPtr delete_bitmap, RowsetWriter* rowset_writer,
1116
                                       const RowsetIdUnorderedSet& cur_rowset_ids, int64_t lock_id,
1117
0
                                       int64_t next_visible_version) {
1118
0
    RowsetSharedPtr rowset = txn_info->rowset;
1119
0
    int64_t cur_version = rowset->start_version();
1120
    // update delete bitmap info, in order to avoid recalculation when trying again
1121
0
    RETURN_IF_ERROR(_engine.txn_delete_bitmap_cache().update_tablet_txn_info(
1122
0
            txn_id, tablet_id(), delete_bitmap, cur_rowset_ids, PublishStatus::PREPARE));
1123
1124
0
    if (txn_info->partial_update_info && txn_info->partial_update_info->is_partial_update() &&
1125
0
        rowset_writer->num_rows() > 0) {
1126
0
        DBUG_EXECUTE_IF("CloudTablet::save_delete_bitmap.update_tmp_rowset.error", {
1127
0
            return Status::InternalError<false>("injected update_tmp_rowset error.");
1128
0
        });
1129
0
        const auto& rowset_meta = rowset->rowset_meta();
1130
0
        RETURN_IF_ERROR(_engine.meta_mgr().update_tmp_rowset(*rowset_meta));
1131
0
    }
1132
1133
0
    RETURN_IF_ERROR(save_delete_bitmap_to_ms(cur_version, txn_id, delete_bitmap, lock_id,
1134
0
                                             next_visible_version, rowset));
1135
1136
    // store the delete bitmap with sentinel marks in txn_delete_bitmap_cache because if the txn is retried for some reason,
1137
    // it will use the delete bitmap from txn_delete_bitmap_cache when re-calculating the delete bitmap, during which it will do
1138
    // delete bitmap correctness check. If we store the new_delete_bitmap, the delete bitmap correctness check will fail
1139
0
    RETURN_IF_ERROR(_engine.txn_delete_bitmap_cache().update_tablet_txn_info(
1140
0
            txn_id, tablet_id(), delete_bitmap, cur_rowset_ids, PublishStatus::SUCCEED,
1141
0
            txn_info->publish_info));
1142
1143
0
    DBUG_EXECUTE_IF("CloudTablet::save_delete_bitmap.enable_sleep", {
1144
0
        auto sleep_sec = dp->param<int>("sleep", 5);
1145
0
        std::this_thread::sleep_for(std::chrono::seconds(sleep_sec));
1146
0
    });
1147
1148
0
    DBUG_EXECUTE_IF("CloudTablet::save_delete_bitmap.injected_error", {
1149
0
        auto retry = dp->param<bool>("retry", false);
1150
0
        auto sleep_sec = dp->param<int>("sleep", 0);
1151
0
        std::this_thread::sleep_for(std::chrono::seconds(sleep_sec));
1152
0
        if (retry) { // return DELETE_BITMAP_LOCK_ERROR to let it retry
1153
0
            return Status::Error<ErrorCode::DELETE_BITMAP_LOCK_ERROR>(
1154
0
                    "injected DELETE_BITMAP_LOCK_ERROR");
1155
0
        } else {
1156
0
            return Status::InternalError<false>("injected non-retryable error");
1157
0
        }
1158
0
    });
1159
1160
0
    return Status::OK();
1161
0
}
1162
1163
Status CloudTablet::save_delete_bitmap_to_ms(int64_t cur_version, int64_t txn_id,
1164
                                             DeleteBitmapPtr delete_bitmap, int64_t lock_id,
1165
0
                                             int64_t next_visible_version, RowsetSharedPtr rowset) {
1166
0
    DeleteBitmapPtr new_delete_bitmap = std::make_shared<DeleteBitmap>(tablet_id());
1167
0
    for (auto iter = delete_bitmap->delete_bitmap.begin();
1168
0
         iter != delete_bitmap->delete_bitmap.end(); ++iter) {
1169
        // skip sentinel mark, which is used for delete bitmap correctness check
1170
0
        if (std::get<1>(iter->first) != DeleteBitmap::INVALID_SEGMENT_ID) {
1171
0
            new_delete_bitmap->merge(
1172
0
                    {std::get<0>(iter->first), std::get<1>(iter->first), cur_version},
1173
0
                    iter->second);
1174
0
        }
1175
0
    }
1176
    // lock_id != -1 means this is in an explict txn
1177
0
    bool is_explicit_txn = (lock_id != -1);
1178
0
    auto ms_lock_id = !is_explicit_txn ? txn_id : lock_id;
1179
0
    std::optional<StorageResource> storage_resource;
1180
0
    auto storage_resource_result = rowset->rowset_meta()->remote_storage_resource();
1181
0
    if (storage_resource_result) {
1182
0
        storage_resource = *storage_resource_result.value();
1183
0
    }
1184
0
    RETURN_IF_ERROR(_engine.meta_mgr().update_delete_bitmap(
1185
0
            *this, ms_lock_id, LOAD_INITIATOR_ID, new_delete_bitmap.get(), new_delete_bitmap.get(),
1186
0
            rowset->rowset_id().to_string(), storage_resource,
1187
0
            config::delete_bitmap_store_write_version, txn_id, is_explicit_txn,
1188
0
            next_visible_version));
1189
0
    return Status::OK();
1190
0
}
1191
1192
0
Versions CloudTablet::calc_missed_versions(int64_t spec_version, Versions existing_versions) const {
1193
0
    DCHECK(spec_version > 0) << "invalid spec_version: " << spec_version;
1194
1195
    // sort the existing versions in ascending order
1196
0
    std::sort(existing_versions.begin(), existing_versions.end(),
1197
0
              [](const Version& a, const Version& b) {
1198
                  // simple because 2 versions are certainly not overlapping
1199
0
                  return a.first < b.first;
1200
0
              });
1201
1202
    // From the first version(=0), find the missing version until spec_version
1203
0
    int64_t last_version = -1;
1204
0
    Versions missed_versions;
1205
0
    for (const Version& version : existing_versions) {
1206
0
        if (version.first > last_version + 1) {
1207
            // there is a hole between versions
1208
0
            missed_versions.emplace_back(last_version + 1, std::min(version.first, spec_version));
1209
0
        }
1210
0
        last_version = version.second;
1211
0
        if (last_version >= spec_version) {
1212
0
            break;
1213
0
        }
1214
0
    }
1215
0
    if (last_version < spec_version) {
1216
        // there is a hole between the last version and the specificed version.
1217
0
        missed_versions.emplace_back(last_version + 1, spec_version);
1218
0
    }
1219
0
    return missed_versions;
1220
0
}
1221
1222
Status CloudTablet::calc_delete_bitmap_for_compaction(
1223
        const std::vector<RowsetSharedPtr>& input_rowsets, const RowsetSharedPtr& output_rowset,
1224
        const RowIdConversion& rowid_conversion, ReaderType compaction_type, int64_t merged_rows,
1225
        int64_t filtered_rows, int64_t initiator, DeleteBitmapPtr& output_rowset_delete_bitmap,
1226
0
        bool allow_delete_in_cumu_compaction, int64_t& get_delete_bitmap_lock_start_time) {
1227
0
    output_rowset_delete_bitmap = std::make_shared<DeleteBitmap>(tablet_id());
1228
0
    std::unique_ptr<RowLocationSet> missed_rows;
1229
0
    if ((config::enable_missing_rows_correctness_check ||
1230
0
         config::enable_mow_compaction_correctness_check_core ||
1231
0
         config::enable_mow_compaction_correctness_check_fail) &&
1232
0
        !allow_delete_in_cumu_compaction &&
1233
0
        (compaction_type == ReaderType::READER_CUMULATIVE_COMPACTION ||
1234
0
         !config::enable_prune_delete_sign_when_base_compaction)) {
1235
        // also check duplicate key for base compaction when config::enable_prune_delete_sign_when_base_compaction==false
1236
0
        missed_rows = std::make_unique<RowLocationSet>();
1237
0
        LOG(INFO) << "RowLocation Set inited succ for tablet:" << tablet_id();
1238
0
    }
1239
1240
0
    std::unique_ptr<std::map<RowsetSharedPtr, RowLocationPairList>> location_map;
1241
0
    if (config::enable_rowid_conversion_correctness_check &&
1242
0
        tablet_schema()->cluster_key_uids().empty()) {
1243
0
        location_map = std::make_unique<std::map<RowsetSharedPtr, RowLocationPairList>>();
1244
0
        LOG(INFO) << "Location Map inited succ for tablet:" << tablet_id();
1245
0
    }
1246
1247
    // 1. calc delete bitmap for historical data
1248
0
    RETURN_IF_ERROR(_engine.meta_mgr().sync_tablet_rowsets(this));
1249
0
    Version version = max_version();
1250
0
    std::size_t missed_rows_size = 0;
1251
0
    calc_compaction_output_rowset_delete_bitmap(
1252
0
            input_rowsets, rowid_conversion, 0, version.second + 1, missed_rows.get(),
1253
0
            location_map.get(), tablet_meta()->delete_bitmap(), output_rowset_delete_bitmap.get());
1254
0
    if (missed_rows) {
1255
0
        missed_rows_size = missed_rows->size();
1256
0
        if (!allow_delete_in_cumu_compaction) {
1257
0
            if ((compaction_type == ReaderType::READER_CUMULATIVE_COMPACTION ||
1258
0
                 !config::enable_prune_delete_sign_when_base_compaction) &&
1259
0
                tablet_state() == TABLET_RUNNING) {
1260
0
                if (merged_rows + filtered_rows >= 0 &&
1261
0
                    merged_rows + filtered_rows != missed_rows_size) {
1262
0
                    std::string err_msg = fmt::format(
1263
0
                            "cumulative compaction: the merged rows({}), the filtered rows({}) is "
1264
0
                            "not equal to missed rows({}) in rowid conversion, tablet_id: {}, "
1265
0
                            "table_id:{}",
1266
0
                            merged_rows, filtered_rows, missed_rows_size, tablet_id(), table_id());
1267
0
                    LOG(WARNING) << err_msg;
1268
0
                    if (config::enable_mow_compaction_correctness_check_core) {
1269
0
                        CHECK(false) << err_msg;
1270
0
                    } else if (config::enable_mow_compaction_correctness_check_fail) {
1271
0
                        return Status::InternalError<false>(err_msg);
1272
0
                    } else {
1273
0
                        DCHECK(false) << err_msg;
1274
0
                    }
1275
0
                }
1276
0
            }
1277
0
        }
1278
0
    }
1279
0
    if (location_map) {
1280
0
        RETURN_IF_ERROR(check_rowid_conversion(output_rowset, *location_map));
1281
0
        location_map->clear();
1282
0
    }
1283
1284
    // 2. calc delete bitmap for incremental data
1285
0
    int64_t t1 = MonotonicMicros();
1286
0
    RETURN_IF_ERROR(_engine.meta_mgr().get_delete_bitmap_update_lock(
1287
0
            *this, COMPACTION_DELETE_BITMAP_LOCK_ID, initiator));
1288
0
    int64_t t2 = MonotonicMicros();
1289
0
    if (compaction_type == ReaderType::READER_CUMULATIVE_COMPACTION) {
1290
0
        g_cu_compaction_get_delete_bitmap_lock_time_ms << (t2 - t1) / 1000;
1291
0
    } else if (compaction_type == ReaderType::READER_BASE_COMPACTION) {
1292
0
        g_base_compaction_get_delete_bitmap_lock_time_ms << (t2 - t1) / 1000;
1293
0
    }
1294
0
    get_delete_bitmap_lock_start_time = t2;
1295
0
    RETURN_IF_ERROR(_engine.meta_mgr().sync_tablet_rowsets(this));
1296
0
    int64_t t3 = MonotonicMicros();
1297
1298
0
    calc_compaction_output_rowset_delete_bitmap(
1299
0
            input_rowsets, rowid_conversion, version.second, UINT64_MAX, missed_rows.get(),
1300
0
            location_map.get(), tablet_meta()->delete_bitmap(), output_rowset_delete_bitmap.get());
1301
0
    int64_t t4 = MonotonicMicros();
1302
0
    if (location_map) {
1303
0
        RETURN_IF_ERROR(check_rowid_conversion(output_rowset, *location_map));
1304
0
    }
1305
0
    int64_t t5 = MonotonicMicros();
1306
1307
    // 3. store delete bitmap
1308
0
    DeleteBitmapPtr delete_bitmap_v2 = nullptr;
1309
0
    auto delete_bitmap_size = output_rowset_delete_bitmap->delete_bitmap.size();
1310
0
    auto store_version = config::delete_bitmap_store_write_version;
1311
0
    if (store_version == 2 || store_version == 3) {
1312
0
        delete_bitmap_v2 = std::make_shared<DeleteBitmap>(*output_rowset_delete_bitmap);
1313
0
        std::vector<std::pair<RowsetId, int64_t>> retained_rowsets_to_seg_num;
1314
0
        {
1315
0
            std::shared_lock rlock(get_header_lock());
1316
0
            for (const auto& [rowset_version, rowset_ptr] : rowset_map()) {
1317
0
                if (rowset_version.second < output_rowset->start_version()) {
1318
0
                    retained_rowsets_to_seg_num.emplace_back(
1319
0
                            std::make_pair(rowset_ptr->rowset_id(), rowset_ptr->num_segments()));
1320
0
                }
1321
0
            }
1322
0
        }
1323
0
        if (config::enable_agg_delta_delete_bitmap_for_store_v2) {
1324
0
            tablet_meta()->delete_bitmap().subset_and_agg(
1325
0
                    retained_rowsets_to_seg_num, output_rowset->start_version(),
1326
0
                    output_rowset->end_version(), delete_bitmap_v2.get());
1327
0
        } else {
1328
0
            tablet_meta()->delete_bitmap().subset(
1329
0
                    retained_rowsets_to_seg_num, output_rowset->start_version(),
1330
0
                    output_rowset->end_version(), delete_bitmap_v2.get());
1331
0
        }
1332
0
    }
1333
0
    std::optional<StorageResource> storage_resource;
1334
0
    auto storage_resource_result = output_rowset->rowset_meta()->remote_storage_resource();
1335
0
    if (storage_resource_result) {
1336
0
        storage_resource = *storage_resource_result.value();
1337
0
    }
1338
0
    auto st = _engine.meta_mgr().update_delete_bitmap(
1339
0
            *this, -1, initiator, output_rowset_delete_bitmap.get(), delete_bitmap_v2.get(),
1340
0
            output_rowset->rowset_id().to_string(), storage_resource, store_version);
1341
0
    int64_t t6 = MonotonicMicros();
1342
0
    LOG(INFO) << "calc_delete_bitmap_for_compaction, tablet_id=" << tablet_id()
1343
0
              << ", get lock cost " << (t2 - t1) << " us, sync rowsets cost " << (t3 - t2)
1344
0
              << " us, calc delete bitmap cost " << (t4 - t3) << " us, check rowid conversion cost "
1345
0
              << (t5 - t4) << " us, store delete bitmap cost " << (t6 - t5)
1346
0
              << " us, st=" << st.to_string() << ". store_version=" << store_version
1347
0
              << ", calculated delete bitmap size=" << delete_bitmap_size
1348
0
              << ", update delete bitmap size="
1349
0
              << output_rowset_delete_bitmap->delete_bitmap.size();
1350
0
    return st;
1351
0
}
1352
1353
void CloudTablet::agg_delete_bitmap_for_compaction(
1354
        int64_t start_version, int64_t end_version, const std::vector<RowsetSharedPtr>& pre_rowsets,
1355
        DeleteBitmapPtr& new_delete_bitmap,
1356
0
        std::map<std::string, int64_t>& pre_rowset_to_versions) {
1357
0
    for (auto& rowset : pre_rowsets) {
1358
0
        for (uint32_t seg_id = 0; seg_id < rowset->num_segments(); ++seg_id) {
1359
0
            auto d = tablet_meta()->delete_bitmap().get_agg_without_cache(
1360
0
                    {rowset->rowset_id(), seg_id, end_version}, start_version);
1361
0
            if (d->isEmpty()) {
1362
0
                continue;
1363
0
            }
1364
0
            VLOG_DEBUG << "agg delete bitmap for tablet_id=" << tablet_id()
1365
0
                       << ", rowset_id=" << rowset->rowset_id() << ", seg_id=" << seg_id
1366
0
                       << ", rowset_version=" << rowset->version().to_string()
1367
0
                       << ". compaction start_version=" << start_version
1368
0
                       << ", end_version=" << end_version
1369
0
                       << ". delete_bitmap cardinality=" << d->cardinality();
1370
0
            DeleteBitmap::BitmapKey end_key {rowset->rowset_id(), seg_id, end_version};
1371
0
            new_delete_bitmap->set(end_key, *d);
1372
0
            pre_rowset_to_versions[rowset->rowset_id().to_string()] = rowset->version().second;
1373
0
        }
1374
0
    }
1375
0
}
1376
1377
5
Status CloudTablet::sync_meta() {
1378
5
    if (!config::enable_file_cache) {
1379
1
        return Status::OK();
1380
1
    }
1381
1382
4
    TabletMetaSharedPtr tablet_meta;
1383
4
    auto st = _engine.meta_mgr().get_tablet_meta(tablet_id(), &tablet_meta);
1384
4
    if (!st.ok()) {
1385
0
        if (st.is<ErrorCode::NOT_FOUND>()) {
1386
0
            clear_cache();
1387
0
        }
1388
0
        return st;
1389
0
    }
1390
1391
4
    auto new_compaction_policy = tablet_meta->compaction_policy();
1392
4
    if (_tablet_meta->compaction_policy() != new_compaction_policy) {
1393
1
        _tablet_meta->set_compaction_policy(new_compaction_policy);
1394
1
    }
1395
4
    auto new_time_series_compaction_goal_size_mbytes =
1396
4
            tablet_meta->time_series_compaction_goal_size_mbytes();
1397
4
    if (_tablet_meta->time_series_compaction_goal_size_mbytes() !=
1398
4
        new_time_series_compaction_goal_size_mbytes) {
1399
0
        _tablet_meta->set_time_series_compaction_goal_size_mbytes(
1400
0
                new_time_series_compaction_goal_size_mbytes);
1401
0
    }
1402
4
    auto new_time_series_compaction_file_count_threshold =
1403
4
            tablet_meta->time_series_compaction_file_count_threshold();
1404
4
    if (_tablet_meta->time_series_compaction_file_count_threshold() !=
1405
4
        new_time_series_compaction_file_count_threshold) {
1406
0
        _tablet_meta->set_time_series_compaction_file_count_threshold(
1407
0
                new_time_series_compaction_file_count_threshold);
1408
0
    }
1409
4
    auto new_time_series_compaction_time_threshold_seconds =
1410
4
            tablet_meta->time_series_compaction_time_threshold_seconds();
1411
4
    if (_tablet_meta->time_series_compaction_time_threshold_seconds() !=
1412
4
        new_time_series_compaction_time_threshold_seconds) {
1413
0
        _tablet_meta->set_time_series_compaction_time_threshold_seconds(
1414
0
                new_time_series_compaction_time_threshold_seconds);
1415
0
    }
1416
4
    auto new_time_series_compaction_empty_rowsets_threshold =
1417
4
            tablet_meta->time_series_compaction_empty_rowsets_threshold();
1418
4
    if (_tablet_meta->time_series_compaction_empty_rowsets_threshold() !=
1419
4
        new_time_series_compaction_empty_rowsets_threshold) {
1420
0
        _tablet_meta->set_time_series_compaction_empty_rowsets_threshold(
1421
0
                new_time_series_compaction_empty_rowsets_threshold);
1422
0
    }
1423
4
    auto new_time_series_compaction_level_threshold =
1424
4
            tablet_meta->time_series_compaction_level_threshold();
1425
4
    if (_tablet_meta->time_series_compaction_level_threshold() !=
1426
4
        new_time_series_compaction_level_threshold) {
1427
0
        _tablet_meta->set_time_series_compaction_level_threshold(
1428
0
                new_time_series_compaction_level_threshold);
1429
0
    }
1430
    // Sync disable_auto_compaction (stored in tablet_schema)
1431
4
    auto new_disable_auto_compaction = tablet_meta->tablet_schema()->disable_auto_compaction();
1432
4
    if (_tablet_meta->tablet_schema()->disable_auto_compaction() != new_disable_auto_compaction) {
1433
3
        _tablet_meta->mutable_tablet_schema()->set_disable_auto_compaction(
1434
3
                new_disable_auto_compaction);
1435
3
    }
1436
    // Sync vertical_compaction_num_columns_per_group
1437
4
    auto new_vertical_compaction_num_columns_per_group =
1438
4
            tablet_meta->vertical_compaction_num_columns_per_group();
1439
4
    if (_tablet_meta->vertical_compaction_num_columns_per_group() !=
1440
4
        new_vertical_compaction_num_columns_per_group) {
1441
0
        _tablet_meta->set_vertical_compaction_num_columns_per_group(
1442
0
                new_vertical_compaction_num_columns_per_group);
1443
0
    }
1444
1445
4
    return Status::OK();
1446
4
}
1447
1448
0
void CloudTablet::build_tablet_report_info(TTabletInfo* tablet_info) {
1449
0
    std::shared_lock rdlock(_meta_lock);
1450
0
    tablet_info->__set_total_version_count(_tablet_meta->version_count());
1451
0
    tablet_info->__set_tablet_id(_tablet_meta->tablet_id());
1452
    // Currently, this information will not be used by the cloud report,
1453
    // but it may be used in the future.
1454
0
}
1455
1456
Status CloudTablet::check_delete_bitmap_cache(int64_t txn_id,
1457
0
                                              DeleteBitmap* expected_delete_bitmap) {
1458
0
    DeleteBitmapPtr cached_delete_bitmap;
1459
0
    CloudStorageEngine& engine = ExecEnv::GetInstance()->storage_engine().to_cloud();
1460
0
    Status st = engine.txn_delete_bitmap_cache().get_delete_bitmap(
1461
0
            txn_id, tablet_id(), &cached_delete_bitmap, nullptr, nullptr);
1462
0
    if (st.ok()) {
1463
0
        bool res = (expected_delete_bitmap->cardinality() == cached_delete_bitmap->cardinality());
1464
0
        auto msg = fmt::format(
1465
0
                "delete bitmap cache check failed, cur_cardinality={}, cached_cardinality={}"
1466
0
                "txn_id={}, tablet_id={}",
1467
0
                expected_delete_bitmap->cardinality(), cached_delete_bitmap->cardinality(), txn_id,
1468
0
                tablet_id());
1469
0
        if (!res) {
1470
0
            DCHECK(res) << msg;
1471
0
            return Status::InternalError<false>(msg);
1472
0
        }
1473
0
    }
1474
0
    return Status::OK();
1475
0
}
1476
1477
34
WarmUpState CloudTablet::get_rowset_warmup_state(RowsetId rowset_id) {
1478
34
    std::shared_lock rlock(_meta_lock);
1479
34
    if (!_rowset_warm_up_states.contains(rowset_id)) {
1480
1
        return {.trigger_source = WarmUpTriggerSource::NONE, .progress = WarmUpProgress::NONE};
1481
1
    }
1482
33
    auto& warmup_info = _rowset_warm_up_states[rowset_id];
1483
33
    warmup_info.update_state();
1484
33
    return warmup_info.state;
1485
34
}
1486
1487
bool CloudTablet::add_rowset_warmup_state(const RowsetMeta& rowset, WarmUpTriggerSource source,
1488
34
                                          std::chrono::steady_clock::time_point start_tp) {
1489
34
    std::lock_guard wlock(_meta_lock);
1490
34
    return add_rowset_warmup_state_unlocked(rowset, source, start_tp);
1491
34
}
1492
1493
bool CloudTablet::update_rowset_warmup_state_inverted_idx_num(WarmUpTriggerSource source,
1494
5
                                                              RowsetId rowset_id, int64_t delta) {
1495
5
    std::lock_guard wlock(_meta_lock);
1496
5
    return update_rowset_warmup_state_inverted_idx_num_unlocked(source, rowset_id, delta);
1497
5
}
1498
1499
bool CloudTablet::update_rowset_warmup_state_inverted_idx_num_unlocked(WarmUpTriggerSource source,
1500
                                                                       RowsetId rowset_id,
1501
5
                                                                       int64_t delta) {
1502
5
    auto it = _rowset_warm_up_states.find(rowset_id);
1503
5
    if (it == _rowset_warm_up_states.end()) {
1504
0
        return false;
1505
0
    }
1506
5
    if (it->second.state.trigger_source != source) {
1507
        // Only the same trigger source can update the state
1508
2
        return false;
1509
2
    }
1510
3
    it->second.num_inverted_idx += delta;
1511
3
    return true;
1512
5
}
1513
1514
bool CloudTablet::add_rowset_warmup_state_unlocked(const RowsetMeta& rowset,
1515
                                                   WarmUpTriggerSource source,
1516
34
                                                   std::chrono::steady_clock::time_point start_tp) {
1517
34
    auto rowset_id = rowset.rowset_id();
1518
1519
    // Check if rowset already has warmup state
1520
34
    if (_rowset_warm_up_states.contains(rowset_id)) {
1521
10
        auto existing_state = _rowset_warm_up_states[rowset_id].state;
1522
1523
        // For job-triggered warmup (one-time and periodic warmup), allow it to proceed
1524
        // except when there's already another job-triggered warmup in progress
1525
10
        if (source == WarmUpTriggerSource::JOB) {
1526
5
            if (existing_state.trigger_source == WarmUpTriggerSource::JOB &&
1527
5
                existing_state.progress == WarmUpProgress::DOING) {
1528
                // Same job type already in progress, skip to avoid duplicate warmup
1529
1
                return false;
1530
1
            }
1531
5
        } else {
1532
            // For non-job warmup (EVENT_DRIVEN, SYNC_ROWSET), skip if any warmup exists
1533
5
            return false;
1534
5
        }
1535
10
    }
1536
1537
28
    if (source == WarmUpTriggerSource::JOB) {
1538
9
        g_file_cache_warm_up_rowset_triggered_by_job_num << 1;
1539
19
    } else if (source == WarmUpTriggerSource::SYNC_ROWSET) {
1540
6
        g_file_cache_warm_up_rowset_triggered_by_sync_rowset_num << 1;
1541
13
    } else if (source == WarmUpTriggerSource::EVENT_DRIVEN) {
1542
13
        g_file_cache_warm_up_rowset_triggered_by_event_driven_num << 1;
1543
13
    }
1544
28
    _rowset_warm_up_states[rowset_id] = {
1545
28
            .state = {.trigger_source = source,
1546
28
                      .progress = (rowset.num_segments() == 0 ? WarmUpProgress::DONE
1547
28
                                                              : WarmUpProgress::DOING)},
1548
28
            .num_segments = rowset.num_segments(),
1549
28
            .start_tp = start_tp};
1550
28
    return true;
1551
34
}
1552
1553
51
void CloudTablet::RowsetWarmUpInfo::update_state() {
1554
51
    if (has_finished()) {
1555
14
        g_file_cache_warm_up_rowset_complete_num << 1;
1556
14
        auto cost = std::chrono::duration_cast<std::chrono::milliseconds>(
1557
14
                            std::chrono::steady_clock::now() - start_tp)
1558
14
                            .count();
1559
14
        g_file_cache_warm_up_rowset_all_segments_latency << cost;
1560
14
        state.progress = WarmUpProgress::DONE;
1561
14
    }
1562
51
}
1563
1564
WarmUpState CloudTablet::complete_rowset_segment_warmup(WarmUpTriggerSource trigger_source,
1565
                                                        RowsetId rowset_id, Status status,
1566
                                                        int64_t segment_num,
1567
21
                                                        int64_t inverted_idx_num) {
1568
21
    std::lock_guard wlock(_meta_lock);
1569
21
    auto it = _rowset_warm_up_states.find(rowset_id);
1570
21
    if (it == _rowset_warm_up_states.end()) {
1571
1
        return {.trigger_source = WarmUpTriggerSource::NONE, .progress = WarmUpProgress::NONE};
1572
1
    }
1573
20
    auto& warmup_info = it->second;
1574
20
    if (warmup_info.state.trigger_source != trigger_source) {
1575
        // Only the same trigger source can update the state
1576
2
        return warmup_info.state;
1577
2
    }
1578
18
    VLOG_DEBUG << "complete rowset segment warmup for rowset " << rowset_id << ", " << status;
1579
18
    if (segment_num > 0) {
1580
16
        g_file_cache_warm_up_segment_complete_num << segment_num;
1581
16
        if (!status.ok()) {
1582
1
            g_file_cache_warm_up_segment_failed_num << segment_num;
1583
1
        }
1584
16
    }
1585
18
    if (inverted_idx_num > 0) {
1586
2
        g_file_cache_warm_up_inverted_idx_complete_num << inverted_idx_num;
1587
2
        if (!status.ok()) {
1588
0
            g_file_cache_warm_up_inverted_idx_failed_num << inverted_idx_num;
1589
0
        }
1590
2
    }
1591
18
    warmup_info.done(segment_num, inverted_idx_num);
1592
18
    return warmup_info.state;
1593
20
}
1594
1595
200
bool CloudTablet::is_rowset_warmed_up(const RowsetId& rowset_id) const {
1596
200
    auto it = _rowset_warm_up_states.find(rowset_id);
1597
200
    if (it == _rowset_warm_up_states.end()) {
1598
58
        return false;
1599
58
    }
1600
142
    return it->second.state.progress == WarmUpProgress::DONE;
1601
200
}
1602
1603
598
void CloudTablet::add_warmed_up_rowset(const RowsetId& rowset_id) {
1604
598
    _rowset_warm_up_states[rowset_id] = {
1605
598
            .state = {.trigger_source = WarmUpTriggerSource::SYNC_ROWSET,
1606
598
                      .progress = WarmUpProgress::DONE},
1607
598
            .num_segments = 1,
1608
598
            .start_tp = std::chrono::steady_clock::now()};
1609
598
}
1610
1611
bool CloudTablet::_check_rowset_should_be_visible_but_not_warmed_up(
1612
        const RowsetMetaSharedPtr& rs_meta, int64_t path_max_version,
1613
335
        std::chrono::system_clock::time_point freshness_limit_tp) const {
1614
335
    if (rs_meta->version() == Version {0, 1}) {
1615
        // skip rowset[0-1]
1616
18
        return false;
1617
18
    }
1618
317
    bool ret = rs_meta->start_version() > path_max_version &&
1619
317
               rs_meta->visible_timestamp() < freshness_limit_tp;
1620
317
    if (ret && config::read_cluster_cache_opt_verbose_log) {
1621
5
        using namespace std::chrono;
1622
5
        std::time_t t1 = system_clock::to_time_t(rs_meta->visible_timestamp());
1623
5
        std::tm tm1 = *std::localtime(&t1);
1624
5
        std::ostringstream oss1;
1625
5
        oss1 << std::put_time(&tm1, "%Y-%m-%d %H:%M:%S");
1626
1627
5
        std::time_t t2 = system_clock::to_time_t(freshness_limit_tp);
1628
5
        std::tm tm2 = *std::localtime(&t2);
1629
5
        std::ostringstream oss2;
1630
5
        oss2 << std::put_time(&tm2, "%Y-%m-%d %H:%M:%S");
1631
5
        LOG_INFO(
1632
5
                "[verbose] CloudTablet::capture_rs_readers_with_freshness_tolerance, "
1633
5
                "find a rowset which should be visible but not warmed up, tablet_id={}, "
1634
5
                "path_max_version={}, rowset_id={}, version={}, visible_time={}, "
1635
5
                "freshness_limit={}, version_graph={}, rowset_warmup_digest={}",
1636
5
                tablet_id(), path_max_version, rs_meta->rowset_id().to_string(),
1637
5
                rs_meta->version().to_string(), oss1.str(), oss2.str(),
1638
5
                _timestamped_version_tracker.debug_string(), rowset_warmup_digest());
1639
5
    }
1640
317
    return ret;
1641
335
}
1642
1643
void CloudTablet::_submit_segment_download_task(const RowsetSharedPtr& rs,
1644
                                                const StorageResource* storage_resource, int seg_id,
1645
1646
0
                                                int64_t expiration_time) {
1647
    // clang-format off
1648
0
    const auto& rowset_meta = rs->rowset_meta();
1649
0
    auto self = std::dynamic_pointer_cast<CloudTablet>(shared_from_this());
1650
    // Use rowset_meta->fs() instead of storage_resource->fs to support packed file.
1651
    // RowsetMeta::fs() wraps the underlying FileSystem with PackedFileSystem when
1652
    // packed_slice_locations is not empty, which correctly maps segment file paths
1653
    // to their actual locations within packed files.
1654
0
    auto file_system = rowset_meta->fs();
1655
0
    if (!file_system) {
1656
0
        LOG(WARNING) << "failed to get file system for tablet_id=" << _tablet_meta->tablet_id()
1657
0
                     << ", rowset_id=" << rowset_meta->rowset_id();
1658
0
        return;
1659
0
    }
1660
0
    _engine.file_cache_block_downloader().submit_download_task(io::DownloadFileMeta {
1661
0
            .path = storage_resource->remote_segment_path(*rowset_meta, seg_id),
1662
0
            .file_size = rs->rowset_meta()->segment_file_size(seg_id),
1663
0
            .file_system = file_system,
1664
0
            .ctx = {
1665
0
                    .expiration_time = expiration_time,
1666
0
                    .is_dryrun = config::enable_reader_dryrun_when_download_file_cache,
1667
0
                    .is_warmup = true
1668
0
            },
1669
0
            .download_done {[=](Status st) {
1670
0
                DBUG_EXECUTE_IF("CloudTablet::add_rowsets.download_data.callback.block_compaction_rowset", {
1671
0
                            if (rs->version().second > rs->version().first) {
1672
0
                                auto sleep_time = dp->param<int>("sleep", 3);
1673
0
                                LOG_INFO(
1674
0
                                        "[verbose] block download for rowset={}, "
1675
0
                                        "version={}, sleep={}",
1676
0
                                        rs->rowset_id().to_string(),
1677
0
                                        rs->version().to_string(), sleep_time);
1678
0
                                std::this_thread::sleep_for(
1679
0
                                        std::chrono::seconds(sleep_time));
1680
0
                            }
1681
0
                });
1682
0
                self->complete_rowset_segment_warmup(WarmUpTriggerSource::SYNC_ROWSET, rowset_meta->rowset_id(), st, 1, 0);
1683
0
                if (!st) {
1684
0
                    LOG_WARNING("add rowset warm up error ").error(st);
1685
0
                }
1686
0
            }},
1687
0
    });
1688
    // clang-format on
1689
0
}
1690
1691
void CloudTablet::_submit_inverted_index_download_task(const RowsetSharedPtr& rs,
1692
                                                       const StorageResource* storage_resource,
1693
                                                       const io::Path& idx_path, int64_t idx_size,
1694
0
                                                       int64_t expiration_time) {
1695
    // clang-format off
1696
0
    const auto& rowset_meta = rs->rowset_meta();
1697
0
    auto self = std::dynamic_pointer_cast<CloudTablet>(shared_from_this());
1698
    // Use rowset_meta->fs() instead of storage_resource->fs to support packed file for idx files.
1699
0
    auto file_system = rowset_meta->fs();
1700
0
    if (!file_system) {
1701
0
        LOG(WARNING) << "failed to get file system for tablet_id=" << _tablet_meta->tablet_id()
1702
0
                     << ", rowset_id=" << rowset_meta->rowset_id();
1703
0
        return;
1704
0
    }
1705
0
    io::DownloadFileMeta meta {
1706
0
            .path = idx_path,
1707
0
            .file_size = idx_size,
1708
0
            .file_system = file_system,
1709
0
            .ctx = {
1710
0
                    .expiration_time = expiration_time,
1711
0
                    .is_dryrun = config::enable_reader_dryrun_when_download_file_cache,
1712
0
                    .is_warmup = true
1713
0
            },
1714
0
            .download_done {[=](Status st) {
1715
0
                DBUG_EXECUTE_IF("CloudTablet::add_rowsets.download_idx.callback.block", {
1716
0
                    auto sleep_time = dp->param<int>("sleep", 3);
1717
0
                    LOG_INFO(
1718
0
                            "[verbose] block download for "
1719
0
                            "rowset={}, inverted_idx_file={}, "
1720
0
                            "sleep={}",
1721
0
                            rs->rowset_id().to_string(), idx_path.string(), sleep_time);
1722
0
                    std::this_thread::sleep_for(std::chrono::seconds(sleep_time));
1723
0
                });
1724
0
                self->complete_rowset_segment_warmup(WarmUpTriggerSource::SYNC_ROWSET, rowset_meta->rowset_id(), st, 0, 1);
1725
0
                if (!st) {
1726
0
                    LOG_WARNING("add rowset warm up error ").error(st);
1727
0
                }
1728
0
            }},
1729
0
    };
1730
0
    self->update_rowset_warmup_state_inverted_idx_num_unlocked(WarmUpTriggerSource::SYNC_ROWSET, rowset_meta->rowset_id(), 1);
1731
0
    _engine.file_cache_block_downloader().submit_download_task(std::move(meta));
1732
0
    g_file_cache_cloud_tablet_submitted_index_num << 1;
1733
0
    g_file_cache_cloud_tablet_submitted_index_size << idx_size;
1734
    // clang-format on
1735
0
}
1736
1737
void CloudTablet::_add_rowsets_directly(std::vector<RowsetSharedPtr>& rowsets,
1738
268
                                        bool warmup_delta_data) {
1739
268
#ifdef BE_TEST
1740
268
    warmup_delta_data = false;
1741
268
#endif
1742
760
    for (auto& rs : rowsets) {
1743
760
        if (warmup_delta_data) {
1744
            // Pre-set encryption algorithm to avoid re-entrant get_tablet() call
1745
            // inside RowsetMeta::fs() which causes SingleFlight deadlock when the
1746
            // tablet is not yet cached (during initial load_tablet).
1747
0
            rs->rowset_meta()->set_encryption_algorithm(_tablet_meta->encryption_algorithm());
1748
0
            bool warm_up_state_updated = false;
1749
            // Warmup rowset data in background
1750
0
            for (int seg_id = 0; seg_id < rs->num_segments(); ++seg_id) {
1751
0
                const auto& rowset_meta = rs->rowset_meta();
1752
0
                constexpr int64_t interval = 600; // 10 mins
1753
                // When BE restart and receive the `load_sync` rpc, it will sync all historical rowsets first time.
1754
                // So we need to filter out the old rowsets avoid to download the whole table.
1755
0
                if (warmup_delta_data &&
1756
0
                    ::time(nullptr) - rowset_meta->newest_write_timestamp() >= interval) {
1757
0
                    continue;
1758
0
                }
1759
1760
0
                auto storage_resource = rowset_meta->remote_storage_resource();
1761
0
                if (!storage_resource) {
1762
0
                    LOG(WARNING) << storage_resource.error();
1763
0
                    continue;
1764
0
                }
1765
1766
0
                int64_t expiration_time = _tablet_meta->ttl_seconds();
1767
0
                g_file_cache_cloud_tablet_submitted_segment_num << 1;
1768
0
                if (rs->rowset_meta()->segment_file_size(seg_id) > 0) {
1769
0
                    g_file_cache_cloud_tablet_submitted_segment_size
1770
0
                            << rs->rowset_meta()->segment_file_size(seg_id);
1771
0
                }
1772
0
                if (!warm_up_state_updated) {
1773
0
                    VLOG_DEBUG << "warm up rowset " << rs->version() << "(" << rs->rowset_id()
1774
0
                               << ") triggerd by sync rowset";
1775
0
                    if (!add_rowset_warmup_state_unlocked(*(rs->rowset_meta()),
1776
0
                                                          WarmUpTriggerSource::SYNC_ROWSET)) {
1777
0
                        LOG(INFO) << "found duplicate warmup task for rowset " << rs->rowset_id()
1778
0
                                  << ", skip it";
1779
0
                        break;
1780
0
                    }
1781
0
                    warm_up_state_updated = true;
1782
0
                }
1783
1784
0
                if (!config::file_cache_enable_only_warm_up_idx) {
1785
0
                    _submit_segment_download_task(rs, storage_resource.value(), seg_id,
1786
0
                                                  expiration_time);
1787
0
                }
1788
1789
0
                auto schema_ptr = rowset_meta->tablet_schema();
1790
0
                auto idx_version = schema_ptr->get_inverted_index_storage_format();
1791
0
                if (idx_version == InvertedIndexStorageFormatPB::V1) {
1792
0
                    std::unordered_map<int64_t, int64_t> index_size_map;
1793
0
                    auto&& inverted_index_info = rowset_meta->inverted_index_file_info(seg_id);
1794
0
                    for (const auto& info : inverted_index_info.index_info()) {
1795
0
                        if (info.index_file_size() != -1) {
1796
0
                            index_size_map[info.index_id()] = info.index_file_size();
1797
0
                        } else {
1798
0
                            VLOG_DEBUG << "Invalid index_file_size for segment_id " << seg_id
1799
0
                                       << ", index_id " << info.index_id();
1800
0
                        }
1801
0
                    }
1802
0
                    for (const auto& index : schema_ptr->inverted_indexes()) {
1803
0
                        auto idx_path = storage_resource.value()->remote_idx_v1_path(
1804
0
                                *rowset_meta, seg_id, index->index_id(), index->get_index_suffix());
1805
0
                        _submit_inverted_index_download_task(rs, storage_resource.value(), idx_path,
1806
0
                                                             index_size_map[index->index_id()],
1807
0
                                                             expiration_time);
1808
0
                    }
1809
0
                } else {
1810
0
                    if (schema_ptr->has_inverted_index() || schema_ptr->has_ann_index()) {
1811
0
                        auto&& inverted_index_info = rowset_meta->inverted_index_file_info(seg_id);
1812
0
                        int64_t idx_size = 0;
1813
0
                        if (inverted_index_info.has_index_size()) {
1814
0
                            idx_size = inverted_index_info.index_size();
1815
0
                        } else {
1816
0
                            VLOG_DEBUG << "index_size is not set for segment " << seg_id;
1817
0
                        }
1818
0
                        auto idx_path =
1819
0
                                storage_resource.value()->remote_idx_v2_path(*rowset_meta, seg_id);
1820
0
                        _submit_inverted_index_download_task(rs, storage_resource.value(), idx_path,
1821
0
                                                             idx_size, expiration_time);
1822
0
                    }
1823
0
                }
1824
0
            }
1825
0
        }
1826
760
        _rs_version_map.emplace(rs->version(), rs);
1827
760
        _timestamped_version_tracker.add_version(rs->version());
1828
760
        _max_version = std::max(rs->end_version(), _max_version);
1829
760
        update_base_size(*rs);
1830
760
    }
1831
268
    _tablet_meta->add_rowsets_unchecked(rowsets);
1832
268
}
1833
1834
15
void CloudTablet::clear_unused_visible_pending_rowsets() {
1835
15
    int64_t cur_max_version = max_version().second;
1836
15
    int32_t max_version_count = max_version_config();
1837
15
    int64_t current_time = std::chrono::duration_cast<std::chrono::seconds>(
1838
15
                                   std::chrono::system_clock::now().time_since_epoch())
1839
15
                                   .count();
1840
1841
15
    std::unique_lock<std::mutex> wlock(_visible_pending_rs_lock);
1842
38
    for (auto it = _visible_pending_rs_map.begin(); it != _visible_pending_rs_map.end();) {
1843
23
        if (int64_t version = it->first, expiration_time = it->second.expiration_time;
1844
23
            version <= cur_max_version || expiration_time < current_time) {
1845
19
            it = _visible_pending_rs_map.erase(it);
1846
19
        } else {
1847
4
            ++it;
1848
4
        }
1849
23
    }
1850
1851
15
    while (!_visible_pending_rs_map.empty() && _visible_pending_rs_map.size() > max_version_count) {
1852
0
        _visible_pending_rs_map.erase(--_visible_pending_rs_map.end());
1853
0
    }
1854
15
}
1855
1856
void CloudTablet::try_make_committed_rs_visible(int64_t txn_id, int64_t visible_version,
1857
0
                                                int64_t version_update_time_ms) {
1858
0
    if (enable_unique_key_merge_on_write()) {
1859
        // for mow tablet, we get committed rowset from `CloudTxnDeleteBitmapCache` rather than `CommittedRowsetManager`
1860
0
        try_make_committed_rs_visible_for_mow(txn_id, visible_version, version_update_time_ms);
1861
0
        return;
1862
0
    }
1863
1864
0
    auto& committed_rs_mgr = _engine.committed_rs_mgr();
1865
0
    auto res = committed_rs_mgr.get_committed_rowset(txn_id, tablet_id());
1866
0
    if (!res.has_value()) {
1867
0
        return;
1868
0
    }
1869
0
    auto [rowset_meta, expiration_time] = res.value();
1870
0
    bool is_empty_rowset = (rowset_meta == nullptr);
1871
0
    if (!is_empty_rowset) {
1872
0
        rowset_meta->set_cloud_fields_after_visible(visible_version, version_update_time_ms);
1873
0
    }
1874
0
    {
1875
0
        std::lock_guard<std::mutex> lock(_visible_pending_rs_lock);
1876
0
        _visible_pending_rs_map.emplace(
1877
0
                visible_version,
1878
0
                VisiblePendingRowset {rowset_meta, expiration_time, is_empty_rowset});
1879
0
    }
1880
0
    apply_visible_pending_rowsets();
1881
0
    committed_rs_mgr.remove_committed_rowset(txn_id, tablet_id());
1882
0
}
1883
1884
void CloudTablet::try_make_committed_rs_visible_for_mow(int64_t txn_id, int64_t visible_version,
1885
0
                                                        int64_t version_update_time_ms) {
1886
0
    Defer defer {[&] {
1887
0
        _engine.txn_delete_bitmap_cache().remove_unused_tablet_txn_info(txn_id, tablet_id());
1888
0
    }};
1889
0
    auto res = _engine.txn_delete_bitmap_cache().get_rowset_and_delete_bitmap(txn_id, tablet_id());
1890
0
    if (!res.has_value()) {
1891
0
        return;
1892
0
    }
1893
0
    auto [rowset, delete_bitmap] = res.value();
1894
0
    bool is_empty_rowset = (rowset == nullptr);
1895
0
    {
1896
0
        std::unique_lock lock {_sync_meta_lock};
1897
0
        std::unique_lock meta_wlock {_meta_lock};
1898
0
        if (_max_version + 1 != visible_version) {
1899
0
            return;
1900
0
        }
1901
0
        if (is_empty_rowset) {
1902
0
            Versions existing_versions;
1903
0
            for (const auto& [_, rs] : tablet_meta()->all_rs_metas()) {
1904
0
                existing_versions.emplace_back(rs->version());
1905
0
            }
1906
0
            if (existing_versions.empty()) {
1907
0
                return;
1908
0
            }
1909
0
            auto max_version = std::ranges::max(existing_versions, {}, &Version::first);
1910
0
            auto prev_rowset = get_rowset_by_version(max_version);
1911
0
            auto st = _engine.meta_mgr().create_empty_rowset_for_hole(
1912
0
                    this, visible_version, prev_rowset->rowset_meta(), &rowset);
1913
0
            if (!st.ok()) {
1914
0
                return;
1915
0
            }
1916
0
        } else {
1917
0
            for (const auto& [delete_bitmap_key, bitmap_value] : delete_bitmap->delete_bitmap) {
1918
                // skip sentinel mark, which is used for delete bitmap correctness check
1919
0
                if (std::get<1>(delete_bitmap_key) != DeleteBitmap::INVALID_SEGMENT_ID) {
1920
0
                    tablet_meta()->delete_bitmap().merge(
1921
0
                            {std::get<0>(delete_bitmap_key), std::get<1>(delete_bitmap_key),
1922
0
                             visible_version},
1923
0
                            bitmap_value);
1924
0
                }
1925
0
            }
1926
0
        }
1927
0
        rowset->rowset_meta()->set_cloud_fields_after_visible(visible_version,
1928
0
                                                              version_update_time_ms);
1929
0
        add_rowsets({rowset}, false, meta_wlock, true);
1930
0
    }
1931
0
    LOG(INFO) << "mow added visible pending rowset, txn_id=" << txn_id
1932
0
              << ", tablet_id=" << tablet_id() << ", version=" << visible_version
1933
0
              << ", rowset_id=" << rowset->rowset_id().to_string();
1934
0
}
1935
1936
15
void CloudTablet::apply_visible_pending_rowsets() {
1937
15
    Defer defer {[&] { clear_unused_visible_pending_rowsets(); }};
1938
1939
15
    std::unique_lock lock(_sync_meta_lock);
1940
15
    std::unique_lock<std::shared_mutex> meta_wlock(_meta_lock);
1941
15
    int64_t next_version = _max_version + 1;
1942
15
    std::vector<RowsetSharedPtr> to_add;
1943
15
    std::lock_guard<std::mutex> pending_lock(_visible_pending_rs_lock);
1944
15
    for (auto it = _visible_pending_rs_map.upper_bound(_max_version);
1945
31
         it != _visible_pending_rs_map.end(); ++it) {
1946
21
        int64_t version = it->first;
1947
21
        if (version != next_version) break;
1948
1949
17
        auto& pending_rs = it->second;
1950
17
        if (pending_rs.is_empty_rowset) {
1951
3
            RowsetSharedPtr prev_rowset {nullptr};
1952
3
            if (!to_add.empty()) {
1953
1
                prev_rowset = to_add.back();
1954
2
            } else {
1955
2
                Versions existing_versions;
1956
2
                for (const auto& [_, rs] : tablet_meta()->all_rs_metas()) {
1957
1
                    existing_versions.emplace_back(rs->version());
1958
1
                }
1959
2
                if (existing_versions.empty()) {
1960
1
                    break;
1961
1
                }
1962
1
                auto max_version = std::ranges::max(existing_versions, {}, &Version::first);
1963
1
                prev_rowset = get_rowset_by_version(max_version);
1964
1
            }
1965
2
            RowsetSharedPtr rowset;
1966
2
            auto st = _engine.meta_mgr().create_empty_rowset_for_hole(
1967
2
                    this, version, prev_rowset->rowset_meta(), &rowset);
1968
2
            if (!st.ok()) {
1969
0
                return;
1970
0
            }
1971
2
            to_add.push_back(std::move(rowset));
1972
14
        } else {
1973
14
            RowsetSharedPtr rowset;
1974
14
            auto st = RowsetFactory::create_rowset(nullptr, "", pending_rs.rowset_meta, &rowset);
1975
14
            if (!st.ok()) {
1976
0
                LOG(WARNING) << "failed to create rowset from pending rowset meta, tablet_id="
1977
0
                             << tablet_id() << ", version=" << version
1978
0
                             << ", rowset_id=" << pending_rs.rowset_meta->rowset_id().to_string()
1979
0
                             << ", error=" << st;
1980
0
                break;
1981
0
            }
1982
14
            to_add.push_back(std::move(rowset));
1983
14
        }
1984
16
        next_version++;
1985
16
    }
1986
15
    if (!to_add.empty()) {
1987
10
        add_rowsets(to_add, false, meta_wlock, true);
1988
10
        LOG_INFO(
1989
10
                "applied_visible_pending_rowsets, tablet_id={}, new_max_version={}, "
1990
10
                "count={}, new_rowsets={}",
1991
10
                tablet_id(), _max_version, to_add.size(),
1992
16
                fmt::join(to_add | std::views::transform([](const RowsetSharedPtr& rs) {
1993
16
                              return fmt::format("{}{}", rs->rowset_id().to_string(),
1994
16
                                                 rs->version().to_string());
1995
16
                          }),
1996
10
                          ","));
1997
10
    }
1998
15
}
1999
2000
#include "common/compile_check_end.h"
2001
2002
} // namespace doris