Coverage Report

Created: 2026-02-09 16:43

/root/doris/cloud/src/recycler/recycler.h
Line
Count
Source (jump to first uncovered line)
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#pragma once
19
20
#include <gen_cpp/cloud.pb.h>
21
#include <glog/logging.h>
22
23
#include <atomic>
24
#include <condition_variable>
25
#include <cstdint>
26
#include <deque>
27
#include <functional>
28
#include <memory>
29
#include <string>
30
#include <string_view>
31
#include <thread>
32
#include <unordered_map>
33
#include <unordered_set>
34
#include <utility>
35
36
#include "common/bvars.h"
37
#include "meta-service/delete_bitmap_lock_white_list.h"
38
#include "meta-service/txn_lazy_committer.h"
39
#include "meta-store/versionstamp.h"
40
#include "recycler/snapshot_chain_compactor.h"
41
#include "recycler/snapshot_data_migrator.h"
42
#include "recycler/storage_vault_accessor.h"
43
#include "recycler/white_black_list.h"
44
#include "snapshot/snapshot_manager.h"
45
46
namespace brpc {
47
class Server;
48
} // namespace brpc
49
50
namespace doris::cloud {
51
class TxnKv;
52
class InstanceRecycler;
53
class StorageVaultAccessor;
54
class Checker;
55
class SimpleThreadPool;
56
class RecyclerMetricsContext;
57
class TabletRecyclerMetricsContext;
58
class SegmentRecyclerMetricsContext;
59
struct RecyclerThreadPoolGroup {
60
8
    RecyclerThreadPoolGroup() = default;
61
    RecyclerThreadPoolGroup(std::shared_ptr<SimpleThreadPool> s3_producer_pool,
62
                            std::shared_ptr<SimpleThreadPool> recycle_tablet_pool,
63
                            std::shared_ptr<SimpleThreadPool> group_recycle_function_pool)
64
            : s3_producer_pool(std::move(s3_producer_pool)),
65
              recycle_tablet_pool(std::move(recycle_tablet_pool)),
66
11
              group_recycle_function_pool(std::move(group_recycle_function_pool)) {}
67
279
    ~RecyclerThreadPoolGroup() = default;
68
130
    RecyclerThreadPoolGroup(const RecyclerThreadPoolGroup&) = default;
69
    RecyclerThreadPoolGroup& operator=(RecyclerThreadPoolGroup& other) = default;
70
11
    RecyclerThreadPoolGroup& operator=(RecyclerThreadPoolGroup&& other) = default;
71
130
    RecyclerThreadPoolGroup(RecyclerThreadPoolGroup&&) = default;
72
    // used for accessor.delete_files, accessor.delete_directory
73
    std::shared_ptr<SimpleThreadPool> s3_producer_pool;
74
    // used for InstanceRecycler::recycle_tablet
75
    std::shared_ptr<SimpleThreadPool> recycle_tablet_pool;
76
    std::shared_ptr<SimpleThreadPool> group_recycle_function_pool;
77
};
78
79
class Recycler {
80
public:
81
    explicit Recycler(std::shared_ptr<TxnKv> txn_kv);
82
    ~Recycler();
83
84
    // returns 0 for success otherwise error
85
    int start(brpc::Server* server);
86
87
    void stop();
88
89
288
    bool stopped() const { return stopped_.load(std::memory_order_acquire); }
90
91
private:
92
    void recycle_callback();
93
94
    void instance_scanner_callback();
95
96
    void lease_recycle_jobs();
97
98
    void check_recycle_tasks();
99
100
private:
101
    friend class RecyclerServiceImpl;
102
103
    std::shared_ptr<TxnKv> txn_kv_;
104
    std::atomic_bool stopped_ {false};
105
106
    std::vector<std::thread> workers_;
107
108
    std::mutex mtx_;
109
    // notify recycle workers
110
    std::condition_variable pending_instance_cond_;
111
    std::deque<InstanceInfoPB> pending_instance_queue_;
112
    std::unordered_set<std::string> pending_instance_set_;
113
    std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map_;
114
    // notify instance scanner and lease thread
115
    std::condition_variable notifier_;
116
117
    std::string ip_port_;
118
119
    WhiteBlackList instance_filter_;
120
    std::unique_ptr<Checker> checker_;
121
122
    RecyclerThreadPoolGroup _thread_pool_group;
123
124
    std::shared_ptr<TxnLazyCommitter> txn_lazy_committer_;
125
    std::shared_ptr<SnapshotManager> snapshot_manager_;
126
    std::shared_ptr<SnapshotDataMigrator> snapshot_data_migrator_;
127
    std::shared_ptr<SnapshotChainCompactor> snapshot_chain_compactor_;
128
};
129
130
enum class RowsetRecyclingState {
131
    FORMAL_ROWSET,
132
    TMP_ROWSET,
133
};
134
135
// Represents a single rowset deletion task for batch delete
136
struct RowsetDeleteTask {
137
    RowsetMetaCloudPB rowset_meta;
138
    std::string recycle_rowset_key;       // Primary key marking "pending recycle"
139
    std::string non_versioned_rowset_key; // Legacy non-versioned rowset meta key
140
    std::string versioned_rowset_key;     // Versioned meta rowset key
141
    std::string rowset_ref_count_key;
142
};
143
144
class RecyclerMetricsContext {
145
public:
146
9
    RecyclerMetricsContext() = default;
147
148
    RecyclerMetricsContext(std::string instance_id, std::string operation_type)
149
494
            : operation_type(std::move(operation_type)), instance_id(std::move(instance_id)) {
150
494
        start();
151
494
    }
152
153
501
    ~RecyclerMetricsContext() = default;
154
155
    std::atomic_ullong total_need_recycle_data_size = 0;
156
    std::atomic_ullong total_need_recycle_num = 0;
157
158
    std::atomic_ullong total_recycled_data_size = 0;
159
    std::atomic_ullong total_recycled_num = 0;
160
161
    std::string operation_type;
162
    std::string instance_id;
163
164
    double start_time = 0;
165
166
494
    void start() {
167
494
        start_time = duration_cast<std::chrono::milliseconds>(
168
494
                             std::chrono::system_clock::now().time_since_epoch())
169
494
                             .count();
170
494
    }
171
172
239
    double duration() const {
173
239
        return duration_cast<std::chrono::milliseconds>(
174
239
                       std::chrono::system_clock::now().time_since_epoch())
175
239
                       .count() -
176
239
               start_time;
177
239
    }
178
179
20
    void reset() {
180
20
        total_need_recycle_data_size = 0;
181
20
        total_need_recycle_num = 0;
182
20
        total_recycled_data_size = 0;
183
20
        total_recycled_num = 0;
184
20
        start_time = duration_cast<std::chrono::milliseconds>(
185
20
                             std::chrono::system_clock::now().time_since_epoch())
186
20
                             .count();
187
20
    }
188
189
238
    void finish_report() {
190
238
        if (!operation_type.empty()) {
191
238
            double cost = duration();
192
238
            g_bvar_recycler_instance_last_round_recycle_elpased_ts.put(
193
238
                    {instance_id, operation_type}, cost);
194
238
            g_bvar_recycler_instance_recycle_round.put({instance_id, operation_type}, 1);
195
238
            LOG(INFO) << "recycle instance: " << instance_id
196
238
                      << ", operation type: " << operation_type << ", cost: " << cost
197
238
                      << " ms, total recycled num: " << total_recycled_num.load()
198
238
                      << ", total recycled data size: " << total_recycled_data_size.load()
199
238
                      << " bytes";
200
238
            if (cost != 0) {
201
217
                if (total_recycled_num.load() != 0) {
202
58
                    g_bvar_recycler_instance_recycle_time_per_resource.put(
203
58
                            {instance_id, operation_type}, cost / total_recycled_num.load());
204
58
                }
205
217
                g_bvar_recycler_instance_recycle_bytes_per_ms.put(
206
217
                        {instance_id, operation_type}, total_recycled_data_size.load() / cost);
207
217
            }
208
238
        }
209
238
    }
210
211
    // `is_begin` is used to initialize total num of items need to be recycled
212
24.7k
    void report(bool is_begin = false) {
213
24.7k
        if (!operation_type.empty()) {
214
            // is init
215
24.7k
            if (is_begin) {
216
3
                auto value = total_need_recycle_num.load();
217
218
3
                g_bvar_recycler_instance_last_round_to_recycle_bytes.put(
219
3
                        {instance_id, operation_type}, total_need_recycle_data_size.load());
220
3
                g_bvar_recycler_instance_last_round_to_recycle_num.put(
221
3
                        {instance_id, operation_type}, value);
222
24.6k
            } else {
223
24.6k
                g_bvar_recycler_instance_last_round_recycled_bytes.put(
224
24.6k
                        {instance_id, operation_type}, total_recycled_data_size.load());
225
24.6k
                g_bvar_recycler_instance_recycle_total_bytes_since_started.put(
226
24.6k
                        {instance_id, operation_type}, total_recycled_data_size.load());
227
24.6k
                g_bvar_recycler_instance_last_round_recycled_num.put({instance_id, operation_type},
228
24.6k
                                                                     total_recycled_num.load());
229
24.6k
                g_bvar_recycler_instance_recycle_total_num_since_started.put(
230
24.6k
                        {instance_id, operation_type}, total_recycled_num.load());
231
24.6k
            }
232
24.7k
        }
233
24.7k
    }
234
};
235
236
class TabletRecyclerMetricsContext : public RecyclerMetricsContext {
237
public:
238
130
    TabletRecyclerMetricsContext() : RecyclerMetricsContext("global_recycler", "recycle_tablet") {}
239
};
240
241
class SegmentRecyclerMetricsContext : public RecyclerMetricsContext {
242
public:
243
    SegmentRecyclerMetricsContext()
244
130
            : RecyclerMetricsContext("global_recycler", "recycle_segment") {}
245
};
246
247
struct OplogRecycleStats;
248
249
class InstanceRecycler {
250
public:
251
    struct PackedFileRecycleStats {
252
        int64_t num_scanned = 0;          // packed-file kv scanned
253
        int64_t num_corrected = 0;        // packed-file kv corrected
254
        int64_t num_deleted = 0;          // packed-file kv deleted
255
        int64_t num_failed = 0;           // packed-file kv failed
256
        int64_t bytes_deleted = 0;        // packed-file kv bytes deleted from txn-kv
257
        int64_t num_object_deleted = 0;   // packed-file objects deleted from storage (vault/HDFS)
258
        int64_t bytes_object_deleted = 0; // bytes deleted from storage objects
259
        int64_t rowset_scan_count = 0;    // rowset metas scanned during correction
260
    };
261
262
    explicit InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
263
                              RecyclerThreadPoolGroup thread_pool_group,
264
                              std::shared_ptr<TxnLazyCommitter> txn_lazy_committer);
265
    ~InstanceRecycler();
266
267
0
    std::string_view instance_id() const { return instance_id_; }
268
3
    const InstanceInfoPB& instance_info() const { return instance_info_; }
269
270
    // returns 0 for success otherwise error
271
    int init();
272
273
0
    void stop() { stopped_.store(true, std::memory_order_release); }
274
80
    bool stopped() const { return stopped_.load(std::memory_order_acquire); }
275
276
    // returns 0 for success otherwise error
277
    int do_recycle();
278
279
    // remove all kv and data in this instance, ONLY be called when instance has been deleted
280
    // returns 0 for success otherwise error
281
    int recycle_deleted_instance();
282
283
    // scan and recycle expired indexes:
284
    // 1. dropped table, dropped mv
285
    // 2. half-successtable/index when create
286
    // returns 0 for success otherwise error
287
    int recycle_indexes();
288
289
    // scan and recycle expired partitions:
290
    // 1. dropped parttion
291
    // 2. half-success partition when create
292
    // returns 0 for success otherwise error
293
    int recycle_partitions();
294
295
    // scan and recycle expired rowsets:
296
    // 1. prepare_rowset will produce recycle_rowset before uploading data to remote storage (memo)
297
    // 2. compaction will change the input rowsets to recycle_rowset
298
    // returns 0 for success otherwise error
299
    int recycle_rowsets();
300
301
    // like `recycle_rowsets`, but for versioned rowsets.
302
    int recycle_versioned_rowsets();
303
304
    // scan and recycle expired tmp rowsets:
305
    // 1. commit_rowset will produce tmp_rowset when finish upload data (load or compaction) to remote storage
306
    // returns 0 for success otherwise error
307
    int recycle_tmp_rowsets();
308
309
    /**
310
     * recycle all tablets belonging to the index specified by `index_id`
311
     *
312
     * @param partition_id if positive, only recycle tablets in this partition belonging to the specified index
313
     * @return 0 for success otherwise error
314
     */
315
    int recycle_tablets(int64_t table_id, int64_t index_id, RecyclerMetricsContext& ctx,
316
                        int64_t partition_id = -1);
317
318
    /**
319
     * recycle all rowsets belonging to the tablet specified by `tablet_id`
320
     *
321
     * @return 0 for success otherwise error
322
     */
323
    int recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context);
