Coverage Report

Created: 2026-06-06 16:55

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