Coverage Report

Created: 2026-06-17 00:50

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