324
325
    /**
326
     * like `recycle_tablet`, but for versioned tablet
327
     */
328
    int recycle_versioned_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context);
329
330
    // scan and recycle useless partition version kv
331
    int recycle_versions();
332
333
    // scan and recycle the orphan partitions
334
    int recycle_orphan_partitions();
335
336
    // scan and abort timeout txn label
337
    // returns 0 for success otherwise error
338
    int abort_timeout_txn();
339
340
    //scan and recycle expire txn label
341
    // returns 0 for success otherwise error
342
    int recycle_expired_txn_label();
343
344
    // scan and recycle finished or timeout copy jobs
345
    // returns 0 for success otherwise error
346
    int recycle_copy_jobs();
347
348
    // scan and recycle dropped internal stage
349
    // returns 0 for success otherwise error
350
    int recycle_stage();
351
352
    // scan and recycle expired stage objects
353
    // returns 0 for success otherwise error
354
    int recycle_expired_stage_objects();
355
356
    // scan and recycle operation logs
357
    // returns 0 for success otherwise error
358
    int recycle_operation_logs();
359
360
    // scan and recycle expired restore jobs
361
    // returns 0 for success otherwise error
362
    int recycle_restore_jobs();
363
364
    /**
365
     * Scan packed-file metadata, correct reference counters, and recycle unused packed files.
366
     *
367
     * @return 0 on success, non-zero error code otherwise
368
     */
