Coverage Report

Created: 2026-09-14 12:59

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