Coverage Report

Created: 2026-06-12 09:54

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