369
    int recycle_packed_files();
370
371
    // scan and recycle snapshots
372
    // returns 0 for success otherwise error
373
    int recycle_cluster_snapshots();
374
375
    // scan and recycle ref rowsets for deleted instance
376
    // returns 0 for success otherwise error
377
    int recycle_ref_rowsets(bool* has_unrecycled_rowsets);
378
379
    bool check_recycle_tasks();
380
381
    int scan_and_statistics_indexes();
382
383
    int scan_and_statistics_partitions();
384
385
    int scan_and_statistics_rowsets();
386
387
    int scan_and_statistics_tmp_rowsets();
388
389
    int scan_and_statistics_abort_timeout_txn();
390
391
    int scan_and_statistics_expired_txn_label();
392
393
    int scan_and_statistics_copy_jobs();
394
395
    int scan_and_statistics_stage();
396
397
    int scan_and_statistics_expired_stage_objects();
398
399
    int scan_and_statistics_versions();
400
401
    int scan_and_statistics_restore_jobs();
402
403
    void scan_and_statistics_operation_logs();
404
405
    /**
406
     * Decode the key of a packed-file metadata record into the persisted object path.
407
     *
408
     * @param key raw key persisted in txn-kv
409
     * @param packed_path output object storage path referenced by the key
410
     * @return true if decoding succeeds, false otherwise
411
     */
