Coverage Report

Created: 2026-07-27 19:42

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