412
    static bool decode_packed_file_key(std::string_view key, std::string* packed_path);
413
414
29
    void TEST_add_accessor(std::string_view id, std::shared_ptr<StorageVaultAccessor> accessor) {
415
29
        accessor_map_.insert({std::string(id), std::move(accessor)});
416
29
    }
417
418
    // Recycle snapshot meta and data, return 0 for success otherwise error.
419
    int recycle_snapshot_meta_and_data(const std::string& resource_id,
420
                                       Versionstamp snapshot_version,
421
                                       const SnapshotPB& snapshot_pb);
422
423
private:
424
    // returns 0 for success otherwise error
425
    int init_obj_store_accessors();
426
427
    // returns 0 for success otherwise error
428
    int init_storage_vault_accessors();
429
430
    /**
431
     * Scan key-value pairs between [`begin`, `end`), and perform `recycle_func` on each key-value pair.
432
     *
433
     * @param recycle_func defines how to recycle resources corresponding to a key-value pair. Returns 0 if the recycling is successful.
434
     * @param loop_done is called after `RangeGetIterator` has no next kv. Usually used to perform a batch recycling. Returns 0 if success. 
435
     * @return 0 if all corresponding resources are recycled successfully, otherwise non-zero
436
     */
437
    int scan_and_recycle(std::string begin, std::string_view end,
438
                         std::function<int(std::string_view k, std::string_view v)> recycle_func,
439
                         std::function<int()> loop_done = nullptr);
440
441
    // return 0 for success otherwise error
442
    int delete_rowset_data(const doris::RowsetMetaCloudPB& rs_meta_pb);
443
444
    // return 0 for success otherwise error
445
    // NOTE: this function ONLY be called when the file paths cannot be calculated
446
    int delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
447
                           const std::string& rowset_id);
448
449
    // return 0 for success otherwise error
450
    int delete_rowset_data(const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets,
451
                           RowsetRecyclingState type, RecyclerMetricsContext& metrics_context);
452
453
    // return 0 for success otherwise error
454
    int decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb);
455
456
    int delete_packed_file_and_kv(const std::string& packed_file_path,
457
                                  const std::string& packed_key,
458
                                  const cloud::PackedFileInfoPB& packed_info);
459
460
    /**
461
     * Get stage storage info from instance and init StorageVaultAccessor
462
     * @return 0 if accessor is successfully inited, 1 if stage not found, negative for error
463
     */
464
    int init_copy_job_accessor(const std::string& stage_id, const StagePB::StageType& stage_type,
465
                               std::shared_ptr<StorageVaultAccessor>* accessor);
466
467
    void register_recycle_task(const std::string& task_name, int64_t start_time);
468
469
    void unregister_recycle_task(const std::string& task_name);
470
471
    // for scan all tablets and statistics metrics
472
    int scan_tablets_and_statistics(int64_t tablet_id, int64_t index_id,
473
                                    RecyclerMetricsContext& metrics_context,
474
                                    int64_t partition_id = -1, bool is_empty_tablet = false);
475
476
    // for scan all rs of tablet and statistics metrics
477
    int scan_tablet_and_statistics(int64_t tablet_id, RecyclerMetricsContext& metrics_context);
478
479
    // Recycle operation log and the log keys. The log keys are specified by `raw_keys`.
480
    //
481
    // Both `operation_log` and `raw_keys` will be removed in the same transaction, to ensure atomicity.
482
    int recycle_operation_log(Versionstamp log_version, const std::vector<std::string>& raw_keys,
483
                              OperationLogPB operation_log,
484
                              OplogRecycleStats* oplog_stats = nullptr);
485
486
    // Recycle rowset meta and data, return 0 for success otherwise error
487
    //
488
    // Both recycle_rowset_key and non_versioned_rowset_key will be removed in the same transaction.
489
    //
490
    // This function will decrease the rowset ref count and remove the rowset meta and data if the ref count is 1.
491
    int recycle_rowset_meta_and_data(std::string_view recycle_rowset_key,
492
                                     const RowsetMetaCloudPB& rowset_meta,
493
                                     std::string_view non_versioned_rowset_key = "");
494
495
    // Classify rowset task by ref_count, return 0 to add to batch delete, 1 if handled (ref>1), -1 on error
496
    int classify_rowset_task_by_ref_count(RowsetDeleteTask& task,
497
                                          std::vector<RowsetDeleteTask>& batch_delete_tasks);
498
499
    // Cleanup metadata for deleted rowsets, return 0 for success otherwise error
500
    int cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks);
501
502
    // Whether the instance has any snapshots, return 0 for success otherwise error.
503
    int has_cluster_snapshots(bool* any);
504
505
    // Whether need to recycle versioned keys
506
    bool should_recycle_versioned_keys() const;
507
508
    /**
509
     * Parse the path of a packed-file fragment and output the owning tablet and rowset identifiers.
510
     *
511
     * @param path packed-file fragment path to decode
512
     * @param tablet_id output tablet identifier extracted from the path
513
     * @param rowset_id output rowset identifier extracted from the path
514
     * @return true if both identifiers are successfully parsed, false otherwise
515
     */
516
    static bool parse_packed_slice_path(std::string_view path, int64_t* tablet_id,
517
                                        std::string* rowset_id);
518
    // Check whether a rowset referenced by a packed file still exists in metadata.
519
    // @param stats optional recycle statistics collector.
520
    int check_rowset_exists(int64_t tablet_id, const std::string& rowset_id, bool* exists,
521
                            PackedFileRecycleStats* stats = nullptr);
522
    int check_recycle_and_tmp_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
523
                                            int64_t txn_id, bool* recycle_exists, bool* tmp_exists);
524
    /**
525
     * Resolve which storage accessor should be used for a packed file.
526
     *
527
     * @param hint preferred storage resource identifier persisted with the file
528
     * @return pair of the resolved resource identifier and accessor; the accessor can be null if unavailable
529
     */
530
    std::pair<std::string, std::shared_ptr<StorageVaultAccessor>> resolve_packed_file_accessor(
531
            const std::string& hint);
532
    // Recompute packed-file counters and lifecycle state after validating contained fragments.
533
    // @param stats optional recycle statistics collector.
534
    int correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
535
                                 const std::string& packed_file_path,
536
                                 PackedFileRecycleStats* stats = nullptr);
537
    // Correct and recycle a single packed-file record, updating metadata and accounting statistics.
538
    // @param stats optional recycle statistics collector.
539
    int process_single_packed_file(const std::string& packed_key,
540
                                   const std::string& packed_file_path,
541
                                   PackedFileRecycleStats* stats);
542
    // Process a packed-file KV while scanning and aggregate recycling statistics.
543
    int handle_packed_file_kv(std::string_view key, std::string_view value,
544
                              PackedFileRecycleStats* stats, int* ret);
545
546
    // Abort the transaction/job associated with a rowset that is about to be recycled.
547
    // This function is called during rowset recycling to prevent data loss by ensuring that
548
    // the transaction/job cannot be committed after its rowset data has been deleted.
549
    //
550
    // Scenario:
551
    // When recycler detects an expired prepared rowset (e.g., from a failed load transaction/job),
552
    // it needs to recycle the rowset data. However, if the transaction/job is still active and gets
553
    // committed after the data is deleted, it would lead to data loss - the transaction/job would
554
    // reference non-existent data.
555
    //
556
    // Solution:
557
    // Before recycling the rowset data, this function aborts the associated transaction/job to ensure
558
    // it cannot be committed. This guarantees that:
559
    // 1. The transaction/job state is marked as ABORTED
560
    // 2. Any subsequent commit_rowset/commit_txn attempts will fail
561
    // 3. The rowset data can be safely deleted without risk of data loss
562
    //
563
    // Parameters:
564
    //   txn_id: The transaction/job ID associated with the rowset to be recycled
565
    //
566
    // Returns:
567
    //   0 on success, -1 on failure
568
    int abort_txn_for_related_rowset(int64_t txn_id);
569
    int abort_job_for_related_rowset(const RowsetMetaCloudPB& rowset_meta);
570
571
    template <typename T>
572
    int abort_txn_or_job_for_recycle(T& rowset_meta_pb);
573
574
private:
575
    std::atomic_bool stopped_ {false};
576
    std::shared_ptr<TxnKv> txn_kv_;
577
    std::string instance_id_;
578
    InstanceInfoPB instance_info_;
579
580
    // TODO(plat1ko): Add new accessor to map in runtime for new created storage vaults
581
    std::unordered_map<std::string, std::shared_ptr<StorageVaultAccessor>> accessor_map_;
582
    using InvertedIndexInfo =
583
            std::pair<InvertedIndexStorageFormatPB, std::vector<std::pair<int64_t, std::string>>>;
584
585
    class InvertedIndexIdCache;
586
    std::unique_ptr<InvertedIndexIdCache> inverted_index_id_cache_;
587
588
    std::mutex recycled_tablets_mtx_;
589
    // Store recycled tablets, we can skip deleting rowset data of these tablets because these data has already been deleted.
590
    std::unordered_set<int64_t> recycled_tablets_;
591
592
    std::mutex recycle_tasks_mutex;
593
    // <task_name, start_time>>
594
    std::map<std::string, int64_t> running_recycle_tasks;
595
596
    RecyclerThreadPoolGroup _thread_pool_group;
597
598
    std::shared_ptr<TxnLazyCommitter> txn_lazy_committer_;
599
    std::shared_ptr<SnapshotManager> snapshot_manager_;
600
    std::shared_ptr<DeleteBitmapLockWhiteList> delete_bitmap_lock_white_list_;
601
    std::shared_ptr<ResourceManager> resource_mgr_;
602
603
    TabletRecyclerMetricsContext tablet_metrics_context_;
604
    SegmentRecyclerMetricsContext segment_metrics_context_;
605
};
606
607
struct OperationLogReferenceInfo {
608
    bool referenced_by_instance = false;
609
    bool referenced_by_snapshot = false;
610
    Versionstamp referenced_snapshot_timestamp;
611
};
612
613
struct OplogRecycleStats {
614
    // Total oplog count scanned per round
615
    std::atomic<int64_t> total_num {0};
616
    // Oplogs not recycled this round (per round, written to mBvarStatus)
617
    std::atomic<int64_t> not_recycled_num {0};
618
    // Recycle failures (per round, accumulated to mBvarIntAdder at end)
619
    std::atomic<int64_t> failed_num {0};
620
    // Per-oplog-type recycled counts (incremented after successful commit)
621
    std::atomic<int64_t> recycled_commit_partition {0};
622
    std::atomic<int64_t> recycled_drop_partition {0};
623
    std::atomic<int64_t> recycled_commit_index {0};
624
    std::atomic<int64_t> recycled_drop_index {0};
625
    std::atomic<int64_t> recycled_update_tablet {0};
626
    std::atomic<int64_t> recycled_compaction {0};
627
    std::atomic<int64_t> recycled_schema_change {0};
628
    std::atomic<int64_t> recycled_commit_txn {0};
629
};
630
631
// Helper class to check if operation logs can be recycled based on snapshots and versionstamps
632
class OperationLogRecycleChecker {
633
public:
634
    OperationLogRecycleChecker(std::string_view instance_id, TxnKv* txn_kv,
635
                               const InstanceInfoPB& instance_info)
636
34
            : instance_id_(instance_id), txn_kv_(txn_kv), instance_info_(instance_info) {}
637
638
    // Initialize the checker by loading snapshots and setting max version stamp
639
    int init();
640
641
    // Check if an operation log can be recycled
642
    bool can_recycle(const Versionstamp& log_versionstamp, int64_t log_min_timestamp,
643
                     OperationLogReferenceInfo* reference_info) const;
644
645
0
    Versionstamp max_versionstamp() const { return max_versionstamp_; }
646
647
27
    const std::vector<std::pair<SnapshotPB, Versionstamp>>& get_snapshots() const {
648
27
        return snapshots_;
649
27
    }
650
651
private:
652
    std::string_view instance_id_;
653
    TxnKv* txn_kv_;
654
    const InstanceInfoPB& instance_info_;
655
    Versionstamp max_versionstamp_;
656
    Versionstamp source_snapshot_versionstamp_;
657
    std::map<Versionstamp, size_t> snapshot_indexes_;
658
    std::vector<std::pair<SnapshotPB, Versionstamp>> snapshots_;
659
};
660
661
class SnapshotDataSizeCalculator {
662
public:
663
    SnapshotDataSizeCalculator(std::string_view instance_id, std::shared_ptr<TxnKv> txn_kv)
664
28
            : instance_id_(instance_id), txn_kv_(std::move(txn_kv)) {}
665
666
    void init(const std::vector<std::pair<SnapshotPB, Versionstamp>>& snapshots);
667
668
    int calculate_operation_log_data_size(const std::string_view& log_key,
669
                                          OperationLogPB& operation_log,
670
                                          OperationLogReferenceInfo& reference_info);
671
672
    int save_snapshot_data_size_with_retry();
673
674
private:
675
    int get_all_index_partitions(int64_t db_id, int64_t table_id, int64_t index_id,
676
                                 std::vector<int64_t>* partition_ids);
677
    int get_index_partition_data_size(int64_t db_id, int64_t table_id, int64_t index_id,
678
                                      int64_t partition_id, int64_t* data_size);
679
    int save_operation_log(const std::string_view& log_key, OperationLogPB& operation_log);
680
    int save_snapshot_data_size();
681
682
    std::string_view instance_id_;
683
    std::shared_ptr<TxnKv> txn_kv_;
684
685
    int64_t instance_retained_data_size_ = 0;
686
    std::map<Versionstamp, int64_t> retained_data_size_;
687
    std::set<std::string> calculated_partitions_;
688
};
689
690
} // namespace doris::cloud